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