X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=c-bindings-gen%2Fsrc%2Fmain.rs;h=a0acfc65dd6a27cc9e30a0f0167210526ca434bd;hb=c42ea50cc703f03465d52b5fccfc4a90466d9fea;hp=07948ed42fa4b737b8dc9584a81e0925783772d7;hpb=494e0fd8a01dc0b7dfa61f14782805dd7da92395;p=rust-lightning diff --git a/c-bindings-gen/src/main.rs b/c-bindings-gen/src/main.rs index 07948ed4..a0acfc65 100644 --- a/c-bindings-gen/src/main.rs +++ b/c-bindings-gen/src/main.rs @@ -10,7 +10,7 @@ //! It also generates relevant memory-management functions and free-standing functions with //! parameters mapped. -use std::collections::{HashMap, HashSet}; +use std::collections::{HashMap, hash_map, HashSet}; use std::env; use std::fs::File; use std::io::{Read, Write}; @@ -536,7 +536,7 @@ fn writeln_opaque(w: &mut W, ident: &syn::Ident, struct_name: writeln!(w, "\t/// the Rust equivalent takes an Option, it may be set to null to indicate None.").unwrap(); writeln!(w, "\tpub inner: *mut native{},\n\tpub is_owned: bool,\n}}\n", ident).unwrap(); writeln!(w, "impl Drop for {} {{\n\tfn drop(&mut self) {{", struct_name).unwrap(); - writeln!(w, "\t\tif self.is_owned && !self.inner.is_null() {{").unwrap(); + writeln!(w, "\t\tif self.is_owned && !<*mut native{}>::is_null(self.inner) {{", ident).unwrap(); writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(self.inner) }};\n\t\t}}\n\t}}\n}}").unwrap(); writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", struct_name, struct_name).unwrap(); writeln!(w, "#[allow(unused)]").unwrap(); @@ -808,10 +808,10 @@ fn writeln_impl(w: &mut W, i: &syn::ItemImpl, types: &mut Typ } } ) ); - write!(w, "\t}}\n}}\nuse {}::{} as {}TraitImport;\n", types.orig_crate, full_trait_path, trait_obj.ident).unwrap(); + writeln!(w, "\t}}\n}}\n").unwrap(); macro_rules! impl_meth { - ($m: expr, $trait: expr, $indent: expr) => { + ($m: expr, $trait_path: expr, $trait: expr, $indent: expr) => { let trait_method = $trait.items.iter().filter_map(|item| { if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None } }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap(); @@ -835,10 +835,16 @@ fn writeln_impl(w: &mut W, i: &syn::ItemImpl, types: &mut Typ takes_self = true; } } + + let mut t_gen_args = String::new(); + for (idx, _) in $trait.generics.params.iter().enumerate() { + if idx != 0 { t_gen_args += ", " }; + t_gen_args += "_" + } if takes_self { - write!(w, "unsafe {{ &mut *(this_arg as *mut native{}) }}.{}(", ident, $m.sig.ident).unwrap(); + write!(w, ">::{}(unsafe {{ &mut *(this_arg as *mut native{}) }}, ", ident, types.orig_crate, $trait_path, t_gen_args, $m.sig.ident, ident).unwrap(); } else { - write!(w, "{}::{}::{}(", types.orig_crate, resolved_path, $m.sig.ident).unwrap(); + write!(w, ">::{}(", ident, types.orig_crate, $trait_path, t_gen_args, $m.sig.ident).unwrap(); } let mut real_type = "".to_string(); @@ -875,20 +881,19 @@ fn writeln_impl(w: &mut W, i: &syn::ItemImpl, types: &mut Typ for item in i.items.iter() { match item { syn::ImplItem::Method(m) => { - impl_meth!(m, trait_obj, ""); + impl_meth!(m, full_trait_path, trait_obj, ""); }, syn::ImplItem::Type(_) => {}, _ => unimplemented!(), } } walk_supertraits!(trait_obj, Some(&types), ( - (s, t) => { + (s, _) => { if let Some(supertrait_obj) = types.crate_types.traits.get(s).cloned() { - writeln!(w, "use {}::{} as native{}Trait;", types.orig_crate, s, t).unwrap(); for item in supertrait_obj.items.iter() { match item { syn::TraitItem::Method(m) => { - impl_meth!(m, supertrait_obj, "\t"); + impl_meth!(m, s, supertrait_obj, "\t"); }, _ => {}, } @@ -903,11 +908,12 @@ fn writeln_impl(w: &mut W, i: &syn::ItemImpl, types: &mut Typ write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap(); write!(w, "}}\n").unwrap(); } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "PartialEq"]) { - } else if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) && types.c_type_has_inner_from_path(&resolved_path) { + } else if (path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) || path_matches_nongeneric(&trait_path.1, &["Clone"])) && + types.c_type_has_inner_from_path(&resolved_path) { writeln!(w, "impl Clone for {} {{", ident).unwrap(); writeln!(w, "\tfn clone(&self) -> Self {{").unwrap(); writeln!(w, "\t\tSelf {{").unwrap(); - writeln!(w, "\t\t\tinner: if self.inner.is_null() {{ std::ptr::null_mut() }} else {{").unwrap(); + writeln!(w, "\t\t\tinner: if <*mut native{}>::is_null(self.inner) {{ std::ptr::null_mut() }} else {{", ident).unwrap(); writeln!(w, "\t\t\t\tBox::into_raw(Box::new(unsafe {{ &*self.inner }}.clone())) }},").unwrap(); writeln!(w, "\t\t\tis_owned: true,").unwrap(); writeln!(w, "\t\t}}\n\t}}\n}}").unwrap(); @@ -975,8 +981,62 @@ fn writeln_impl(w: &mut W, i: &syn::ItemImpl, types: &mut Typ } } } + } else if let Some(resolved_path) = types.maybe_resolve_ident(&ident) { + if let Some(aliases) = types.crate_types.reverse_alias_map.get(&resolved_path).cloned() { + 'alias_impls: for (alias, arguments) in aliases { + let alias_resolved = types.resolve_path(&alias, None); + for (idx, gen) in i.generics.params.iter().enumerate() { + match gen { + syn::GenericParam::Type(type_param) => { + 'bounds_check: for bound in type_param.bounds.iter() { + if let syn::TypeParamBound::Trait(trait_bound) = bound { + if let syn::PathArguments::AngleBracketed(ref t) = &arguments { + assert!(idx < t.args.len()); + if let syn::GenericArgument::Type(syn::Type::Path(p)) = &t.args[idx] { + let generic_arg = types.resolve_path(&p.path, None); + let generic_bound = types.resolve_path(&trait_bound.path, None); + if let Some(traits_impld) = types.crate_types.trait_impls.get(&generic_arg) { + for trait_impld in traits_impld { + if *trait_impld == generic_bound { continue 'bounds_check; } + } + eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound); + continue 'alias_impls; + } else { + eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound); + continue 'alias_impls; + } + } else { unimplemented!(); } + } else { unimplemented!(); } + } else { unimplemented!(); } + } + }, + syn::GenericParam::Lifetime(_) => {}, + syn::GenericParam::Const(_) => unimplemented!(), + } + } + let aliased_impl = syn::ItemImpl { + attrs: i.attrs.clone(), + brace_token: syn::token::Brace(Span::call_site()), + defaultness: None, + generics: syn::Generics { + lt_token: None, + params: syn::punctuated::Punctuated::new(), + gt_token: None, + where_clause: None, + }, + impl_token: syn::Token![impl](Span::call_site()), + items: i.items.clone(), + self_ty: Box::new(syn::Type::Path(syn::TypePath { qself: None, path: alias.clone() })), + trait_: i.trait_.clone(), + unsafety: None, + }; + writeln_impl(w, &aliased_impl, types); + } + } else { + eprintln!("Not implementing anything for {} due to it being marked not exported", ident); + } } else { - eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub or its marked not exported)", ident); + eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub)", ident); } } } @@ -1021,6 +1081,17 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type writeln!(w, ",").unwrap(); } write!(w, "\t}}").unwrap(); + } else if let syn::Fields::Unnamed(fields) = &var.fields { + needs_free = true; + write!(w, "(").unwrap(); + for (idx, field) in fields.unnamed.iter().enumerate() { + if export_status(&field.attrs) == ExportStatus::TestOnly { continue; } + types.write_c_type(w, &field.ty, None, false); + if idx != fields.unnamed.len() - 1 { + write!(w, ",").unwrap(); + } + } + write!(w, ")").unwrap(); } if var.discriminant.is_some() { unimplemented!(); } writeln!(w, ",").unwrap(); @@ -1039,28 +1110,35 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, field.ident.as_ref().unwrap()).unwrap(); } write!(w, "}} ").unwrap(); + } else if let syn::Fields::Unnamed(fields) = &var.fields { + write!(w, "(").unwrap(); + for (idx, field) in fields.unnamed.iter().enumerate() { + if export_status(&field.attrs) == ExportStatus::TestOnly { continue; } + write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, ('a' as u8 + idx as u8) as char).unwrap(); + } + write!(w, ") ").unwrap(); } write!(w, "=>").unwrap(); - if let syn::Fields::Named(fields) = &var.fields { - write!(w, " {{\n\t\t\t\t").unwrap(); - for field in fields.named.iter() { - if export_status(&field.attrs) == ExportStatus::TestOnly { continue; } + + macro_rules! handle_field_a { + ($field: expr, $field_ident: expr) => { { + if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; } let mut sink = ::std::io::sink(); let mut out: &mut dyn std::io::Write = if $ref { &mut sink } else { w }; let new_var = if $to_c { - types.write_to_c_conversion_new_var(&mut out, field.ident.as_ref().unwrap(), &field.ty, None, false) + types.write_to_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None, false) } else { - types.write_from_c_conversion_new_var(&mut out, field.ident.as_ref().unwrap(), &field.ty, None) + types.write_from_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None) }; if $ref || new_var { if $ref { - write!(w, "let mut {}_nonref = (*{}).clone();\n\t\t\t\t", field.ident.as_ref().unwrap(), field.ident.as_ref().unwrap()).unwrap(); + write!(w, "let mut {}_nonref = (*{}).clone();\n\t\t\t\t", $field_ident, $field_ident).unwrap(); if new_var { - let nonref_ident = syn::Ident::new(&format!("{}_nonref", field.ident.as_ref().unwrap()), Span::call_site()); + let nonref_ident = syn::Ident::new(&format!("{}_nonref", $field_ident), Span::call_site()); if $to_c { - types.write_to_c_conversion_new_var(w, &nonref_ident, &field.ty, None, false); + types.write_to_c_conversion_new_var(w, &nonref_ident, &$field.ty, None, false); } else { - types.write_from_c_conversion_new_var(w, &nonref_ident, &field.ty, None); + types.write_from_c_conversion_new_var(w, &nonref_ident, &$field.ty, None); } write!(w, "\n\t\t\t\t").unwrap(); } @@ -1068,31 +1146,58 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type write!(w, "\n\t\t\t\t").unwrap(); } } + } } + } + if let syn::Fields::Named(fields) = &var.fields { + write!(w, " {{\n\t\t\t\t").unwrap(); + for field in fields.named.iter() { + handle_field_a!(field, field.ident.as_ref().unwrap()); + } + } else if let syn::Fields::Unnamed(fields) = &var.fields { + write!(w, " {{\n\t\t\t\t").unwrap(); + for (idx, field) in fields.unnamed.iter().enumerate() { + handle_field_a!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site())); } } else { write!(w, " ").unwrap(); } + write!(w, "{}{}::{}", if $to_c { "" } else { "native" }, e.ident, var.ident).unwrap(); - if let syn::Fields::Named(fields) = &var.fields { - write!(w, " {{").unwrap(); - for field in fields.named.iter() { - if export_status(&field.attrs) == ExportStatus::TestOnly { continue; } - write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap(); + + macro_rules! handle_field_b { + ($field: expr, $field_ident: expr) => { { + if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; } if $to_c { - types.write_to_c_conversion_inline_prefix(w, &field.ty, None, false); + types.write_to_c_conversion_inline_prefix(w, &$field.ty, None, false); } else { - types.write_from_c_conversion_prefix(w, &field.ty, None); + types.write_from_c_conversion_prefix(w, &$field.ty, None); } - write!(w, "{}{}", - field.ident.as_ref().unwrap(), + write!(w, "{}{}", $field_ident, if $ref { "_nonref" } else { "" }).unwrap(); if $to_c { - types.write_to_c_conversion_inline_suffix(w, &field.ty, None, false); + types.write_to_c_conversion_inline_suffix(w, &$field.ty, None, false); } else { - types.write_from_c_conversion_suffix(w, &field.ty, None); + types.write_from_c_conversion_suffix(w, &$field.ty, None); } write!(w, ",").unwrap(); + } } + } + + if let syn::Fields::Named(fields) = &var.fields { + write!(w, " {{").unwrap(); + for field in fields.named.iter() { + if export_status(&field.attrs) == ExportStatus::TestOnly { continue; } + write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap(); + handle_field_b!(field, field.ident.as_ref().unwrap()); } writeln!(w, "\n\t\t\t\t}}").unwrap(); write!(w, "\t\t\t}}").unwrap(); + } else if let syn::Fields::Unnamed(fields) = &var.fields { + write!(w, " (").unwrap(); + for (idx, field) in fields.unnamed.iter().enumerate() { + write!(w, "\n\t\t\t\t\t").unwrap(); + handle_field_b!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site())); + } + writeln!(w, "\n\t\t\t\t)").unwrap(); + write!(w, "\t\t\t}}").unwrap(); } writeln!(w, ",").unwrap(); } @@ -1165,9 +1270,12 @@ impl FullLibraryAST { }; self.load_module(modname, m.attrs, m.content.unwrap().1); submods.push(modident); + } else { + non_mod_items.push(syn::Item::Mod(m)); } } }, + syn::Item::Mod(_) => panic!("--pretty=expanded output should never have non-body modules"), _ => { non_mod_items.push(item); } } } @@ -1306,50 +1414,28 @@ fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &mut CrateTypes } } -/// Insert ident -> absolute Path resolutions into imports from the given UseTree and path-prefix. -fn process_use_intern<'a>(u: &'a syn::UseTree, mut path: syn::punctuated::Punctuated, imports: &mut HashMap<&'a syn::Ident, syn::Path>) { - match u { - syn::UseTree::Path(p) => { - path.push(syn::PathSegment { ident: p.ident.clone(), arguments: syn::PathArguments::None }); - process_use_intern(&p.tree, path, imports); - }, - syn::UseTree::Name(n) => { - path.push(syn::PathSegment { ident: n.ident.clone(), arguments: syn::PathArguments::None }); - imports.insert(&n.ident, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }); - }, - syn::UseTree::Group(g) => { - for i in g.items.iter() { - process_use_intern(i, path.clone(), imports); - } - }, - _ => {} - } -} - -/// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern) -fn resolve_imported_refs(imports: &HashMap<&syn::Ident, syn::Path>, mut ty: syn::Type) -> syn::Type { - match &mut ty { - syn::Type::Path(p) => { - if let Some(ident) = p.path.get_ident() { - if let Some(newpath) = imports.get(ident) { - p.path = newpath.clone(); +fn walk_private_mod<'a>(module: String, items: &'a syn::ItemMod, crate_types: &mut CrateTypes<'a>) { + let import_resolver = ImportResolver::new(&module, &items.content.as_ref().unwrap().1); + for item in items.content.as_ref().unwrap().1.iter() { + match item { + syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types), + syn::Item::Impl(i) => { + if let &syn::Type::Path(ref p) = &*i.self_ty { + if let Some(trait_path) = i.trait_.as_ref() { + if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) { + if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) { + match crate_types.trait_impls.entry(sp) { + hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); }, + hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); }, + } + } + } + } } - } else { unimplemented!(); } - }, - syn::Type::Reference(r) => { - r.elem = Box::new(resolve_imported_refs(imports, (*r.elem).clone())); - }, - syn::Type::Slice(s) => { - s.elem = Box::new(resolve_imported_refs(imports, (*s.elem).clone())); - }, - syn::Type::Tuple(t) => { - for e in t.elems.iter_mut() { - *e = resolve_imported_refs(imports, e.clone()); - } - }, - _ => unimplemented!(), + }, + _ => {}, + } } - ty } /// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes. @@ -1357,13 +1443,10 @@ fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a for (module, astmod) in ast_storage.modules.iter() { let ASTModule { ref attrs, ref items, submods: _ } = astmod; assert_eq!(export_status(&attrs), ExportStatus::Export); - let mut import_maps = HashMap::new(); + let import_resolver = ImportResolver::new(module, items); for item in items.iter() { match item { - syn::Item::Use(u) => { - process_use_intern(&u.tree, syn::punctuated::Punctuated::new(), &mut import_maps); - }, syn::Item::Struct(s) => { if let syn::Visibility::Public(_) = s.vis { match export_status(&s.attrs) { @@ -1404,12 +1487,24 @@ fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a } if process_alias { match &*t.ty { - syn::Type::Path(_) => { + syn::Type::Path(p) => { // If its a path with no generics, assume we don't map the aliased type and map it opaque - crate_types.opaques.insert(type_path, &t.ident); + let mut segments = syn::punctuated::Punctuated::new(); + segments.push(syn::PathSegment { + ident: t.ident.clone(), + arguments: syn::PathArguments::None, + }); + let path_obj = syn::Path { leading_colon: None, segments }; + let args_obj = p.path.segments.last().unwrap().arguments.clone(); + match crate_types.reverse_alias_map.entry(import_resolver.maybe_resolve_path(&p.path, None).unwrap()) { + hash_map::Entry::Occupied(mut e) => { e.get_mut().push((path_obj, args_obj)); }, + hash_map::Entry::Vacant(e) => { e.insert(vec![(path_obj, args_obj)]); }, + } + + crate_types.opaques.insert(type_path.clone(), &t.ident); }, _ => { - crate_types.type_aliases.insert(type_path, resolve_imported_refs(&import_maps, (*t.ty).clone())); + crate_types.type_aliases.insert(type_path, import_resolver.resolve_imported_refs((*t.ty).clone())); } } } @@ -1439,15 +1534,22 @@ fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a if let &syn::Type::Path(ref p) = &*i.self_ty { if let Some(trait_path) = i.trait_.as_ref() { if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) { - // Note, we should probably have more full-featured type resolution here, - // but for now we don't have any cases where we impl X for A::B. - let ident = single_ident_generic_path_to_ident(&p.path).expect("impl X for A::B currently unsupported"); - assert!(import_maps.get(&ident).is_none()); - crate_types.clonable_types.insert(format!("crate::{}::{}", module, ident)); + if let Some(full_path) = import_resolver.maybe_resolve_path(&p.path, None) { + crate_types.clonable_types.insert("crate::".to_owned() + &full_path); + } + } + if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) { + if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) { + match crate_types.trait_impls.entry(sp) { + hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); }, + hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); }, + } + } } } } }, + syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types), _ => {}, } } @@ -1492,8 +1594,9 @@ fn main() { // ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them // when parsing other file ASTs... let mut libtypes = CrateTypes { traits: HashMap::new(), opaques: HashMap::new(), mirrored_enums: HashMap::new(), - type_aliases: HashMap::new(), templates_defined: HashMap::default(), template_file: &mut derived_templates, - clonable_types: HashSet::new() }; + type_aliases: HashMap::new(), reverse_alias_map: HashMap::new(), templates_defined: HashMap::default(), + template_file: &mut derived_templates, + clonable_types: HashSet::new(), trait_impls: HashMap::new() }; walk_ast(&libast, &mut libtypes); // ... finally, do the actual file conversion/mapping, writing out types as we go.