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