Handle traits which require Clone when their supertraits do not
[ldk-c-bindings] / c-bindings-gen / src / main.rs
index a0acfc65dd6a27cc9e30a0f0167210526ca434bd..06050c5c8e8b84d31c89460c81e5a3f5d2bc19de 100644 (file)
@@ -1,3 +1,11 @@
+// This file is Copyright its original authors, visible in version control
+// history.
+//
+// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE>
+// or the MIT license <LICENSE-MIT>, at your option.
+// You may not use this file except in accordance with one or both of these
+// licenses.
+
 //! Converts a rust crate into a rust crate containing a number of C-exported wrapper functions and
 //! classes (which is exportable using cbindgen).
 //! In general, supports convering:
@@ -37,6 +45,7 @@ fn convert_macro<W: std::io::Write>(w: &mut W, macro_path: &syn::Path, stream: &
                        if let Some(s) = types.maybe_resolve_ident(&struct_for) {
                                if !types.crate_types.opaques.get(&s).is_some() { return; }
                                writeln!(w, "#[no_mangle]").unwrap();
+                               writeln!(w, "/// Serialize the {} into a byte array which can be read by {}_read", struct_for, struct_for).unwrap();
                                writeln!(w, "pub extern \"C\" fn {}_write(obj: &{}) -> crate::c_types::derived::CVec_u8Z {{", struct_for, struct_for).unwrap();
                                writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &(*(*obj).inner) }})").unwrap();
                                writeln!(w, "}}").unwrap();
@@ -45,6 +54,7 @@ fn convert_macro<W: std::io::Write>(w: &mut W, macro_path: &syn::Path, stream: &
                                writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &*(obj as *const native{}) }})", struct_for).unwrap();
                                writeln!(w, "}}").unwrap();
                                writeln!(w, "#[no_mangle]").unwrap();
