[bindings] Support mapping slices which contain tuples (with refs)
[rust-lightning] / c-bindings-gen / src / types.rs
index 5dab31622d2f8660b8b521e01868a2bceecb39cf..46f6f984fef99787df3418732240d9ccab7b11d9 100644 (file)
@@ -340,8 +340,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 +412,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 +470,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 +551,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 +614,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(")"),
@@ -653,6 +649,8 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
        fn empty_val_check_suffix_from_path(&self, full_path: &str) -> Option<&str> {
                match full_path {
                        "ln::channelmanager::PaymentSecret" => Some(".data == [0; 32]"),
+                       "bitcoin::secp256k1::key::PublicKey" => Some(".is_null()"),
+                       "bitcoin::secp256k1::Signature" => Some(".is_null()"),
                        _ => None
                }
        }
@@ -757,12 +755,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))
@@ -1056,20 +1058,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, ".is_null()").unwrap();
-                                               false
+                                               write!(w, " == std::ptr::null_mut()").unwrap();
+                                               (true, false)
                                        }
                                }
                        },
@@ -1077,15 +1079,15 @@ 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!(); }
                        },
                        syn::Type::Slice(_) => {
                                // Option<[]> always implies that we want to treat len() == 0 differently from
                                // None, so we always map an Option<[]> into a pointer.
-                               write!(w, ".is_null()").unwrap();
-                               true
+                               write!(w, " == std::ptr::null_mut()").unwrap();
+                               (true, true)
                        },
                        _ => unimplemented!(),
                }
@@ -1203,6 +1205,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) => {
@@ -1489,6 +1518,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) => {
@@ -1696,7 +1743,10 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                        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 {
+                                                       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 { unimplemented!(); }
                        } else if let syn::Type::Array(a_arg) = t {
@@ -1756,7 +1806,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 {
@@ -1802,6 +1853,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();
@@ -1957,6 +2012,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) => {