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