[bindings] Handle type X = Y aliasing in type resolution
[rust-lightning] / c-bindings-gen / src / types.rs
index 1fe427d54f51c1bfe11ac729bd32ffd0a90e327d..c7a13fe0d540bd5e76706075715544f49f70c368 100644 (file)
@@ -234,6 +234,8 @@ pub struct CrateTypes<'a> {
        pub mirrored_enums: HashMap<String, &'a syn::ItemEnum>,
        /// Traits which are mapped as a pointer + jump table
        pub traits: HashMap<String, &'a syn::ItemTrait>,
+       /// Aliases from paths to some other Type
+       pub type_aliases: HashMap<String, syn::Type>,
        /// Template continer types defined, map from mangled type name -> whether a destructor fn
        /// exists.
        ///
@@ -340,8 +342,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice"),
                        "bitcoin::blockdata::script::Script" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
                        "bitcoin::blockdata::transaction::OutPoint" if is_ref => Some("crate::chain::transaction::OutPoint"),
-                       "bitcoin::blockdata::transaction::Transaction" if is_ref && !ptr_for_ref => Some("crate::c_types::Transaction"),
-                       "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::derived::CVec_u8Z"),
+                       "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction"),
                        "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut"),
                        "bitcoin::OutPoint" => Some("crate::chain::transaction::OutPoint"),
                        "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network"),
@@ -413,7 +414,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        "bitcoin::blockdata::script::Script" if is_ref => Some("&::bitcoin::blockdata::script::Script::from(Vec::from("),
                        "bitcoin::blockdata::script::Script" if !is_ref => Some("::bitcoin::blockdata::script::Script::from("),
                        "bitcoin::blockdata::transaction::Transaction" if is_ref => Some("&"),
-                       "bitcoin::blockdata::transaction::Transaction" => Some("::bitcoin::consensus::encode::deserialize(&"),
+                       "bitcoin::blockdata::transaction::Transaction" => Some(""),
                        "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(""),
                        "bitcoin::network::constants::Network" => Some(""),
                        "bitcoin::blockdata::block::BlockHeader" => Some("&::bitcoin::consensus::encode::deserialize(unsafe { &*"),
@@ -471,8 +472,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        "bitcoin::secp256k1::key::SecretKey" if is_ref => Some("}[..]).unwrap()"),
                        "bitcoin::blockdata::script::Script" if is_ref => Some(".to_slice()))"),
                        "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_rust())"),
-                       "bitcoin::blockdata::transaction::Transaction" if is_ref => Some(".into_bitcoin()"),
-                       "bitcoin::blockdata::transaction::Transaction" => Some(".into_rust()[..]).unwrap()"),
+                       "bitcoin::blockdata::transaction::Transaction" => Some(".into_bitcoin()"),
                        "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(".into_rust()"),
                        "bitcoin::network::constants::Network" => Some(".into_bitcoin()"),
                        "bitcoin::blockdata::block::BlockHeader" => Some(" }).unwrap()"),
@@ -553,8 +553,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        "bitcoin::secp256k1::Error" if !is_ref => Some("crate::c_types::Secp256k1Error::from_rust("),
                        "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice::from_slice(&"),
                        "bitcoin::blockdata::script::Script" if !is_ref => Some(""),
-                       "bitcoin::blockdata::transaction::Transaction" if is_ref && !ptr_for_ref => Some("crate::c_types::Transaction::from_slice(&local_"),
-                       "bitcoin::blockdata::transaction::Transaction" => Some("local_"),
+                       "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction::from_vec(local_"),
                        "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut::from_rust("),
                        "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("&local_"),
                        "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice::from_slice(&local_"),
@@ -617,8 +616,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        "bitcoin::secp256k1::Error" if !is_ref => Some(")"),
                        "bitcoin::blockdata::script::Script" if is_ref => Some("[..])"),
                        "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_bytes().into()"),
-                       "bitcoin::blockdata::transaction::Transaction" if is_ref && !ptr_for_ref => Some(")"),
-                       "bitcoin::blockdata::transaction::Transaction" => Some(".into()"),
+                       "bitcoin::blockdata::transaction::Transaction" => Some(")"),
                        "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(")"),
                        "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(""),
                        "bitcoin::blockdata::block::Block" if is_ref => Some(")"),
