[bindings] Give Transaction objects a buffer-is-owned flag.
[rust-lightning] / c-bindings-gen / src / types.rs
index e24add068da4a22e7bee92b486990834ce9bda9f..1ddbe3cb98975c20ff8b95f59aa910617d82bc9f 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
                }
        }
@@ -681,7 +679,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
        fn is_known_container(&self, full_path: &str, is_ref: bool) -> bool {
                (full_path == "Result" && !is_ref) || (full_path == "Vec" && !is_ref) || full_path.ends_with("Tuple")
        }
-       fn to_c_conversion_container_new_var<'b>(&self, full_path: &str, is_ref: bool, single_contained: Option<&syn::Type>, var_name: &syn::Ident, var_access: &str)
+       fn to_c_conversion_container_new_var<'b>(&self, generics: Option<&GenericTypes>, full_path: &str, is_ref: bool, single_contained: Option<&syn::Type>, var_name: &syn::Ident, var_access: &str)
                        // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
                        // expecting one element in the vec per generic type, each of which is inline-converted
                        -> Option<(&'b str, Vec<(String, String)>, &'b str)> {
@@ -700,7 +698,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        },
                        "Option" => {
                                if let Some(syn::Type::Path(p)) = single_contained {
-                                       if self.c_type_has_inner_from_path(&self.resolve_path(&p.path, None)) {
+                                       if self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)) {
                                                if is_ref {
                                                        return Some(("if ", vec![
                                                                (".is_none() { std::ptr::null() } else { ".to_owned(), format!("({}.as_ref().unwrap())", var_access))
@@ -714,7 +712,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                }
                                if let Some(t) = single_contained {
                                        let mut v = Vec::new();
-                                       self.write_empty_rust_val(&mut v, t);
+                                       self.write_empty_rust_val(generics, &mut v, t);
                                        let s = String::from_utf8(v).unwrap();
                                        return Some(("if ", vec![
                                                (format!(".is_none() {{ {} }} else {{ ", s), format!("({}.unwrap())", var_access))
@@ -727,7 +725,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
 
        /// only_contained_has_inner implies that there is only one contained element in the container
        /// and it has an inner field (ie is an "opaque" type we've defined).
-       fn from_c_conversion_container_new_var<'b>(&self, full_path: &str, is_ref: bool, single_contained: Option<&syn::Type>, var_name: &syn::Ident, var_access: &str)
+       fn from_c_conversion_container_new_var<'b>(&self, generics: Option<&GenericTypes>, full_path: &str, is_ref: bool, single_contained: Option<&syn::Type>, var_name: &syn::Ident, var_access: &str)
                        // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
                        // expecting one element in the vec per generic type, each of which is inline-converted
                        -> Option<(&'b str, Vec<(String, String)>, &'b str)> {
@@ -746,7 +744,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        },
                        "Option" => {
                                if let Some(syn::Type::Path(p)) = single_contained {
-                                       if self.c_type_has_inner_from_path(&self.resolve_path(&p.path, None)) {
+                                       if self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)) {
                                                if is_ref {
                                                        return Some(("if ", vec![(".inner.is_null() { None } else { Some((*".to_string(), format!("{}", var_name))], ").clone()) }"))
                                                } else {
@@ -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(&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))
@@ -1023,10 +1025,10 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
 
        /// Prints a constructor for something which is "uninitialized" (but obviously not actually
        /// unint'd memory).
-       pub fn write_empty_rust_val<W: std::io::Write>(&self, w: &mut W, t: &syn::Type) {
+       pub fn write_empty_rust_val<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) {
                match t {
                        syn::Type::Path(p) => {
-                               let resolved = self.resolve_path(&p.path, None);
+                               let resolved = self.resolve_path(&p.path, generics);
                                if self.crate_types.opaques.get(&resolved).is_some() {
                                        write!(w, "crate::{} {{ inner: std::ptr::null_mut(), is_owned: true }}", resolved).unwrap();
                                } else {
@@ -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, 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, None);
+                               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,26 +1079,26 @@ 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!(),
                }
        }
 
        /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
-       pub fn write_empty_rust_val_check<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, var_access: &str) {
+       pub fn write_empty_rust_val_check<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type, var_access: &str) {
                match t {
                        syn::Type::Path(_) => {
                                write!(w, "{}", var_access).unwrap();
-                               self.write_empty_rust_val_check_suffix(w, t);
+                               self.write_empty_rust_val_check_suffix(generics, w, t);
                        },
                        syn::Type::Array(a) => {
                                if let syn::Expr::Lit(l) = &a.len {
@@ -1108,7 +1110,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                                        self.from_c_conversion_prefix_from_path(&arrty, false).unwrap(),
                                                        var_access,
                                                        self.from_c_conversion_suffix_from_path(&arrty, false).unwrap()).unwrap();
-                                               self.write_empty_rust_val_check_suffix(w, t);
+                                               self.write_empty_rust_val_check_suffix(generics, w, t);
                                        } else { unimplemented!(); }
                                } else { unimplemented!(); }
                        }
@@ -1561,7 +1563,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
        pub fn write_to_c_conversion_new_var_inner<W: std::io::Write>(&self, w: &mut W, ident: &syn::Ident, var_access: &str, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) -> bool {
                self.write_conversion_new_var_intern(w, ident, var_access, t, generics, false, ptr_for_ref, true,
                        &|a, b| self.to_c_conversion_new_var_from_path(a, b),
-                       &|a, b, c, d, e| self.to_c_conversion_container_new_var(a, b, c, d, e),
+                       &|a, b, c, d, e| self.to_c_conversion_container_new_var(generics, a, b, c, d, e),
                        // We force ptr_for_ref here since we can't generate a ref on one line and use it later
                        &|a, b, c, d, e, f| self.write_to_c_conversion_inline_prefix_inner(a, b, c, d, e, f),
                        &|a, b, c, d, e, f| self.write_to_c_conversion_inline_suffix_inner(a, b, c, d, e, f))
@@ -1572,7 +1574,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
        pub fn write_from_c_conversion_new_var<W: std::io::Write>(&self, w: &mut W, ident: &syn::Ident, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
                self.write_conversion_new_var_intern(w, ident, &format!("{}", ident), t, generics, false, false, false,
                        &|a, b| self.from_c_conversion_new_var_from_path(a, b),
-                       &|a, b, c, d, e| self.from_c_conversion_container_new_var(a, b, c, d, e),
+                       &|a, b, c, d, e| self.from_c_conversion_container_new_var(generics, a, b, c, d, e),
                        // We force ptr_for_ref here since we can't generate a ref on one line and use it later
                        &|a, b, c, d, e, _f| self.write_from_c_conversion_prefix_inner(a, b, c, d, e),
                        &|a, b, c, d, e, _f| self.write_from_c_conversion_suffix_inner(a, b, c, d, e))
@@ -1696,7 +1698,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 +1761,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 {