[bindings] Avoid double-use'ing traits by writing out the path
[rust-lightning] / c-bindings-gen / src / main.rs
index f8e5b48492fd3944ca4775b7d593025f8ee79f0c..f2f684fd64e985179af6ec5839374caa6f2da142 100644 (file)
@@ -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};
@@ -808,10 +808,10 @@ fn writeln_impl<W: std::io::Write>(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: std::io::Write>(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, "<native{} as {}::{}<{}>>::{}(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, "<native{} as {}::{}<{}>>::{}(", 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: std::io::Write>(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,7 +908,8 @@ fn writeln_impl<W: std::io::Write>(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();
@@ -975,8 +981,62 @@ fn writeln_impl<W: std::io::Write>(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();
                        }
@@ -1309,6 +1414,30 @@ fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &mut CrateTypes
        }
 }
 
+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]); },
+                                                               }
+                                                       }
+                                               }
+                                       }
+                               }
+                       },
+                       _ => {},
+               }
+       }
+}
+
 /// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
 fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
        for (module, astmod) in ast_storage.modules.iter() {
@@ -1358,9 +1487,21 @@ 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, import_resolver.resolve_imported_refs((*t.ty).clone()));
@@ -1397,9 +1538,18 @@ fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a
                                                                        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),
                                _ => {},
                        }
                }
@@ -1444,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.