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