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