Handle traits which require Clone when their supertraits do not
[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, is_clonable) 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), true));
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), true));
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), true));
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         let mut requires_clone = false;
359         walk_supertraits!(t, Some(&types), (
360                 ("Clone", _) => requires_clone = true,
361                 (_, _) => {}
362         ) );
363         walk_supertraits!(t, Some(&types), (
364                 ("Clone", _) => {
365                         writeln!(w, "\t/// Creates a copy of the object pointed to by this_arg, for a copy of this {}.", trait_name).unwrap();
366                         writeln!(w, "\t/// Note that the ultimate copy of the {} will have all function pointers the same as the original.", trait_name).unwrap();
367                         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();
368                         writeln!(w, "\tpub clone: Option<extern \"C\" fn (this_arg: *const c_void) -> *mut c_void>,").unwrap();
369                         generated_fields.push(("clone".to_owned(), true));
370                 },
371                 ("std::cmp::Eq", _) => {
372                         writeln!(w, "\t/// Checks if two objects are equal given this object's this_arg pointer and another object.").unwrap();
373                         writeln!(w, "\tpub eq: extern \"C\" fn (this_arg: *const c_void, other_arg: &{}) -> bool,", trait_name).unwrap();
374                         writeln!(extra_headers, "typedef struct LDK{} LDK{};", trait_name, trait_name).unwrap();
375                         generated_fields.push(("eq".to_owned(), true));
376                 },
377                 ("std::hash::Hash", _) => {
378                         writeln!(w, "\t/// Calculate a succinct non-cryptographic hash for an object given its this_arg pointer.").unwrap();
379                         writeln!(w, "\t/// This is used, for example, for inclusion of this object in a hash map.").unwrap();
380                         writeln!(w, "\tpub hash: extern \"C\" fn (this_arg: *const c_void) -> u64,").unwrap();
381                         generated_fields.push(("hash".to_owned(), true));
382                 },
383                 ("Send", _) => {}, ("Sync", _) => {},
384                 (s, i) => {
385                         generated_fields.push(if types.crate_types.traits.get(s).is_none() {
386                                 let (docs, name, ret) = convert_trait_impl_field(s);
387                                 writeln!(w, "\t/// {}", docs).unwrap();
388                                 writeln!(w, "\tpub {}: extern \"C\" fn (this_arg: *const c_void) -> {},", name, ret).unwrap();
389                                 (name, true) // Assume clonable
390                         } else {
391                                 // For in-crate supertraits, just store a C-mapped copy of the supertrait as a member.
392                                 writeln!(w, "\t/// Implementation of {} for this object.", i).unwrap();
393                                 writeln!(w, "\tpub {}: crate::{},", i, s).unwrap();
394                                 let is_clonable = types.is_clonable(s);
395                                 if !is_clonable && requires_clone {
396                                         writeln!(w, "\t/// Creates a copy of the {}, for a copy of this {}.", i, trait_name).unwrap();
397                                         writeln!(w, "\t/// Because {} doesn't natively support copying itself, you have to provide a full copy implementation here.", i).unwrap();
398                                         writeln!(w, "\tpub {}_clone: extern \"C\" fn (orig_{}: &{}) -> {},", i, i, i, i).unwrap();
399                                 }
400                                 (format!("{}", i), is_clonable)
401                         });
402                 }
403         ) );
404         writeln!(w, "\t/// Frees any resources associated with this object given its this_arg pointer.").unwrap();
405         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();
406         writeln!(w, "\tpub free: Option<extern \"C\" fn(this_arg: *mut c_void)>,").unwrap();
407         generated_fields.push(("free".to_owned(), true));
408         writeln!(w, "}}").unwrap();
409
410         macro_rules! impl_trait_for_c {
411                 ($t: expr, $impl_accessor: expr) => {
412                         for item in $t.items.iter() {
413                                 match item {
414                                         syn::TraitItem::Method(m) => {
415                                                 if let ExportStatus::TestOnly = export_status(&m.attrs) { continue; }
416                                                 if m.default.is_some() { unimplemented!(); }
417                                                 if m.sig.constness.is_some() || m.sig.asyncness.is_some() || m.sig.unsafety.is_some() ||
418                                                                 m.sig.abi.is_some() || m.sig.variadic.is_some() {
419                                                         unimplemented!();
420                                                 }
421                                                 gen_types.push_ctx();
422                                                 assert!(gen_types.learn_generics(&m.sig.generics, types));
423                                                 write!(w, "\tfn {}", m.sig.ident).unwrap();
424                                                 types.write_rust_generic_param(w, Some(&gen_types), m.sig.generics.params.iter());
425                                                 write!(w, "(").unwrap();
426                                                 for inp in m.sig.inputs.iter() {
427                                                         match inp {
428                                                                 syn::FnArg::Receiver(recv) => {
429                                                                         if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
430                                                                         write!(w, "&").unwrap();
431                                                                         if let Some(lft) = &recv.reference.as_ref().unwrap().1 {
432                                                                                 write!(w, "'{} ", lft.ident).unwrap();
433                                                                         }
434                                                                         if recv.mutability.is_some() {
435                                                                                 write!(w, "mut self").unwrap();
436                                                                         } else {
437                                                                                 write!(w, "self").unwrap();
438                                                                         }
439                                                                 },
440                                                                 syn::FnArg::Typed(arg) => {
441                                                                         if !arg.attrs.is_empty() { unimplemented!(); }
442                                                                         match &*arg.pat {
443                                                                                 syn::Pat::Ident(ident) => {
444                                                                                         if !ident.attrs.is_empty() || ident.by_ref.is_some() ||
445                                                                                                         ident.mutability.is_some() || ident.subpat.is_some() {
446                                                                                                 unimplemented!();
447                                                                                         }
448                                                                                         write!(w, ", {}{}: ", if types.skip_arg(&*arg.ty, Some(&gen_types)) { "_" } else { "" }, ident.ident).unwrap();
449                                                                                 }
450                                                                                 _ => unimplemented!(),
451                                                                         }
452                                                                         types.write_rust_type(w, Some(&gen_types), &*arg.ty);
453                                                                 }
454                                                         }
455                                                 }
456                                                 write!(w, ")").unwrap();
457                                                 match &m.sig.output {
458                                                         syn::ReturnType::Type(_, rtype) => {
459                                                                 write!(w, " -> ").unwrap();
460                                                                 types.write_rust_type(w, Some(&gen_types), &*rtype)
461                                                         },
462                                                         _ => {},
463                                                 }
464                                                 write!(w, " {{\n\t\t").unwrap();
465                                                 match export_status(&m.attrs) {
466                                                         ExportStatus::NoExport => {
467                                                                 unimplemented!();
468                                                         },
469                                                         _ => {},
470                                                 }
471                                                 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
472                                                         if let syn::Type::Reference(r) = &**rtype {
473                                                                 assert_eq!(m.sig.inputs.len(), 1); // Must only take self!
474                                                                 writeln!(w, "if let Some(f) = self{}.set_{} {{", $impl_accessor, m.sig.ident).unwrap();
475                                                                 writeln!(w, "\t\t\t(f)(&self{});", $impl_accessor).unwrap();
476                                                                 write!(w, "\t\t}}\n\t\t").unwrap();
477                                                                 types.write_from_c_conversion_to_ref_prefix(w, &*r.elem, Some(&gen_types));
478                                                                 write!(w, "self{}.{}", $impl_accessor, m.sig.ident).unwrap();
479                                                                 types.write_from_c_conversion_to_ref_suffix(w, &*r.elem, Some(&gen_types));
480                                                                 writeln!(w, "\n\t}}").unwrap();
481                                                                 gen_types.pop_ctx();
482                                                                 continue;
483                                                         }
484                                                 }
485                                                 write_method_var_decl_body(w, &m.sig, "\t", types, Some(&gen_types), true);
486                                                 write!(w, "(self{}.{})(", $impl_accessor, m.sig.ident).unwrap();
487                                                 write_method_call_params(w, &m.sig, "\t", types, Some(&gen_types), "", true);
488
489                                                 writeln!(w, "\n\t}}").unwrap();
490                                                 gen_types.pop_ctx();
491                                         },
492                                         &syn::TraitItem::Type(ref t) => {
493                                                 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
494                                                 let mut bounds_iter = t.bounds.iter();
495                                                 match bounds_iter.next().unwrap() {
496                                                         syn::TypeParamBound::Trait(tr) => {
497                                                                 writeln!(w, "\ttype {} = crate::{};", t.ident, types.resolve_path(&tr.path, Some(&gen_types))).unwrap();
498                                                         },
499                                                         _ => unimplemented!(),
500                                                 }
501                                                 if bounds_iter.next().is_some() { unimplemented!(); }
502                                         },
503                                         _ => unimplemented!(),
504                                 }
505                         }
506                 }
507         }
508
509
510         // Implement supertraits for the C-mapped struct.
511         walk_supertraits!(t, Some(&types), (
512                 ("Send", _) => writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap(),
513                 ("Sync", _) => writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap(),
514                 ("std::cmp::Eq", _) => {
515                         writeln!(w, "impl std::cmp::Eq for {} {{}}", trait_name).unwrap();
516                         writeln!(w, "impl std::cmp::PartialEq for {} {{", trait_name).unwrap();
517                         writeln!(w, "\tfn eq(&self, o: &Self) -> bool {{ (self.eq)(self.this_arg, o) }}\n}}").unwrap();
518                 },
519                 ("std::hash::Hash", _) => {
520                         writeln!(w, "impl std::hash::Hash for {} {{", trait_name).unwrap();
521                         writeln!(w, "\tfn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {{ hasher.write_u64((self.hash)(self.this_arg)) }}\n}}").unwrap();
522                 },
523                 ("Clone", _) => {
524                         writeln!(w, "#[no_mangle]").unwrap();
525                         writeln!(w, "/// Creates a copy of a {}", trait_name).unwrap();
526                         writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", trait_name, trait_name, trait_name).unwrap();
527                         writeln!(w, "\t{} {{", trait_name).unwrap();
528                         writeln!(w, "\t\tthis_arg: if let Some(f) = orig.clone {{ (f)(orig.this_arg) }} else {{ orig.this_arg }},").unwrap();
529                         for (field, clonable) in generated_fields.iter() {
530                                 if *clonable {
531                                         writeln!(w, "\t\t{}: Clone::clone(&orig.{}),", field, field).unwrap();
532                                 } else {
533                                         writeln!(w, "\t\t{}: (orig.{}_clone)(&orig.{}),", field, field, field).unwrap();
534                                         writeln!(w, "\t\t{}_clone: orig.{}_clone,", field, field).unwrap();
535                                 }
536                         }
537                         writeln!(w, "\t}}\n}}").unwrap();
538                         writeln!(w, "impl Clone for {} {{", trait_name).unwrap();
539                         writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
540                         writeln!(w, "\t\t{}_clone(self)", trait_name).unwrap();
541                         writeln!(w, "\t}}\n}}").unwrap();
542                 },
543                 (s, i) => {
544                         if let Some(supertrait) = types.crate_types.traits.get(s) {
545                                 writeln!(w, "impl lightning::{} for {} {{", s, trait_name).unwrap(); // TODO: Drop hard-coded crate name here
546                                 impl_trait_for_c!(supertrait, format!(".{}", i));
547                                 writeln!(w, "}}").unwrap();
548                                 walk_supertraits!(supertrait, Some(&types), (
549                                         ("Send", _) => writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap(),
550                                         ("Sync", _) => writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap(),
551                                         _ => unimplemented!()
552                                 ) );
553                         } else {
554                                 do_write_impl_trait(w, s, i, &trait_name);
555                         }
556                 }
557         ) );
558
559         // Finally, implement the original Rust trait for the newly created mapped trait.
560         writeln!(w, "\nuse {}::{}::{} as rust{};", types.orig_crate, types.module_path, t.ident, trait_name).unwrap();
561         write!(w, "impl rust{}", t.ident).unwrap();
562         maybe_write_generics(w, &t.generics, types, false);
563         writeln!(w, " for {} {{", trait_name).unwrap();
564         impl_trait_for_c!(t, "");
565         writeln!(w, "}}\n").unwrap();
566         writeln!(w, "// We're essentially a pointer already, or at least a set of pointers, so allow us to be used").unwrap();
567         writeln!(w, "// directly as a Deref trait in higher-level structs:").unwrap();
568         writeln!(w, "impl std::ops::Deref for {} {{\n\ttype Target = Self;", trait_name).unwrap();
569         writeln!(w, "\tfn deref(&self) -> &Self {{\n\t\tself\n\t}}\n}}").unwrap();
570
571         writeln!(w, "/// Calls the free function if one is set").unwrap();
572         writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", trait_name, trait_name).unwrap();
573         writeln!(w, "impl Drop for {} {{", trait_name).unwrap();
574         writeln!(w, "\tfn drop(&mut self) {{").unwrap();
575         writeln!(w, "\t\tif let Some(f) = self.free {{").unwrap();
576         writeln!(w, "\t\t\tf(self.this_arg);").unwrap();
577         writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
578
579         write_cpp_wrapper(cpp_headers, &trait_name, true);
580 }
581
582 /// Write out a simple "opaque" type (eg structs) which contain a pointer to the native Rust type
583 /// and a flag to indicate whether Drop'ing the mapped struct drops the underlying Rust type.
584 ///
585 /// Also writes out a _free function and a C++ wrapper which handles calling _free.
586 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) {
587         // If we directly read the original type by its original name, cbindgen hits
588         // https://github.com/eqrion/cbindgen/issues/286 Thus, instead, we import it as a temporary
589         // name and then reference it by that name, which works around the issue.
590         write!(w, "\nuse {}::{}::{} as native{}Import;\ntype native{} = native{}Import", types.orig_crate, types.module_path, ident, ident, ident, ident).unwrap();
591         maybe_write_generics(w, &generics, &types, true);
592         writeln!(w, ";\n").unwrap();
593         writeln!(extra_headers, "struct native{}Opaque;\ntypedef struct native{}Opaque LDKnative{};", ident, ident, ident).unwrap();
594         writeln_docs(w, &attrs, "");
595         writeln!(w, "#[must_use]\n#[repr(C)]\npub struct {} {{", struct_name).unwrap();
596         writeln!(w, "\t/// A pointer to the opaque Rust object.\n").unwrap();
597         writeln!(w, "\t/// Nearly everywhere, inner must be non-null, however in places where").unwrap();
598         writeln!(w, "\t/// the Rust equivalent takes an Option, it may be set to null to indicate None.").unwrap();
599         writeln!(w, "\tpub inner: *mut native{},", ident).unwrap();
600         writeln!(w, "\t/// Indicates that this is the only struct which contains the same pointer.\n").unwrap();
601         writeln!(w, "\t/// Rust functions which take ownership of an object provided via an argument require").unwrap();
602         writeln!(w, "\t/// this to be true and invalidate the object pointed to by inner.").unwrap();
603         writeln!(w, "\tpub is_owned: bool,").unwrap();
604         writeln!(w, "}}\n").unwrap();
605         writeln!(w, "impl Drop for {} {{\n\tfn drop(&mut self) {{", struct_name).unwrap();
606         writeln!(w, "\t\tif self.is_owned && !<*mut native{}>::is_null(self.inner) {{", ident).unwrap();
607         writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(self.inner) }};\n\t\t}}\n\t}}\n}}").unwrap();
608         writeln!(w, "/// Frees any resources used by the {}, if is_owned is set and inner is non-NULL.", struct_name).unwrap();
609         writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_obj: {}) {{ }}", struct_name, struct_name).unwrap();
610         writeln!(w, "#[allow(unused)]").unwrap();
611         writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
612         writeln!(w, "extern \"C\" fn {}_free_void(this_ptr: *mut c_void) {{", struct_name).unwrap();
613         writeln!(w, "\tunsafe {{ let _ = Box::from_raw(this_ptr as *mut native{}); }}\n}}", struct_name).unwrap();
614         writeln!(w, "#[allow(unused)]").unwrap();
615         writeln!(w, "/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy").unwrap();
616         writeln!(w, "impl {} {{", struct_name).unwrap();
617         writeln!(w, "\tpub(crate) fn take_inner(mut self) -> *mut native{} {{", struct_name).unwrap();
618         writeln!(w, "\t\tassert!(self.is_owned);").unwrap();
619         writeln!(w, "\t\tlet ret = self.inner;").unwrap();
620         writeln!(w, "\t\tself.inner = std::ptr::null_mut();").unwrap();
621         writeln!(w, "\t\tret").unwrap();
622         writeln!(w, "\t}}\n}}").unwrap();
623
624         write_cpp_wrapper(cpp_headers, &format!("{}", ident), true);
625 }
626
627 /// Writes out all the relevant mappings for a Rust struct, deferring to writeln_opaque to generate
628 /// the struct itself, and then writing getters and setters for public, understood-type fields and
629 /// a constructor if every field is public.
630 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) {
631         if export_status(&s.attrs) != ExportStatus::Export { return; }
632
633         let struct_name = &format!("{}", s.ident);
634         writeln_opaque(w, &s.ident, struct_name, &s.generics, &s.attrs, types, extra_headers, cpp_headers);
635
636         if let syn::Fields::Named(fields) = &s.fields {
637                 let mut gen_types = GenericTypes::new();
638                 assert!(gen_types.learn_generics(&s.generics, types));
639
640                 let mut all_fields_settable = true;
641                 for field in fields.named.iter() {
642                         if let syn::Visibility::Public(_) = field.vis {
643                                 let export = export_status(&field.attrs);
644                                 match export {
645                                         ExportStatus::Export => {},
646                                         ExportStatus::NoExport|ExportStatus::TestOnly => {
647                                                 all_fields_settable = false;
648                                                 continue
649                                         },
650                                 }
651
652                                 if let Some(ident) = &field.ident {
653                                         let ref_type = syn::Type::Reference(syn::TypeReference {
654                                                 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
655                                                 elem: Box::new(field.ty.clone()) });
656                                         if types.understood_c_type(&ref_type, Some(&gen_types)) {
657                                                 writeln_docs(w, &field.attrs, "");
658                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> ", struct_name, ident, struct_name).unwrap();
659                                                 types.write_c_type(w, &ref_type, Some(&gen_types), true);
660                                                 write!(w, " {{\n\tlet mut inner_val = &mut unsafe {{ &mut *this_ptr.inner }}.{};\n\t", ident).unwrap();
661                                                 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);
662                                                 if local_var { write!(w, "\n\t").unwrap(); }
663                                                 types.write_to_c_conversion_inline_prefix(w, &ref_type, Some(&gen_types), true);
664                                                 if local_var {
665                                                         write!(w, "inner_val").unwrap();
666                                                 } else {
667                                                         write!(w, "(*inner_val)").unwrap();
668                                                 }
669                                                 types.write_to_c_conversion_inline_suffix(w, &ref_type, Some(&gen_types), true);
670                                                 writeln!(w, "\n}}").unwrap();
671                                         }
672
673                                         if types.understood_c_type(&field.ty, Some(&gen_types)) {
674                                                 writeln_docs(w, &field.attrs, "");
675                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_set_{}(this_ptr: &mut {}, mut val: ", struct_name, ident, struct_name).unwrap();
676                                                 types.write_c_type(w, &field.ty, Some(&gen_types), false);
677                                                 write!(w, ") {{\n\t").unwrap();
678                                                 let local_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("val", Span::call_site()), &field.ty, Some(&gen_types));
679                                                 if local_var { write!(w, "\n\t").unwrap(); }
680                                                 write!(w, "unsafe {{ &mut *this_ptr.inner }}.{} = ", ident).unwrap();
681                                                 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
682                                                 write!(w, "val").unwrap();
683                                                 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
684                                                 writeln!(w, ";\n}}").unwrap();
685                                         } else { all_fields_settable = false; }
686                                 } else { all_fields_settable = false; }
687                         } else { all_fields_settable = false; }
688                 }
689
690                 if all_fields_settable {
691                         // Build a constructor!
692                         writeln!(w, "/// Constructs a new {} given each field", struct_name).unwrap();
693                         write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_new(", struct_name).unwrap();
694                         for (idx, field) in fields.named.iter().enumerate() {
695                                 if idx != 0 { write!(w, ", ").unwrap(); }
696                                 write!(w, "mut {}_arg: ", field.ident.as_ref().unwrap()).unwrap();
697                                 types.write_c_type(w, &field.ty, Some(&gen_types), false);
698                         }
699                         write!(w, ") -> {} {{\n\t", struct_name).unwrap();
700                         for field in fields.named.iter() {
701                                 let field_name = format!("{}_arg", field.ident.as_ref().unwrap());
702                                 if types.write_from_c_conversion_new_var(w, &syn::Ident::new(&field_name, Span::call_site()), &field.ty, Some(&gen_types)) {
703                                         write!(w, "\n\t").unwrap();
704                                 }
705                         }
706                         writeln!(w, "{} {{ inner: Box::into_raw(Box::new(native{} {{", struct_name, s.ident).unwrap();
707                         for field in fields.named.iter() {
708                                 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
709                                 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
710                                 write!(w, "{}_arg", field.ident.as_ref().unwrap()).unwrap();
711                                 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
712                                 writeln!(w, ",").unwrap();
713                         }
714                         writeln!(w, "\t}})), is_owned: true }}\n}}").unwrap();
715                 }
716         }
717 }
718
719 /// Prints a relevant conversion for impl *
720 ///
721 /// For simple impl Struct {}s, this just outputs the wrapper functions as Struct_fn_name() { .. }.
722 ///
723 /// For impl Trait for Struct{}s, this non-exported generates wrapper functions as
724 /// Trait_Struct_fn_name and a Struct_as_Trait(&struct) -> Trait function which returns a populated
725 /// Trait struct containing a pointer to the passed struct's inner field and the wrapper functions.
726 ///
727 /// A few non-crate Traits are hard-coded including Default.
728 fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut TypeResolver) {
729         match export_status(&i.attrs) {
730                 ExportStatus::Export => {},
731                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
732         }
733
734         if let syn::Type::Tuple(_) = &*i.self_ty {
735                 if types.understood_c_type(&*i.self_ty, None) {
736                         let mut gen_types = GenericTypes::new();
737                         if !gen_types.learn_generics(&i.generics, types) {
738                                 eprintln!("Not implementing anything for `impl (..)` due to not understood generics");
739                                 return;
740                         }
741
742                         if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
743                         if let Some(trait_path) = i.trait_.as_ref() {
744                                 if trait_path.0.is_some() { unimplemented!(); }
745                                 if types.understood_c_path(&trait_path.1) {
746                                         eprintln!("Not implementing anything for `impl Trait for (..)` - we only support manual defines");
747                                         return;
748                                 } else {
749                                         // Just do a manual implementation:
750                                         maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
751                                 }
752                         } else {
753                                 eprintln!("Not implementing anything for plain `impl (..)` block - we only support `impl Trait for (..)` blocks");
754                                 return;
755                         }
756                 }
757                 return;
758         }
759         if let &syn::Type::Path(ref p) = &*i.self_ty {
760                 if p.qself.is_some() { unimplemented!(); }
761                 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
762                         if let Some(resolved_path) = types.maybe_resolve_non_ignored_ident(&ident) {
763                                 let mut gen_types = GenericTypes::new();
764                                 if !gen_types.learn_generics(&i.generics, types) {
765                                         eprintln!("Not implementing anything for impl {} due to not understood generics", ident);
766                                         return;
767                                 }
768
769                                 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
770                                 if let Some(trait_path) = i.trait_.as_ref() {
771                                         if trait_path.0.is_some() { unimplemented!(); }
772                                         if types.understood_c_path(&trait_path.1) {
773                                                 let full_trait_path = types.resolve_path(&trait_path.1, None);
774                                                 let trait_obj = *types.crate_types.traits.get(&full_trait_path).unwrap();
775                                                 // We learn the associated types maping from the original trait object.
776                                                 // That's great, except that they are unresolved idents, so if we learn
777                                                 // mappings from a trai defined in a different file, we may mis-resolve or
778                                                 // fail to resolve the mapped types.
779                                                 gen_types.learn_associated_types(trait_obj, types);
780                                                 let mut impl_associated_types = HashMap::new();
781                                                 for item in i.items.iter() {
782                                                         match item {
783                                                                 syn::ImplItem::Type(t) => {
784                                                                         if let syn::Type::Path(p) = &t.ty {
785                                                                                 if let Some(id) = single_ident_generic_path_to_ident(&p.path) {
786                                                                                         impl_associated_types.insert(&t.ident, id);
787                                                                                 }
788                                                                         }
789                                                                 },
790                                                                 _ => {},
791                                                         }
792                                                 }
793
794                                                 let export = export_status(&trait_obj.attrs);
795                                                 match export {
796                                                         ExportStatus::Export => {},
797                                                         ExportStatus::NoExport|ExportStatus::TestOnly => return,
798                                                 }
799
800                                                 // For cases where we have a concrete native object which implements a
801                                                 // trait and need to return the C-mapped version of the trait, provide a
802                                                 // From<> implementation which does all the work to ensure free is handled
803                                                 // properly. This way we can call this method from deep in the
804                                                 // type-conversion logic without actually knowing the concrete native type.
805                                                 writeln!(w, "impl From<native{}> for crate::{} {{", ident, full_trait_path).unwrap();
806                                                 writeln!(w, "\tfn from(obj: native{}) -> Self {{", ident).unwrap();
807                                                 writeln!(w, "\t\tlet mut rust_obj = {} {{ inner: Box::into_raw(Box::new(obj)), is_owned: true }};", ident).unwrap();
808                                                 writeln!(w, "\t\tlet mut ret = {}_as_{}(&rust_obj);", ident, trait_obj.ident).unwrap();
809                                                 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();
810                                                 writeln!(w, "\t\trust_obj.inner = std::ptr::null_mut();").unwrap();
811                                                 writeln!(w, "\t\tret.free = Some({}_free_void);", ident).unwrap();
812                                                 writeln!(w, "\t\tret\n\t}}\n}}").unwrap();
813
814                                                 writeln!(w, "/// Constructs a new {} which calls the relevant methods on this_arg.", trait_obj.ident).unwrap();
815                                                 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();
816                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_as_{}(this_arg: &{}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
817                                                 writeln!(w, "\tcrate::{} {{", full_trait_path).unwrap();
818                                                 writeln!(w, "\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
819                                                 writeln!(w, "\t\tfree: None,").unwrap();
820
821                                                 macro_rules! write_meth {
822                                                         ($m: expr, $trait: expr, $indent: expr) => {
823                                                                 let trait_method = $trait.items.iter().filter_map(|item| {
824                                                                         if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
825                                                                 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
826                                                                 match export_status(&trait_method.attrs) {
827                                                                         ExportStatus::Export => {},
828                                                                         ExportStatus::NoExport => {
829                                                                                 write!(w, "{}\t\t//XXX: Need to export {}\n", $indent, $m.sig.ident).unwrap();
830                                                                                 continue;
831                                                                         },
832                                                                         ExportStatus::TestOnly => continue,
833                                                                 }
834
835                                                                 let mut printed = false;
836                                                                 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
837                                                                         if let syn::Type::Reference(r) = &**rtype {
838                                                                                 write!(w, "\n\t\t{}{}: ", $indent, $m.sig.ident).unwrap();
839                                                                                 types.write_empty_rust_val(Some(&gen_types), w, &*r.elem);
840                                                                                 writeln!(w, ",\n{}\t\tset_{}: Some({}_{}_set_{}),", $indent, $m.sig.ident, ident, trait_obj.ident, $m.sig.ident).unwrap();
841                                                                                 printed = true;
842                                                                         }
843                                                                 }
844                                                                 if !printed {
845                                                                         write!(w, "{}\t\t{}: {}_{}_{},\n", $indent, $m.sig.ident, ident, trait_obj.ident, $m.sig.ident).unwrap();
846                                                                 }
847                                                         }
848                                                 }
849                                                 for item in trait_obj.items.iter() {
850                                                         match item {
851                                                                 syn::TraitItem::Method(m) => {
852                                                                         write_meth!(m, trait_obj, "");
853                                                                 },
854                                                                 _ => {},
855                                                         }
856                                                 }
857                                                 let mut requires_clone = false;
858                                                 walk_supertraits!(trait_obj, Some(&types), (
859                                                         ("Clone", _) => requires_clone = true,
860                                                         (_, _) => {}
861                                                 ) );
862                                                 walk_supertraits!(trait_obj, Some(&types), (
863                                                         ("Clone", _) => {
864                                                                 writeln!(w, "\t\tclone: Some({}_clone_void),", ident).unwrap();
865                                                         },
866                                                         ("Sync", _) => {}, ("Send", _) => {},
867                                                         ("std::marker::Sync", _) => {}, ("std::marker::Send", _) => {},
868                                                         (s, t) => {
869                                                                 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
870                                                                         writeln!(w, "\t\t{}: crate::{} {{", t, s).unwrap();
871                                                                         writeln!(w, "\t\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
872                                                                         writeln!(w, "\t\t\tfree: None,").unwrap();
873                                                                         for item in supertrait_obj.items.iter() {
874                                                                                 match item {
875                                                                                         syn::TraitItem::Method(m) => {
876                                                                                                 write_meth!(m, supertrait_obj, "\t");
877                                                                                         },
878                                                                                         _ => {},
879                                                                                 }
880                                                                         }
881                                                                         write!(w, "\t\t}},\n").unwrap();
882                                                                         if !types.is_clonable(s) && requires_clone {
883                                                                                 writeln!(w, "\t\t{}_clone: {}_{}_clone,", t, ident, t).unwrap();
884                                                                         }
885                                                                 } else {
886                                                                         write_trait_impl_field_assign(w, s, ident);
887                                                                 }
888                                                         }
889                                                 ) );
890                                                 writeln!(w, "\t}}\n}}\n").unwrap();
891
892                                                 macro_rules! impl_meth {
893                                                         ($m: expr, $trait_path: expr, $trait: expr, $indent: expr) => {
894                                                                 let trait_method = $trait.items.iter().filter_map(|item| {
895                                                                         if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
896                                                                 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
897                                                                 match export_status(&trait_method.attrs) {
898                                                                         ExportStatus::Export => {},
899                                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
900                                                                 }
901
902                                                                 if let syn::ReturnType::Type(_, _) = &$m.sig.output {
903                                                                         writeln!(w, "#[must_use]").unwrap();
904                                                                 }
905                                                                 write!(w, "extern \"C\" fn {}_{}_{}(", ident, trait_obj.ident, $m.sig.ident).unwrap();
906                                                                 gen_types.push_ctx();
907                                                                 assert!(gen_types.learn_generics(&$m.sig.generics, types));
908                                                                 write_method_params(w, &$m.sig, "c_void", types, Some(&gen_types), true, true);
909                                                                 write!(w, " {{\n\t").unwrap();
910                                                                 write_method_var_decl_body(w, &$m.sig, "", types, Some(&gen_types), false);
911                                                                 let mut takes_self = false;
912                                                                 for inp in $m.sig.inputs.iter() {
913                                                                         if let syn::FnArg::Receiver(_) = inp {
914                                                                                 takes_self = true;
915                                                                         }
916                                                                 }
917
918                                                                 let mut t_gen_args = String::new();
919                                                                 for (idx, _) in $trait.generics.params.iter().enumerate() {
920                                                                         if idx != 0 { t_gen_args += ", " };
921                                                                         t_gen_args += "_"
922                                                                 }
923                                                                 if takes_self {
924                                                                         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();
925                                                                 } else {
926                                                                         write!(w, "<native{} as {}::{}<{}>>::{}(", ident, types.orig_crate, $trait_path, t_gen_args, $m.sig.ident).unwrap();
927                                                                 }
928
929                                                                 let mut real_type = "".to_string();
930                                                                 match &$m.sig.output {
931                                                                         syn::ReturnType::Type(_, rtype) => {
932                                                                                 if let Some(mut remaining_path) = first_seg_self(&*rtype) {
933                                                                                         if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
934                                                                                                 real_type = format!("{}", impl_associated_types.get(associated_seg).unwrap());
935                                                                                         }
936                                                                                 }
937                                                                         },
938                                                                         _ => {},
939                                                                 }
940                                                                 write_method_call_params(w, &$m.sig, "", types, Some(&gen_types), &real_type, false);
941                                                                 gen_types.pop_ctx();
942                                                                 write!(w, "\n}}\n").unwrap();
943                                                                 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
944                                                                         if let syn::Type::Reference(r) = &**rtype {
945                                                                                 assert_eq!($m.sig.inputs.len(), 1); // Must only take self
946                                                                                 writeln!(w, "extern \"C\" fn {}_{}_set_{}(trait_self_arg: &{}) {{", ident, trait_obj.ident, $m.sig.ident, trait_obj.ident).unwrap();
947                                                                                 writeln!(w, "\t// This is a bit race-y in the general case, but for our specific use-cases today, we're safe").unwrap();
948                                                                                 writeln!(w, "\t// Specifically, we must ensure that the first time we're called it can never be in parallel").unwrap();
949                                                                                 write!(w, "\tif ").unwrap();
950                                                                                 types.write_empty_rust_val_check(Some(&gen_types), w, &*r.elem, &format!("trait_self_arg.{}", $m.sig.ident));
951                                                                                 writeln!(w, " {{").unwrap();
952                                                                                 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();
953                                                                                 writeln!(w, "\t}}").unwrap();
954                                                                                 writeln!(w, "}}").unwrap();
955                                                                         }
956                                                                 }
957                                                         }
958                                                 }
959
960                                                 for item in i.items.iter() {
961                                                         match item {
962                                                                 syn::ImplItem::Method(m) => {
963                                                                         impl_meth!(m, full_trait_path, trait_obj, "");
964                                                                 },
965                                                                 syn::ImplItem::Type(_) => {},
966                                                                 _ => unimplemented!(),
967                                                         }
968                                                 }
969                                                 walk_supertraits!(trait_obj, Some(&types), (
970                                                         (s, t) => {
971                                                                 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
972                                                                         if !types.is_clonable(s) && requires_clone {
973                                                                                 writeln!(w, "extern \"C\" fn {}_{}_clone(orig: &crate::{}) -> crate::{} {{", ident, t, s, s).unwrap();
974                                                                                 writeln!(w, "\tcrate::{} {{", s).unwrap();
975                                                                                 writeln!(w, "\t\tthis_arg: orig.this_arg,").unwrap();
976                                                                                 writeln!(w, "\t\tfree: None,").unwrap();
977                                                                                 for item in supertrait_obj.items.iter() {
978                                                                                         match item {
979                                                                                                 syn::TraitItem::Method(m) => {
980                                                                                                         write_meth!(m, supertrait_obj, "");
981                                                                                                 },
982                                                                                                 _ => {},
983                                                                                         }
984                                                                                 }
985                                                                                 write!(w, "\t}}\n}}\n").unwrap();
986                                                                         }
987                                                                 }
988                                                         }
989                                                 ) );
990                                                 write!(w, "\n").unwrap();
991                                         } else if path_matches_nongeneric(&trait_path.1, &["From"]) {
992                                         } else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
993                                                 writeln!(w, "/// Creates a \"default\" {}. See struct and individual field documentaiton for details on which values are used.", ident).unwrap();
994                                                 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
995                                                 write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
996                                                 write!(w, "}}\n").unwrap();
997                                         } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "PartialEq"]) {
998                                         } else if (path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) || path_matches_nongeneric(&trait_path.1, &["Clone"])) &&
999                                                         types.c_type_has_inner_from_path(&resolved_path) {
1000                                                 writeln!(w, "impl Clone for {} {{", ident).unwrap();
1001                                                 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
1002                                                 writeln!(w, "\t\tSelf {{").unwrap();
1003                                                 writeln!(w, "\t\t\tinner: if <*mut native{}>::is_null(self.inner) {{ std::ptr::null_mut() }} else {{", ident).unwrap();
1004                                                 writeln!(w, "\t\t\t\tBox::into_raw(Box::new(unsafe {{ &*self.inner }}.clone())) }},").unwrap();
1005                                                 writeln!(w, "\t\t\tis_owned: true,").unwrap();
1006                                                 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
1007                                                 writeln!(w, "#[allow(unused)]").unwrap();
1008                                                 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
1009                                                 writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", ident).unwrap();
1010                                                 writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", ident).unwrap();
1011                                                 writeln!(w, "}}").unwrap();
1012                                                 writeln!(w, "#[no_mangle]").unwrap();
1013                                                 writeln!(w, "/// Creates a copy of the {}", ident).unwrap();
1014                                                 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", ident, ident, ident).unwrap();
1015                                                 writeln!(w, "\torig.clone()").unwrap();
1016                                                 writeln!(w, "}}").unwrap();
1017                                         } else {
1018                                                 //XXX: implement for other things like ToString
1019                                                 // If we have no generics, try a manual implementation:
1020                                                 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
1021                                         }
1022                                 } else {
1023                                         let declared_type = (*types.get_declared_type(&ident).unwrap()).clone();
1024                                         for item in i.items.iter() {
1025                                                 match item {
1026                                                         syn::ImplItem::Method(m) => {
1027                                                                 if let syn::Visibility::Public(_) = m.vis {
1028                                                                         match export_status(&m.attrs) {
1029                                                                                 ExportStatus::Export => {},
1030                                                                                 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1031                                                                         }
1032                                                                         if m.defaultness.is_some() { unimplemented!(); }
1033                                                                         writeln_docs(w, &m.attrs, "");
1034                                                                         if let syn::ReturnType::Type(_, _) = &m.sig.output {
1035                                                                                 writeln!(w, "#[must_use]").unwrap();
1036                                                                         }
1037                                                                         write!(w, "#[no_mangle]\npub extern \"C\" fn {}_{}(", ident, m.sig.ident).unwrap();
1038                                                                         let ret_type = match &declared_type {
1039                                                                                 DeclType::MirroredEnum => format!("{}", ident),
1040                                                                                 DeclType::StructImported => format!("{}", ident),
1041                                                                                 _ => unimplemented!(),
1042                                                                         };
1043                                                                         gen_types.push_ctx();
1044                                                                         assert!(gen_types.learn_generics(&m.sig.generics, types));
1045                                                                         write_method_params(w, &m.sig, &ret_type, types, Some(&gen_types), false, true);
1046                                                                         write!(w, " {{\n\t").unwrap();
1047                                                                         write_method_var_decl_body(w, &m.sig, "", types, Some(&gen_types), false);
1048                                                                         let mut takes_self = false;
1049                                                                         let mut takes_mut_self = false;
1050                                                                         for inp in m.sig.inputs.iter() {
1051                                                                                 if let syn::FnArg::Receiver(r) = inp {
1052                                                                                         takes_self = true;
1053                                                                                         if r.mutability.is_some() { takes_mut_self = true; }
1054                                                                                 }
1055                                                                         }
1056                                                                         if takes_mut_self {
1057                                                                                 write!(w, "unsafe {{ &mut (*(this_arg.inner as *mut native{})) }}.{}(", ident, m.sig.ident).unwrap();
1058                                                                         } else if takes_self {
1059                                                                                 write!(w, "unsafe {{ &*this_arg.inner }}.{}(", m.sig.ident).unwrap();
1060                                                                         } else {
1061                                                                                 write!(w, "{}::{}::{}(", types.orig_crate, resolved_path, m.sig.ident).unwrap();
1062                                                                         }
1063                                                                         write_method_call_params(w, &m.sig, "", types, Some(&gen_types), &ret_type, false);
1064                                                                         gen_types.pop_ctx();
1065                                                                         writeln!(w, "\n}}\n").unwrap();
1066                                                                 }
1067                                                         },
1068                                                         _ => {},
1069                                                 }
1070                                         }
1071                                 }
1072                         } else if let Some(resolved_path) = types.maybe_resolve_ident(&ident) {
1073                                 if let Some(aliases) = types.crate_types.reverse_alias_map.get(&resolved_path).cloned() {
1074                                         'alias_impls: for (alias, arguments) in aliases {
1075                                                 let alias_resolved = types.resolve_path(&alias, None);
1076                                                 for (idx, gen) in i.generics.params.iter().enumerate() {
1077                                                         match gen {
1078                                                                 syn::GenericParam::Type(type_param) => {
1079                                                                         'bounds_check: for bound in type_param.bounds.iter() {
1080                                                                                 if let syn::TypeParamBound::Trait(trait_bound) = bound {
1081                                                                                         if let syn::PathArguments::AngleBracketed(ref t) = &arguments {
1082                                                                                                 assert!(idx < t.args.len());
1083                                                                                                 if let syn::GenericArgument::Type(syn::Type::Path(p)) = &t.args[idx] {
1084                                                                                                         let generic_arg = types.resolve_path(&p.path, None);
1085                                                                                                         let generic_bound = types.resolve_path(&trait_bound.path, None);
1086                                                                                                         if let Some(traits_impld) = types.crate_types.trait_impls.get(&generic_arg) {
1087                                                                                                                 for trait_impld in traits_impld {
1088                                                                                                                         if *trait_impld == generic_bound { continue 'bounds_check; }
1089                                                                                                                 }
1090                                                                                                                 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1091                                                                                                                 continue 'alias_impls;
1092                                                                                                         } else {
1093                                                                                                                 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1094                                                                                                                 continue 'alias_impls;
1095                                                                                                         }
1096                                                                                                 } else { unimplemented!(); }
1097                                                                                         } else { unimplemented!(); }
1098                                                                                 } else { unimplemented!(); }
1099                                                                         }
1100                                                                 },
1101                                                                 syn::GenericParam::Lifetime(_) => {},
1102                                                                 syn::GenericParam::Const(_) => unimplemented!(),
1103                                                         }
1104                                                 }
1105                                                 let aliased_impl = syn::ItemImpl {
1106                                                         attrs: i.attrs.clone(),
1107                                                         brace_token: syn::token::Brace(Span::call_site()),
1108                                                         defaultness: None,
1109                                                         generics: syn::Generics {
1110                                                                 lt_token: None,
1111                                                                 params: syn::punctuated::Punctuated::new(),
1112                                                                 gt_token: None,
1113                                                                 where_clause: None,
1114                                                         },
1115                                                         impl_token: syn::Token![impl](Span::call_site()),
1116                                                         items: i.items.clone(),
1117                                                         self_ty: Box::new(syn::Type::Path(syn::TypePath { qself: None, path: alias.clone() })),
1118                                                         trait_: i.trait_.clone(),
1119                                                         unsafety: None,
1120                                                 };
1121                                                 writeln_impl(w, &aliased_impl, types);
1122                                         }
1123                                 } else {
1124                                         eprintln!("Not implementing anything for {} due to it being marked not exported", ident);
1125                                 }
1126                         } else {
1127                                 eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub)", ident);
1128                         }
1129                 }
1130         }
1131 }
1132
1133
1134 /// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
1135 /// is unitary), we generate an equivalent enum with all types replaced with their C mapped
1136 /// versions followed by conversion functions which map between the Rust version and the C mapped
1137 /// version.
1138 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) {
1139         match export_status(&e.attrs) {
1140                 ExportStatus::Export => {},
1141                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1142         }
1143
1144         if is_enum_opaque(e) {
1145                 eprintln!("Skipping enum {} as it contains non-unit fields", e.ident);
1146                 writeln_opaque(w, &e.ident, &format!("{}", e.ident), &e.generics, &e.attrs, types, extra_headers, cpp_headers);
1147                 return;
1148         }
1149         writeln_docs(w, &e.attrs, "");
1150
1151         if e.generics.lt_token.is_some() {
1152                 unimplemented!();
1153         }
1154
1155         let mut needs_free = false;
1156
1157         writeln!(w, "#[must_use]\n#[derive(Clone)]\n#[repr(C)]\npub enum {} {{", e.ident).unwrap();
1158         for var in e.variants.iter() {
1159                 assert_eq!(export_status(&var.attrs), ExportStatus::Export); // We can't partially-export a mirrored enum
1160                 writeln_docs(w, &var.attrs, "\t");
1161                 write!(w, "\t{}", var.ident).unwrap();
1162                 if let syn::Fields::Named(fields) = &var.fields {
1163                         needs_free = true;
1164                         writeln!(w, " {{").unwrap();
1165                         for field in fields.named.iter() {
1166                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1167                                 writeln_docs(w, &field.attrs, "\t\t");
1168                                 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1169                                 types.write_c_type(w, &field.ty, None, false);
1170                                 writeln!(w, ",").unwrap();
1171                         }
1172                         write!(w, "\t}}").unwrap();
1173                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1174                         needs_free = true;
1175                         write!(w, "(").unwrap();
1176                         for (idx, field) in fields.unnamed.iter().enumerate() {
1177                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1178                                 types.write_c_type(w, &field.ty, None, false);
1179                                 if idx != fields.unnamed.len() - 1 {
1180                                         write!(w, ",").unwrap();
1181                                 }
1182                         }
1183                         write!(w, ")").unwrap();
1184                 }
1185                 if var.discriminant.is_some() { unimplemented!(); }
1186                 writeln!(w, ",").unwrap();
1187         }
1188         writeln!(w, "}}\nuse {}::{}::{} as native{};\nimpl {} {{", types.orig_crate, types.module_path, e.ident, e.ident, e.ident).unwrap();
1189
1190         macro_rules! write_conv {
1191                 ($fn_sig: expr, $to_c: expr, $ref: expr) => {
1192                         writeln!(w, "\t#[allow(unused)]\n\tpub(crate) fn {} {{\n\t\tmatch {} {{", $fn_sig, if $to_c { "native" } else { "self" }).unwrap();
1193                         for var in e.variants.iter() {
1194                                 write!(w, "\t\t\t{}{}::{} ", if $to_c { "native" } else { "" }, e.ident, var.ident).unwrap();
1195                                 if let syn::Fields::Named(fields) = &var.fields {
1196                                         write!(w, "{{").unwrap();
1197                                         for field in fields.named.iter() {
1198                                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1199                                                 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, field.ident.as_ref().unwrap()).unwrap();
1200                                         }
1201                                         write!(w, "}} ").unwrap();
1202                                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1203                                         write!(w, "(").unwrap();
1204                                         for (idx, field) in fields.unnamed.iter().enumerate() {
1205                                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1206                                                 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, ('a' as u8 + idx as u8) as char).unwrap();
1207                                         }
1208                                         write!(w, ") ").unwrap();
1209                                 }
1210                                 write!(w, "=>").unwrap();
1211
1212                                 macro_rules! handle_field_a {
1213                                         ($field: expr, $field_ident: expr) => { {
1214                                                 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1215                                                 let mut sink = ::std::io::sink();
1216                                                 let mut out: &mut dyn std::io::Write = if $ref { &mut sink } else { w };
1217                                                 let new_var = if $to_c {
1218                                                         types.write_to_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None, false)
1219                                                 } else {
1220                                                         types.write_from_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None)
1221                                                 };
1222                                                 if $ref || new_var {
1223                                                         if $ref {
1224                                                                 write!(w, "let mut {}_nonref = (*{}).clone();\n\t\t\t\t", $field_ident, $field_ident).unwrap();
1225                                                                 if new_var {
1226                                                                         let nonref_ident = syn::Ident::new(&format!("{}_nonref", $field_ident), Span::call_site());
1227                                                                         if $to_c {
1228                                                                                 types.write_to_c_conversion_new_var(w, &nonref_ident, &$field.ty, None, false);
1229                                                                         } else {
1230                                                                                 types.write_from_c_conversion_new_var(w, &nonref_ident, &$field.ty, None);
1231                                                                         }
1232                                                                         write!(w, "\n\t\t\t\t").unwrap();
1233                                                                 }
1234                                                         } else {
1235                                                                 write!(w, "\n\t\t\t\t").unwrap();
1236                                                         }
1237                                                 }
1238                                         } }
1239                                 }
1240                                 if let syn::Fields::Named(fields) = &var.fields {
1241                                         write!(w, " {{\n\t\t\t\t").unwrap();
1242                                         for field in fields.named.iter() {
1243                                                 handle_field_a!(field, field.ident.as_ref().unwrap());
1244                                         }
1245                                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1246                                         write!(w, " {{\n\t\t\t\t").unwrap();
1247                                         for (idx, field) in fields.unnamed.iter().enumerate() {
1248                                                 handle_field_a!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1249                                         }
1250                                 } else { write!(w, " ").unwrap(); }
1251
1252                                 write!(w, "{}{}::{}", if $to_c { "" } else { "native" }, e.ident, var.ident).unwrap();
1253
1254                                 macro_rules! handle_field_b {
1255                                         ($field: expr, $field_ident: expr) => { {
1256                                                 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1257                                                 if $to_c {
1258                                                         types.write_to_c_conversion_inline_prefix(w, &$field.ty, None, false);
1259                                                 } else {
1260                                                         types.write_from_c_conversion_prefix(w, &$field.ty, None);
1261                                                 }
1262                                                 write!(w, "{}{}", $field_ident,
1263                                                         if $ref { "_nonref" } else { "" }).unwrap();
1264                                                 if $to_c {
1265                                                         types.write_to_c_conversion_inline_suffix(w, &$field.ty, None, false);
1266                                                 } else {
1267                                                         types.write_from_c_conversion_suffix(w, &$field.ty, None);
1268                                                 }
1269                                                 write!(w, ",").unwrap();
1270                                         } }
1271                                 }
1272
1273                                 if let syn::Fields::Named(fields) = &var.fields {
1274                                         write!(w, " {{").unwrap();
1275                                         for field in fields.named.iter() {
1276                                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1277                                                 write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1278                                                 handle_field_b!(field, field.ident.as_ref().unwrap());
1279                                         }
1280                                         writeln!(w, "\n\t\t\t\t}}").unwrap();
1281                                         write!(w, "\t\t\t}}").unwrap();
1282                                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1283                                         write!(w, " (").unwrap();
1284                                         for (idx, field) in fields.unnamed.iter().enumerate() {
1285                                                 write!(w, "\n\t\t\t\t\t").unwrap();
1286                                                 handle_field_b!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1287                                         }
1288                                         writeln!(w, "\n\t\t\t\t)").unwrap();
1289                                         write!(w, "\t\t\t}}").unwrap();
1290                                 }
1291                                 writeln!(w, ",").unwrap();
1292                         }
1293                         writeln!(w, "\t\t}}\n\t}}").unwrap();
1294                 }
1295         }
1296
1297         write_conv!(format!("to_native(&self) -> native{}", e.ident), false, true);
1298         write_conv!(format!("into_native(self) -> native{}", e.ident), false, false);
1299         write_conv!(format!("from_native(native: &native{}) -> Self", e.ident), true, true);
1300         write_conv!(format!("native_into(native: native{}) -> Self", e.ident), true, false);
1301         writeln!(w, "}}").unwrap();
1302
1303         if needs_free {
1304                 writeln!(w, "/// Frees any resources used by the {}", e.ident).unwrap();
1305                 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", e.ident, e.ident).unwrap();
1306         }
1307         writeln!(w, "/// Creates a copy of the {}", e.ident).unwrap();
1308         writeln!(w, "#[no_mangle]").unwrap();
1309         writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
1310         writeln!(w, "\torig.clone()").unwrap();
1311         writeln!(w, "}}").unwrap();
1312         write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free);
1313 }
1314
1315 fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &mut TypeResolver<'b, 'a>) {
1316         match export_status(&f.attrs) {
1317                 ExportStatus::Export => {},
1318                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1319         }
1320         writeln_docs(w, &f.attrs, "");
1321
1322         let mut gen_types = GenericTypes::new();
1323         if !gen_types.learn_generics(&f.sig.generics, types) { return; }
1324
1325         write!(w, "#[no_mangle]\npub extern \"C\" fn {}(", f.sig.ident).unwrap();
1326         write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
1327         write!(w, " {{\n\t").unwrap();
1328         write_method_var_decl_body(w, &f.sig, "", types, Some(&gen_types), false);
1329         write!(w, "{}::{}::{}(", types.orig_crate, types.module_path, f.sig.ident).unwrap();
1330         write_method_call_params(w, &f.sig, "", types, Some(&gen_types), "", false);
1331         writeln!(w, "\n}}\n").unwrap();
1332 }
1333
1334 // ********************************
1335 // *** File/Crate Walking Logic ***
1336 // ********************************
1337 /// A public module
1338 struct ASTModule {
1339         pub attrs: Vec<syn::Attribute>,
1340         pub items: Vec<syn::Item>,
1341         pub submods: Vec<String>,
1342 }
1343 /// A struct containing the syn::File AST for each file in the crate.
1344 struct FullLibraryAST {
1345         modules: HashMap<String, ASTModule, NonRandomHash>,
1346 }
1347 impl FullLibraryAST {
1348         fn load_module(&mut self, module: String, attrs: Vec<syn::Attribute>, mut items: Vec<syn::Item>) {
1349                 let mut non_mod_items = Vec::with_capacity(items.len());
1350                 let mut submods = Vec::with_capacity(items.len());
1351                 for item in items.drain(..) {
1352                         match item {
1353                                 syn::Item::Mod(m) if m.content.is_some() => {
1354                                         if export_status(&m.attrs) == ExportStatus::Export {
1355                                                 if let syn::Visibility::Public(_) = m.vis {
1356                                                         let modident = format!("{}", m.ident);
1357                                                         let modname = if module != "" {
1358                                                                 module.clone() + "::" + &modident
1359                                                         } else {
1360                                                                 modident.clone()
1361                                                         };
1362                                                         self.load_module(modname, m.attrs, m.content.unwrap().1);
1363                                                         submods.push(modident);
1364                                                 } else {
1365                                                         non_mod_items.push(syn::Item::Mod(m));
1366                                                 }
1367                                         }
1368                                 },
1369                                 syn::Item::Mod(_) => panic!("--pretty=expanded output should never have non-body modules"),
1370                                 _ => { non_mod_items.push(item); }
1371                         }
1372                 }
1373                 self.modules.insert(module, ASTModule { attrs, items: non_mod_items, submods });
1374         }
1375
1376         pub fn load_lib(lib: syn::File) -> Self {
1377                 assert_eq!(export_status(&lib.attrs), ExportStatus::Export);
1378                 let mut res = Self { modules: HashMap::default() };
1379                 res.load_module("".to_owned(), lib.attrs, lib.items);
1380                 res
1381         }
1382 }
1383
1384 /// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
1385 /// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
1386 /// at `module` from C.
1387 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) {
1388         for (module, astmod) in libast.modules.iter() {
1389                 let ASTModule { ref attrs, ref items, ref submods } = astmod;
1390                 assert_eq!(export_status(&attrs), ExportStatus::Export);
1391
1392                 let new_file_path = if submods.is_empty() {
1393                         format!("{}/{}.rs", out_dir, module.replace("::", "/"))
1394                 } else if module != "" {
1395                         format!("{}/{}/mod.rs", out_dir, module.replace("::", "/"))
1396                 } else {
1397                         format!("{}/lib.rs", out_dir)
1398                 };
1399                 let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
1400                 let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1401                         .open(new_file_path).expect("Unable to open new src file");
1402
1403                 writeln!(out, "// This file is Copyright its original authors, visible in version control").unwrap();
1404                 writeln!(out, "// history and in the source files from which this was generated.").unwrap();
1405                 writeln!(out, "//").unwrap();
1406                 writeln!(out, "// This file is licensed under the license available in the LICENSE or LICENSE.md").unwrap();
1407                 writeln!(out, "// file in the root of this repository or, if no such file exists, the same").unwrap();
1408                 writeln!(out, "// license as that which applies to the original source files from which this").unwrap();
1409                 writeln!(out, "// source was automatically generated.").unwrap();
1410                 writeln!(out, "").unwrap();
1411
1412                 writeln_docs(&mut out, &attrs, "");
1413
1414                 if module == "" {
1415                         // Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
1416                         // and bitcoin hand-written modules.
1417                         writeln!(out, "#![allow(unknown_lints)]").unwrap();
1418                         writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
1419                         writeln!(out, "#![allow(non_snake_case)]").unwrap();
1420                         writeln!(out, "#![allow(unused_imports)]").unwrap();
1421                         writeln!(out, "#![allow(unused_variables)]").unwrap();
1422                         writeln!(out, "#![allow(unused_mut)]").unwrap();
1423                         writeln!(out, "#![allow(unused_parens)]").unwrap();
1424                         writeln!(out, "#![allow(unused_unsafe)]").unwrap();
1425                         writeln!(out, "#![allow(unused_braces)]").unwrap();
1426                         writeln!(out, "#![deny(missing_docs)]").unwrap();
1427                         writeln!(out, "pub mod c_types;").unwrap();
1428                         writeln!(out, "pub mod bitcoin;").unwrap();
1429                 } else {
1430                         writeln!(out, "\nuse std::ffi::c_void;\nuse bitcoin::hashes::Hash;\nuse crate::c_types::*;\n").unwrap();
1431                 }
1432
1433                 for m in submods {
1434                         writeln!(out, "pub mod {};", m).unwrap();
1435                 }
1436
1437                 eprintln!("Converting {} entries...", module);
1438
1439                 let import_resolver = ImportResolver::new(module, items);
1440                 let mut type_resolver = TypeResolver::new(orig_crate, module, import_resolver, crate_types);
1441
1442                 for item in items.iter() {
1443                         match item {
1444                                 syn::Item::Use(_) => {}, // Handled above
1445                                 syn::Item::Static(_) => {},
1446                                 syn::Item::Enum(e) => {
1447                                         if let syn::Visibility::Public(_) = e.vis {
1448                                                 writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
1449                                         }
1450                                 },
1451                                 syn::Item::Impl(i) => {
1452                                         writeln_impl(&mut out, &i, &mut type_resolver);
1453                                 },
1454                                 syn::Item::Struct(s) => {
1455                                         if let syn::Visibility::Public(_) = s.vis {
1456                                                 writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
1457                                         }
1458                                 },
1459                                 syn::Item::Trait(t) => {
1460                                         if let syn::Visibility::Public(_) = t.vis {
1461                                                 writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
1462                                         }
1463                                 },
1464                                 syn::Item::Mod(_) => {}, // We don't have to do anything - the top loop handles these.
1465                                 syn::Item::Const(c) => {
1466                                         // Re-export any primitive-type constants.
1467                                         if let syn::Visibility::Public(_) = c.vis {
1468                                                 if let syn::Type::Path(p) = &*c.ty {
1469                                                         let resolved_path = type_resolver.resolve_path(&p.path, None);
1470                                                         if type_resolver.is_primitive(&resolved_path) {
1471                                                                 writeln_docs(&mut out, &c.attrs, "");
1472                                                                 writeln!(out, "\n#[no_mangle]").unwrap();
1473                                                                 writeln!(out, "pub static {}: {} = {}::{}::{};", c.ident, resolved_path, orig_crate, module, c.ident).unwrap();
1474                                                         }
1475                                                 }
1476                                         }
1477                                 },
1478                                 syn::Item::Type(t) => {
1479                                         if let syn::Visibility::Public(_) = t.vis {
1480                                                 match export_status(&t.attrs) {
1481                                                         ExportStatus::Export => {},
1482                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1483                                                 }
1484
1485                                                 let mut process_alias = true;
1486                                                 for tok in t.generics.params.iter() {
1487                                                         if let syn::GenericParam::Lifetime(_) = tok {}
1488                                                         else { process_alias = false; }
1489                                                 }
1490                                                 if process_alias {
1491                                                         match &*t.ty {
1492                                                                 syn::Type::Path(_) =>
1493                                                                         writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &t.generics, &t.attrs, &type_resolver, header_file, cpp_header_file),
1494                                                                 _ => {}
1495                                                         }
1496                                                 }
1497                                         }
1498                                 },
1499                                 syn::Item::Fn(f) => {
1500                                         if let syn::Visibility::Public(_) = f.vis {
1501                                                 writeln_fn(&mut out, &f, &mut type_resolver);
1502                                         }
1503                                 },
1504                                 syn::Item::Macro(m) => {
1505                                         if m.ident.is_none() { // If its not a macro definition
1506                                                 convert_macro(&mut out, &m.mac.path, &m.mac.tokens, &type_resolver);
1507                                         }
1508                                 },
1509                                 syn::Item::Verbatim(_) => {},
1510                                 syn::Item::ExternCrate(_) => {},
1511                                 _ => unimplemented!(),
1512                         }
1513                 }
1514
1515                 out.flush().unwrap();
1516         }
1517 }
1518
1519 fn walk_private_mod<'a>(module: String, items: &'a syn::ItemMod, crate_types: &mut CrateTypes<'a>) {
1520         let import_resolver = ImportResolver::new(&module, &items.content.as_ref().unwrap().1);
1521         for item in items.content.as_ref().unwrap().1.iter() {
1522                 match item {
1523                         syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types),
1524                         syn::Item::Impl(i) => {
1525                                 if let &syn::Type::Path(ref p) = &*i.self_ty {
1526                                         if let Some(trait_path) = i.trait_.as_ref() {
1527                                                 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1528                                                         if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1529                                                                 match crate_types.trait_impls.entry(sp) {
1530                                                                         hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1531                                                                         hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1532                                                                 }
1533                                                         }
1534                                                 }
1535                                         }
1536                                 }
1537                         },
1538                         _ => {},
1539                 }
1540         }
1541 }
1542
1543 /// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
1544 fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
1545         for (module, astmod) in ast_storage.modules.iter() {
1546                 let ASTModule { ref attrs, ref items, submods: _ } = astmod;
1547                 assert_eq!(export_status(&attrs), ExportStatus::Export);
1548                 let import_resolver = ImportResolver::new(module, items);
1549
1550                 for item in items.iter() {
1551                         match item {
1552                                 syn::Item::Struct(s) => {
1553                                         if let syn::Visibility::Public(_) = s.vis {
1554                                                 match export_status(&s.attrs) {
1555                                                         ExportStatus::Export => {},
1556                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1557                                                 }
1558                                                 let struct_path = format!("{}::{}", module, s.ident);
1559                                                 crate_types.opaques.insert(struct_path, &s.ident);
1560                                         }
1561                                 },
1562                                 syn::Item::Trait(t) => {
1563                                         if let syn::Visibility::Public(_) = t.vis {
1564                                                 match export_status(&t.attrs) {
1565                                                         ExportStatus::Export => {},
1566                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1567                                                 }
1568                                                 let trait_path = format!("{}::{}", module, t.ident);
1569                                                 walk_supertraits!(t, None, (
1570                                                         ("Clone", _) => {
1571                                                                 crate_types.clonable_types.insert("crate::".to_owned() + &trait_path);
1572                                                         },
1573                                                         (_, _) => {}
1574                                                 ) );
1575                                                 crate_types.traits.insert(trait_path, &t);
1576                                         }
1577                                 },
1578                                 syn::Item::Type(t) => {
1579                                         if let syn::Visibility::Public(_) = t.vis {
1580                                                 match export_status(&t.attrs) {
1581                                                         ExportStatus::Export => {},
1582                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1583                                                 }
1584                                                 let type_path = format!("{}::{}", module, t.ident);
1585                                                 let mut process_alias = true;
1586                                                 for tok in t.generics.params.iter() {
1587                                                         if let syn::GenericParam::Lifetime(_) = tok {}
1588                                                         else { process_alias = false; }
1589                                                 }
1590                                                 if process_alias {
1591                                                         match &*t.ty {
1592                                                                 syn::Type::Path(p) => {
1593                                                                         // If its a path with no generics, assume we don't map the aliased type and map it opaque
1594                                                                         let mut segments = syn::punctuated::Punctuated::new();
1595                                                                         segments.push(syn::PathSegment {
1596                                                                                 ident: t.ident.clone(),
1597                                                                                 arguments: syn::PathArguments::None,
1598                                                                         });
1599                                                                         let path_obj = syn::Path { leading_colon: None, segments };
1600                                                                         let args_obj = p.path.segments.last().unwrap().arguments.clone();
1601                                                                         match crate_types.reverse_alias_map.entry(import_resolver.maybe_resolve_path(&p.path, None).unwrap()) {
1602                                                                                 hash_map::Entry::Occupied(mut e) => { e.get_mut().push((path_obj, args_obj)); },
1603                                                                                 hash_map::Entry::Vacant(e) => { e.insert(vec![(path_obj, args_obj)]); },
1604                                                                         }
1605
1606                                                                         crate_types.opaques.insert(type_path.clone(), &t.ident);
1607                                                                 },
1608                                                                 _ => {
1609                                                                         crate_types.type_aliases.insert(type_path, import_resolver.resolve_imported_refs((*t.ty).clone()));
1610                                                                 }
1611                                                         }
1612                                                 }
1613                                         }
1614                                 },
1615                                 syn::Item::Enum(e) if is_enum_opaque(e) => {
1616                                         if let syn::Visibility::Public(_) = e.vis {
1617                                                 match export_status(&e.attrs) {
1618                                                         ExportStatus::Export => {},
1619                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1620                                                 }
1621                                                 let enum_path = format!("{}::{}", module, e.ident);
1622                                                 crate_types.opaques.insert(enum_path, &e.ident);
1623                                         }
1624                                 },
1625                                 syn::Item::Enum(e) => {
1626                                         if let syn::Visibility::Public(_) = e.vis {
1627                                                 match export_status(&e.attrs) {
1628                                                         ExportStatus::Export => {},
1629                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1630                                                 }
1631                                                 let enum_path = format!("{}::{}", module, e.ident);
1632                                                 crate_types.mirrored_enums.insert(enum_path, &e);
1633                                         }
1634                                 },
1635                                 syn::Item::Impl(i) => {
1636                                         if let &syn::Type::Path(ref p) = &*i.self_ty {
1637                                                 if let Some(trait_path) = i.trait_.as_ref() {
1638                                                         if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) {
1639                                                                 if let Some(full_path) = import_resolver.maybe_resolve_path(&p.path, None) {
1640                                                                         crate_types.clonable_types.insert("crate::".to_owned() + &full_path);
1641                                                                 }
1642                                                         }
1643                                                         if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1644                                                                 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1645                                                                         match crate_types.trait_impls.entry(sp) {
1646                                                                                 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1647                                                                                 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1648                                                                         }
1649                                                                 }
1650                                                         }
1651                                                 }
1652                                         }
1653                                 },
1654                                 syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types),
1655                                 _ => {},
1656                         }
1657                 }
1658         }
1659 }
1660
1661 fn main() {
1662         let args: Vec<String> = env::args().collect();
1663         if args.len() != 6 {
1664                 eprintln!("Usage: target/dir source_crate_name derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
1665                 process::exit(1);
1666         }
1667
1668         let mut derived_templates = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1669                 .open(&args[3]).expect("Unable to open new header file");
1670         let mut header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1671                 .open(&args[4]).expect("Unable to open new header file");
1672         let mut cpp_header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1673                 .open(&args[5]).expect("Unable to open new header file");
1674
1675         writeln!(header_file, "#if defined(__GNUC__)").unwrap();
1676         writeln!(header_file, "#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
1677         writeln!(header_file, "#define MUST_USE_RES __attribute__((warn_unused_result))").unwrap();
1678         writeln!(header_file, "#else").unwrap();
1679         writeln!(header_file, "#define MUST_USE_STRUCT").unwrap();
1680         writeln!(header_file, "#define MUST_USE_RES").unwrap();
1681         writeln!(header_file, "#endif").unwrap();
1682         writeln!(header_file, "#if defined(__clang__)").unwrap();
1683         writeln!(header_file, "#define NONNULL_PTR _Nonnull").unwrap();
1684         writeln!(header_file, "#else").unwrap();
1685         writeln!(header_file, "#define NONNULL_PTR").unwrap();
1686         writeln!(header_file, "#endif").unwrap();
1687         writeln!(cpp_header_file, "#include <string.h>\nnamespace LDK {{").unwrap();
1688
1689         // First parse the full crate's ASTs, caching them so that we can hold references to the AST
1690         // objects in other datastructures:
1691         let mut lib_src = String::new();
1692         std::io::stdin().lock().read_to_string(&mut lib_src).unwrap();
1693         let lib_syntax = syn::parse_file(&lib_src).expect("Unable to parse file");
1694         let libast = FullLibraryAST::load_lib(lib_syntax);
1695
1696         // ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
1697         // when parsing other file ASTs...
1698         let mut libtypes = CrateTypes { traits: HashMap::new(), opaques: HashMap::new(), mirrored_enums: HashMap::new(),
1699                 type_aliases: HashMap::new(), reverse_alias_map: HashMap::new(), templates_defined: HashMap::default(),
1700                 template_file: &mut derived_templates,
1701                 clonable_types: HashSet::new(), trait_impls: HashMap::new() };
1702         walk_ast(&libast, &mut libtypes);
1703
1704         // ... finally, do the actual file conversion/mapping, writing out types as we go.
1705         convert_file(&libast, &mut libtypes, &args[1], &args[2], &mut header_file, &mut cpp_header_file);
1706
1707         // For container templates which we created while walking the crate, make sure we add C++
1708         // mapped types so that C++ users can utilize the auto-destructors available.
1709         for (ty, has_destructor) in libtypes.templates_defined.iter() {
1710                 write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor);
1711         }
1712         writeln!(cpp_header_file, "}}").unwrap();
1713
1714         header_file.flush().unwrap();
1715         cpp_header_file.flush().unwrap();
1716         derived_templates.flush().unwrap();
1717 }