X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=c-bindings-gen%2Fsrc%2Ftypes.rs;h=3fc35e8b2558f8de6f7da2d4d017664a8b3390d1;hb=2d0cdbd33e63a82b5c9215d21a730e3e7a96ee74;hp=14b2826f1e8b880824ebc8191398d771e64e6396;hpb=00fb152758261ff6274b732bccaa211ed8321d06;p=rust-lightning diff --git a/c-bindings-gen/src/types.rs b/c-bindings-gen/src/types.rs index 14b2826f..3fc35e8b 100644 --- a/c-bindings-gen/src/types.rs +++ b/c-bindings-gen/src/types.rs @@ -1,6 +1,7 @@ use std::collections::HashMap; use std::fs::File; use std::io::Write; +use std::hash; use proc_macro2::{TokenTree, Span}; @@ -225,6 +226,13 @@ pub enum DeclType<'a> { EnumIgnored, } +// templates_defined is walked to write the C++ header, so if we use the default hashing it get +// reordered on each genbindings run. Instead, we use SipHasher (which defaults to 0-keys) so that +// the sorting is stable across runs. It is deprecated, but the "replacement" doesn't actually +// accomplish the same goals, so we just ignore it. +#[allow(deprecated)] +type NonRandomHash = hash::BuildHasherDefault; + /// Top-level struct tracking everything which has been defined while walking the crate. pub struct CrateTypes<'a> { /// This may contain structs or enums, but only when either is mapped as @@ -234,11 +242,13 @@ pub struct CrateTypes<'a> { pub mirrored_enums: HashMap, /// Traits which are mapped as a pointer + jump table pub traits: HashMap, + /// Aliases from paths to some other Type + pub type_aliases: HashMap, /// Template continer types defined, map from mangled type name -> whether a destructor fn /// exists. /// /// This is used at the end of processing to make C++ wrapper classes - pub templates_defined: HashMap, + pub templates_defined: HashMap, /// The output file for any created template container types, written to as we find new /// template containers which need to be defined. pub template_file: &'a mut File, @@ -255,6 +265,17 @@ pub struct TypeResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> { pub crate_types: &'mod_lifetime mut CrateTypes<'crate_lft>, } +/// Returned by write_empty_rust_val_check_suffix to indicate what type of dereferencing needs to +/// happen to get the inner value of a generic. +enum EmptyValExpectedTy { + /// A type which has a flag for being empty (eg an array where we treat all-0s as empty). + NonPointer, + /// A pointer that we want to dereference and move out of. + OwnedPointer, + /// A pointer which we want to convert to a reference. + ReferenceAsPointer, +} + impl<'a, 'c: 'a> TypeResolver<'a, 'c> { pub fn new(orig_crate: &'a str, module_path: &'a str, crate_types: &'a mut CrateTypes<'c>) -> Self { let mut imports = HashMap::new(); @@ -755,20 +776,21 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { if let Some(t) = single_contained { let mut v = Vec::new(); - let (needs_deref, ret_ref) = self.write_empty_rust_val_check_suffix(generics, &mut v, t); + let ret_ref = self.write_empty_rust_val_check_suffix(generics, &mut v, t); let s = String::from_utf8(v).unwrap(); - if needs_deref && ret_ref { - return Some(("if ", vec![ - (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ &mut *{} }}", var_access)) - ], ") }")); - } else if needs_deref { - return Some(("if ", vec![ - (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ *Box::from_raw({}) }}", var_access)) - ], ") }")); - } else { - return Some(("if ", vec![ - (format!("{} {{ None }} else {{ Some(", s), format!("{}", var_access)) - ], ") }")); + match ret_ref { + EmptyValExpectedTy::ReferenceAsPointer => + return Some(("if ", vec![ + (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ &mut *{} }}", var_access)) + ], ") }")), + EmptyValExpectedTy::OwnedPointer => + return Some(("if ", vec![ + (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ *Box::from_raw({}) }}", var_access)) + ], ") }")), + EmptyValExpectedTy::NonPointer => + return Some(("if ", vec![ + (format!("{} {{ None }} else {{ Some(", s), format!("{}", var_access)) + ], ") }")), } } else { unreachable!(); } }, @@ -1052,23 +1074,23 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { } } - /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val), - /// returning whether we need to dereference the inner value before using it (ie it is a - /// pointer). - pub fn write_empty_rust_val_check_suffix(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) -> (bool, bool) { + /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val). + /// See EmptyValExpectedTy for information on return types. + fn write_empty_rust_val_check_suffix(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) -> EmptyValExpectedTy { match t { syn::Type::Path(p) => { let resolved = self.resolve_path(&p.path, generics); if self.crate_types.opaques.get(&resolved).is_some() { write!(w, ".inner.is_null()").unwrap(); - (false, false) + EmptyValExpectedTy::NonPointer } else { if let Some(suffix) = self.empty_val_check_suffix_from_path(&resolved) { write!(w, "{}", suffix).unwrap(); - (false, false) // We may eventually need to allow empty_val_check_suffix_from_path to specify if we need a deref or not + // We may eventually need to allow empty_val_check_suffix_from_path to specify if we need a deref or not + EmptyValExpectedTy::NonPointer } else { write!(w, " == std::ptr::null_mut()").unwrap(); - (true, false) + EmptyValExpectedTy::OwnedPointer } } }, @@ -1076,7 +1098,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { if let syn::Expr::Lit(l) = &a.len { if let syn::Lit::Int(i) = &l.lit { write!(w, " == [0; {}]", i.base10_digits()).unwrap(); - (false, false) + EmptyValExpectedTy::NonPointer } else { unimplemented!(); } } else { unimplemented!(); } }, @@ -1084,7 +1106,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { // Option<[]> always implies that we want to treat len() == 0 differently from // None, so we always map an Option<[]> into a pointer. write!(w, " == std::ptr::null_mut()").unwrap(); - (true, true) + EmptyValExpectedTy::ReferenceAsPointer }, _ => unimplemented!(), } @@ -1164,7 +1186,9 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { } let resolved_path = self.resolve_path(&p.path, generics); - if let Some(c_type) = path_lookup(&resolved_path, is_ref, ptr_for_ref) { + if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) { + return self.write_conversion_inline_intern(w, aliased_type, None, is_ref, is_mut, ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup); + } else if let Some(c_type) = path_lookup(&resolved_path, is_ref, ptr_for_ref) { write!(w, "{}", c_type).unwrap(); } else if self.crate_types.opaques.get(&resolved_path).is_some() { decl_lookup(w, &DeclType::StructImported, &resolved_path, is_ref, is_mut); @@ -1476,6 +1500,9 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { unimplemented!(); } let resolved_path = self.resolve_path(&p.path, generics); + if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) { + return self.write_conversion_new_var_intern(w, ident, var, aliased_type, None, is_ref, ptr_for_ref, to_c, path_lookup, container_lookup, var_prefix, var_suffix); + } if self.is_known_container(&resolved_path, is_ref) || self.is_transparent_container(&resolved_path, is_ref) { if let syn::PathArguments::AngleBracketed(args) = &p.path.segments.iter().next().unwrap().arguments { convert_container!(resolved_path, args.args.len(), || args.args.iter().map(|arg| { @@ -1667,14 +1694,14 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { write!(w, "#[no_mangle]\npub extern \"C\" fn {}_new(", mangled_container).unwrap(); for (idx, gen) in args.iter().enumerate() { write!(w, "{}{}: ", if idx != 0 { ", " } else { "" }, ('a' as u8 + idx as u8) as char).unwrap(); - self.write_c_type_intern(w, gen, None, false, false, false); + assert!(self.write_c_type_intern(w, gen, None, false, false, false)); } writeln!(w, ") -> {} {{", mangled_container).unwrap(); - writeln!(w, "\t{} {{", mangled_container).unwrap(); + write!(w, "\t{} {{ ", mangled_container).unwrap(); for idx in 0..args.len() { - writeln!(w, "\t\t{}: Box::into_raw(Box::new({})),", ('a' as u8 + idx as u8) as char, ('a' as u8 + idx as u8) as char).unwrap(); + write!(w, "{}, ", ('a' as u8 + idx as u8) as char).unwrap(); } - writeln!(w, "\t}}\n}}\n").unwrap(); + writeln!(w, "}}\n}}\n").unwrap(); } else { writeln!(w, "").unwrap(); } @@ -1949,13 +1976,13 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { if self.is_known_container(&full_path, is_ref) || self.is_transparent_container(&full_path, is_ref) { return self.write_c_mangled_container_path(w, Self::path_to_generic_args(&p.path), generics, &full_path, is_ref, is_mut, ptr_for_ref); } + if let Some(aliased_type) = self.crate_types.type_aliases.get(&full_path).cloned() { + return self.write_c_type_intern(w, &aliased_type, None, is_ref, is_mut, ptr_for_ref); + } } self.write_c_path_intern(w, &p.path, generics, is_ref, is_mut, ptr_for_ref) }, syn::Type::Reference(r) => { - if let Some(lft) = &r.lifetime { - if format!("{}", lft.ident) != "static" { return false; } - } self.write_c_type_intern(w, &*r.elem, generics, true, r.mutability.is_some(), ptr_for_ref) }, syn::Type::Array(a) => {