@@ -759,12 +757,16 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
 
                                if let Some(t) = single_contained {
                                        let mut v = Vec::new();
-                                       let needs_deref = self.write_empty_rust_val_check_suffix(generics, &mut v, t);
+                                       let (needs_deref, ret_ref) = self.write_empty_rust_val_check_suffix(generics, &mut v, t);
                                        let s = String::from_utf8(v).unwrap();
-                                       if needs_deref {
+                                       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))
@@ -878,8 +880,9 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                } else { p_arg };
 
                if p.leading_colon.is_some() {
-                       // At some point we may need this, but for now, its unused, so just fail.
-                       return None;
+                       Some(p.segments.iter().enumerate().map(|(idx, seg)| {
+                               format!("{}{}", if idx == 0 { "" } else { "::" }, seg.ident)
+                       }).collect())
                } else if let Some(id) = p.get_ident() {
                        self.maybe_resolve_ident(id)
                } else {
@@ -890,15 +893,11 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        let mut seg_iter = p.segments.iter();
                        let first_seg = seg_iter.next().unwrap();
                        let remaining: String = seg_iter.map(|seg| {
-                               if let syn::PathArguments::None = seg.arguments {
-                                       format!("{}", seg.ident)
-                               } else {
-                                       format!("{}", seg.ident)
-                               }
+                               format!("::{}", seg.ident)
                        }).collect();
                        if let Some(imp) = self.imports.get(&first_seg.ident) {
                                if remaining != "" {
-                                       Some(imp.clone() + "::" + &remaining)
+                                       Some(imp.clone() + &remaining)
                                } else {
                                        Some(imp.clone())
                                }
@@ -1058,20 +1057,20 @@ 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<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) -> bool {
+       pub fn write_empty_rust_val_check_suffix<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) -> (bool, bool) {
                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, false)
                                } else {
                                        if let Some(suffix) = self.empty_val_check_suffix_from_path(&resolved) {
                                                write!(w, "{}", suffix).unwrap();
-                                               false // We may eventually need to allow empty_val_check_suffix_from_path to specify if we need a deref or not
+                                               (false, false) // We may eventually need to allow empty_val_check_suffix_from_path to specify if we need a deref or not
                                        } else {
                                                write!(w, " == std::ptr::null_mut()").unwrap();
-                                               false
+                                               (true, false)
                                        }
                                }
                        },
@@ -1079,7 +1078,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, false)
                                        } else { unimplemented!(); }
                                } else { unimplemented!(); }
                        },
@@ -1087,7 +1086,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, true)
                        },
                        _ => unimplemented!(),
                }
@@ -1162,12 +1161,14 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                        ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
                        },
                        syn::Type::Path(p) => {
-                               if p.qself.is_some() || p.path.leading_colon.is_some() {
+                               if p.qself.is_some() {
                                        unimplemented!();
                                }
 
                                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);
@@ -1205,6 +1206,33 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                        if let syn::Type::Path(p) = &*r.elem {
                                                write!(w, "{}", sliceconv(self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)))).unwrap();
                                        } else { unimplemented!(); }