+                               writeln!(w, "/// Read a {} from a byte array, created by {}_write", struct_for, struct_for).unwrap();
                                writeln!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice) -> {} {{", struct_for, struct_for).unwrap();
                                writeln!(w, "\tif let Ok(res) = crate::c_types::deserialize_obj(ser) {{").unwrap();
                                writeln!(w, "\t\t{} {{ inner: Box::into_raw(Box::new(res)), is_owned: true }}", struct_for).unwrap();
@@ -82,6 +92,7 @@ fn maybe_convert_trait_impl<W: std::io::Write>(w: &mut W, trait_path: &syn::Path
                match &t as &str {
                        "util::ser::Writeable" => {
                                writeln!(w, "#[no_mangle]").unwrap();
+                               writeln!(w, "/// Serialize the {} object into a byte array which can be read by {}_read", for_obj, for_obj).unwrap();
                                writeln!(w, "pub extern \"C\" fn {}_write(obj: &{}) -> crate::c_types::derived::CVec_u8Z {{", for_obj, full_obj_path).unwrap();
 
                                let ref_type = syn::Type::Reference(syn::TypeReference {
@@ -127,6 +138,7 @@ fn maybe_convert_trait_impl<W: std::io::Write>(w: &mut W, trait_path: &syn::Path
                                        leading_colon: None, segments: res_segs } });
 
                                writeln!(w, "#[no_mangle]").unwrap();
+                               writeln!(w, "/// Read a {} from a byte array, created by {}_write", for_obj, for_obj).unwrap();
                                write!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice", for_obj).unwrap();
 
                                let mut arg_conv = Vec::new();
@@ -180,9 +192,9 @@ fn maybe_convert_trait_impl<W: std::io::Write>(w: &mut W, trait_path: &syn::Path
 ///
 /// This is (obviously) somewhat over-specialized and only useful for TraitB's that only require a
 /// single function (eg for serialization).
-fn convert_trait_impl_field(trait_path: &str) -> (String, &'static str) {
+fn convert_trait_impl_field(trait_path: &str) -> (&'static str, String, &'static str) {
        match trait_path {
-               "util::ser::Writeable" => ("write".to_owned(), "crate::c_types::derived::CVec_u8Z"),
+               "util::ser::Writeable" => ("Serialize the object into a byte array", "write".to_owned(), "crate::c_types::derived::CVec_u8Z"),
                _ => unimplemented!(),
        }
 }
@@ -274,8 +286,10 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
        gen_types.learn_associated_types(&t, types);
 
        writeln!(w, "#[repr(C)]\npub struct {} {{", trait_name).unwrap();
+       writeln!(w, "\t/// An opaque pointer which is passed to your function implementations as an argument.").unwrap();
+       writeln!(w, "\t/// This has no meaning in the LDK, and can be NULL or any other value.").unwrap();
        writeln!(w, "\tpub this_arg: *mut c_void,").unwrap();
-       let mut generated_fields = Vec::new(); // Every field's name except this_arg, used in Clone generation
+       let mut generated_fields = Vec::new(); // Every field's (name, is_clonable) except this_arg, used in Clone generation
        for item in t.items.iter() {
                match item {
                        &syn::TraitItem::Method(ref m) => {
@@ -308,14 +322,14 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
                                                // happen) as well as provide an Option<>al function pointer which is
                                                // called when the trait method is called which allows updating on the fly.
                                                write!(w, "\tpub {}: ", m.sig.ident).unwrap();
-                                               generated_fields.push(format!("{}", m.sig.ident));
+                                               generated_fields.push((format!("{}", m.sig.ident), true));
                                                types.write_c_type(w, &*r.elem, Some(&gen_types), false);
                                                writeln!(w, ",").unwrap();
                                                writeln!(w, "\t/// Fill in the {} field as a reference to it will be given to Rust after this returns", m.sig.ident).unwrap();
                                                writeln!(w, "\t/// Note that this takes a pointer to this object, not the this_ptr like other methods do").unwrap();
                                                writeln!(w, "\t/// This function pointer may be NULL if {} is filled in when this object is created and never needs updating.", m.sig.ident).unwrap();
                                                writeln!(w, "\tpub set_{}: Option<extern \"C\" fn(&{})>,", m.sig.ident, trait_name).unwrap();
-                                               generated_fields.push(format!("set_{}", m.sig.ident));
+                                               generated_fields.push((format!("set_{}", m.sig.ident), true));
                                                // Note that cbindgen will now generate
                                                // typedef struct Thing {..., set_thing: (const Thing*), ...} Thing;
                                                // which does not compile since Thing is not defined before it is used.
@@ -330,7 +344,7 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
                                }
 
                                write!(w, "\tpub {}: extern \"C\" fn (", m.sig.ident).unwrap();
-                               generated_fields.push(format!("{}", m.sig.ident));
+                               generated_fields.push((format!("{}", m.sig.ident), true));
                                write_method_params(w, &m.sig, "c_void", types, Some(&gen_types), true, false);
                                writeln!(w, ",").unwrap();
 
@@ -341,36 +355,158 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
                }
        }
        // Add functions which may be required for supertrait implementations.
+       let mut requires_clone = false;
+       walk_supertraits!(t, Some(&types), (
+               ("Clone", _) => requires_clone = true,
+               (_, _) => {}
+       ) );
        walk_supertraits!(t, Some(&types), (
                ("Clone", _) => {
+                       writeln!(w, "\t/// Creates a copy of the object pointed to by this_arg, for a copy of this {}.", trait_name).unwrap();
+                       writeln!(w, "\t/// Note that the ultimate copy of the {} will have all function pointers the same as the original.", trait_name).unwrap();
+                       writeln!(w, "\t/// May be NULL if no action needs to be taken, the this_arg pointer will be copied into the new {}.", trait_name).unwrap();
                        writeln!(w, "\tpub clone: Option<extern \"C\" fn (this_arg: *const c_void) -> *mut c_void>,").unwrap();
-                       generated_fields.push("clone".to_owned());
+                       generated_fields.push(("clone".to_owned(), true));
                },
                ("std::cmp::Eq", _) => {
+                       writeln!(w, "\t/// Checks if two objects are equal given this object's this_arg pointer and another object.").unwrap();
                        writeln!(w, "\tpub eq: extern \"C\" fn (this_arg: *const c_void, other_arg: &{}) -> bool,", trait_name).unwrap();
                        writeln!(extra_headers, "typedef struct LDK{} LDK{};", trait_name, trait_name).unwrap();
-                       generated_fields.push("eq".to_owned());
+                       generated_fields.push(("eq".to_owned(), true));
                },
                ("std::hash::Hash", _) => {
+                       writeln!(w, "\t/// Calculate a succinct non-cryptographic hash for an object given its this_arg pointer.").unwrap();
+                       writeln!(w, "\t/// This is used, for example, for inclusion of this object in a hash map.").unwrap();
                        writeln!(w, "\tpub hash: extern \"C\" fn (this_arg: *const c_void) -> u64,").unwrap();
-                       generated_fields.push("hash".to_owned());
+                       generated_fields.push(("hash".to_owned(), true));
                },
                ("Send", _) => {}, ("Sync", _) => {},
                (s, i) => {
                        generated_fields.push(if types.crate_types.traits.get(s).is_none() {
-                               let (name, ret) = convert_trait_impl_field(s);
+                               let (docs, name, ret) = convert_trait_impl_field(s);
+                               writeln!(w, "\t/// {}", docs).unwrap();
                                writeln!(w, "\tpub {}: extern \"C\" fn (this_arg: *const c_void) -> {},", name, ret).unwrap();
-                               name
+                               (name, true) // Assume clonable
                        } else {
                                // For in-crate supertraits, just store a C-mapped copy of the supertrait as a member.
+                               writeln!(w, "\t/// Implementation of {} for this object.", i).unwrap();
                                writeln!(w, "\tpub {}: crate::{},", i, s).unwrap();
-                               format!("{}", i)
+                               let is_clonable = types.is_clonable(s);
+                               if !is_clonable && requires_clone {
+                                       writeln!(w, "\t/// Creates a copy of the {}, for a copy of this {}.", i, trait_name).unwrap();
+                                       writeln!(w, "\t/// Because {} doesn't natively support copying itself, you have to provide a full copy implementation here.", i).unwrap();
+                                       writeln!(w, "\tpub {}_clone: extern \"C\" fn (orig_{}: &{}) -> {},", i, i, i, i).unwrap();
+                               }
+                               (format!("{}", i), is_clonable)
                        });
                }
        ) );
+       writeln!(w, "\t/// Frees any resources associated with this object given its this_arg pointer.").unwrap();
+       writeln!(w, "\t/// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.").unwrap();
        writeln!(w, "\tpub free: Option<extern \"C\" fn(this_arg: *mut c_void)>,").unwrap();
-       generated_fields.push("free".to_owned());
+       generated_fields.push(("free".to_owned(), true));
        writeln!(w, "}}").unwrap();
+
+       macro_rules! impl_trait_for_c {
+               ($t: expr, $impl_accessor: expr) => {
+                       for item in $t.items.iter() {
+                               match item {
+                                       syn::TraitItem::Method(m) => {
+                                               if let ExportStatus::TestOnly = export_status(&m.attrs) { continue; }
+                                               if m.default.is_some() { unimplemented!(); }
+                                               if m.sig.constness.is_some() || m.sig.asyncness.is_some() || m.sig.unsafety.is_some() ||
+                                                               m.sig.abi.is_some() || m.sig.variadic.is_some() {
+                                                       unimplemented!();
+                                               }
+                                               gen_types.push_ctx();
+                                               assert!(gen_types.learn_generics(&m.sig.generics, types));
+                                               write!(w, "\tfn {}", m.sig.ident).unwrap();
+                                               types.write_rust_generic_param(w, Some(&gen_types), m.sig.generics.params.iter());
+                                               write!(w, "(").unwrap();
+                                               for inp in m.sig.inputs.iter() {
+                                                       match inp {
+                                                               syn::FnArg::Receiver(recv) => {
+                                                                       if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
+                                                                       write!(w, "&").unwrap();
+                                                                       if let Some(lft) = &recv.reference.as_ref().unwrap().1 {
+                                                                               write!(w, "'{} ", lft.ident).unwrap();
+                                                                       }
+                                                                       if recv.mutability.is_some() {
+                                                                               write!(w, "mut self").unwrap();
+                                                                       } else {
+                                                                               write!(w, "self").unwrap();
+                                                                       }
+                                                               },
+                                                               syn::FnArg::Typed(arg) => {
+                                                                       if !arg.attrs.is_empty() { unimplemented!(); }
+                                                                       match &*arg.pat {
+                                                                               syn::Pat::Ident(ident) => {
+                                                                                       if !ident.attrs.is_empty() || ident.by_ref.is_some() ||
+                                                                                                       ident.mutability.is_some() || ident.subpat.is_some() {
+                                                                                               unimplemented!();
+                                                                                       }
+                                                                                       write!(w, ", {}{}: ", if types.skip_arg(&*arg.ty, Some(&gen_types)) { "_" } else { "" }, ident.ident).unwrap();
+                                                                               }
+                                                                               _ => unimplemented!(),
+                                                                       }
+                                                                       types.write_rust_type(w, Some(&gen_types), &*arg.ty);
+                                                               }
+                                                       }
+                                               }
+                                               write!(w, ")").unwrap();
+                                               match &m.sig.output {
+                                                       syn::ReturnType::Type(_, rtype) => {
+                                                               write!(w, " -> ").unwrap();
+                                                               types.write_rust_type(w, Some(&gen_types), &*rtype)
+                                                       },
+                                                       _ => {},
+                                               }
+                                               write!(w, " {{\n\t\t").unwrap();
+                                               match export_status(&m.attrs) {
+                                                       ExportStatus::NoExport => {
+                                                               unimplemented!();
+                                                       },
+                                                       _ => {},
+                                               }
+                                               if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
+                                                       if let syn::Type::Reference(r) = &**rtype {
+                                                               assert_eq!(m.sig.inputs.len(), 1); // Must only take self!
+                                                               writeln!(w, "if let Some(f) = self{}.set_{} {{", $impl_accessor, m.sig.ident).unwrap();
+                                                               writeln!(w, "\t\t\t(f)(&self{});", $impl_accessor).unwrap();
+                                                               write!(w, "\t\t}}\n\t\t").unwrap();
+                                                               types.write_from_c_conversion_to_ref_prefix(w, &*r.elem, Some(&gen_types));
+                                                               write!(w, "self{}.{}", $impl_accessor, m.sig.ident).unwrap();
+                                                               types.write_from_c_conversion_to_ref_suffix(w, &*r.elem, Some(&gen_types));
+                                                               writeln!(w, "\n\t}}").unwrap();
+                                                               gen_types.pop_ctx();
+                                                               continue;
+                                                       }
+                                               }
+                                               write_method_var_decl_body(w, &m.sig, "\t", types, Some(&gen_types), true);
+                                               write!(w, "(self{}.{})(", $impl_accessor, m.sig.ident).unwrap();
+                                               write_method_call_params(w, &m.sig, "\t", types, Some(&gen_types), "", true);
+
+                                               writeln!(w, "\n\t}}").unwrap();
+                                               gen_types.pop_ctx();
+                                       },
+                                       &syn::TraitItem::Type(ref t) => {
+                                               if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
+                                               let mut bounds_iter = t.bounds.iter();
+                                               match bounds_iter.next().unwrap() {
+                                                       syn::TypeParamBound::Trait(tr) => {
+                                                               writeln!(w, "\ttype {} = crate::{};", t.ident, types.resolve_path(&tr.path, Some(&gen_types))).unwrap();
+                                                       },
+                                                       _ => unimplemented!(),
+                                               }
+                                               if bounds_iter.next().is_some() { unimplemented!(); }
+                                       },
+                                       _ => unimplemented!(),
+                               }
+                       }
+               }
+       }
+
+
        // Implement supertraits for the C-mapped struct.
        walk_supertraits!(t, Some(&types), (
                ("Send", _) => writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap(),
@@ -386,11 +522,17 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
                },
                ("Clone", _) => {
                        writeln!(w, "#[no_mangle]").unwrap();
+                       writeln!(w, "/// Creates a copy of a {}", trait_name).unwrap();
                        writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", trait_name, trait_name, trait_name).unwrap();
                        writeln!(w, "\t{} {{", trait_name).unwrap();
                        writeln!(w, "\t\tthis_arg: if let Some(f) = orig.clone {{ (f)(orig.this_arg) }} else {{ orig.this_arg }},").unwrap();
-                       for field in generated_fields.iter() {
-                               writeln!(w, "\t\t{}: orig.{}.clone(),", field, field).unwrap();
+                       for (field, clonable) in generated_fields.iter() {
+                               if *clonable {
+                                       writeln!(w, "\t\t{}: Clone::clone(&orig.{}),", field, field).unwrap();
+                               } else {
+                                       writeln!(w, "\t\t{}: (orig.{}_clone)(&orig.{}),", field, field, field).unwrap();
+                                       writeln!(w, "\t\t{}_clone: orig.{}_clone,", field, field).unwrap();
+                               }
                        }
                        writeln!(w, "\t}}\n}}").unwrap();
                        writeln!(w, "impl Clone for {} {{", trait_name).unwrap();
@@ -399,7 +541,18 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
                        writeln!(w, "\t}}\n}}").unwrap();
                },
                (s, i) => {
-                       do_write_impl_trait(w, s, i, &trait_name);
+                       if let Some(supertrait) = types.crate_types.traits.get(s) {
+                               writeln!(w, "impl lightning::{} for {} {{", s, trait_name).unwrap(); // TODO: Drop hard-coded crate name here
+                               impl_trait_for_c!(supertrait, format!(".{}", i));
+                               writeln!(w, "}}").unwrap();
+                               walk_supertraits!(supertrait, Some(&types), (
+                                       ("Send", _) => writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap(),
+                                       ("Sync", _) => writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap(),
+                                       _ => unimplemented!()
+                               ) );
+                       } else {
+                               do_write_impl_trait(w, s, i, &trait_name);
+                       }
                }
        ) );
 
@@ -408,100 +561,7 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
        write!(w, "impl rust{}", t.ident).unwrap();
        maybe_write_generics(w, &t.generics, types, false);
        writeln!(w, " for {} {{", trait_name).unwrap();
-       for item in t.items.iter() {
-               match item {
-                       syn::TraitItem::Method(m) => {
-                               if let ExportStatus::TestOnly = export_status(&m.attrs) { continue; }
-                               if m.default.is_some() { unimplemented!(); }
-                               if m.sig.constness.is_some() || m.sig.asyncness.is_some() || m.sig.unsafety.is_some() ||
-                                               m.sig.abi.is_some() || m.sig.variadic.is_some() {
-                                       unimplemented!();
-                               }
-                               gen_types.push_ctx();
-                               assert!(gen_types.learn_generics(&m.sig.generics, types));
-                               write!(w, "\tfn {}", m.sig.ident).unwrap();
-                               types.write_rust_generic_param(w, Some(&gen_types), m.sig.generics.params.iter());
-                               write!(w, "(").unwrap();
-                               for inp in m.sig.inputs.iter() {
-                                       match inp {
-                                               syn::FnArg::Receiver(recv) => {
-                                                       if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
-                                                       write!(w, "&").unwrap();
-                                                       if let Some(lft) = &recv.reference.as_ref().unwrap().1 {
-                                                               write!(w, "'{} ", lft.ident).unwrap();
-                                                       }
-                                                       if recv.mutability.is_some() {
-                                                               write!(w, "mut self").unwrap();
-                                                       } else {
-                                                               write!(w, "self").unwrap();
-                                                       }
-                                               },
-                                               syn::FnArg::Typed(arg) => {
-                                                       if !arg.attrs.is_empty() { unimplemented!(); }
-                                                       match &*arg.pat {
-                                                               syn::Pat::Ident(ident) => {
-                                                                       if !ident.attrs.is_empty() || ident.by_ref.is_some() ||
-                                                                                       ident.mutability.is_some() || ident.subpat.is_some() {
-                                                                               unimplemented!();
-                                                                       }
-                                                                       write!(w, ", {}{}: ", if types.skip_arg(&*arg.ty, Some(&gen_types)) { "_" } else { "" }, ident.ident).unwrap();
-                                                               }
-                                                               _ => unimplemented!(),
-                                                       }
-                                                       types.write_rust_type(w, Some(&gen_types), &*arg.ty);
-                                               }
-                                       }
-                               }
-                               write!(w, ")").unwrap();
-                               match &m.sig.output {
-                                       syn::ReturnType::Type(_, rtype) => {
-                                               write!(w, " -> ").unwrap();
-                                               types.write_rust_type(w, Some(&gen_types), &*rtype)
-                                       },
-                                       _ => {},
-                               }
-                               write!(w, " {{\n\t\t").unwrap();
-                               match export_status(&m.attrs) {
-                                       ExportStatus::NoExport => {
-                                               unimplemented!();
-                                       },
-                                       _ => {},
-                               }
-                               if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
-                                       if let syn::Type::Reference(r) = &**rtype {
-                                               assert_eq!(m.sig.inputs.len(), 1); // Must only take self!
-                                               writeln!(w, "if let Some(f) = self.set_{} {{", m.sig.ident).unwrap();
-                                               writeln!(w, "\t\t\t(f)(self);").unwrap();
-                                               write!(w, "\t\t}}\n\t\t").unwrap();
-                                               types.write_from_c_conversion_to_ref_prefix(w, &*r.elem, Some(&gen_types));
-                                               write!(w, "self.{}", m.sig.ident).unwrap();
-                                               types.write_from_c_conversion_to_ref_suffix(w, &*r.elem, Some(&gen_types));
-                                               writeln!(w, "\n\t}}").unwrap();
-                                               gen_types.pop_ctx();
-                                               continue;
-                                       }
-                               }
-                               write_method_var_decl_body(w, &m.sig, "\t", types, Some(&gen_types), true);
-                               write!(w, "(self.{})(", m.sig.ident).unwrap();
-                               write_method_call_params(w, &m.sig, "\t", types, Some(&gen_types), "", true);
-
-                               writeln!(w, "\n\t}}").unwrap();
-                               gen_types.pop_ctx();
-                       },
-                       &syn::TraitItem::Type(ref t) => {
-                               if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
-                               let mut bounds_iter = t.bounds.iter();
-                               match bounds_iter.next().unwrap() {
-                                       syn::TypeParamBound::Trait(tr) => {
-                                               writeln!(w, "\ttype {} = crate::{};", t.ident, types.resolve_path(&tr.path, Some(&gen_types))).unwrap();
-                                       },
-                                       _ => unimplemented!(),
-                               }
-                               if bounds_iter.next().is_some() { unimplemented!(); }
-                       },
-                       _ => unimplemented!(),
-               }
-       }
+       impl_trait_for_c!(t, "");
        writeln!(w, "}}\n").unwrap();
        writeln!(w, "// We're essentially a pointer already, or at least a set of pointers, so allow us to be used").unwrap();
        writeln!(w, "// directly as a Deref trait in higher-level structs:").unwrap();
@@ -532,13 +592,21 @@ fn writeln_opaque<W: std::io::Write>(w: &mut W, ident: &syn::Ident, struct_name:
        writeln!(w, ";\n").unwrap();
        writeln!(extra_headers, "struct native{}Opaque;\ntypedef struct native{}Opaque LDKnative{};", ident, ident, ident).unwrap();
        writeln_docs(w, &attrs, "");
-       writeln!(w, "#[must_use]\n#[repr(C)]\npub struct {} {{\n\t/// Nearly everywhere, inner must be non-null, however in places where", struct_name).unwrap();
+       writeln!(w, "#[must_use]\n#[repr(C)]\npub struct {} {{", struct_name).unwrap();
+       writeln!(w, "\t/// A pointer to the opaque Rust object.\n").unwrap();
+       writeln!(w, "\t/// Nearly everywhere, inner must be non-null, however in places where").unwrap();
        writeln!(w, "\t/// the Rust equivalent takes an Option, it may be set to null to indicate None.").unwrap();
-       writeln!(w, "\tpub inner: *mut native{},\n\tpub is_owned: bool,\n}}\n", ident).unwrap();
+       writeln!(w, "\tpub inner: *mut native{},", ident).unwrap();
+       writeln!(w, "\t/// Indicates that this is the only struct which contains the same pointer.\n").unwrap();
+       writeln!(w, "\t/// Rust functions which take ownership of an object provided via an argument require").unwrap();
+       writeln!(w, "\t/// this to be true and invalidate the object pointed to by inner.").unwrap();
+       writeln!(w, "\tpub is_owned: bool,").unwrap();
+       writeln!(w, "}}\n").unwrap();
        writeln!(w, "impl Drop for {} {{\n\tfn drop(&mut self) {{", struct_name).unwrap();
        writeln!(w, "\t\tif self.is_owned && !<*mut native{}>::is_null(self.inner) {{", ident).unwrap();
        writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(self.inner) }};\n\t\t}}\n\t}}\n}}").unwrap();
