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