Merge pull request #3 from TheBlueMatt/main
[ldk-c-bindings] / c-bindings-gen / src / main.rs
1 //! Converts a rust crate into a rust crate containing a number of C-exported wrapper functions and
2 //! classes (which is exportable using cbindgen).
3 //! In general, supports convering:
4 //!  * structs as a pointer to the underlying type (either owned or not owned),
5 //!  * traits as a void-ptr plus a jump table,
6 //!  * enums as an equivalent enum with all the inner fields mapped to the mapped types,
7 //!  * certain containers (tuples, slices, Vecs, Options, and Results currently) to a concrete
8 //!    version of a defined container template.
9 //!
10 //! It also generates relevant memory-management functions and free-standing functions with
11 //! parameters mapped.
12
13 use std::collections::{HashMap, hash_map, HashSet};
14 use std::env;
15 use std::fs::File;
16 use std::io::{Read, Write};
17 use std::process;
18
19 use proc_macro2::{TokenTree, TokenStream, Span};
20
21 mod types;
22 mod blocks;
23 use types::*;
24 use blocks::*;
25
26 // *************************************
27 // *** Manually-expanded conversions ***
28 // *************************************
29
30 /// Because we don't expand macros, any code that we need to generated based on their contents has
31 /// to be completely manual. In this case its all just serialization, so its not too hard.
32 fn convert_macro<W: std::io::Write>(w: &mut W, macro_path: &syn::Path, stream: &TokenStream, types: &TypeResolver) {
33         assert_eq!(macro_path.segments.len(), 1);
34         match &format!("{}", macro_path.segments.iter().next().unwrap().ident) as &str {
35                 "impl_writeable" | "impl_writeable_len_match" => {
36                         let struct_for = if let TokenTree::Ident(i) = stream.clone().into_iter().next().unwrap() { i } else { unimplemented!(); };
37                         if let Some(s) = types.maybe_resolve_ident(&struct_for) {
38                                 if !types.crate_types.opaques.get(&s).is_some() { return; }
39                                 writeln!(w, "#[no_mangle]").unwrap();
40                                 writeln!(w, "/// Serialize the {} into a byte array which can be read by {}_read", struct_for, struct_for).unwrap();
41                                 writeln!(w, "pub extern \"C\" fn {}_write(obj: &{}) -> crate::c_types::derived::CVec_u8Z {{", struct_for, struct_for).unwrap();
42                                 writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &(*(*obj).inner) }})").unwrap();
43                                 writeln!(w, "}}").unwrap();
44                                 writeln!(w, "#[no_mangle]").unwrap();
45                                 writeln!(w, "pub(crate) extern \"C\" fn {}_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {{", struct_for).unwrap();
46                                 writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &*(obj as *const native{}) }})", struct_for).unwrap();
47                                 writeln!(w, "}}").unwrap();
48                                 writeln!(w, "#[no_mangle]").unwrap();
49                                 writeln!(w, "/// Read a {} from a byte array, created by {}_write", struct_for, struct_for).unwrap();
50                                 writeln!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice) -> {} {{", struct_for, struct_for).unwrap();
51                                 writeln!(w, "\tif let Ok(res) = crate::c_types::deserialize_obj(ser) {{").unwrap();
52                                 writeln!(w, "\t\t{} {{ inner: Box::into_raw(Box::new(res)), is_owned: true }}", struct_for).unwrap();
53                                 writeln!(w, "\t}} else {{").unwrap();
54                                 writeln!(w, "\t\t{} {{ inner: std::ptr::null_mut(), is_owned: true }}", struct_for).unwrap();
55                                 writeln!(w, "\t}}\n}}").unwrap();
56                         }
57                 },
58                 _ => {},
59         }
60 }
61
62 /// Convert "impl trait_path for for_ty { .. }" for manually-mapped types (ie (de)serialization)
63 fn maybe_convert_trait_impl<W: std::io::Write>(w: &mut W, trait_path: &syn::Path, for_ty: &syn::Type, types: &mut TypeResolver, generics: &GenericTypes) {
64         if let Some(t) = types.maybe_resolve_path(&trait_path, Some(generics)) {
65                 let for_obj;
66                 let full_obj_path;
67                 let mut has_inner = false;
68                 if let syn::Type::Path(ref p) = for_ty {
69                         if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
70                                 for_obj = format!("{}", ident);
71                                 full_obj_path = for_obj.clone();
72                                 has_inner = types.c_type_has_inner_from_path(&types.resolve_path(&p.path, Some(generics)));
73                         } else { return; }
74                 } else {
75                         // We assume that anything that isn't a Path is somehow a generic that ends up in our
76                         // derived-types module.
77                         let mut for_obj_vec = Vec::new();
78                         types.write_c_type(&mut for_obj_vec, for_ty, Some(generics), false);
79                         full_obj_path = String::from_utf8(for_obj_vec).unwrap();
80                         assert!(full_obj_path.starts_with(TypeResolver::generated_container_path()));
81                         for_obj = full_obj_path[TypeResolver::generated_container_path().len() + 2..].into();
82                 }
83
84                 match &t as &str {
85                         "util::ser::Writeable" => {
86                                 writeln!(w, "#[no_mangle]").unwrap();
87                                 writeln!(w, "/// Serialize the {} object into a byte array which can be read by {}_read", for_obj, for_obj).unwrap();
88                                 writeln!(w, "pub extern \"C\" fn {}_write(obj: &{}) -> crate::c_types::derived::CVec_u8Z {{", for_obj, full_obj_path).unwrap();
89
90                                 let ref_type = syn::Type::Reference(syn::TypeReference {
91                                         and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
92                                         elem: Box::new(for_ty.clone()) });
93                                 assert!(!types.write_from_c_conversion_new_var(w, &syn::Ident::new("obj", Span::call_site()), &ref_type, Some(generics)));
94
95                                 write!(w, "\tcrate::c_types::serialize_obj(").unwrap();
96                                 types.write_from_c_conversion_prefix(w, &ref_type, Some(generics));
97                                 write!(w, "unsafe {{ &*obj }}").unwrap();
98                                 types.write_from_c_conversion_suffix(w, &ref_type, Some(generics));
99                                 writeln!(w, ")").unwrap();
100
101                                 writeln!(w, "}}").unwrap();
102                                 if has_inner {
103                                         writeln!(w, "#[no_mangle]").unwrap();
104                                         writeln!(w, "pub(crate) extern \"C\" fn {}_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {{", for_obj).unwrap();
105                                         writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &*(obj as *const native{}) }})", for_obj).unwrap();
106                                         writeln!(w, "}}").unwrap();
107                                 }
108                         },
109                         "util::ser::Readable"|"util::ser::ReadableArgs" => {
110                                 // Create the Result<Object, DecodeError> syn::Type
111                                 let mut err_segs = syn::punctuated::Punctuated::new();
112                                 err_segs.push(syn::PathSegment { ident: syn::Ident::new("ln", Span::call_site()), arguments: syn::PathArguments::None });
113                                 err_segs.push(syn::PathSegment { ident: syn::Ident::new("msgs", Span::call_site()), arguments: syn::PathArguments::None });
114                                 err_segs.push(syn::PathSegment { ident: syn::Ident::new("DecodeError", Span::call_site()), arguments: syn::PathArguments::None });
115                                 let mut args = syn::punctuated::Punctuated::new();
116                                 args.push(syn::GenericArgument::Type(for_ty.clone()));
117                                 args.push(syn::GenericArgument::Type(syn::Type::Path(syn::TypePath {
118                                         qself: None, path: syn::Path {
119                                                 leading_colon: Some(syn::Token![::](Span::call_site())), segments: err_segs,
120                                         }
121                                 })));
122                                 let mut res_segs = syn::punctuated::Punctuated::new();
123                                 res_segs.push(syn::PathSegment {
124                                         ident: syn::Ident::new("Result", Span::call_site()),
125                                         arguments: syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
126                                                 colon2_token: None, lt_token: syn::Token![<](Span::call_site()), args, gt_token: syn::Token![>](Span::call_site()),
127                                         })
128                                 });
129                                 let res_ty = syn::Type::Path(syn::TypePath { qself: None, path: syn::Path {
130                                         leading_colon: None, segments: res_segs } });
131
132                                 writeln!(w, "#[no_mangle]").unwrap();
133                                 writeln!(w, "/// Read a {} from a byte array, created by {}_write", for_obj, for_obj).unwrap();
134                                 write!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice", for_obj).unwrap();
135
136                                 let mut arg_conv = Vec::new();
137                                 if t == "util::ser::ReadableArgs" {
138                                         write!(w, ", arg: ").unwrap();
139                                         assert!(trait_path.leading_colon.is_none());
140                                         let args_seg = trait_path.segments.iter().last().unwrap();
141                                         assert_eq!(format!("{}", args_seg.ident), "ReadableArgs");
142                                         if let syn::PathArguments::AngleBracketed(args) = &args_seg.arguments {
143                                                 assert_eq!(args.args.len(), 1);
144                                                 if let syn::GenericArgument::Type(args_ty) = args.args.iter().next().unwrap() {
145                                                         types.write_c_type(w, args_ty, Some(generics), false);
146
147                                                         assert!(!types.write_from_c_conversion_new_var(&mut arg_conv, &syn::Ident::new("arg", Span::call_site()), &args_ty, Some(generics)));
148
149                                                         write!(&mut arg_conv, "\tlet arg_conv = ").unwrap();
150                                                         types.write_from_c_conversion_prefix(&mut arg_conv, &args_ty, Some(generics));
151                                                         write!(&mut arg_conv, "arg").unwrap();
152                                                         types.write_from_c_conversion_suffix(&mut arg_conv, &args_ty, Some(generics));
153                                                 } else { unreachable!(); }
154                                         } else { unreachable!(); }
155                                 }
156                                 write!(w, ") -> ").unwrap();
157                                 types.write_c_type(w, &res_ty, Some(generics), false);
158                                 writeln!(w, " {{").unwrap();
159
160                                 if t == "util::ser::ReadableArgs" {
161                                         w.write(&arg_conv).unwrap();
162                                         write!(w, ";\n\tlet res: ").unwrap();
163                                         // At least in one case we need type annotations here, so provide them.
164                                         types.write_rust_type(w, Some(generics), &res_ty);
165                                         writeln!(w, " = crate::c_types::deserialize_obj_arg(ser, arg_conv);").unwrap();
166                                 } else {
167                                         writeln!(w, "\tlet res = crate::c_types::deserialize_obj(ser);").unwrap();
168                                 }
169                                 write!(w, "\t").unwrap();
170                                 if types.write_to_c_conversion_new_var(w, &syn::Ident::new("res", Span::call_site()), &res_ty, Some(generics), false) {
171                                         write!(w, "\n\t").unwrap();
172                                 }
173                                 types.write_to_c_conversion_inline_prefix(w, &res_ty, Some(generics), false);
174                                 write!(w, "res").unwrap();
175                                 types.write_to_c_conversion_inline_suffix(w, &res_ty, Some(generics), false);
176                                 writeln!(w, "\n}}").unwrap();
177                         },
178                         _ => {},
179                 }
180         }
181 }
182
183 /// Convert "TraitA : TraitB" to a single function name and return type.
184 ///
185 /// This is (obviously) somewhat over-specialized and only useful for TraitB's that only require a
186 /// single function (eg for serialization).
187 fn convert_trait_impl_field(trait_path: &str) -> (&'static str, String, &'static str) {
188         match trait_path {
189                 "util::ser::Writeable" => ("Serialize the object into a byte array", "write".to_owned(), "crate::c_types::derived::CVec_u8Z"),
190                 _ => unimplemented!(),
191         }
192 }
193
194 /// Companion to convert_trait_impl_field, write an assignment for the function defined by it for
195 /// `for_obj` which implements the the trait at `trait_path`.
196 fn write_trait_impl_field_assign<W: std::io::Write>(w: &mut W, trait_path: &str, for_obj: &syn::Ident) {
197         match trait_path {
198                 "util::ser::Writeable" => {
199                         writeln!(w, "\t\twrite: {}_write_void,", for_obj).unwrap();
200                 },
201                 _ => unimplemented!(),
202         }
203 }
204
205 /// Write out the impl block for a defined trait struct which has a supertrait
206 fn do_write_impl_trait<W: std::io::Write>(w: &mut W, trait_path: &str, trait_name: &syn::Ident, for_obj: &str) {
207         match trait_path {
208                 "util::events::MessageSendEventsProvider" => {
209                         writeln!(w, "impl lightning::{} for {} {{", trait_path, for_obj).unwrap();
210                         writeln!(w, "\tfn get_and_clear_pending_msg_events(&self) -> Vec<lightning::util::events::MessageSendEvent> {{").unwrap();
211                         writeln!(w, "\t\t<crate::{} as lightning::{}>::get_and_clear_pending_msg_events(&self.{})", trait_path, trait_path, trait_name).unwrap();
212                         writeln!(w, "\t}}\n}}").unwrap();
213                 },
214                 "util::ser::Writeable" => {
215                         writeln!(w, "impl lightning::{} for {} {{", trait_path, for_obj).unwrap();
216                         writeln!(w, "\tfn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {{").unwrap();
217                         writeln!(w, "\t\tlet vec = (self.write)(self.this_arg);").unwrap();
218                         writeln!(w, "\t\tw.write_all(vec.as_slice())").unwrap();
219                         writeln!(w, "\t}}\n}}").unwrap();
220                 },
221                 _ => panic!(),
222         }
223 }
224
225 // *******************************
226 // *** Per-Type Printing Logic ***
227 // *******************************
228
229 macro_rules! walk_supertraits { ($t: expr, $types: expr, ($( $pat: pat => $e: expr),*) ) => { {
230         if $t.colon_token.is_some() {
231                 for st in $t.supertraits.iter() {
232                         match st {
233                                 syn::TypeParamBound::Trait(supertrait) => {
234                                         if supertrait.paren_token.is_some() || supertrait.lifetimes.is_some() {
235                                                 unimplemented!();
236                                         }
237                                         // First try to resolve path to find in-crate traits, but if that doesn't work
238                                         // assume its a prelude trait (eg Clone, etc) and just use the single ident.
239                                         let types_opt: Option<&TypeResolver> = $types;
240                                         if let Some(types) = types_opt {
241                                                 if let Some(path) = types.maybe_resolve_path(&supertrait.path, None) {
242                                                         match (&path as &str, &supertrait.path.segments.iter().last().unwrap().ident) {
243                                                                 $( $pat => $e, )*
244                                                         }
245                                                         continue;
246                                                 }
247                                         }
248                                         if let Some(ident) = supertrait.path.get_ident() {
249                                                 match (&format!("{}", ident) as &str, &ident) {
250                                                         $( $pat => $e, )*
251                                                 }
252                                         } else if types_opt.is_some() {
253                                                 panic!("Supertrait unresolvable and not single-ident");
254                                         }
255                                 },
256                                 syn::TypeParamBound::Lifetime(_) => unimplemented!(),
257                         }
258                 }
259         }
260 } } }
261
262 /// Prints a C-mapped trait object containing a void pointer and a jump table for each function in
263 /// the original trait.
264 /// Implements the native Rust trait and relevant parent traits for the new C-mapped trait.
265 ///
266 /// Finally, implements Deref<MappedTrait> for MappedTrait which allows its use in types which need
267 /// a concrete Deref to the Rust trait.
268 fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, types: &mut TypeResolver<'b, 'a>, extra_headers: &mut File, cpp_headers: &mut File) {
269         let trait_name = format!("{}", t.ident);
270         match export_status(&t.attrs) {
271                 ExportStatus::Export => {},
272                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
273         }
274         writeln_docs(w, &t.attrs, "");
275
276         let mut gen_types = GenericTypes::new();
277         assert!(gen_types.learn_generics(&t.generics, types));
278         gen_types.learn_associated_types(&t, types);
279
280         writeln!(w, "#[repr(C)]\npub struct {} {{", trait_name).unwrap();
281         writeln!(w, "\t/// An opaque pointer which is passed to your function implementations as an argument.").unwrap();
282         writeln!(w, "\t/// This has no meaning in the LDK, and can be NULL or any other value.").unwrap();
283         writeln!(w, "\tpub this_arg: *mut c_void,").unwrap();
284         let mut generated_fields = Vec::new(); // Every field's name except this_arg, used in Clone generation
285         for item in t.items.iter() {
286                 match item {
287                         &syn::TraitItem::Method(ref m) => {
288                                 match export_status(&m.attrs) {
289                                         ExportStatus::NoExport => {
290                                                 // NoExport in this context means we'll hit an unimplemented!() at runtime,
291                                                 // so bail out.
292                                                 unimplemented!();
293                                         },
294                                         ExportStatus::Export => {},
295                                         ExportStatus::TestOnly => continue,
296                                 }
297                                 if m.default.is_some() { unimplemented!(); }
298
299                                 gen_types.push_ctx();
300                                 assert!(gen_types.learn_generics(&m.sig.generics, types));
301
302                                 writeln_docs(w, &m.attrs, "\t");
303
304                                 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
305                                         if let syn::Type::Reference(r) = &**rtype {
306                                                 // We have to do quite a dance for trait functions which return references
307                                                 // - they ultimately require us to have a native Rust object stored inside
308                                                 // our concrete trait to return a reference to. However, users may wish to
309                                                 // update the value to be returned each time the function is called (or, to
310                                                 // make C copies of Rust impls equivalent, we have to be able to).
311                                                 //
312                                                 // Thus, we store a copy of the C-mapped type (which is just a pointer to
313                                                 // the Rust type and a flag to indicate whether deallocation needs to
314                                                 // happen) as well as provide an Option<>al function pointer which is
315                                                 // called when the trait method is called which allows updating on the fly.
316                                                 write!(w, "\tpub {}: ", m.sig.ident).unwrap();
317                                                 generated_fields.push(format!("{}", m.sig.ident));
318                                                 types.write_c_type(w, &*r.elem, Some(&gen_types), false);
319                                                 writeln!(w, ",").unwrap();
320                                                 writeln!(w, "\t/// Fill in the {} field as a reference to it will be given to Rust after this returns", m.sig.ident).unwrap();
321                                                 writeln!(w, "\t/// Note that this takes a pointer to this object, not the this_ptr like other methods do").unwrap();
322                                                 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();
323                                                 writeln!(w, "\tpub set_{}: Option<extern \"C\" fn(&{})>,", m.sig.ident, trait_name).unwrap();
324                                                 generated_fields.push(format!("set_{}", m.sig.ident));
325                                                 // Note that cbindgen will now generate
326                                                 // typedef struct Thing {..., set_thing: (const Thing*), ...} Thing;
327                                                 // which does not compile since Thing is not defined before it is used.
328                                                 writeln!(extra_headers, "struct LDK{};", trait_name).unwrap();
329                                                 writeln!(extra_headers, "typedef struct LDK{} LDK{};", trait_name, trait_name).unwrap();
330                                                 gen_types.pop_ctx();
331                                                 continue;
332                                         }
333                                         // Sadly, this currently doesn't do what we want, but it should be easy to get
334                                         // cbindgen to support it. See https://github.com/eqrion/cbindgen/issues/531
335                                         writeln!(w, "\t#[must_use]").unwrap();
336                                 }
337
338                                 write!(w, "\tpub {}: extern \"C\" fn (", m.sig.ident).unwrap();
339                                 generated_fields.push(format!("{}", m.sig.ident));
340                                 write_method_params(w, &m.sig, "c_void", types, Some(&gen_types), true, false);
341                                 writeln!(w, ",").unwrap();
342
343                                 gen_types.pop_ctx();
344                         },
345                         &syn::TraitItem::Type(_) => {},
346                         _ => unimplemented!(),
347                 }
348         }
349         // Add functions which may be required for supertrait implementations.
350         walk_supertraits!(t, Some(&types), (
351                 ("Clone", _) => {
352                         writeln!(w, "\t/// Creates a copy of the object pointed to by this_arg, for a copy of this {}.", trait_name).unwrap();
353                         writeln!(w, "\t/// Note that the ultimate copy of the {} will have all function pointers the same as the original.", trait_name).unwrap();
354                         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();
355                         writeln!(w, "\tpub clone: Option<extern \"C\" fn (this_arg: *const c_void) -> *mut c_void>,").unwrap();
356                         generated_fields.push("clone".to_owned());
357                 },
358                 ("std::cmp::Eq", _) => {
359                         writeln!(w, "\t/// Checks if two objects are equal given this object's this_arg pointer and another object.").unwrap();
360                         writeln!(w, "\tpub eq: extern \"C\" fn (this_arg: *const c_void, other_arg: &{}) -> bool,", trait_name).unwrap();
361                         writeln!(extra_headers, "typedef struct LDK{} LDK{};", trait_name, trait_name).unwrap();
362                         generated_fields.push("eq".to_owned());
363                 },
364                 ("std::hash::Hash", _) => {
365                         writeln!(w, "\t/// Calculate a succinct non-cryptographic hash for an object given its this_arg pointer.").unwrap();
366                         writeln!(w, "\t/// This is used, for example, for inclusion of this object in a hash map.").unwrap();
367                         writeln!(w, "\tpub hash: extern \"C\" fn (this_arg: *const c_void) -> u64,").unwrap();
368                         generated_fields.push("hash".to_owned());
369                 },
370                 ("Send", _) => {}, ("Sync", _) => {},
371                 (s, i) => {
372                         generated_fields.push(if types.crate_types.traits.get(s).is_none() {
373                                 let (docs, name, ret) = convert_trait_impl_field(s);
374                                 writeln!(w, "\t/// {}", docs).unwrap();
375                                 writeln!(w, "\tpub {}: extern \"C\" fn (this_arg: *const c_void) -> {},", name, ret).unwrap();
376                                 name
377                         } else {
378                                 // For in-crate supertraits, just store a C-mapped copy of the supertrait as a member.
379                                 writeln!(w, "/// Implementation of {} for this object.", i).unwrap();
380                                 writeln!(w, "\tpub {}: crate::{},", i, s).unwrap();
381                                 format!("{}", i)
382                         });
383                 }
384         ) );
385         writeln!(w, "\t/// Frees any resources associated with this object given its this_arg pointer.").unwrap();
386         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();
387         writeln!(w, "\tpub free: Option<extern \"C\" fn(this_arg: *mut c_void)>,").unwrap();
388         generated_fields.push("free".to_owned());
389         writeln!(w, "}}").unwrap();
390         // Implement supertraits for the C-mapped struct.
391         walk_supertraits!(t, Some(&types), (
392                 ("Send", _) => writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap(),
393                 ("Sync", _) => writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap(),
394                 ("std::cmp::Eq", _) => {
395                         writeln!(w, "impl std::cmp::Eq for {} {{}}", trait_name).unwrap();
396                         writeln!(w, "impl std::cmp::PartialEq for {} {{", trait_name).unwrap();
397                         writeln!(w, "\tfn eq(&self, o: &Self) -> bool {{ (self.eq)(self.this_arg, o) }}\n}}").unwrap();
398                 },
399                 ("std::hash::Hash", _) => {
400                         writeln!(w, "impl std::hash::Hash for {} {{", trait_name).unwrap();
401                         writeln!(w, "\tfn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {{ hasher.write_u64((self.hash)(self.this_arg)) }}\n}}").unwrap();
402                 },
403                 ("Clone", _) => {
404                         writeln!(w, "#[no_mangle]").unwrap();
405                         writeln!(w, "/// Creates a copy of a {}", trait_name).unwrap();
406                         writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", trait_name, trait_name, trait_name).unwrap();
407                         writeln!(w, "\t{} {{", trait_name).unwrap();
408                         writeln!(w, "\t\tthis_arg: if let Some(f) = orig.clone {{ (f)(orig.this_arg) }} else {{ orig.this_arg }},").unwrap();
409                         for field in generated_fields.iter() {
410                                 writeln!(w, "\t\t{}: orig.{}.clone(),", field, field).unwrap();
411                         }
412                         writeln!(w, "\t}}\n}}").unwrap();
413                         writeln!(w, "impl Clone for {} {{", trait_name).unwrap();
414                         writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
415                         writeln!(w, "\t\t{}_clone(self)", trait_name).unwrap();
416                         writeln!(w, "\t}}\n}}").unwrap();
417                 },
418                 (s, i) => {
419                         do_write_impl_trait(w, s, i, &trait_name);
420                 }
421         ) );
422
423         // Finally, implement the original Rust trait for the newly created mapped trait.
424         writeln!(w, "\nuse {}::{}::{} as rust{};", types.orig_crate, types.module_path, t.ident, trait_name).unwrap();
425         write!(w, "impl rust{}", t.ident).unwrap();
426         maybe_write_generics(w, &t.generics, types, false);
427         writeln!(w, " for {} {{", trait_name).unwrap();
428         for item in t.items.iter() {
429                 match item {
430                         syn::TraitItem::Method(m) => {
431                                 if let ExportStatus::TestOnly = export_status(&m.attrs) { continue; }
432                                 if m.default.is_some() { unimplemented!(); }
433                                 if m.sig.constness.is_some() || m.sig.asyncness.is_some() || m.sig.unsafety.is_some() ||
434                                                 m.sig.abi.is_some() || m.sig.variadic.is_some() {
435                                         unimplemented!();
436                                 }
437                                 gen_types.push_ctx();
438                                 assert!(gen_types.learn_generics(&m.sig.generics, types));
439                                 write!(w, "\tfn {}", m.sig.ident).unwrap();
440                                 types.write_rust_generic_param(w, Some(&gen_types), m.sig.generics.params.iter());
441                                 write!(w, "(").unwrap();
442                                 for inp in m.sig.inputs.iter() {
443                                         match inp {
444                                                 syn::FnArg::Receiver(recv) => {
445                                                         if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
446                                                         write!(w, "&").unwrap();
447                                                         if let Some(lft) = &recv.reference.as_ref().unwrap().1 {
448                                                                 write!(w, "'{} ", lft.ident).unwrap();
449                                                         }
450                                                         if recv.mutability.is_some() {
451                                                                 write!(w, "mut self").unwrap();
452                                                         } else {
453                                                                 write!(w, "self").unwrap();
454                                                         }
455                                                 },
456                                                 syn::FnArg::Typed(arg) => {
457                                                         if !arg.attrs.is_empty() { unimplemented!(); }
458                                                         match &*arg.pat {
459                                                                 syn::Pat::Ident(ident) => {
460                                                                         if !ident.attrs.is_empty() || ident.by_ref.is_some() ||
461                                                                                         ident.mutability.is_some() || ident.subpat.is_some() {
462                                                                                 unimplemented!();
463                                                                         }
464                                                                         write!(w, ", {}{}: ", if types.skip_arg(&*arg.ty, Some(&gen_types)) { "_" } else { "" }, ident.ident).unwrap();
465                                                                 }
466                                                                 _ => unimplemented!(),
467                                                         }
468                                                         types.write_rust_type(w, Some(&gen_types), &*arg.ty);
469                                                 }
470                                         }
471                                 }
472                                 write!(w, ")").unwrap();
473                                 match &m.sig.output {
474                                         syn::ReturnType::Type(_, rtype) => {
475                                                 write!(w, " -> ").unwrap();
476                                                 types.write_rust_type(w, Some(&gen_types), &*rtype)
477                                         },
478                                         _ => {},
479                                 }
480                                 write!(w, " {{\n\t\t").unwrap();
481                                 match export_status(&m.attrs) {
482                                         ExportStatus::NoExport => {
483                                                 unimplemented!();
484                                         },
485                                         _ => {},
486                                 }
487                                 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
488                                         if let syn::Type::Reference(r) = &**rtype {
489                                                 assert_eq!(m.sig.inputs.len(), 1); // Must only take self!
490                                                 writeln!(w, "if let Some(f) = self.set_{} {{", m.sig.ident).unwrap();
491                                                 writeln!(w, "\t\t\t(f)(self);").unwrap();
492                                                 write!(w, "\t\t}}\n\t\t").unwrap();
493                                                 types.write_from_c_conversion_to_ref_prefix(w, &*r.elem, Some(&gen_types));
494                                                 write!(w, "self.{}", m.sig.ident).unwrap();
495                                                 types.write_from_c_conversion_to_ref_suffix(w, &*r.elem, Some(&gen_types));
496                                                 writeln!(w, "\n\t}}").unwrap();
497                                                 gen_types.pop_ctx();
498                                                 continue;
499                                         }
500                                 }
501                                 write_method_var_decl_body(w, &m.sig, "\t", types, Some(&gen_types), true);
502                                 write!(w, "(self.{})(", m.sig.ident).unwrap();
503                                 write_method_call_params(w, &m.sig, "\t", types, Some(&gen_types), "", true);
504
505                                 writeln!(w, "\n\t}}").unwrap();
506                                 gen_types.pop_ctx();
507                         },
508                         &syn::TraitItem::Type(ref t) => {
509                                 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
510                                 let mut bounds_iter = t.bounds.iter();
511                                 match bounds_iter.next().unwrap() {
512                                         syn::TypeParamBound::Trait(tr) => {
513                                                 writeln!(w, "\ttype {} = crate::{};", t.ident, types.resolve_path(&tr.path, Some(&gen_types))).unwrap();
514                                         },
515                                         _ => unimplemented!(),
516                                 }
517                                 if bounds_iter.next().is_some() { unimplemented!(); }
518                         },
519                         _ => unimplemented!(),
520                 }
521         }
522         writeln!(w, "}}\n").unwrap();
523         writeln!(w, "// We're essentially a pointer already, or at least a set of pointers, so allow us to be used").unwrap();
524         writeln!(w, "// directly as a Deref trait in higher-level structs:").unwrap();
525         writeln!(w, "impl std::ops::Deref for {} {{\n\ttype Target = Self;", trait_name).unwrap();
526         writeln!(w, "\tfn deref(&self) -> &Self {{\n\t\tself\n\t}}\n}}").unwrap();
527
528         writeln!(w, "/// Calls the free function if one is set").unwrap();
529         writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", trait_name, trait_name).unwrap();
530         writeln!(w, "impl Drop for {} {{", trait_name).unwrap();
531         writeln!(w, "\tfn drop(&mut self) {{").unwrap();
532         writeln!(w, "\t\tif let Some(f) = self.free {{").unwrap();
533         writeln!(w, "\t\t\tf(self.this_arg);").unwrap();
534         writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
535
536         write_cpp_wrapper(cpp_headers, &trait_name, true);
537 }
538
539 /// Write out a simple "opaque" type (eg structs) which contain a pointer to the native Rust type
540 /// and a flag to indicate whether Drop'ing the mapped struct drops the underlying Rust type.
541 ///
542 /// Also writes out a _free function and a C++ wrapper which handles calling _free.
543 fn writeln_opaque<W: std::io::Write>(w: &mut W, ident: &syn::Ident, struct_name: &str, generics: &syn::Generics, attrs: &[syn::Attribute], types: &TypeResolver, extra_headers: &mut File, cpp_headers: &mut File) {
544         // If we directly read the original type by its original name, cbindgen hits
545         // https://github.com/eqrion/cbindgen/issues/286 Thus, instead, we import it as a temporary
546         // name and then reference it by that name, which works around the issue.
547         write!(w, "\nuse {}::{}::{} as native{}Import;\ntype native{} = native{}Import", types.orig_crate, types.module_path, ident, ident, ident, ident).unwrap();
548         maybe_write_generics(w, &generics, &types, true);
549         writeln!(w, ";\n").unwrap();
550         writeln!(extra_headers, "struct native{}Opaque;\ntypedef struct native{}Opaque LDKnative{};", ident, ident, ident).unwrap();
551         writeln_docs(w, &attrs, "");
552         writeln!(w, "#[must_use]\n#[repr(C)]\npub struct {} {{", struct_name).unwrap();
553         writeln!(w, "\t/// A pointer to the opaque Rust object.\n").unwrap();
554         writeln!(w, "\t/// Nearly everywhere, inner must be non-null, however in places where").unwrap();
555         writeln!(w, "\t/// the Rust equivalent takes an Option, it may be set to null to indicate None.").unwrap();
556         writeln!(w, "\tpub inner: *mut native{},", ident).unwrap();
557         writeln!(w, "\t/// Indicates that this is the only struct which contains the same pointer.\n").unwrap();
558         writeln!(w, "\t/// Rust functions which take ownership of an object provided via an argument require").unwrap();
559         writeln!(w, "\t/// this to be true and invalidate the object pointed to by inner.").unwrap();
560         writeln!(w, "\tpub is_owned: bool,").unwrap();
561         writeln!(w, "}}\n").unwrap();
562         writeln!(w, "impl Drop for {} {{\n\tfn drop(&mut self) {{", struct_name).unwrap();
563         writeln!(w, "\t\tif self.is_owned && !<*mut native{}>::is_null(self.inner) {{", ident).unwrap();
564         writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(self.inner) }};\n\t\t}}\n\t}}\n}}").unwrap();
565         writeln!(w, "/// Frees any resources used by the {}, if is_owned is set and inner is non-NULL.", struct_name).unwrap();
566         writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_obj: {}) {{ }}", struct_name, struct_name).unwrap();
567         writeln!(w, "#[allow(unused)]").unwrap();
568         writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
569         writeln!(w, "extern \"C\" fn {}_free_void(this_ptr: *mut c_void) {{", struct_name).unwrap();
570         writeln!(w, "\tunsafe {{ let _ = Box::from_raw(this_ptr as *mut native{}); }}\n}}", struct_name).unwrap();
571         writeln!(w, "#[allow(unused)]").unwrap();
572         writeln!(w, "/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy").unwrap();
573         writeln!(w, "impl {} {{", struct_name).unwrap();
574         writeln!(w, "\tpub(crate) fn take_inner(mut self) -> *mut native{} {{", struct_name).unwrap();
575         writeln!(w, "\t\tassert!(self.is_owned);").unwrap();
576         writeln!(w, "\t\tlet ret = self.inner;").unwrap();
577         writeln!(w, "\t\tself.inner = std::ptr::null_mut();").unwrap();
578         writeln!(w, "\t\tret").unwrap();
579         writeln!(w, "\t}}\n}}").unwrap();
580
581         write_cpp_wrapper(cpp_headers, &format!("{}", ident), true);
582 }
583
584 /// Writes out all the relevant mappings for a Rust struct, deferring to writeln_opaque to generate
585 /// the struct itself, and then writing getters and setters for public, understood-type fields and
586 /// a constructor if every field is public.
587 fn writeln_struct<'a, 'b, W: std::io::Write>(w: &mut W, s: &'a syn::ItemStruct, types: &mut TypeResolver<'b, 'a>, extra_headers: &mut File, cpp_headers: &mut File) {
588         if export_status(&s.attrs) != ExportStatus::Export { return; }
589
590         let struct_name = &format!("{}", s.ident);
591         writeln_opaque(w, &s.ident, struct_name, &s.generics, &s.attrs, types, extra_headers, cpp_headers);
592
593         if let syn::Fields::Named(fields) = &s.fields {
594                 let mut gen_types = GenericTypes::new();
595                 assert!(gen_types.learn_generics(&s.generics, types));
596
597                 let mut all_fields_settable = true;
598                 for field in fields.named.iter() {
599                         if let syn::Visibility::Public(_) = field.vis {
600                                 let export = export_status(&field.attrs);
601                                 match export {
602                                         ExportStatus::Export => {},
603                                         ExportStatus::NoExport|ExportStatus::TestOnly => {
604                                                 all_fields_settable = false;
605                                                 continue
606                                         },
607                                 }
608
609                                 if let Some(ident) = &field.ident {
610                                         let ref_type = syn::Type::Reference(syn::TypeReference {
611                                                 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
612                                                 elem: Box::new(field.ty.clone()) });
613                                         if types.understood_c_type(&ref_type, Some(&gen_types)) {
614                                                 writeln_docs(w, &field.attrs, "");
615                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> ", struct_name, ident, struct_name).unwrap();
616                                                 types.write_c_type(w, &ref_type, Some(&gen_types), true);
617                                                 write!(w, " {{\n\tlet mut inner_val = &mut unsafe {{ &mut *this_ptr.inner }}.{};\n\t", ident).unwrap();
618                                                 let local_var = types.write_to_c_conversion_new_var(w, &syn::Ident::new("inner_val", Span::call_site()), &ref_type, Some(&gen_types), true);
619                                                 if local_var { write!(w, "\n\t").unwrap(); }
620                                                 types.write_to_c_conversion_inline_prefix(w, &ref_type, Some(&gen_types), true);
621                                                 if local_var {
622                                                         write!(w, "inner_val").unwrap();
623                                                 } else {
624                                                         write!(w, "(*inner_val)").unwrap();
625                                                 }
626                                                 types.write_to_c_conversion_inline_suffix(w, &ref_type, Some(&gen_types), true);
627                                                 writeln!(w, "\n}}").unwrap();
628                                         }
629
630                                         if types.understood_c_type(&field.ty, Some(&gen_types)) {
631                                                 writeln_docs(w, &field.attrs, "");
632                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_set_{}(this_ptr: &mut {}, mut val: ", struct_name, ident, struct_name).unwrap();
633                                                 types.write_c_type(w, &field.ty, Some(&gen_types), false);
634                                                 write!(w, ") {{\n\t").unwrap();
635                                                 let local_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("val", Span::call_site()), &field.ty, Some(&gen_types));
636                                                 if local_var { write!(w, "\n\t").unwrap(); }
637                                                 write!(w, "unsafe {{ &mut *this_ptr.inner }}.{} = ", ident).unwrap();
638                                                 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
639                                                 write!(w, "val").unwrap();
640                                                 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
641                                                 writeln!(w, ";\n}}").unwrap();
642                                         } else { all_fields_settable = false; }
643                                 } else { all_fields_settable = false; }
644                         } else { all_fields_settable = false; }
645                 }
646
647                 if all_fields_settable {
648                         // Build a constructor!
649                         writeln!(w, "/// Constructs a new {} given each field", struct_name).unwrap();
650                         write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_new(", struct_name).unwrap();
651                         for (idx, field) in fields.named.iter().enumerate() {
652                                 if idx != 0 { write!(w, ", ").unwrap(); }
653                                 write!(w, "mut {}_arg: ", field.ident.as_ref().unwrap()).unwrap();
654                                 types.write_c_type(w, &field.ty, Some(&gen_types), false);
655                         }
656                         write!(w, ") -> {} {{\n\t", struct_name).unwrap();
657                         for field in fields.named.iter() {
658                                 let field_name = format!("{}_arg", field.ident.as_ref().unwrap());
659                                 if types.write_from_c_conversion_new_var(w, &syn::Ident::new(&field_name, Span::call_site()), &field.ty, Some(&gen_types)) {
660                                         write!(w, "\n\t").unwrap();
661                                 }
662                         }
663                         writeln!(w, "{} {{ inner: Box::into_raw(Box::new(native{} {{", struct_name, s.ident).unwrap();
664                         for field in fields.named.iter() {
665                                 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
666                                 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
667                                 write!(w, "{}_arg", field.ident.as_ref().unwrap()).unwrap();
668                                 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
669                                 writeln!(w, ",").unwrap();
670                         }
671                         writeln!(w, "\t}})), is_owned: true }}\n}}").unwrap();
672                 }
673         }
674 }
675
676 /// Prints a relevant conversion for impl *
677 ///
678 /// For simple impl Struct {}s, this just outputs the wrapper functions as Struct_fn_name() { .. }.
679 ///
680 /// For impl Trait for Struct{}s, this non-exported generates wrapper functions as
681 /// Trait_Struct_fn_name and a Struct_as_Trait(&struct) -> Trait function which returns a populated
682 /// Trait struct containing a pointer to the passed struct's inner field and the wrapper functions.
683 ///
684 /// A few non-crate Traits are hard-coded including Default.
685 fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut TypeResolver) {
686         match export_status(&i.attrs) {
687                 ExportStatus::Export => {},
688                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
689         }
690
691         if let syn::Type::Tuple(_) = &*i.self_ty {
692                 if types.understood_c_type(&*i.self_ty, None) {
693                         let mut gen_types = GenericTypes::new();
694                         if !gen_types.learn_generics(&i.generics, types) {
695                                 eprintln!("Not implementing anything for `impl (..)` due to not understood generics");
696                                 return;
697                         }
698
699                         if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
700                         if let Some(trait_path) = i.trait_.as_ref() {
701                                 if trait_path.0.is_some() { unimplemented!(); }
702                                 if types.understood_c_path(&trait_path.1) {
703                                         eprintln!("Not implementing anything for `impl Trait for (..)` - we only support manual defines");
704                                         return;
705                                 } else {
706                                         // Just do a manual implementation:
707                                         maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
708                                 }
709                         } else {
710                                 eprintln!("Not implementing anything for plain `impl (..)` block - we only support `impl Trait for (..)` blocks");
711                                 return;
712                         }
713                 }
714                 return;
715         }
716         if let &syn::Type::Path(ref p) = &*i.self_ty {
717                 if p.qself.is_some() { unimplemented!(); }
718                 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
719                         if let Some(resolved_path) = types.maybe_resolve_non_ignored_ident(&ident) {
720                                 let mut gen_types = GenericTypes::new();
721                                 if !gen_types.learn_generics(&i.generics, types) {
722                                         eprintln!("Not implementing anything for impl {} due to not understood generics", ident);
723                                         return;
724                                 }
725
726                                 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
727                                 if let Some(trait_path) = i.trait_.as_ref() {
728                                         if trait_path.0.is_some() { unimplemented!(); }
729                                         if types.understood_c_path(&trait_path.1) {
730                                                 let full_trait_path = types.resolve_path(&trait_path.1, None);
731                                                 let trait_obj = *types.crate_types.traits.get(&full_trait_path).unwrap();
732                                                 // We learn the associated types maping from the original trait object.
733                                                 // That's great, except that they are unresolved idents, so if we learn
734                                                 // mappings from a trai defined in a different file, we may mis-resolve or
735                                                 // fail to resolve the mapped types.
736                                                 gen_types.learn_associated_types(trait_obj, types);
737                                                 let mut impl_associated_types = HashMap::new();
738                                                 for item in i.items.iter() {
739                                                         match item {
740                                                                 syn::ImplItem::Type(t) => {
741                                                                         if let syn::Type::Path(p) = &t.ty {
742                                                                                 if let Some(id) = single_ident_generic_path_to_ident(&p.path) {
743                                                                                         impl_associated_types.insert(&t.ident, id);
744                                                                                 }
745                                                                         }
746                                                                 },
747                                                                 _ => {},
748                                                         }
749                                                 }
750
751                                                 let export = export_status(&trait_obj.attrs);
752                                                 match export {
753                                                         ExportStatus::Export => {},
754                                                         ExportStatus::NoExport|ExportStatus::TestOnly => return,
755                                                 }
756
757                                                 // For cases where we have a concrete native object which implements a
758                                                 // trait and need to return the C-mapped version of the trait, provide a
759                                                 // From<> implementation which does all the work to ensure free is handled
760                                                 // properly. This way we can call this method from deep in the
761                                                 // type-conversion logic without actually knowing the concrete native type.
762                                                 writeln!(w, "impl From<native{}> for crate::{} {{", ident, full_trait_path).unwrap();
763                                                 writeln!(w, "\tfn from(obj: native{}) -> Self {{", ident).unwrap();
764                                                 writeln!(w, "\t\tlet mut rust_obj = {} {{ inner: Box::into_raw(Box::new(obj)), is_owned: true }};", ident).unwrap();
765                                                 writeln!(w, "\t\tlet mut ret = {}_as_{}(&rust_obj);", ident, trait_obj.ident).unwrap();
766                                                 writeln!(w, "\t\t// We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn").unwrap();
767                                                 writeln!(w, "\t\trust_obj.inner = std::ptr::null_mut();").unwrap();
768                                                 writeln!(w, "\t\tret.free = Some({}_free_void);", ident).unwrap();
769                                                 writeln!(w, "\t\tret\n\t}}\n}}").unwrap();
770
771                                                 writeln!(w, "/// Constructs a new {} which calls the relevant methods on this_arg.", trait_obj.ident).unwrap();
772                                                 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();
773                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_as_{}(this_arg: &{}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
774                                                 writeln!(w, "\tcrate::{} {{", full_trait_path).unwrap();
775                                                 writeln!(w, "\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
776                                                 writeln!(w, "\t\tfree: None,").unwrap();
777
778                                                 macro_rules! write_meth {
779                                                         ($m: expr, $trait: expr, $indent: expr) => {
780                                                                 let trait_method = $trait.items.iter().filter_map(|item| {
781                                                                         if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
782                                                                 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
783                                                                 match export_status(&trait_method.attrs) {
784                                                                         ExportStatus::Export => {},
785                                                                         ExportStatus::NoExport => {
786                                                                                 write!(w, "{}\t\t//XXX: Need to export {}\n", $indent, $m.sig.ident).unwrap();
787                                                                                 continue;
788                                                                         },
789                                                                         ExportStatus::TestOnly => continue,
790                                                                 }
791
792                                                                 let mut printed = false;
793                                                                 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
794                                                                         if let syn::Type::Reference(r) = &**rtype {
795                                                                                 write!(w, "\n\t\t{}{}: ", $indent, $m.sig.ident).unwrap();
796                                                                                 types.write_empty_rust_val(Some(&gen_types), w, &*r.elem);
797                                                                                 writeln!(w, ",\n{}\t\tset_{}: Some({}_{}_set_{}),", $indent, $m.sig.ident, ident, trait_obj.ident, $m.sig.ident).unwrap();
798                                                                                 printed = true;
799                                                                         }
800                                                                 }
801                                                                 if !printed {
802                                                                         write!(w, "{}\t\t{}: {}_{}_{},\n", $indent, $m.sig.ident, ident, trait_obj.ident, $m.sig.ident).unwrap();
803                                                                 }
804                                                         }
805                                                 }
806                                                 for item in trait_obj.items.iter() {
807                                                         match item {
808                                                                 syn::TraitItem::Method(m) => {
809                                                                         write_meth!(m, trait_obj, "");
810                                                                 },
811                                                                 _ => {},
812                                                         }
813                                                 }
814                                                 walk_supertraits!(trait_obj, Some(&types), (
815                                                         ("Clone", _) => {
816                                                                 writeln!(w, "\t\tclone: Some({}_clone_void),", ident).unwrap();
817                                                         },
818                                                         ("Sync", _) => {}, ("Send", _) => {},
819                                                         ("std::marker::Sync", _) => {}, ("std::marker::Send", _) => {},
820                                                         (s, t) => {
821                                                                 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
822                                                                         writeln!(w, "\t\t{}: crate::{} {{", t, s).unwrap();
823                                                                         writeln!(w, "\t\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
824                                                                         writeln!(w, "\t\t\tfree: None,").unwrap();
825                                                                         for item in supertrait_obj.items.iter() {
826                                                                                 match item {
827                                                                                         syn::TraitItem::Method(m) => {
828                                                                                                 write_meth!(m, supertrait_obj, "\t");
829                                                                                         },
830                                                                                         _ => {},
831                                                                                 }
832                                                                         }
833                                                                         write!(w, "\t\t}},\n").unwrap();
834                                                                 } else {
835                                                                         write_trait_impl_field_assign(w, s, ident);
836                                                                 }
837                                                         }
838                                                 ) );
839                                                 writeln!(w, "\t}}\n}}\n").unwrap();
840
841                                                 macro_rules! impl_meth {
842                                                         ($m: expr, $trait_path: expr, $trait: expr, $indent: expr) => {
843                                                                 let trait_method = $trait.items.iter().filter_map(|item| {
844                                                                         if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
845                                                                 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
846                                                                 match export_status(&trait_method.attrs) {
847                                                                         ExportStatus::Export => {},
848                                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
849                                                                 }
850
851                                                                 if let syn::ReturnType::Type(_, _) = &$m.sig.output {
852                                                                         writeln!(w, "#[must_use]").unwrap();
853                                                                 }
854                                                                 write!(w, "extern \"C\" fn {}_{}_{}(", ident, trait_obj.ident, $m.sig.ident).unwrap();
855                                                                 gen_types.push_ctx();
856                                                                 assert!(gen_types.learn_generics(&$m.sig.generics, types));
857                                                                 write_method_params(w, &$m.sig, "c_void", types, Some(&gen_types), true, true);
858                                                                 write!(w, " {{\n\t").unwrap();
859                                                                 write_method_var_decl_body(w, &$m.sig, "", types, Some(&gen_types), false);
860                                                                 let mut takes_self = false;
861                                                                 for inp in $m.sig.inputs.iter() {
862                                                                         if let syn::FnArg::Receiver(_) = inp {
863                                                                                 takes_self = true;
864                                                                         }
865                                                                 }
866
867                                                                 let mut t_gen_args = String::new();
868                                                                 for (idx, _) in $trait.generics.params.iter().enumerate() {
869                                                                         if idx != 0 { t_gen_args += ", " };
870                                                                         t_gen_args += "_"
871                                                                 }
872                                                                 if takes_self {
873                                                                         write!(w, "<native{} as {}::{}<{}>>::{}(unsafe {{ &mut *(this_arg as *mut native{}) }}, ", ident, types.orig_crate, $trait_path, t_gen_args, $m.sig.ident, ident).unwrap();
874                                                                 } else {
875                                                                         write!(w, "<native{} as {}::{}<{}>>::{}(", ident, types.orig_crate, $trait_path, t_gen_args, $m.sig.ident).unwrap();
876                                                                 }
877
878                                                                 let mut real_type = "".to_string();
879                                                                 match &$m.sig.output {
880                                                                         syn::ReturnType::Type(_, rtype) => {
881                                                                                 if let Some(mut remaining_path) = first_seg_self(&*rtype) {
882                                                                                         if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
883                                                                                                 real_type = format!("{}", impl_associated_types.get(associated_seg).unwrap());
884                                                                                         }
885                                                                                 }
886                                                                         },
887                                                                         _ => {},
888                                                                 }
889                                                                 write_method_call_params(w, &$m.sig, "", types, Some(&gen_types), &real_type, false);
890                                                                 gen_types.pop_ctx();
891                                                                 write!(w, "\n}}\n").unwrap();
892                                                                 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
893                                                                         if let syn::Type::Reference(r) = &**rtype {
894                                                                                 assert_eq!($m.sig.inputs.len(), 1); // Must only take self
895                                                                                 writeln!(w, "extern \"C\" fn {}_{}_set_{}(trait_self_arg: &{}) {{", ident, trait_obj.ident, $m.sig.ident, trait_obj.ident).unwrap();
896                                                                                 writeln!(w, "\t// This is a bit race-y in the general case, but for our specific use-cases today, we're safe").unwrap();
897                                                                                 writeln!(w, "\t// Specifically, we must ensure that the first time we're called it can never be in parallel").unwrap();
898                                                                                 write!(w, "\tif ").unwrap();
899                                                                                 types.write_empty_rust_val_check(Some(&gen_types), w, &*r.elem, &format!("trait_self_arg.{}", $m.sig.ident));
900                                                                                 writeln!(w, " {{").unwrap();
901                                                                                 writeln!(w, "\t\tunsafe {{ &mut *(trait_self_arg as *const {}  as *mut {}) }}.{} = {}_{}_{}(trait_self_arg.this_arg);", trait_obj.ident, trait_obj.ident, $m.sig.ident, ident, trait_obj.ident, $m.sig.ident).unwrap();
902                                                                                 writeln!(w, "\t}}").unwrap();
903                                                                                 writeln!(w, "}}").unwrap();
904                                                                         }
905                                                                 }
906                                                         }
907                                                 }
908
909                                                 for item in i.items.iter() {
910                                                         match item {
911                                                                 syn::ImplItem::Method(m) => {
912                                                                         impl_meth!(m, full_trait_path, trait_obj, "");
913                                                                 },
914                                                                 syn::ImplItem::Type(_) => {},
915                                                                 _ => unimplemented!(),
916                                                         }
917                                                 }
918                                                 walk_supertraits!(trait_obj, Some(&types), (
919                                                         (s, _) => {
920                                                                 if let Some(supertrait_obj) = types.crate_types.traits.get(s).cloned() {
921                                                                         for item in supertrait_obj.items.iter() {
922                                                                                 match item {
923                                                                                         syn::TraitItem::Method(m) => {
924                                                                                                 impl_meth!(m, s, supertrait_obj, "\t");
925                                                                                         },
926                                                                                         _ => {},
927                                                                                 }
928                                                                         }
929                                                                 }
930                                                         }
931                                                 ) );
932                                                 write!(w, "\n").unwrap();
933                                         } else if path_matches_nongeneric(&trait_path.1, &["From"]) {
934                                         } else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
935                                                 writeln!(w, "/// Creates a \"default\" {}. See struct and individual field documentaiton for details on which values are used.", ident).unwrap();
936                                                 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
937                                                 write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
938                                                 write!(w, "}}\n").unwrap();
939                                         } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "PartialEq"]) {
940                                         } else if (path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) || path_matches_nongeneric(&trait_path.1, &["Clone"])) &&
941                                                         types.c_type_has_inner_from_path(&resolved_path) {
942                                                 writeln!(w, "impl Clone for {} {{", ident).unwrap();
943                                                 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
944                                                 writeln!(w, "\t\tSelf {{").unwrap();
945                                                 writeln!(w, "\t\t\tinner: if <*mut native{}>::is_null(self.inner) {{ std::ptr::null_mut() }} else {{", ident).unwrap();
946                                                 writeln!(w, "\t\t\t\tBox::into_raw(Box::new(unsafe {{ &*self.inner }}.clone())) }},").unwrap();
947                                                 writeln!(w, "\t\t\tis_owned: true,").unwrap();
948                                                 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
949                                                 writeln!(w, "#[allow(unused)]").unwrap();
950                                                 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
951                                                 writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", ident).unwrap();
952                                                 writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", ident).unwrap();
953                                                 writeln!(w, "}}").unwrap();
954                                                 writeln!(w, "#[no_mangle]").unwrap();
955                                                 writeln!(w, "/// Creates a copy of the {}", ident).unwrap();
956                                                 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", ident, ident, ident).unwrap();
957                                                 writeln!(w, "\torig.clone()").unwrap();
958                                                 writeln!(w, "}}").unwrap();
959                                         } else {
960                                                 //XXX: implement for other things like ToString
961                                                 // If we have no generics, try a manual implementation:
962                                                 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
963                                         }
964                                 } else {
965                                         let declared_type = (*types.get_declared_type(&ident).unwrap()).clone();
966                                         for item in i.items.iter() {
967                                                 match item {
968                                                         syn::ImplItem::Method(m) => {
969                                                                 if let syn::Visibility::Public(_) = m.vis {
970                                                                         match export_status(&m.attrs) {
971                                                                                 ExportStatus::Export => {},
972                                                                                 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
973                                                                         }
974                                                                         if m.defaultness.is_some() { unimplemented!(); }
975                                                                         writeln_docs(w, &m.attrs, "");
976                                                                         if let syn::ReturnType::Type(_, _) = &m.sig.output {
977                                                                                 writeln!(w, "#[must_use]").unwrap();
978                                                                         }
979                                                                         write!(w, "#[no_mangle]\npub extern \"C\" fn {}_{}(", ident, m.sig.ident).unwrap();
980                                                                         let ret_type = match &declared_type {
981                                                                                 DeclType::MirroredEnum => format!("{}", ident),
982                                                                                 DeclType::StructImported => format!("{}", ident),
983                                                                                 _ => unimplemented!(),
984                                                                         };
985                                                                         gen_types.push_ctx();
986                                                                         assert!(gen_types.learn_generics(&m.sig.generics, types));
987                                                                         write_method_params(w, &m.sig, &ret_type, types, Some(&gen_types), false, true);
988                                                                         write!(w, " {{\n\t").unwrap();
989                                                                         write_method_var_decl_body(w, &m.sig, "", types, Some(&gen_types), false);
990                                                                         let mut takes_self = false;
991                                                                         let mut takes_mut_self = false;
992                                                                         for inp in m.sig.inputs.iter() {
993                                                                                 if let syn::FnArg::Receiver(r) = inp {
994                                                                                         takes_self = true;
995                                                                                         if r.mutability.is_some() { takes_mut_self = true; }
996                                                                                 }
997                                                                         }
998                                                                         if takes_mut_self {
999                                                                                 write!(w, "unsafe {{ &mut (*(this_arg.inner as *mut native{})) }}.{}(", ident, m.sig.ident).unwrap();
1000                                                                         } else if takes_self {
1001                                                                                 write!(w, "unsafe {{ &*this_arg.inner }}.{}(", m.sig.ident).unwrap();
1002                                                                         } else {
1003                                                                                 write!(w, "{}::{}::{}(", types.orig_crate, resolved_path, m.sig.ident).unwrap();
1004                                                                         }
1005                                                                         write_method_call_params(w, &m.sig, "", types, Some(&gen_types), &ret_type, false);
1006                                                                         gen_types.pop_ctx();
1007                                                                         writeln!(w, "\n}}\n").unwrap();
1008                                                                 }
1009                                                         },
1010                                                         _ => {},
1011                                                 }
1012                                         }
1013                                 }
1014                         } else if let Some(resolved_path) = types.maybe_resolve_ident(&ident) {
1015                                 if let Some(aliases) = types.crate_types.reverse_alias_map.get(&resolved_path).cloned() {
1016                                         'alias_impls: for (alias, arguments) in aliases {
1017                                                 let alias_resolved = types.resolve_path(&alias, None);
1018                                                 for (idx, gen) in i.generics.params.iter().enumerate() {
1019                                                         match gen {
1020                                                                 syn::GenericParam::Type(type_param) => {
1021                                                                         'bounds_check: for bound in type_param.bounds.iter() {
1022                                                                                 if let syn::TypeParamBound::Trait(trait_bound) = bound {
1023                                                                                         if let syn::PathArguments::AngleBracketed(ref t) = &arguments {
1024                                                                                                 assert!(idx < t.args.len());
1025                                                                                                 if let syn::GenericArgument::Type(syn::Type::Path(p)) = &t.args[idx] {
1026                                                                                                         let generic_arg = types.resolve_path(&p.path, None);
1027                                                                                                         let generic_bound = types.resolve_path(&trait_bound.path, None);
1028                                                                                                         if let Some(traits_impld) = types.crate_types.trait_impls.get(&generic_arg) {
1029                                                                                                                 for trait_impld in traits_impld {
1030                                                                                                                         if *trait_impld == generic_bound { continue 'bounds_check; }
1031                                                                                                                 }
1032                                                                                                                 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1033                                                                                                                 continue 'alias_impls;
1034                                                                                                         } else {
1035                                                                                                                 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1036                                                                                                                 continue 'alias_impls;
1037                                                                                                         }
1038                                                                                                 } else { unimplemented!(); }
1039                                                                                         } else { unimplemented!(); }
1040                                                                                 } else { unimplemented!(); }
1041                                                                         }
1042                                                                 },
1043                                                                 syn::GenericParam::Lifetime(_) => {},
1044                                                                 syn::GenericParam::Const(_) => unimplemented!(),
1045                                                         }
1046                                                 }
1047                                                 let aliased_impl = syn::ItemImpl {
1048                                                         attrs: i.attrs.clone(),
1049                                                         brace_token: syn::token::Brace(Span::call_site()),
1050                                                         defaultness: None,
1051                                                         generics: syn::Generics {
1052                                                                 lt_token: None,
1053                                                                 params: syn::punctuated::Punctuated::new(),
1054                                                                 gt_token: None,
1055                                                                 where_clause: None,
1056                                                         },
1057                                                         impl_token: syn::Token![impl](Span::call_site()),
1058                                                         items: i.items.clone(),
1059                                                         self_ty: Box::new(syn::Type::Path(syn::TypePath { qself: None, path: alias.clone() })),
1060                                                         trait_: i.trait_.clone(),
1061                                                         unsafety: None,
1062                                                 };
1063                                                 writeln_impl(w, &aliased_impl, types);
1064                                         }
1065                                 } else {
1066                                         eprintln!("Not implementing anything for {} due to it being marked not exported", ident);
1067                                 }
1068                         } else {
1069                                 eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub)", ident);
1070                         }
1071                 }
1072         }
1073 }
1074
1075
1076 /// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
1077 /// is unitary), we generate an equivalent enum with all types replaced with their C mapped
1078 /// versions followed by conversion functions which map between the Rust version and the C mapped
1079 /// version.
1080 fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, types: &mut TypeResolver<'b, 'a>, extra_headers: &mut File, cpp_headers: &mut File) {
1081         match export_status(&e.attrs) {
1082                 ExportStatus::Export => {},
1083                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1084         }
1085
1086         if is_enum_opaque(e) {
1087                 eprintln!("Skipping enum {} as it contains non-unit fields", e.ident);
1088                 writeln_opaque(w, &e.ident, &format!("{}", e.ident), &e.generics, &e.attrs, types, extra_headers, cpp_headers);
1089                 return;
1090         }
1091         writeln_docs(w, &e.attrs, "");
1092
1093         if e.generics.lt_token.is_some() {
1094                 unimplemented!();
1095         }
1096
1097         let mut needs_free = false;
1098
1099         writeln!(w, "#[must_use]\n#[derive(Clone)]\n#[repr(C)]\npub enum {} {{", e.ident).unwrap();
1100         for var in e.variants.iter() {
1101                 assert_eq!(export_status(&var.attrs), ExportStatus::Export); // We can't partially-export a mirrored enum
1102                 writeln_docs(w, &var.attrs, "\t");
1103                 write!(w, "\t{}", var.ident).unwrap();
1104                 if let syn::Fields::Named(fields) = &var.fields {
1105                         needs_free = true;
1106                         writeln!(w, " {{").unwrap();
1107                         for field in fields.named.iter() {
1108                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1109                                 writeln_docs(w, &field.attrs, "\t\t");
1110                                 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1111                                 types.write_c_type(w, &field.ty, None, false);
1112                                 writeln!(w, ",").unwrap();
1113                         }
1114                         write!(w, "\t}}").unwrap();
1115                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1116                         needs_free = true;
1117                         write!(w, "(").unwrap();
1118                         for (idx, field) in fields.unnamed.iter().enumerate() {
1119                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1120                                 types.write_c_type(w, &field.ty, None, false);
1121                                 if idx != fields.unnamed.len() - 1 {
1122                                         write!(w, ",").unwrap();
1123                                 }
1124                         }
1125                         write!(w, ")").unwrap();
1126                 }
1127                 if var.discriminant.is_some() { unimplemented!(); }
1128                 writeln!(w, ",").unwrap();
1129         }
1130         writeln!(w, "}}\nuse {}::{}::{} as native{};\nimpl {} {{", types.orig_crate, types.module_path, e.ident, e.ident, e.ident).unwrap();
1131
1132         macro_rules! write_conv {
1133                 ($fn_sig: expr, $to_c: expr, $ref: expr) => {
1134                         writeln!(w, "\t#[allow(unused)]\n\tpub(crate) fn {} {{\n\t\tmatch {} {{", $fn_sig, if $to_c { "native" } else { "self" }).unwrap();
1135                         for var in e.variants.iter() {
1136                                 write!(w, "\t\t\t{}{}::{} ", if $to_c { "native" } else { "" }, e.ident, var.ident).unwrap();
1137                                 if let syn::Fields::Named(fields) = &var.fields {
1138                                         write!(w, "{{").unwrap();
1139                                         for field in fields.named.iter() {
1140                                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1141                                                 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, field.ident.as_ref().unwrap()).unwrap();
1142                                         }
1143                                         write!(w, "}} ").unwrap();
1144                                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1145                                         write!(w, "(").unwrap();
1146                                         for (idx, field) in fields.unnamed.iter().enumerate() {
1147                                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1148                                                 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, ('a' as u8 + idx as u8) as char).unwrap();
1149                                         }
1150                                         write!(w, ") ").unwrap();
1151                                 }
1152                                 write!(w, "=>").unwrap();
1153
1154                                 macro_rules! handle_field_a {
1155                                         ($field: expr, $field_ident: expr) => { {
1156                                                 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1157                                                 let mut sink = ::std::io::sink();
1158                                                 let mut out: &mut dyn std::io::Write = if $ref { &mut sink } else { w };
1159                                                 let new_var = if $to_c {
1160                                                         types.write_to_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None, false)
1161                                                 } else {
1162                                                         types.write_from_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None)
1163                                                 };
1164                                                 if $ref || new_var {
1165                                                         if $ref {
1166                                                                 write!(w, "let mut {}_nonref = (*{}).clone();\n\t\t\t\t", $field_ident, $field_ident).unwrap();
1167                                                                 if new_var {
1168                                                                         let nonref_ident = syn::Ident::new(&format!("{}_nonref", $field_ident), Span::call_site());
1169                                                                         if $to_c {
1170                                                                                 types.write_to_c_conversion_new_var(w, &nonref_ident, &$field.ty, None, false);
1171                                                                         } else {
1172                                                                                 types.write_from_c_conversion_new_var(w, &nonref_ident, &$field.ty, None);
1173                                                                         }
1174                                                                         write!(w, "\n\t\t\t\t").unwrap();
1175                                                                 }
1176                                                         } else {
1177                                                                 write!(w, "\n\t\t\t\t").unwrap();
1178                                                         }
1179                                                 }
1180                                         } }
1181                                 }
1182                                 if let syn::Fields::Named(fields) = &var.fields {
1183                                         write!(w, " {{\n\t\t\t\t").unwrap();
1184                                         for field in fields.named.iter() {
1185                                                 handle_field_a!(field, field.ident.as_ref().unwrap());
1186                                         }
1187                                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1188                                         write!(w, " {{\n\t\t\t\t").unwrap();
1189                                         for (idx, field) in fields.unnamed.iter().enumerate() {
1190                                                 handle_field_a!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1191                                         }
1192                                 } else { write!(w, " ").unwrap(); }
1193
1194                                 write!(w, "{}{}::{}", if $to_c { "" } else { "native" }, e.ident, var.ident).unwrap();
1195
1196                                 macro_rules! handle_field_b {
1197                                         ($field: expr, $field_ident: expr) => { {
1198                                                 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1199                                                 if $to_c {
1200                                                         types.write_to_c_conversion_inline_prefix(w, &$field.ty, None, false);
1201                                                 } else {
1202                                                         types.write_from_c_conversion_prefix(w, &$field.ty, None);
1203                                                 }
1204                                                 write!(w, "{}{}", $field_ident,
1205                                                         if $ref { "_nonref" } else { "" }).unwrap();
1206                                                 if $to_c {
1207                                                         types.write_to_c_conversion_inline_suffix(w, &$field.ty, None, false);
1208                                                 } else {
1209                                                         types.write_from_c_conversion_suffix(w, &$field.ty, None);
1210                                                 }
1211                                                 write!(w, ",").unwrap();
1212                                         } }
1213                                 }
1214
1215                                 if let syn::Fields::Named(fields) = &var.fields {
1216                                         write!(w, " {{").unwrap();
1217                                         for field in fields.named.iter() {
1218                                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1219                                                 write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1220                                                 handle_field_b!(field, field.ident.as_ref().unwrap());
1221                                         }
1222                                         writeln!(w, "\n\t\t\t\t}}").unwrap();
1223                                         write!(w, "\t\t\t}}").unwrap();
1224                                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1225                                         write!(w, " (").unwrap();
1226                                         for (idx, field) in fields.unnamed.iter().enumerate() {
1227                                                 write!(w, "\n\t\t\t\t\t").unwrap();
1228                                                 handle_field_b!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1229                                         }
1230                                         writeln!(w, "\n\t\t\t\t)").unwrap();
1231                                         write!(w, "\t\t\t}}").unwrap();
1232                                 }
1233                                 writeln!(w, ",").unwrap();
1234                         }
1235                         writeln!(w, "\t\t}}\n\t}}").unwrap();
1236                 }
1237         }
1238
1239         write_conv!(format!("to_native(&self) -> native{}", e.ident), false, true);
1240         write_conv!(format!("into_native(self) -> native{}", e.ident), false, false);
1241         write_conv!(format!("from_native(native: &native{}) -> Self", e.ident), true, true);
1242         write_conv!(format!("native_into(native: native{}) -> Self", e.ident), true, false);
1243         writeln!(w, "}}").unwrap();
1244
1245         if needs_free {
1246                 writeln!(w, "/// Frees any resources used by the {}", e.ident).unwrap();
1247                 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", e.ident, e.ident).unwrap();
1248         }
1249         writeln!(w, "/// Creates a copy of the {}", e.ident).unwrap();
1250         writeln!(w, "#[no_mangle]").unwrap();
1251         writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
1252         writeln!(w, "\torig.clone()").unwrap();
1253         writeln!(w, "}}").unwrap();
1254         write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free);
1255 }
1256
1257 fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &mut TypeResolver<'b, 'a>) {
1258         match export_status(&f.attrs) {
1259                 ExportStatus::Export => {},
1260                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1261         }
1262         writeln_docs(w, &f.attrs, "");
1263
1264         let mut gen_types = GenericTypes::new();
1265         if !gen_types.learn_generics(&f.sig.generics, types) { return; }
1266
1267         write!(w, "#[no_mangle]\npub extern \"C\" fn {}(", f.sig.ident).unwrap();
1268         write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
1269         write!(w, " {{\n\t").unwrap();
1270         write_method_var_decl_body(w, &f.sig, "", types, Some(&gen_types), false);
1271         write!(w, "{}::{}::{}(", types.orig_crate, types.module_path, f.sig.ident).unwrap();
1272         write_method_call_params(w, &f.sig, "", types, Some(&gen_types), "", false);
1273         writeln!(w, "\n}}\n").unwrap();
1274 }
1275
1276 // ********************************
1277 // *** File/Crate Walking Logic ***
1278 // ********************************
1279 /// A public module
1280 struct ASTModule {
1281         pub attrs: Vec<syn::Attribute>,
1282         pub items: Vec<syn::Item>,
1283         pub submods: Vec<String>,
1284 }
1285 /// A struct containing the syn::File AST for each file in the crate.
1286 struct FullLibraryAST {
1287         modules: HashMap<String, ASTModule, NonRandomHash>,
1288 }
1289 impl FullLibraryAST {
1290         fn load_module(&mut self, module: String, attrs: Vec<syn::Attribute>, mut items: Vec<syn::Item>) {
1291                 let mut non_mod_items = Vec::with_capacity(items.len());
1292                 let mut submods = Vec::with_capacity(items.len());
1293                 for item in items.drain(..) {
1294                         match item {
1295                                 syn::Item::Mod(m) if m.content.is_some() => {
1296                                         if export_status(&m.attrs) == ExportStatus::Export {
1297                                                 if let syn::Visibility::Public(_) = m.vis {
1298                                                         let modident = format!("{}", m.ident);
1299                                                         let modname = if module != "" {
1300                                                                 module.clone() + "::" + &modident
1301                                                         } else {
1302                                                                 modident.clone()
1303                                                         };
1304                                                         self.load_module(modname, m.attrs, m.content.unwrap().1);
1305                                                         submods.push(modident);
1306                                                 } else {
1307                                                         non_mod_items.push(syn::Item::Mod(m));
1308                                                 }
1309                                         }
1310                                 },
1311                                 syn::Item::Mod(_) => panic!("--pretty=expanded output should never have non-body modules"),
1312                                 _ => { non_mod_items.push(item); }
1313                         }
1314                 }
1315                 self.modules.insert(module, ASTModule { attrs, items: non_mod_items, submods });
1316         }
1317
1318         pub fn load_lib(lib: syn::File) -> Self {
1319                 assert_eq!(export_status(&lib.attrs), ExportStatus::Export);
1320                 let mut res = Self { modules: HashMap::default() };
1321                 res.load_module("".to_owned(), lib.attrs, lib.items);
1322                 res
1323         }
1324 }
1325
1326 /// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
1327 /// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
1328 /// at `module` from C.
1329 fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>, out_dir: &str, orig_crate: &str, header_file: &mut File, cpp_header_file: &mut File) {
1330         for (module, astmod) in libast.modules.iter() {
1331                 let ASTModule { ref attrs, ref items, ref submods } = astmod;
1332                 assert_eq!(export_status(&attrs), ExportStatus::Export);
1333
1334                 let new_file_path = if submods.is_empty() {
1335                         format!("{}/{}.rs", out_dir, module.replace("::", "/"))
1336                 } else if module != "" {
1337                         format!("{}/{}/mod.rs", out_dir, module.replace("::", "/"))
1338                 } else {
1339                         format!("{}/lib.rs", out_dir)
1340                 };
1341                 let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
1342                 let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1343                         .open(new_file_path).expect("Unable to open new src file");
1344
1345                 writeln_docs(&mut out, &attrs, "");
1346
1347                 if module == "" {
1348                         // Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
1349                         // and bitcoin hand-written modules.
1350                         writeln!(out, "#![allow(unknown_lints)]").unwrap();
1351                         writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
1352                         writeln!(out, "#![allow(non_snake_case)]").unwrap();
1353                         writeln!(out, "#![allow(unused_imports)]").unwrap();
1354                         writeln!(out, "#![allow(unused_variables)]").unwrap();
1355                         writeln!(out, "#![allow(unused_mut)]").unwrap();
1356                         writeln!(out, "#![allow(unused_parens)]").unwrap();
1357                         writeln!(out, "#![allow(unused_unsafe)]").unwrap();
1358                         writeln!(out, "#![allow(unused_braces)]").unwrap();
1359                         writeln!(out, "#![deny(missing_docs)]").unwrap();
1360                         writeln!(out, "mod c_types;").unwrap();
1361                         writeln!(out, "mod bitcoin;").unwrap();
1362                 } else {
1363                         writeln!(out, "\nuse std::ffi::c_void;\nuse bitcoin::hashes::Hash;\nuse crate::c_types::*;\n").unwrap();
1364                 }
1365
1366                 for m in submods {
1367                         writeln!(out, "pub mod {};", m).unwrap();
1368                 }
1369
1370                 eprintln!("Converting {} entries...", module);
1371
1372                 let import_resolver = ImportResolver::new(module, items);
1373                 let mut type_resolver = TypeResolver::new(orig_crate, module, import_resolver, crate_types);
1374
1375                 for item in items.iter() {
1376                         match item {
1377                                 syn::Item::Use(_) => {}, // Handled above
1378                                 syn::Item::Static(_) => {},
1379                                 syn::Item::Enum(e) => {
1380                                         if let syn::Visibility::Public(_) = e.vis {
1381                                                 writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
1382                                         }
1383                                 },
1384                                 syn::Item::Impl(i) => {
1385                                         writeln_impl(&mut out, &i, &mut type_resolver);
1386                                 },
1387                                 syn::Item::Struct(s) => {
1388                                         if let syn::Visibility::Public(_) = s.vis {
1389                                                 writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
1390                                         }
1391                                 },
1392                                 syn::Item::Trait(t) => {
1393                                         if let syn::Visibility::Public(_) = t.vis {
1394                                                 writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
1395                                         }
1396                                 },
1397                                 syn::Item::Mod(_) => {}, // We don't have to do anything - the top loop handles these.
1398                                 syn::Item::Const(c) => {
1399                                         // Re-export any primitive-type constants.
1400                                         if let syn::Visibility::Public(_) = c.vis {
1401                                                 if let syn::Type::Path(p) = &*c.ty {
1402                                                         let resolved_path = type_resolver.resolve_path(&p.path, None);
1403                                                         if type_resolver.is_primitive(&resolved_path) {
1404                                                                 writeln_docs(&mut out, &c.attrs, "");
1405                                                                 writeln!(out, "\n#[no_mangle]").unwrap();
1406                                                                 writeln!(out, "pub static {}: {} = {}::{}::{};", c.ident, resolved_path, orig_crate, module, c.ident).unwrap();
1407                                                         }
1408                                                 }
1409                                         }
1410                                 },
1411                                 syn::Item::Type(t) => {
1412                                         if let syn::Visibility::Public(_) = t.vis {
1413                                                 match export_status(&t.attrs) {
1414                                                         ExportStatus::Export => {},
1415                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1416                                                 }
1417
1418                                                 let mut process_alias = true;
1419                                                 for tok in t.generics.params.iter() {
1420                                                         if let syn::GenericParam::Lifetime(_) = tok {}
1421                                                         else { process_alias = false; }
1422                                                 }
1423                                                 if process_alias {
1424                                                         match &*t.ty {
1425                                                                 syn::Type::Path(_) =>
1426                                                                         writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &t.generics, &t.attrs, &type_resolver, header_file, cpp_header_file),
1427                                                                 _ => {}
1428                                                         }
1429                                                 }
1430                                         }
1431                                 },
1432                                 syn::Item::Fn(f) => {
1433                                         if let syn::Visibility::Public(_) = f.vis {
1434                                                 writeln_fn(&mut out, &f, &mut type_resolver);
1435                                         }
1436                                 },
1437                                 syn::Item::Macro(m) => {
1438                                         if m.ident.is_none() { // If its not a macro definition
1439                                                 convert_macro(&mut out, &m.mac.path, &m.mac.tokens, &type_resolver);
1440                                         }
1441                                 },
1442                                 syn::Item::Verbatim(_) => {},
1443                                 syn::Item::ExternCrate(_) => {},
1444                                 _ => unimplemented!(),
1445                         }
1446                 }
1447
1448                 out.flush().unwrap();
1449         }
1450 }
1451
1452 fn walk_private_mod<'a>(module: String, items: &'a syn::ItemMod, crate_types: &mut CrateTypes<'a>) {
1453         let import_resolver = ImportResolver::new(&module, &items.content.as_ref().unwrap().1);
1454         for item in items.content.as_ref().unwrap().1.iter() {
1455                 match item {
1456                         syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types),
1457                         syn::Item::Impl(i) => {
1458                                 if let &syn::Type::Path(ref p) = &*i.self_ty {
1459                                         if let Some(trait_path) = i.trait_.as_ref() {
1460                                                 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1461                                                         if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1462                                                                 match crate_types.trait_impls.entry(sp) {
1463                                                                         hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1464                                                                         hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1465                                                                 }
1466                                                         }
1467                                                 }
1468                                         }
1469                                 }
1470                         },
1471                         _ => {},
1472                 }
1473         }
1474 }
1475
1476 /// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
1477 fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
1478         for (module, astmod) in ast_storage.modules.iter() {
1479                 let ASTModule { ref attrs, ref items, submods: _ } = astmod;
1480                 assert_eq!(export_status(&attrs), ExportStatus::Export);
1481                 let import_resolver = ImportResolver::new(module, items);
1482
1483                 for item in items.iter() {
1484                         match item {
1485                                 syn::Item::Struct(s) => {
1486                                         if let syn::Visibility::Public(_) = s.vis {
1487                                                 match export_status(&s.attrs) {
1488                                                         ExportStatus::Export => {},
1489                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1490                                                 }
1491                                                 let struct_path = format!("{}::{}", module, s.ident);
1492                                                 crate_types.opaques.insert(struct_path, &s.ident);
1493                                         }
1494                                 },
1495                                 syn::Item::Trait(t) => {
1496                                         if let syn::Visibility::Public(_) = t.vis {
1497                                                 match export_status(&t.attrs) {
1498                                                         ExportStatus::Export => {},
1499                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1500                                                 }
1501                                                 let trait_path = format!("{}::{}", module, t.ident);
1502                                                 walk_supertraits!(t, None, (
1503                                                         ("Clone", _) => {
1504                                                                 crate_types.clonable_types.insert("crate::".to_owned() + &trait_path);
1505                                                         },
1506                                                         (_, _) => {}
1507                                                 ) );
1508                                                 crate_types.traits.insert(trait_path, &t);
1509                                         }
1510                                 },
1511                                 syn::Item::Type(t) => {
1512                                         if let syn::Visibility::Public(_) = t.vis {
1513                                                 match export_status(&t.attrs) {
1514                                                         ExportStatus::Export => {},
1515                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1516                                                 }
1517                                                 let type_path = format!("{}::{}", module, t.ident);
1518                                                 let mut process_alias = true;
1519                                                 for tok in t.generics.params.iter() {
1520                                                         if let syn::GenericParam::Lifetime(_) = tok {}
1521                                                         else { process_alias = false; }
1522                                                 }
1523                                                 if process_alias {
1524                                                         match &*t.ty {
1525                                                                 syn::Type::Path(p) => {
1526                                                                         // If its a path with no generics, assume we don't map the aliased type and map it opaque
1527                                                                         let mut segments = syn::punctuated::Punctuated::new();
1528                                                                         segments.push(syn::PathSegment {
1529                                                                                 ident: t.ident.clone(),
1530                                                                                 arguments: syn::PathArguments::None,
1531                                                                         });
1532                                                                         let path_obj = syn::Path { leading_colon: None, segments };
1533                                                                         let args_obj = p.path.segments.last().unwrap().arguments.clone();
1534                                                                         match crate_types.reverse_alias_map.entry(import_resolver.maybe_resolve_path(&p.path, None).unwrap()) {
1535                                                                                 hash_map::Entry::Occupied(mut e) => { e.get_mut().push((path_obj, args_obj)); },
1536                                                                                 hash_map::Entry::Vacant(e) => { e.insert(vec![(path_obj, args_obj)]); },
1537                                                                         }
1538
1539                                                                         crate_types.opaques.insert(type_path.clone(), &t.ident);
1540                                                                 },
1541                                                                 _ => {
1542                                                                         crate_types.type_aliases.insert(type_path, import_resolver.resolve_imported_refs((*t.ty).clone()));
1543                                                                 }
1544                                                         }
1545                                                 }
1546                                         }
1547                                 },
1548                                 syn::Item::Enum(e) if is_enum_opaque(e) => {
1549                                         if let syn::Visibility::Public(_) = e.vis {
1550                                                 match export_status(&e.attrs) {
1551                                                         ExportStatus::Export => {},
1552                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1553                                                 }
1554                                                 let enum_path = format!("{}::{}", module, e.ident);
1555                                                 crate_types.opaques.insert(enum_path, &e.ident);
1556                                         }
1557                                 },
1558                                 syn::Item::Enum(e) => {
1559                                         if let syn::Visibility::Public(_) = e.vis {
1560                                                 match export_status(&e.attrs) {
1561                                                         ExportStatus::Export => {},
1562                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1563                                                 }
1564                                                 let enum_path = format!("{}::{}", module, e.ident);
1565                                                 crate_types.mirrored_enums.insert(enum_path, &e);
1566                                         }
1567                                 },
1568                                 syn::Item::Impl(i) => {
1569                                         if let &syn::Type::Path(ref p) = &*i.self_ty {
1570                                                 if let Some(trait_path) = i.trait_.as_ref() {
1571                                                         if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) {
1572                                                                 if let Some(full_path) = import_resolver.maybe_resolve_path(&p.path, None) {
1573                                                                         crate_types.clonable_types.insert("crate::".to_owned() + &full_path);
1574                                                                 }
1575                                                         }
1576                                                         if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1577                                                                 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1578                                                                         match crate_types.trait_impls.entry(sp) {
1579                                                                                 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1580                                                                                 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1581                                                                         }
1582                                                                 }
1583                                                         }
1584                                                 }
1585                                         }
1586                                 },
1587                                 syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types),
1588                                 _ => {},
1589                         }
1590                 }
1591         }
1592 }
1593
1594 fn main() {
1595         let args: Vec<String> = env::args().collect();
1596         if args.len() != 6 {
1597                 eprintln!("Usage: target/dir source_crate_name derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
1598                 process::exit(1);
1599         }
1600
1601         let mut derived_templates = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1602                 .open(&args[3]).expect("Unable to open new header file");
1603         let mut header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1604                 .open(&args[4]).expect("Unable to open new header file");
1605         let mut cpp_header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1606                 .open(&args[5]).expect("Unable to open new header file");
1607
1608         writeln!(header_file, "#if defined(__GNUC__)").unwrap();
1609         writeln!(header_file, "#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
1610         writeln!(header_file, "#define MUST_USE_RES __attribute__((warn_unused_result))").unwrap();
1611         writeln!(header_file, "#else").unwrap();
1612         writeln!(header_file, "#define MUST_USE_STRUCT").unwrap();
1613         writeln!(header_file, "#define MUST_USE_RES").unwrap();
1614         writeln!(header_file, "#endif").unwrap();
1615         writeln!(header_file, "#if defined(__clang__)").unwrap();
1616         writeln!(header_file, "#define NONNULL_PTR _Nonnull").unwrap();
1617         writeln!(header_file, "#else").unwrap();
1618         writeln!(header_file, "#define NONNULL_PTR").unwrap();
1619         writeln!(header_file, "#endif").unwrap();
1620         writeln!(cpp_header_file, "#include <string.h>\nnamespace LDK {{").unwrap();
1621
1622         // First parse the full crate's ASTs, caching them so that we can hold references to the AST
1623         // objects in other datastructures:
1624         let mut lib_src = String::new();
1625         std::io::stdin().lock().read_to_string(&mut lib_src).unwrap();
1626         let lib_syntax = syn::parse_file(&lib_src).expect("Unable to parse file");
1627         let libast = FullLibraryAST::load_lib(lib_syntax);
1628
1629         // ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
1630         // when parsing other file ASTs...
1631         let mut libtypes = CrateTypes { traits: HashMap::new(), opaques: HashMap::new(), mirrored_enums: HashMap::new(),
1632                 type_aliases: HashMap::new(), reverse_alias_map: HashMap::new(), templates_defined: HashMap::default(),
1633                 template_file: &mut derived_templates,
1634                 clonable_types: HashSet::new(), trait_impls: HashMap::new() };
1635         walk_ast(&libast, &mut libtypes);
1636
1637         // ... finally, do the actual file conversion/mapping, writing out types as we go.
1638         convert_file(&libast, &mut libtypes, &args[1], &args[2], &mut header_file, &mut cpp_header_file);
1639
1640         // For container templates which we created while walking the crate, make sure we add C++
1641         // mapped types so that C++ users can utilize the auto-destructors available.
1642         for (ty, has_destructor) in libtypes.templates_defined.iter() {
1643                 write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor);
1644         }
1645         writeln!(cpp_header_file, "}}").unwrap();
1646
1647         header_file.flush().unwrap();
1648         cpp_header_file.flush().unwrap();
1649         derived_templates.flush().unwrap();
1650 }