-       writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", struct_name, struct_name).unwrap();
+       writeln!(w, "/// Frees any resources used by the {}, if is_owned is set and inner is non-NULL.", struct_name).unwrap();
+       writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_obj: {}) {{ }}", struct_name, struct_name).unwrap();
        writeln!(w, "#[allow(unused)]").unwrap();
        writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
        writeln!(w, "extern \"C\" fn {}_free_void(this_ptr: *mut c_void) {{", struct_name).unwrap();
@@ -621,6 +689,7 @@ fn writeln_struct<'a, 'b, W: std::io::Write>(w: &mut W, s: &'a syn::ItemStruct,
 
                if all_fields_settable {
                        // Build a constructor!
+                       writeln!(w, "/// Constructs a new {} given each field", struct_name).unwrap();
                        write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_new(", struct_name).unwrap();
                        for (idx, field) in fields.named.iter().enumerate() {
                                if idx != 0 { write!(w, ", ").unwrap(); }
@@ -742,6 +811,8 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                writeln!(w, "\t\tret.free = Some({}_free_void);", ident).unwrap();
                                                writeln!(w, "\t\tret\n\t}}\n}}").unwrap();
 
+                                               writeln!(w, "/// Constructs a new {} which calls the relevant methods on this_arg.", trait_obj.ident).unwrap();
+                                               writeln!(w, "/// This copies the `inner` pointer in this_arg and thus the returned {} must be freed before this_arg is", trait_obj.ident).unwrap();
                                                write!(w, "#[no_mangle]\npub extern \"C\" fn {}_as_{}(this_arg: &{}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
                                                writeln!(w, "\tcrate::{} {{", full_trait_path).unwrap();
                                                writeln!(w, "\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
@@ -783,6 +854,11 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                                _ => {},
                                                        }
                                                }
+                                               let mut requires_clone = false;
+                                               walk_supertraits!(trait_obj, Some(&types), (
+                                                       ("Clone", _) => requires_clone = true,
+                                                       (_, _) => {}
+                                               ) );
                                                walk_supertraits!(trait_obj, Some(&types), (
                                                        ("Clone", _) => {
                                                                writeln!(w, "\t\tclone: Some({}_clone_void),", ident).unwrap();
@@ -803,6 +879,9 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                                                }
                                                                        }
                                                                        write!(w, "\t\t}},\n").unwrap();
+                                                                       if !types.is_clonable(s) && requires_clone {
+                                                                               writeln!(w, "\t\t{}_clone: {}_{}_clone,", t, ident, t).unwrap();
+                                                                       }
                                                                } else {
                                                                        write_trait_impl_field_assign(w, s, ident);
                                                                }
@@ -888,15 +967,22 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                        }
                                                }
                                                walk_supertraits!(trait_obj, Some(&types), (
-                                                       (s, _) => {
-                                                               if let Some(supertrait_obj) = types.crate_types.traits.get(s).cloned() {
-                                                                       for item in supertrait_obj.items.iter() {
-                                                                               match item {
-                                                                                       syn::TraitItem::Method(m) => {
-                                                                                               impl_meth!(m, s, supertrait_obj, "\t");
-                                                                                       },
-                                                                                       _ => {},
+                                                       (s, t) => {
+                                                               if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
+                                                                       if !types.is_clonable(s) && requires_clone {
+                                                                               writeln!(w, "extern \"C\" fn {}_{}_clone(orig: &crate::{}) -> crate::{} {{", ident, t, s, s).unwrap();
+                                                                               writeln!(w, "\tcrate::{} {{", s).unwrap();
+                                                                               writeln!(w, "\t\tthis_arg: orig.this_arg,").unwrap();
+                                                                               writeln!(w, "\t\tfree: None,").unwrap();
+                                                                               for item in supertrait_obj.items.iter() {
+                                                                                       match item {
+                                                                                               syn::TraitItem::Method(m) => {
+                                                                                                       write_meth!(m, supertrait_obj, "");
+                                                                                               },
+                                                                                               _ => {},
+                                                                                       }
                                                                                }
+                                                                               write!(w, "\t}}\n}}\n").unwrap();
                                                                        }
                                                                }
                                                        }
@@ -904,6 +990,7 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                write!(w, "\n").unwrap();
                                        } else if path_matches_nongeneric(&trait_path.1, &["From"]) {
                                        } else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
+                                               writeln!(w, "/// Creates a \"default\" {}. See struct and individual field documentaiton for details on which values are used.", ident).unwrap();
                                                write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
                                                write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
                                                write!(w, "}}\n").unwrap();
@@ -923,6 +1010,7 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", ident).unwrap();
                                                writeln!(w, "}}").unwrap();
                                                writeln!(w, "#[no_mangle]").unwrap();
+                                               writeln!(w, "/// Creates a copy of the {}", ident).unwrap();
                                                writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", ident, ident, ident).unwrap();
                                                writeln!(w, "\torig.clone()").unwrap();
                                                writeln!(w, "}}").unwrap();
@@ -1076,6 +1164,7 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type
                        writeln!(w, " {{").unwrap();
                        for field in fields.named.iter() {
                                if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
+                               writeln_docs(w, &field.attrs, "\t\t");
                                write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
                                types.write_c_type(w, &field.ty, None, false);
                                writeln!(w, ",").unwrap();
@@ -1212,8 +1301,10 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type
        writeln!(w, "}}").unwrap();
 
        if needs_free {
+               writeln!(w, "/// Frees any resources used by the {}", e.ident).unwrap();
                writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", e.ident, e.ident).unwrap();
        }
+       writeln!(w, "/// Creates a copy of the {}", e.ident).unwrap();
        writeln!(w, "#[no_mangle]").unwrap();
        writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
        writeln!(w, "\torig.clone()").unwrap();
@@ -1309,6 +1400,15 @@ fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &mut CrateTypes
                let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
                        .open(new_file_path).expect("Unable to open new src file");
 
+               writeln!(out, "// This file is Copyright its original authors, visible in version control").unwrap();
+               writeln!(out, "// history and in the source files from which this was generated.").unwrap();
+               writeln!(out, "//").unwrap();
+               writeln!(out, "// This file is licensed under the license available in the LICENSE or LICENSE.md").unwrap();
+               writeln!(out, "// file in the root of this repository or, if no such file exists, the same").unwrap();
+               writeln!(out, "// license as that which applies to the original source files from which this").unwrap();
+               writeln!(out, "// source was automatically generated.").unwrap();
+               writeln!(out, "").unwrap();
+
                writeln_docs(&mut out, &attrs, "");
 
                if module == "" {
@@ -1323,8 +1423,9 @@ fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &mut CrateTypes
                        writeln!(out, "#![allow(unused_parens)]").unwrap();
                        writeln!(out, "#![allow(unused_unsafe)]").unwrap();
                        writeln!(out, "#![allow(unused_braces)]").unwrap();
-                       writeln!(out, "mod c_types;").unwrap();
-                       writeln!(out, "mod bitcoin;").unwrap();
+                       writeln!(out, "#![deny(missing_docs)]").unwrap();
+                       writeln!(out, "pub mod c_types;").unwrap();
+                       writeln!(out, "pub mod bitcoin;").unwrap();
                } else {
                        writeln!(out, "\nuse std::ffi::c_void;\nuse bitcoin::hashes::Hash;\nuse crate::c_types::*;\n").unwrap();
                }
@@ -1367,6 +1468,7 @@ fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &mut CrateTypes
                                                if let syn::Type::Path(p) = &*c.ty {
                                                        let resolved_path = type_resolver.resolve_path(&p.path, None);
                                                        if type_resolver.is_primitive(&resolved_path) {
+                                                               writeln_docs(&mut out, &c.attrs, "");
                                                                writeln!(out, "\n#[no_mangle]").unwrap();
                                                                writeln!(out, "pub static {}: {} = {}::{}::{};", c.ident, resolved_path, orig_crate, module, c.ident).unwrap();
                                                        }