From 37af52f724ea03a12bdc6127f027333588af308e Mon Sep 17 00:00:00 2001 From: Marijn Suijten Date: Wed, 18 Nov 2020 23:07:59 +0100 Subject: [PATCH] codegen/enums: Simplify custom to_string with quote! This generates _identical_ code while being much more readable. --- src/codegen/enums.rs | 63 ++++++++++++++++++++------------------------ 1 file changed, 29 insertions(+), 34 deletions(-) diff --git a/src/codegen/enums.rs b/src/codegen/enums.rs index 9e08033fd..36f65af3f 100644 --- a/src/codegen/enums.rs +++ b/src/codegen/enums.rs @@ -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(()) }