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