Skip to content

Commit

Permalink
codegen/enums: Simplify custom to_string with quote!
Browse files Browse the repository at this point in the history
This generates _identical_ code while being much more readable.
  • Loading branch information
MarijnS95 committed Nov 18, 2020
1 parent a674ba8 commit 37af52f
Showing 1 changed file with 29 additions and 34 deletions.
63 changes: 29 additions & 34 deletions src/codegen/enums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,47 +81,42 @@ fn generate_static_to_str(
enum_: &Enumeration,
function: &crate::analysis::functions::Info,
) -> Result<()> {
writeln!(w)?;
version_condition(w, env, function.version, false, 1)?;

// TODO: use the normal to_string name, and pass _by ref_!
// The trait_impls Display impl calls this... But it'll recursively
// call ToString::to_string -> Display::fmt if this function were by reference.
writeln!(w, "\tfn to_string(&self) -> &'static str {{")?;
let condition = version_condition_tokens(env, function.version, false);

let unk_match = if enum_.members.iter().any(|m| m.name == "unknown") {
"Self::Unknown | "
quote!(Self::Unknown |)
} else {
""
quote!()
};

writeln!(
w,
"\
\t\tmatch self {{
\t\t\t{}Self::__Unknown(_) => return \"UNKNOWN\",
\t\t\t_ => {{}},
\t\t}}",
unk_match
)?;

// TODO: Can we somehow reuse function_body_chunk::Builder here?
let native_call = {
// TODO: This can possibly be a function on Info
let crate_ = format_ident!("{}", env.main_sys_crate_name());
let name = format_ident!("{}", function.glib_name);
quote!(#crate_::#name(self.to_glib()))
};

writeln!(
w,
"\
\t\tunsafe {{
\t\t\tlet ptr = {}::{}(self.to_glib());
\t\t\tif ptr.is_null() {{
\t\t\t\treturn \"INVALID\";
\t\t\t}}
\t\t\tCStr::from_ptr(ptr).to_str().unwrap()
\t\t}}
\t}}",
env.main_sys_crate_name(),
function.glib_name
)?;
// TODO: use the normal to_string name, and pass _by ref_!
// The trait_impls Display impl calls this... But it'll recursively
// call ToString::to_string -> Display::fmt if this function were by reference.
let result = quote! {
#condition
fn to_string(&self) -> &'static str {
match self {
#unk_match Self::__Unknown(_) => return "UNKNOWN",
_ => {}
}
unsafe {
let ptr = #native_call;
if ptr.is_null() {
return "INVALID";
}
CStr::from_ptr(ptr).to_str().unwrap()
}
}
};

writeln!(w, "{}", result)?;
Ok(())
}

Expand Down

0 comments on commit 37af52f

Please sign in to comment.