+                               } else if let syn::Type::Tuple(t) = &*s.elem {
+                                       assert!(!t.elems.is_empty());
+                                       if prefix {
+                                               write!(w, "&local_").unwrap();
+                                       } else {
+                                               let mut needs_map = false;
+                                               for e in t.elems.iter() {
+                                                       if let syn::Type::Reference(_) = e {
+                                                               needs_map = true;
+                                                       }
+                                               }
+                                               if needs_map {
+                                                       write!(w, ".iter().map(|(").unwrap();
+                                                       for i in 0..t.elems.len() {
+                                                               write!(w, "{}{}", if i != 0 { ", " } else { "" }, ('a' as u8 + i as u8) as char).unwrap();
+                                                       }
+                                                       write!(w, ")| (").unwrap();
+                                                       for (idx, e) in t.elems.iter().enumerate() {
+                                                               if let syn::Type::Reference(_) = e {
+                                                                       write!(w, "{}{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
+                                                               } else if let syn::Type::Path(_) = e {
+                                                                       write!(w, "{}*{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
+                                                               } else { unimplemented!(); }
+                                                       }
+                                                       write!(w, ")).collect::<Vec<_>>()[..]").unwrap();
+                                               }
+                                       }
                                } else { unimplemented!(); }
                        },
                        syn::Type::Tuple(t) => {
@@ -1448,10 +1476,13 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                }
                        },
                        syn::Type::Path(p) => {
-                               if p.qself.is_some() || p.path.leading_colon.is_some() {
+                               if p.qself.is_some() {
                                        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| {
@@ -1491,6 +1522,24 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                        is_ref = true;
                                        convert_container!("Slice", 1, || tyref.iter());
                                        unimplemented!("convert_container should return true as container_lookup should succeed for slices");
+                               } else if let syn::Type::Tuple(t) = &*s.elem {
+                                       // When mapping into a temporary new var, we need to own all the underlying objects.
+                                       // Thus, we drop any references inside the tuple and convert with non-reference types.
+                                       let mut elems = syn::punctuated::Punctuated::new();
+                                       for elem in t.elems.iter() {
+                                               if let syn::Type::Reference(r) = elem {
+                                                       elems.push((*r.elem).clone());
+                                               } else {
+                                                       elems.push(elem.clone());
+                                               }
+                                       }
+                                       let ty = [syn::Type::Tuple(syn::TypeTuple {
+                                               paren_token: t.paren_token, elems
+                                       })];
+                                       is_ref = false;
+                                       ptr_for_ref = true;
+                                       convert_container!("Slice", 1, || ty.iter());
+                                       unimplemented!("convert_container should return true as container_lookup should succeed for slices");
                                } else { unimplemented!() }
                        },
                        syn::Type::Tuple(t) => {
@@ -1695,11 +1744,12 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        } else if let syn::Type::Reference(r_arg) = t {
                                if let syn::Type::Path(p_arg) = &*r_arg.elem {
                                        let resolved = self.resolve_path(&p_arg.path, None);
-                                       if single_ident_generic_path_to_ident(&p_arg.path).is_some() {
-                                               if self.crate_types.opaques.get(&resolved).is_some() {
-                                                       write!(w, "crate::{}", resolved).unwrap();
-                                               } else { unimplemented!(); }
-                                       } else { unimplemented!(); }
+                                       if self.crate_types.opaques.get(&resolved).is_some() {
+                                               write!(w, "crate::{}", resolved).unwrap();
+                                       } else {
+                                               let cty = self.c_type_from_path(&resolved, true, true).expect("Template generics should be opaque or have a predefined mapping");
+                                               w.write(cty.as_bytes()).unwrap();
+                                       }
                                } else { unimplemented!(); }
                        } else if let syn::Type::Array(a_arg) = t {
                                if let syn::Type::Path(p_arg) = &*a_arg.elem {
@@ -1758,7 +1808,8 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                                        if self.c_type_has_inner_from_path(&subtype) {
                                                                if !self.write_c_path_intern(w, &$p_arg.path, generics, is_ref, is_mut, ptr_for_ref) { return false; }
                                                        } else {
-                                                               if !self.write_c_path_intern(w, &$p_arg.path, generics, true, is_mut, true) { return false; }
+                                                               // Option<T> needs to be converted to a *mut T, ie mut ptr-for-ref
+                                                               if !self.write_c_path_intern(w, &$p_arg.path, generics, true, true, true) { return false; }
                                                        }
                                                } else {
                                                        if $p_arg.path.segments.len() == 1 {
@@ -1778,13 +1829,14 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                                        self.write_c_mangled_container_path_intern(w2, Self::path_to_generic_args(&$p_arg.path),
                                                                generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
                                                }
-                                       } else if let Some(id) = single_ident_generic_path_to_ident(&$p_arg.path) {
+                                       } else {
+                                               let id = &&$p_arg.path.segments.iter().rev().next().unwrap().ident;
                                                write!(w, "{}", id).unwrap();
                                                write!(mangled_type, "{}", id).unwrap();
                                                if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
                                                        write!(w2, "{}", id).unwrap();
                                                }
-                                       } else { return false; }
+                                       }
                                }
                        }
                        if let syn::Type::Tuple(tuple) = arg {
@@ -1804,6 +1856,10 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                        for elem in tuple.elems.iter() {
                                                if let syn::Type::Path(p) = elem {
                                                        write_path!(p, Some(&mut mangled_tuple_type));
+                                               } else if let syn::Type::Reference(refelem) = elem {
+                                                       if let syn::Type::Path(p) = &*refelem.elem {
+                                                               write_path!(p, Some(&mut mangled_tuple_type));
+                                                       } else { return false; }
                                                } else { return false; }
                                        }
                                        write!(w, "Z").unwrap();
@@ -1893,15 +1949,17 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
        fn write_c_type_intern<W: std::io::Write>(&mut self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool) -> bool {
                match t {
                        syn::Type::Path(p) => {
-                               if p.qself.is_some() || p.path.leading_colon.is_some() {
+                               if p.qself.is_some() {
                                        return false;
                                }
                                if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
                                        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);
+                                       }
                                }
-                               if p.path.leading_colon.is_some() { return false; }
                                self.write_c_path_intern(w, &p.path, generics, is_ref, is_mut, ptr_for_ref)
                        },
                        syn::Type::Reference(r) => {
@@ -1959,6 +2017,17 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                                self.check_create_container(mangled_container, "Vec", vec![&*r.elem], generics, false);
                                                true
                                        } else { false }
+                               } else if let syn::Type::Tuple(_) = &*s.elem {
+                                       let mut args = syn::punctuated::Punctuated::new();
+                                       args.push(syn::GenericArgument::Type((*s.elem).clone()));
+                                       let mut segments = syn::punctuated::Punctuated::new();
+                                       segments.push(syn::PathSegment {
+                                               ident: syn::Ident::new("Vec", Span::call_site()),
+                                               arguments: syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
+                                                       colon2_token: None, lt_token: syn::Token![<](Span::call_site()), args, gt_token: syn::Token![>](Span::call_site()),
+                                               })
+                                       });
+                                       self.write_c_type_intern(w, &syn::Type::Path(syn::TypePath { qself: None, path: syn::Path { leading_colon: None, segments } }), generics, false, is_mut, ptr_for_ref)
                                } else { false }
                        },
                        syn::Type::Tuple(t) => {