Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change &str input args into impl IntoGStr #1448

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 41 additions & 5 deletions src/analysis/bounds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,19 @@ use crate::{
consts::TYPE_PARAMETERS_START,
env::Env,
library::{Basic, Class, Concurrency, Function, ParameterDirection, Type, TypeId},
nameutil::use_glib_type,
traits::IntoString,
};

#[derive(Clone, Eq, Debug, PartialEq)]
pub enum BoundType {
NoWrapper,
Custom(String),
// lifetime
IsA(Option<char>),
// lifetime <- shouldn't be used but just in case...
AsRef(Option<char>),
Into,
}

impl BoundType {
Expand Down Expand Up @@ -83,11 +86,19 @@ impl Bounds {
func: &Function,
par: &CParameter,
r#async: bool,
future: bool,
concurrency: Concurrency,
configured_functions: &[&config::functions::Function],
) -> (Option<String>, Option<CallbackInfo>) {
if par.has_length && par.is_gstr(env) {
return (None, None);
}
let type_name = RustType::builder(env, par.typ)
.ref_mode(RefMode::ByRefFake)
.ref_mode(if par.move_ || future {
RefMode::None
} else {
RefMode::ByRefFake
})
.try_build();
if type_name.is_err() {
return (None, None);
Expand All @@ -97,8 +108,13 @@ impl Bounds {
let mut ret = None;
let mut need_is_into_check = false;

let ref_mode = if par.move_ || future {
RefMode::None
} else {
par.ref_mode
};
if !par.instance_parameter && par.direction != ParameterDirection::Out {
if let Some(bound_type) = Bounds::type_for(env, par.typ) {
if let Some(bound_type) = Bounds::type_for(env, par.typ, ref_mode, &par.c_type) {
ret = Some(Bounds::get_to_glib_extra(
&bound_type,
*par.nullable,
Expand Down Expand Up @@ -188,7 +204,7 @@ impl Bounds {
}
}
} else if par.instance_parameter {
if let Some(bound_type) = Bounds::type_for(env, par.typ) {
if let Some(bound_type) = Bounds::type_for(env, par.typ, ref_mode, &par.c_type) {
ret = Some(Bounds::get_to_glib_extra(
&bound_type,
*par.nullable,
Expand All @@ -201,10 +217,28 @@ impl Bounds {
(ret, callback_info)
}

pub fn type_for(env: &Env, type_id: TypeId) -> Option<BoundType> {
pub fn type_for(
env: &Env,
type_id: TypeId,
ref_mode: RefMode,
c_type: &str,
) -> Option<BoundType> {
use self::BoundType::*;
match env.library.type_(type_id) {
Type::Basic(Basic::Filename | Basic::OsString) => Some(AsRef(None)),
Type::Basic(Basic::Utf8) => {
if ref_mode.is_ref() {
Some(Custom(use_glib_type(env, "IntoGStr")))
} else {
Some(Into)
}
}
Type::CArray(inner)
if matches!(env.type_(*inner), Type::Basic(Basic::Utf8))
&& !matches!(c_type, "char**" | "gchar**") =>
{
Some(Custom(use_glib_type(env, "IntoStrV")))
}
Type::Class(Class {
is_fundamental: true,
..
Expand Down Expand Up @@ -238,6 +272,8 @@ impl Bounds {
IsA(_) if nullable && !instance_parameter => ".map(|p| p.as_ref())".to_owned(),
IsA(_) if move_ => ".upcast()".to_owned(),
IsA(_) => ".as_ref()".to_owned(),
Into if nullable => ".map(|p| p.into())".to_owned(),
Into => ".into()".to_owned(),
_ => String::new(),
}
}
Expand Down Expand Up @@ -276,7 +312,7 @@ impl Bounds {
use self::BoundType::*;
for used in &self.used {
match used.bound_type {
NoWrapper => (),
NoWrapper | Custom(_) | Into => (),
IsA(_) => imports.add("glib::prelude::*"),
AsRef(_) => imports.add_used_type(&used.type_str),
}
Expand Down
22 changes: 16 additions & 6 deletions src/analysis/child_properties.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::fmt::Write;

use log::error;

use crate::{
Expand Down Expand Up @@ -120,22 +122,30 @@ fn analyze_property(

let mut bounds_str = String::new();
let dir = ParameterDirection::In;
let set_params = if let Some(bound) = Bounds::type_for(env, typ) {
let set_params = if let Some(bound) = Bounds::type_for(env, typ, RefMode::None, "") {
let r_type = RustType::builder(env, typ)
.ref_mode(RefMode::ByRefFake)
.ref_mode(RefMode::None)
.try_build()
.into_string();

let _bound = Bound {
let bound = Bound {
bound_type: bound,
parameter_name: TYPE_PARAMETERS_START.to_string(),
alias: Some(TYPE_PARAMETERS_START.to_owned()),
type_str: r_type,
callback_modified: false,
};
// TODO: bounds_str push?!?!
bounds_str.push_str("TODO");
format!("{prop_name}: {TYPE_PARAMETERS_START}")
write!(
bounds_str,
"{TYPE_PARAMETERS_START}: {}",
bound.trait_bound(false)
)
.unwrap();
if *nullable {
format!("{prop_name}: Option<{TYPE_PARAMETERS_START}>")
} else {
format!("{prop_name}: {TYPE_PARAMETERS_START}")
}
// let mut bounds = Bounds::default();
// bounds.add_parameter("P", &r_type, bound, false);
// let (s_bounds, _) = function::bounds(&bounds, &[], false);
Expand Down
7 changes: 6 additions & 1 deletion src/analysis/class_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,12 @@ fn analyze_property(
let (get_out_ref_mode, set_in_ref_mode, nullable) = get_property_ref_modes(env, prop);

let mut bounds = Bounds::default();
if let Some(bound) = Bounds::type_for(env, prop.typ) {
if let Some(bound) = Bounds::type_for(
env,
prop.typ,
super::ref_mode::RefMode::None,
prop.c_type.as_deref().unwrap_or_default(),
) {
imports.add("glib::prelude::*");
bounds.add_parameter(&prop.name, &rust_type_res.into_string(), bound, false);
}
Expand Down
119 changes: 92 additions & 27 deletions src/analysis/function_parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ pub struct CParameter {
pub transfer: library::Transfer,
pub caller_allocates: bool,
pub is_error: bool,
pub has_length: bool,
pub scope: ParameterScope,
/// Index of the user data parameter associated with the callback.
pub user_data_index: Option<usize>,
Expand All @@ -76,6 +77,25 @@ pub struct CParameter {
pub move_: bool,
}

impl CParameter {
pub fn is_gstr(&self, env: &Env) -> bool {
matches!(
env.type_(self.typ),
library::Type::Basic(library::Basic::Utf8)
) && self.ref_mode.is_ref()
}
pub fn is_strv(&self, env: &Env) -> bool {
if let library::Type::CArray(inner) = env.type_(self.typ) {
matches!(
env.type_(*inner),
library::Type::Basic(library::Basic::Utf8)
) && !matches!(self.c_type.as_str(), "char**" | "gchar**")
} else {
false
}
}
}

#[derive(Clone, Debug)]
pub enum TransformationType {
ToGlibDirect {
Expand All @@ -89,6 +109,7 @@ pub enum TransformationType {
ToGlibPointer {
name: String,
instance_parameter: bool,
typ: library::TypeId,
transfer: library::Transfer,
ref_mode: RefMode,
// filled by functions
Expand All @@ -110,20 +131,28 @@ pub enum TransformationType {
},
IntoRaw(String),
ToSome(String),
AsPtr(String),
RunWith {
name: String,
func: String,
inner: Box<TransformationType>,
},
}

impl TransformationType {
pub fn is_to_glib(&self) -> bool {
matches!(
*self,
match self {
Self::ToGlibDirect { .. }
| Self::ToGlibScalar { .. }
| Self::ToGlibPointer { .. }
| Self::ToGlibBorrow
| Self::ToGlibUnknown { .. }
| Self::ToSome(_)
| Self::IntoRaw(_)
)
| Self::ToGlibScalar { .. }
| Self::ToGlibPointer { .. }
| Self::ToGlibBorrow
| Self::ToGlibUnknown { .. }
| Self::ToSome(_)
| Self::IntoRaw(_)
| Self::AsPtr(_) => true,
Self::RunWith { inner, .. } => inner.is_to_glib(),
_ => false,
}
}

pub fn set_to_glib_extra(&mut self, to_glib_extra_: &str) {
Expand Down Expand Up @@ -269,6 +298,7 @@ pub fn analyze(
transfer == Transfer::Full && par.direction.is_in()
}
});

let mut array_par = configured_parameters.iter().find_map(|cp| {
cp.length_of
.as_ref()
Expand All @@ -278,11 +308,18 @@ pub fn analyze(
array_par = array_lengths.get(&(pos as u32)).copied();
}
if array_par.is_none() && !disable_length_detect {
array_par = detect_length(env, pos, par, function_parameters);
array_par = detect_array(env, pos, par, function_parameters);
}
if let Some(array_par) = array_par {
let mut array_name = nameutil::mangle_keywords(&array_par.name);
if let Some(bound_type) = Bounds::type_for(env, array_par.typ) {
let ref_mode = if array_par.transfer == Transfer::Full {
RefMode::None
} else {
RefMode::of(env, array_par.typ, array_par.direction)
};
if let Some(bound_type) =
Bounds::type_for(env, array_par.typ, ref_mode, &array_par.c_type)
{
array_name = (array_name.into_owned()
+ &Bounds::get_to_glib_extra(
&bound_type,
Expand All @@ -302,6 +339,9 @@ pub fn analyze(
};
parameters.transformations.push(transformation);
}
let has_length = par.array_length.is_some()
|| (!disable_length_detect
&& detect_length(env, pos, par, function_parameters).is_some());

let immutable = configured_parameters.iter().any(|p| p.constant);
let ref_mode =
Expand All @@ -323,6 +363,7 @@ pub fn analyze(
nullable,
ref_mode,
is_error: par.is_error,
has_length,
scope: par.scope,
user_data_index: par.closure,
destroy_index: par.destroy,
Expand Down Expand Up @@ -389,6 +430,7 @@ pub fn analyze(
ConversionType::Pointer => TransformationType::ToGlibPointer {
name,
instance_parameter: par.instance_parameter,
typ,
transfer,
ref_mode,
to_glib_extra: Default::default(),
Expand Down Expand Up @@ -434,6 +476,26 @@ pub fn analyze(
if let Some(transformation_type) = transformation_type {
transformation.transformation_type = transformation_type;
}

let c_par = parameters.c_parameters.last().unwrap();
if c_par.is_gstr(env) && !has_length {
transformation.transformation_type = TransformationType::RunWith {
name: c_par.name.clone(),
func: if *c_par.nullable {
nameutil::use_glib_type(env, "IntoOptionalGStr::run_with_gstr")
} else {
nameutil::use_glib_type(env, "IntoGStr::run_with_gstr")
},
inner: Box::new(transformation.transformation_type),
};
} else if c_par.is_strv(env) {
transformation.transformation_type = TransformationType::RunWith {
name: c_par.name.clone(),
func: nameutil::use_glib_type(env, "IntoStrV::run_with_strv"),
inner: Box::new(TransformationType::AsPtr(c_par.name.clone())),
};
}

parameters.transformations.push(transformation);
}

Expand All @@ -460,30 +522,33 @@ fn detect_length<'a>(
par: &library::Parameter,
parameters: &'a [library::Parameter],
) -> Option<&'a library::Parameter> {
if !is_length(par) || pos == 0 {
if !has_length(env, par.typ) {
return None;
}

parameters.get(pos - 1).and_then(|p| {
if has_length(env, p.typ) {
Some(p)
} else {
None
}
})
parameters
.get(pos + 1)
.and_then(|p| is_length(p).then_some(p))
}

fn is_length(par: &library::Parameter) -> bool {
if par.direction != library::ParameterDirection::In {
return false;
fn detect_array<'a>(
env: &Env,
pos: usize,
par: &library::Parameter,
parameters: &'a [library::Parameter],
) -> Option<&'a library::Parameter> {
if pos == 0 || !is_length(par) {
return None;
}

let len = par.name.len();
if len >= 3 && &par.name[len - 3..len] == "len" {
return true;
}
parameters
.get(pos - 1)
.and_then(|p| has_length(env, p.typ).then_some(p))
}

par.name.contains("length")
fn is_length(par: &library::Parameter) -> bool {
par.direction == library::ParameterDirection::In
&& (par.name.ends_with("len") || par.name.contains("length"))
}

fn has_length(env: &Env, typ: TypeId) -> bool {
Expand Down
Loading