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