Skip to content

Instead of taking an &str take into<GString> #1184

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

Open
wants to merge 8 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
7 changes: 5 additions & 2 deletions src/analysis/bounds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ pub enum BoundType {
IsA(Option<char>),
// lifetime <- shouldn't be used but just in case...
AsRef(Option<char>),
// lifetime <- shouldn't be used but just in case...
Into(Option<char>),
}

impl BoundType {
Expand Down Expand Up @@ -169,7 +171,7 @@ impl Bounds {
match env.library.type_(type_id) {
Type::Fundamental(Fundamental::Filename) => Some(AsRef(None)),
Type::Fundamental(Fundamental::OsString) => Some(AsRef(None)),
Type::Fundamental(Fundamental::Utf8) if *nullable => None,
Type::Fundamental(Fundamental::Utf8) => Some(Into(None)),
Type::Class(Class {
final_type: true, ..
}) => None,
Expand Down Expand Up @@ -207,6 +209,7 @@ impl Bounds {
return;
}
let alias = self.unused.pop_front().expect("No free type aliases!");

self.used.push(Bound {
bound_type,
parameter_name: name.to_owned(),
Expand All @@ -225,7 +228,7 @@ impl Bounds {
use self::BoundType::*;
for used in &self.used {
match used.bound_type {
NoWrapper => (),
NoWrapper | Into(_) => (),
IsA(_) => imports.add("glib::object::IsA"),
AsRef(_) => imports.add_used_type(&used.type_str),
}
Expand Down
1 change: 1 addition & 0 deletions src/analysis/child_properties.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ 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, nullable) {
let r_type = RustType::builder(env, typ)
.ref_mode(RefMode::ByRefFake)
Expand Down
25 changes: 22 additions & 3 deletions src/analysis/function_parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,11 @@ pub enum TransformationType {
array_length_type: String,
},
IntoRaw(String),
Into {
name: String,
typ: String,
nullable: bool,
},
ToSome(String),
}

Expand Down Expand Up @@ -208,6 +213,7 @@ pub fn analyze(

let c_type = par.c_type.clone();
let typ = override_string_type_parameter(env, par.typ, &configured_parameters);
let rust_type_res = RustType::try_new(env, typ);

let ind_c = parameters.c_parameters.len();
let mut ind_rust = Some(parameters.rust_parameters.len());
Expand All @@ -225,6 +231,22 @@ pub fn analyze(
add_rust_parameter = false;
}

let nullable_override = configured_parameters.iter().find_map(|p| p.nullable);
let nullable = nullable_override.unwrap_or(par.nullable);

if par.typ == TypeId::tid_utf8() {
let transformation = Transformation {
ind_c,
ind_rust,
transformation_type: TransformationType::Into {
name: name.clone(),
typ: rust_type_res.into_string(),
nullable: *nullable,
},
};
parameters.transformations.push(transformation);
}

let mut array_name = configured_parameters
.iter()
.find_map(|p| p.length_of.as_ref());
Expand Down Expand Up @@ -263,9 +285,6 @@ pub fn analyze(
let ref_mode =
RefMode::without_unneeded_mut(env, par, immutable, in_trait && par.instance_parameter);

let nullable_override = configured_parameters.iter().find_map(|p| p.nullable);
let nullable = nullable_override.unwrap_or(par.nullable);

let try_from_glib = TryFromGlib::from_parameter(env, typ, &configured_parameters);

let c_par = CParameter {
Expand Down
2 changes: 2 additions & 0 deletions src/analysis/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ pub fn analyze<F: Borrow<library::Function>>(

'func: for func in functions {
let func = func.borrow();

let configured_functions = obj.functions.matched(&func.name);
let mut status = obj.status;
for f in configured_functions.iter() {
Expand Down Expand Up @@ -703,6 +704,7 @@ fn analyze_function(
used_types.extend(rust_type.into_used_types());
}
}

let (to_glib_extra, callback_info) = bounds.add_for_parameter(
env,
func,
Expand Down
27 changes: 21 additions & 6 deletions src/analysis/rust_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,7 @@ impl<'env> RustTypeBuilder<'env> {
let ok_and_use = |s: &str| Ok(RustType::new_and_use(s));
let err = |s: &str| Err(TypeError::Unimplemented(s.into()));
let mut skip_option = false;
let mut skip_ref = false;
let type_ = self.env.library.type_(self.type_id);
let mut rust_type = match *type_ {
Fundamental(fund) => {
Expand Down Expand Up @@ -270,7 +271,8 @@ impl<'env> RustTypeBuilder<'env> {
UniChar => ok("char"),
Utf8 => {
if self.ref_mode.is_ref() {
ok("str")
skip_ref = true;
ok_and_use(&use_glib_type(&self.env, "GString"))
} else {
ok_and_use(&use_glib_type(&self.env, "GString"))
}
Expand Down Expand Up @@ -540,7 +542,11 @@ impl<'env> RustTypeBuilder<'env> {

opt
})
.apply_ref_mode(self.ref_mode)
.apply_ref_mode(if skip_ref {
RefMode::None
} else {
self.ref_mode
})
});
}
TryFromGlib::Result { ok_type, err_type } => {
Expand All @@ -561,11 +567,21 @@ impl<'env> RustTypeBuilder<'env> {
}
}
TryFromGlib::ResultInfallible { ok_type } => {
let new_rust_type = RustType::new_and_use(ok_type).apply_ref_mode(self.ref_mode);
let new_rust_type = RustType::new_and_use(ok_type).apply_ref_mode(if skip_ref {
RefMode::None
} else {
self.ref_mode
});
rust_type = rust_type.map_any(|_| new_rust_type);
}
_ => {
rust_type = rust_type.map_any(|rust_type| rust_type.apply_ref_mode(self.ref_mode));
rust_type = rust_type.map_any(|rust_type| {
rust_type.apply_ref_mode(if skip_ref {
RefMode::None
} else {
self.ref_mode
})
});
}
}

Expand All @@ -579,7 +595,6 @@ impl<'env> RustTypeBuilder<'env> {
_ => (),
}
}

rust_type
}

Expand Down Expand Up @@ -650,7 +665,7 @@ impl<'env> RustTypeBuilder<'env> {
},
CArray(..) | PtrArray(..) => match self.direction {
ParameterDirection::In | ParameterDirection::Out | ParameterDirection::Return => {
rust_type
rust_type.map_any(|rust_type| rust_type.format_parameter(self.direction))
}
_ => Err(TypeError::Unimplemented(into_inner(rust_type))),
},
Expand Down
16 changes: 16 additions & 0 deletions src/codegen/bound.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ impl Bound {
format!("Option<{}{}>", ref_str, t)
}
BoundType::IsA(_) => format!("{}{}", ref_str, t),
BoundType::Into(_) if *nullable => {
format!("Option<{}>", t)
}
BoundType::Into(_) => {
format!("{}", t)
}
BoundType::NoWrapper | BoundType::AsRef(_) => t.to_string(),
}
}
Expand Down Expand Up @@ -56,6 +62,16 @@ impl Bound {
}
BoundType::AsRef(Some(_ /*lifetime*/)) => panic!("AsRef cannot have a lifetime"),
BoundType::AsRef(None) => format!("AsRef<{}>", self.type_str),
BoundType::Into(Some(_ /*lifetime*/)) => panic!("Into cannot have a lifetime"),
BoundType::Into(None) => {
let is_a = format!("Into<{}>", self.type_str);
let lifetime = r#async
.then(|| " + Clone + 'static".to_string())
.or_else(|| Some("".to_string()))
.unwrap_or_default();

format!("{}{}", is_a, lifetime)
}
}
}
}
52 changes: 38 additions & 14 deletions src/codegen/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ use super::{
};
use crate::{
analysis::{
self, bounds::Bounds, functions::Visibility, namespaces, try_from_glib::TryFromGlib,
self, bounds::Bounds, functions::Visibility, namespaces, rust_type::RustType,
try_from_glib::TryFromGlib,
},
chunk::{ffi_function_todo, Chunk},
env::Env,
library,
library::{self, Fundamental, Type},
version::Version,
writer::{primitives::tabs, safety_assertion_mode_to_str, ToCode},
};
Expand Down Expand Up @@ -205,6 +206,7 @@ pub fn declaration_futures(env: &Env, analysis: &analysis::functions::Info) -> S

let mut skipped = 0;
let mut skipped_bounds = vec![];

for (pos, par) in analysis.parameters.rust_parameters.iter().enumerate() {
let c_par = &analysis.parameters.c_parameters[par.ind_c];

Expand Down Expand Up @@ -376,13 +378,23 @@ pub fn body_chunk_futures(
);

if *c_par.nullable {
writeln!(
body,
"let {} = {}.map(ToOwned::to_owned);",
par.name, par.name
)?;
if is_str {
writeln!(
body,
"let {}: Option<{}> = {}.map(|p| p.into());",
par.name,
RustType::try_new(env, par.typ).unwrap().as_str(),
par.name,
)?;
} else {
writeln!(
body,
"let {} = {}.map(ToOwned::to_owned);",
par.name, par.name
)?;
}
} else if is_str {
writeln!(body, "let {} = String::from({});", par.name, par.name)?;
// writeln!(body, "let {} = String::from({});", par.name, par.name)?;
} else if c_par.ref_mode != RefMode::None {
writeln!(body, "let {} = {}.clone();", par.name, par.name)?;
}
Expand Down Expand Up @@ -424,13 +436,25 @@ pub fn body_chunk_futures(
} else {
let c_par = &analysis.parameters.c_parameters[par.ind_c];

let type_ = env.type_(par.typ);
let is_str = matches!(
*type_,
library::Type::Fundamental(library::Fundamental::Utf8)
);

if *c_par.nullable {
writeln!(
body,
"\t\t{}.as_ref().map(::std::borrow::Borrow::borrow),",
par.name
)?;
} else if c_par.ref_mode != RefMode::None {
if is_str {
writeln!(body, "\t\t{},", par.name)?;
} else {
writeln!(
body,
"\t\t{}.as_ref().map(::std::borrow::Borrow::borrow),",
par.name
)?;
}
} else if c_par.ref_mode != RefMode::None
&& env.library.type_(c_par.typ) != &Type::Fundamental(Fundamental::Utf8)
{
writeln!(body, "\t\t&{},", par.name)?;
} else {
writeln!(body, "\t\t{},", par.name)?;
Expand Down
32 changes: 32 additions & 0 deletions src/codegen/function_body_chunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ impl Builder {

let mut chunks = Vec::new();

self.add_in_into_conversions(&mut chunks);
self.add_in_array_lengths(&mut chunks);
self.add_assertion(&mut chunks);

Expand Down Expand Up @@ -935,6 +936,37 @@ impl Builder {
}
}

fn add_in_into_conversions(&self, chunks: &mut Vec<Chunk>) {
for trans in &self.transformations {
if let TransformationType::Into {
ref name,
ref typ,
ref nullable,
} = &trans.transformation_type
{
if let In = self.parameters[trans.ind_c] {
let (value, typ) = if *nullable {
(
Chunk::Custom(format!("{}.map(|p| p.into())", name)),
Chunk::Custom(format!("Option<{}>", typ)),
)
} else {
(
Chunk::Custom(format!("{}.into()", name)),
Chunk::Custom(format!("{}", typ)),
)
};
chunks.push(Chunk::Let {
name: name.clone(),
is_mut: false,
value: Box::new(value),
type_: Some(Box::new(typ)),
});
}
}
}
}

fn add_in_array_lengths(&self, chunks: &mut Vec<Chunk>) {
for trans in &self.transformations {
if let TransformationType::Length {
Expand Down
9 changes: 8 additions & 1 deletion src/codegen/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ fn generate_builder(w: &mut dyn Write, env: &Env, analysis: &analysis::object::I
analysis.name,
)?;
writeln!(w, "pub struct {}Builder {{", analysis.name)?;

for property in &analysis.builder_properties {
match RustType::try_new(env, property.typ) {
Ok(type_string) => {
Expand All @@ -223,13 +224,19 @@ fn generate_builder(w: &mut dyn Write, env: &Env, analysis: &analysis::object::I
} else {
library::ParameterDirection::Out
};

let mut param_type = RustType::builder(env, property.typ)
.direction(direction)
.ref_mode(property.set_in_ref_mode)
.try_build()
.into_string();

let (param_type_override, bounds, conversion) = match &param_type[..] {
"&str" => (None, String::new(), ".to_string()"),
typ if nameutil::is_gstring(typ) && property.set_in_ref_mode.is_ref() => (
Some("P".to_string()),
"<P: Into<glib::GString>>".to_string(),
".into().to_string()",
),
"&[&str]" => (Some("Vec<String>".to_string()), String::new(), ""),
_ if !property.bounds.is_empty() => {
let (bounds, _) = function::bounds(&property.bounds, &[], false, false);
Expand Down
6 changes: 4 additions & 2 deletions src/codegen/trampoline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::{
},
consts::TYPE_PARAMETERS_START,
env::Env,
library,
library::{self},
nameutil::{use_glib_if_needed, use_gtk_type},
traits::IntoString,
writer::primitives::tabs,
Expand Down Expand Up @@ -79,7 +79,9 @@ pub fn func_string(

format!(
"Fn({}){}{} + 'static",
param_str, return_str, concurrency_str
param_str.replace("glib::GString", "&str"),
return_str,
concurrency_str
)
} else {
format!("({}){}", param_str, return_str,)
Expand Down
Loading