]> git.bitcoin.ninja Git - rust-lightning/blob - c-bindings-gen/src/main.rs
[bindings] Figure out in-file structs and enums before processing
[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 fn declare_struct<'a, 'b>(s: &'a syn::ItemStruct, types: &mut TypeResolver<'b, 'a>) -> bool {
504         let export = export_status(&s.attrs);
505         match export {
506                 ExportStatus::Export => {},
507                 ExportStatus::TestOnly => return false,
508                 ExportStatus::NoExport => {
509                         types.struct_ignored(&s.ident);
510                         return false;
511                 }
512         }
513
514         types.struct_imported(&s.ident, format!("{}", s.ident));
515         true
516 }
517
518 /// Writes out all the relevant mappings for a Rust struct, deferring to writeln_opaque to generate
519 /// the struct itself, and then writing getters and setters for public, understood-type fields and
520 /// a constructor if every field is public.
521 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) {
522         if !declare_struct(s, types) { return; }
523
524         let struct_name = &format!("{}", s.ident);
525         writeln_opaque(w, &s.ident, struct_name, &s.generics, &s.attrs, types, extra_headers, cpp_headers);
526
527         eprintln!("exporting fields for {}", struct_name);
528         if let syn::Fields::Named(fields) = &s.fields {
529                 let mut gen_types = GenericTypes::new();
530                 assert!(gen_types.learn_generics(&s.generics, types));
531
532                 let mut all_fields_settable = true;
533                 for field in fields.named.iter() {
534                         if let syn::Visibility::Public(_) = field.vis {
535                                 let export = export_status(&field.attrs);
536                                 match export {
537                                         ExportStatus::Export => {},
538                                         ExportStatus::NoExport|ExportStatus::TestOnly => {
539                                                 all_fields_settable = false;
540                                                 continue
541                                         },
542                                 }
543
544                                 if let Some(ident) = &field.ident {
545                                         let ref_type = syn::Type::Reference(syn::TypeReference {
546                                                 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
547                                                 elem: Box::new(field.ty.clone()) });
548                                         if types.understood_c_type(&ref_type, Some(&gen_types)) {
549                                                 writeln_docs(w, &field.attrs, "");
550                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> ", struct_name, ident, struct_name).unwrap();
551                                                 types.write_c_type(w, &ref_type, Some(&gen_types), true);
552                                                 write!(w, " {{\n\tlet mut inner_val = &mut unsafe {{ &mut *this_ptr.inner }}.{};\n\t", ident).unwrap();
553                                                 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);
554                                                 if local_var { write!(w, "\n\t").unwrap(); }
555                                                 types.write_to_c_conversion_inline_prefix(w, &ref_type, Some(&gen_types), true);
556                                                 if local_var {
557                                                         write!(w, "inner_val").unwrap();
558                                                 } else {
559                                                         write!(w, "(*inner_val)").unwrap();
560                                                 }
561                                                 types.write_to_c_conversion_inline_suffix(w, &ref_type, Some(&gen_types), true);
562                                                 writeln!(w, "\n}}").unwrap();
563                                         }
564
565                                         if types.understood_c_type(&field.ty, Some(&gen_types)) {
566                                                 writeln_docs(w, &field.attrs, "");
567                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_set_{}(this_ptr: &mut {}, mut val: ", struct_name, ident, struct_name).unwrap();
568                                                 types.write_c_type(w, &field.ty, Some(&gen_types), false);
569                                                 write!(w, ") {{\n\t").unwrap();
570                                                 let local_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("val", Span::call_site()), &field.ty, Some(&gen_types));
571                                                 if local_var { write!(w, "\n\t").unwrap(); }
572                                                 write!(w, "unsafe {{ &mut *this_ptr.inner }}.{} = ", ident).unwrap();
573                                                 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
574                                                 write!(w, "val").unwrap();
575                                                 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
576                                                 writeln!(w, ";\n}}").unwrap();
577                                         } else { all_fields_settable = false; }
578                                 } else { all_fields_settable = false; }
579                         } else { all_fields_settable = false; }
580                 }
581
582                 if all_fields_settable {
583                         // Build a constructor!
584                         write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_new(", struct_name).unwrap();
585                         for (idx, field) in fields.named.iter().enumerate() {
586                                 if idx != 0 { write!(w, ", ").unwrap(); }
587                                 write!(w, "mut {}_arg: ", field.ident.as_ref().unwrap()).unwrap();
588                                 types.write_c_type(w, &field.ty, Some(&gen_types), false);
589                         }
590                         write!(w, ") -> {} {{\n\t", struct_name).unwrap();
591                         for field in fields.named.iter() {
592                                 let field_name = format!("{}_arg", field.ident.as_ref().unwrap());
593                                 if types.write_from_c_conversion_new_var(w, &syn::Ident::new(&field_name, Span::call_site()), &field.ty, Some(&gen_types)) {
594                                         write!(w, "\n\t").unwrap();
595                                 }
596                         }
597                         writeln!(w, "{} {{ inner: Box::into_raw(Box::new(native{} {{", struct_name, s.ident).unwrap();
598                         for field in fields.named.iter() {
599                                 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
600                                 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
601                                 write!(w, "{}_arg", field.ident.as_ref().unwrap()).unwrap();
602                                 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
603                                 writeln!(w, ",").unwrap();
604                         }
605                         writeln!(w, "\t}})), is_owned: true }}\n}}").unwrap();
606                 }
607         }
608 }
609
610 /// Prints a relevant conversion for impl *
611 ///
612 /// For simple impl Struct {}s, this just outputs the wrapper functions as Struct_fn_name() { .. }.
613 ///
614 /// For impl Trait for Struct{}s, this non-exported generates wrapper functions as
615 /// Trait_Struct_fn_name and a Struct_as_Trait(&struct) -> Trait function which returns a populated
616 /// Trait struct containing a pointer to the passed struct's inner field and the wrapper functions.
617 ///
618 /// A few non-crate Traits are hard-coded including Default.
619 fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut TypeResolver) {
620         if let &syn::Type::Path(ref p) = &*i.self_ty {
621                 if p.qself.is_some() { unimplemented!(); }
622                 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
623                         if let Some(resolved_path) = types.maybe_resolve_non_ignored_ident(&ident) {
624                                 let mut gen_types = GenericTypes::new();
625                                 if !gen_types.learn_generics(&i.generics, types) {
626                                         eprintln!("Not implementing anything for impl {} due to not understood generics", ident);
627                                         return;
628                                 }
629
630                                 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
631                                 if let Some(trait_path) = i.trait_.as_ref() {
632                                         if trait_path.0.is_some() { unimplemented!(); }
633                                         if types.understood_c_path(&trait_path.1) {
634                                                 let full_trait_path = types.resolve_path(&trait_path.1, None);
635                                                 let trait_obj = *types.crate_types.traits.get(&full_trait_path).unwrap();
636                                                 // We learn the associated types maping from the original trait object.
637                                                 // That's great, except that they are unresolved idents, so if we learn
638                                                 // mappings from a trai defined in a different file, we may mis-resolve or
639                                                 // fail to resolve the mapped types.
640                                                 gen_types.learn_associated_types(trait_obj, types);
641                                                 let mut impl_associated_types = HashMap::new();
642                                                 for item in i.items.iter() {
643                                                         match item {
644                                                                 syn::ImplItem::Type(t) => {
645                                                                         if let syn::Type::Path(p) = &t.ty {
646                                                                                 if let Some(id) = single_ident_generic_path_to_ident(&p.path) {
647                                                                                         impl_associated_types.insert(&t.ident, id);
648                                                                                 }
649                                                                         }
650                                                                 },
651                                                                 _ => {},
652                                                         }
653                                                 }
654
655                                                 let export = export_status(&trait_obj.attrs);
656                                                 match export {
657                                                         ExportStatus::Export => {},
658                                                         ExportStatus::NoExport|ExportStatus::TestOnly => return,
659                                                 }
660
661                                                 // For cases where we have a concrete native object which implements a
662                                                 // trait and need to return the C-mapped version of the trait, provide a
663                                                 // From<> implementation which does all the work to ensure free is handled
664                                                 // properly. This way we can call this method from deep in the
665                                                 // type-conversion logic without actually knowing the concrete native type.
666                                                 writeln!(w, "impl From<native{}> for crate::{} {{", ident, full_trait_path).unwrap();
667                                                 writeln!(w, "\tfn from(obj: native{}) -> Self {{", ident).unwrap();
668                                                 writeln!(w, "\t\tlet mut rust_obj = {} {{ inner: Box::into_raw(Box::new(obj)), is_owned: true }};", ident).unwrap();
669                                                 writeln!(w, "\t\tlet mut ret = {}_as_{}(&rust_obj);", ident, trait_obj.ident).unwrap();
670                                                 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();
671                                                 writeln!(w, "\t\trust_obj.inner = std::ptr::null_mut();").unwrap();
672                                                 writeln!(w, "\t\tret.free = Some({}_free_void);", ident).unwrap();
673                                                 writeln!(w, "\t\tret\n\t}}\n}}").unwrap();
674
675                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_as_{}(this_arg: *const {}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
676                                                 writeln!(w, "\tcrate::{} {{", full_trait_path).unwrap();
677                                                 writeln!(w, "\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
678                                                 writeln!(w, "\t\tfree: None,").unwrap();
679
680                                                 macro_rules! write_meth {
681                                                         ($m: expr, $trait: expr, $indent: expr) => {
682                                                                 let trait_method = $trait.items.iter().filter_map(|item| {
683                                                                         if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
684                                                                 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
685                                                                 match export_status(&trait_method.attrs) {
686                                                                         ExportStatus::Export => {},
687                                                                         ExportStatus::NoExport => {
688                                                                                 write!(w, "{}\t\t//XXX: Need to export {}\n", $indent, $m.sig.ident).unwrap();
689                                                                                 continue;
690                                                                         },
691                                                                         ExportStatus::TestOnly => continue,
692                                                                 }
693
694                                                                 let mut printed = false;
695                                                                 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
696                                                                         if let syn::Type::Reference(r) = &**rtype {
697                                                                                 write!(w, "\n\t\t{}{}: ", $indent, $m.sig.ident).unwrap();
698                                                                                 types.write_empty_rust_val(Some(&gen_types), w, &*r.elem);
699                                                                                 writeln!(w, ",\n{}\t\tset_{}: Some({}_{}_set_{}),", $indent, $m.sig.ident, ident, trait_obj.ident, $m.sig.ident).unwrap();
700                                                                                 printed = true;
701                                                                         }
702                                                                 }
703                                                                 if !printed {
704                                                                         write!(w, "{}\t\t{}: {}_{}_{},\n", $indent, $m.sig.ident, ident, trait_obj.ident, $m.sig.ident).unwrap();
705                                                                 }
706                                                         }
707                                                 }
708                                                 for item in trait_obj.items.iter() {
709                                                         match item {
710                                                                 syn::TraitItem::Method(m) => {
711                                                                         write_meth!(m, trait_obj, "");
712                                                                 },
713                                                                 _ => {},
714                                                         }
715                                                 }
716                                                 walk_supertraits!(trait_obj, types, (
717                                                         ("Clone", _) => {
718                                                                 writeln!(w, "\t\tclone: Some({}_clone_void),", ident).unwrap();
719                                                         },
720                                                         ("Sync", _) => {}, ("Send", _) => {},
721                                                         ("std::marker::Sync", _) => {}, ("std::marker::Send", _) => {},
722                                                         (s, t) => {
723                                                                 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
724                                                                         writeln!(w, "\t\t{}: crate::{} {{", t, s).unwrap();
725                                                                         writeln!(w, "\t\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
726                                                                         writeln!(w, "\t\t\tfree: None,").unwrap();
727                                                                         for item in supertrait_obj.items.iter() {
728                                                                                 match item {
729                                                                                         syn::TraitItem::Method(m) => {
730                                                                                                 write_meth!(m, supertrait_obj, "\t");
731                                                                                         },
732                                                                                         _ => {},
733                                                                                 }
734                                                                         }
735                                                                         write!(w, "\t\t}},\n").unwrap();
736                                                                 } else {
737                                                                         write_trait_impl_field_assign(w, s, ident);
738                                                                 }
739                                                         }
740                                                 ) );
741                                                 write!(w, "\t}}\n}}\nuse {}::{} as {}TraitImport;\n", types.orig_crate, full_trait_path, trait_obj.ident).unwrap();
742
743                                                 macro_rules! impl_meth {
744                                                         ($m: expr, $trait: expr, $indent: expr) => {
745                                                                 let trait_method = $trait.items.iter().filter_map(|item| {
746                                                                         if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
747                                                                 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
748                                                                 match export_status(&trait_method.attrs) {
749                                                                         ExportStatus::Export => {},
750                                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
751                                                                 }
752
753                                                                 if let syn::ReturnType::Type(_, _) = &$m.sig.output {
754                                                                         writeln!(w, "#[must_use]").unwrap();
755                                                                 }
756                                                                 write!(w, "extern \"C\" fn {}_{}_{}(", ident, trait_obj.ident, $m.sig.ident).unwrap();
757                                                                 gen_types.push_ctx();
758                                                                 assert!(gen_types.learn_generics(&$m.sig.generics, types));
759                                                                 write_method_params(w, &$m.sig, "c_void", types, Some(&gen_types), true, true);
760                                                                 write!(w, " {{\n\t").unwrap();
761                                                                 write_method_var_decl_body(w, &$m.sig, "", types, Some(&gen_types), false);
762                                                                 let mut takes_self = false;
763                                                                 for inp in $m.sig.inputs.iter() {
764                                                                         if let syn::FnArg::Receiver(_) = inp {
765                                                                                 takes_self = true;
766                                                                         }
767                                                                 }
768                                                                 if takes_self {
769                                                                         write!(w, "unsafe {{ &mut *(this_arg as *mut native{}) }}.{}(", ident, $m.sig.ident).unwrap();
770                                                                 } else {
771                                                                         write!(w, "{}::{}::{}(", types.orig_crate, resolved_path, $m.sig.ident).unwrap();
772                                                                 }
773
774                                                                 let mut real_type = "".to_string();
775                                                                 match &$m.sig.output {
776                                                                         syn::ReturnType::Type(_, rtype) => {
777                                                                                 if let Some(mut remaining_path) = first_seg_self(&*rtype) {
778                                                                                         if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
779                                                                                                 real_type = format!("{}", impl_associated_types.get(associated_seg).unwrap());
780                                                                                         }
781                                                                                 }
782                                                                         },
783                                                                         _ => {},
784                                                                 }
785                                                                 write_method_call_params(w, &$m.sig, "", types, Some(&gen_types), &real_type, false);
786                                                                 gen_types.pop_ctx();
787                                                                 write!(w, "\n}}\n").unwrap();
788                                                                 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
789                                                                         if let syn::Type::Reference(r) = &**rtype {
790                                                                                 assert_eq!($m.sig.inputs.len(), 1); // Must only take self
791                                                                                 writeln!(w, "extern \"C\" fn {}_{}_set_{}(trait_self_arg: &{}) {{", ident, trait_obj.ident, $m.sig.ident, trait_obj.ident).unwrap();
792                                                                                 writeln!(w, "\t// This is a bit race-y in the general case, but for our specific use-cases today, we're safe").unwrap();
793                                                                                 writeln!(w, "\t// Specifically, we must ensure that the first time we're called it can never be in parallel").unwrap();
794                                                                                 write!(w, "\tif ").unwrap();
795                                                                                 types.write_empty_rust_val_check(Some(&gen_types), w, &*r.elem, &format!("trait_self_arg.{}", $m.sig.ident));
796                                                                                 writeln!(w, " {{").unwrap();
797                                                                                 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();
798                                                                                 writeln!(w, "\t}}").unwrap();
799                                                                                 writeln!(w, "}}").unwrap();
800                                                                         }
801                                                                 }
802                                                         }
803                                                 }
804
805                                                 for item in i.items.iter() {
806                                                         match item {
807                                                                 syn::ImplItem::Method(m) => {
808                                                                         impl_meth!(m, trait_obj, "");
809                                                                 },
810                                                                 syn::ImplItem::Type(_) => {},
811                                                                 _ => unimplemented!(),
812                                                         }
813                                                 }
814                                                 walk_supertraits!(trait_obj, types, (
815                                                         (s, t) => {
816                                                                 if let Some(supertrait_obj) = types.crate_types.traits.get(s).cloned() {
817                                                                         writeln!(w, "use {}::{} as native{}Trait;", types.orig_crate, s, t).unwrap();
818                                                                         for item in supertrait_obj.items.iter() {
819                                                                                 match item {
820                                                                                         syn::TraitItem::Method(m) => {
821                                                                                                 impl_meth!(m, supertrait_obj, "\t");
822                                                                                         },
823                                                                                         _ => {},
824                                                                                 }
825                                                                         }
826                                                                 }
827                                                         }
828                                                 ) );
829                                                 write!(w, "\n").unwrap();
830                                         } else if let Some(trait_ident) = trait_path.1.get_ident() {
831                                                 //XXX: implement for other things like ToString
832                                                 match &format!("{}", trait_ident) as &str {
833                                                         "From" => {},
834                                                         "Default" => {
835                                                                 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
836                                                                 write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
837                                                                 write!(w, "}}\n").unwrap();
838                                                         },
839                                                         "PartialEq" => {},
840                                                         // If we have no generics, try a manual implementation:
841                                                         _ if p.path.get_ident().is_some() => maybe_convert_trait_impl(w, &trait_path.1, &ident, types),
842                                                         _ => {},
843                                                 }
844                                         } else if p.path.get_ident().is_some() {
845                                                 // If we have no generics, try a manual implementation:
846                                                 maybe_convert_trait_impl(w, &trait_path.1, &ident, types);
847                                         }
848                                 } else {
849                                         let declared_type = (*types.get_declared_type(&ident).unwrap()).clone();
850                                         for item in i.items.iter() {
851                                                 match item {
852                                                         syn::ImplItem::Method(m) => {
853                                                                 if let syn::Visibility::Public(_) = m.vis {
854                                                                         match export_status(&m.attrs) {
855                                                                                 ExportStatus::Export => {},
856                                                                                 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
857                                                                         }
858                                                                         if m.defaultness.is_some() { unimplemented!(); }
859                                                                         writeln_docs(w, &m.attrs, "");
860                                                                         if let syn::ReturnType::Type(_, _) = &m.sig.output {
861                                                                                 writeln!(w, "#[must_use]").unwrap();
862                                                                         }
863                                                                         write!(w, "#[no_mangle]\npub extern \"C\" fn {}_{}(", ident, m.sig.ident).unwrap();
864                                                                         let ret_type = match &declared_type {
865                                                                                 DeclType::MirroredEnum => format!("{}", ident),
866                                                                                 DeclType::StructImported => format!("{}", ident),
867                                                                                 _ => unimplemented!(),
868                                                                         };
869                                                                         gen_types.push_ctx();
870                                                                         assert!(gen_types.learn_generics(&m.sig.generics, types));
871                                                                         write_method_params(w, &m.sig, &ret_type, types, Some(&gen_types), false, true);
872                                                                         write!(w, " {{\n\t").unwrap();
873                                                                         write_method_var_decl_body(w, &m.sig, "", types, Some(&gen_types), false);
874                                                                         let mut takes_self = false;
875                                                                         let mut takes_mut_self = false;
876                                                                         for inp in m.sig.inputs.iter() {
877                                                                                 if let syn::FnArg::Receiver(r) = inp {
878                                                                                         takes_self = true;
879                                                                                         if r.mutability.is_some() { takes_mut_self = true; }
880                                                                                 }
881                                                                         }
882                                                                         if takes_mut_self {
883                                                                                 write!(w, "unsafe {{ &mut (*(this_arg.inner as *mut native{})) }}.{}(", ident, m.sig.ident).unwrap();
884                                                                         } else if takes_self {
885                                                                                 write!(w, "unsafe {{ &*this_arg.inner }}.{}(", m.sig.ident).unwrap();
886                                                                         } else {
887                                                                                 write!(w, "{}::{}::{}(", types.orig_crate, resolved_path, m.sig.ident).unwrap();
888                                                                         }
889                                                                         write_method_call_params(w, &m.sig, "", types, Some(&gen_types), &ret_type, false);
890                                                                         gen_types.pop_ctx();
891                                                                         writeln!(w, "\n}}\n").unwrap();
892                                                                 }
893                                                         },
894                                                         _ => {},
895                                                 }
896                                         }
897                                 }
898                         } else {
899                                 eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub or its marked not exported)", ident);
900                         }
901                 }
902         }
903 }
904
905 /// Returns true if the enum will be mapped as an opaue (ie struct with a pointer to the underlying
906 /// type), otherwise it is mapped into a transparent, C-compatible version of itself.
907 fn is_enum_opaque(e: &syn::ItemEnum) -> bool {
908         for var in e.variants.iter() {
909                 if let syn::Fields::Unit = var.fields {
910                 } else if let syn::Fields::Named(fields) = &var.fields {
911                         for field in fields.named.iter() {
912                                 match export_status(&field.attrs) {
913                                         ExportStatus::Export|ExportStatus::TestOnly => {},
914                                         ExportStatus::NoExport => return true,
915                                 }
916                         }
917                 } else {
918                         return true;
919                 }
920         }
921         false
922 }
923
924 fn declare_enum<'a, 'b>(e: &'a syn::ItemEnum, types: &mut TypeResolver<'b, 'a>) {
925         match export_status(&e.attrs) {
926                 ExportStatus::Export => {},
927                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
928         }
929
930         if is_enum_opaque(e) {
931                 types.enum_ignored(&e.ident);
932         } else {
933                 types.mirrored_enum_declared(&e.ident);
934         }
935 }
936
937 /// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
938 /// is unitary), we generate an equivalent enum with all types replaced with their C mapped
939 /// versions followed by conversion functions which map between the Rust version and the C mapped
940 /// version.
941 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) {
942         match export_status(&e.attrs) {
943                 ExportStatus::Export => {},
944                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
945         }
946
947         if is_enum_opaque(e) {
948                 eprintln!("Skipping enum {} as it contains non-unit fields", e.ident);
949                 writeln_opaque(w, &e.ident, &format!("{}", e.ident), &e.generics, &e.attrs, types, extra_headers, cpp_headers);
950                 return;
951         }
952         writeln_docs(w, &e.attrs, "");
953
954         if e.generics.lt_token.is_some() {
955                 unimplemented!();
956         }
957
958         let mut needs_free = false;
959
960         writeln!(w, "#[must_use]\n#[derive(Clone)]\n#[repr(C)]\npub enum {} {{", e.ident).unwrap();
961         for var in e.variants.iter() {
962                 assert_eq!(export_status(&var.attrs), ExportStatus::Export); // We can't partially-export a mirrored enum
963                 writeln_docs(w, &var.attrs, "\t");
964                 write!(w, "\t{}", var.ident).unwrap();
965                 if let syn::Fields::Named(fields) = &var.fields {
966                         needs_free = true;
967                         writeln!(w, " {{").unwrap();
968                         for field in fields.named.iter() {
969                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
970                                 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
971                                 types.write_c_type(w, &field.ty, None, false);
972                                 writeln!(w, ",").unwrap();
973                         }
974                         write!(w, "\t}}").unwrap();
975                 }
976                 if var.discriminant.is_some() { unimplemented!(); }
977                 writeln!(w, ",").unwrap();
978         }
979         writeln!(w, "}}\nuse {}::{}::{} as native{};\nimpl {} {{", types.orig_crate, types.module_path, e.ident, e.ident, e.ident).unwrap();
980
981         macro_rules! write_conv {
982                 ($fn_sig: expr, $to_c: expr, $ref: expr) => {
983                         writeln!(w, "\t#[allow(unused)]\n\tpub(crate) fn {} {{\n\t\tmatch {} {{", $fn_sig, if $to_c { "native" } else { "self" }).unwrap();
984                         for var in e.variants.iter() {
985                                 write!(w, "\t\t\t{}{}::{} ", if $to_c { "native" } else { "" }, e.ident, var.ident).unwrap();
986                                 if let syn::Fields::Named(fields) = &var.fields {
987                                         write!(w, "{{").unwrap();
988                                         for field in fields.named.iter() {
989                                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
990                                                 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, field.ident.as_ref().unwrap()).unwrap();
991                                         }
992                                         write!(w, "}} ").unwrap();
993                                 }
994                                 write!(w, "=>").unwrap();
995                                 if let syn::Fields::Named(fields) = &var.fields {
996                                         write!(w, " {{\n\t\t\t\t").unwrap();
997                                         for field in fields.named.iter() {
998                                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
999                                                 let mut sink = ::std::io::sink();
1000                                                 let mut out: &mut dyn std::io::Write = if $ref { &mut sink } else { w };
1001                                                 let new_var = if $to_c {
1002                                                         types.write_to_c_conversion_new_var(&mut out, field.ident.as_ref().unwrap(), &field.ty, None, false)
1003                                                 } else {
1004                                                         types.write_from_c_conversion_new_var(&mut out, field.ident.as_ref().unwrap(), &field.ty, None)
1005                                                 };
1006                                                 if $ref || new_var {
1007                                                         if $ref {
1008                                                                 write!(w, "let mut {}_nonref = (*{}).clone();\n\t\t\t\t", field.ident.as_ref().unwrap(), field.ident.as_ref().unwrap()).unwrap();
1009                                                                 if new_var {
1010                                                                         let nonref_ident = syn::Ident::new(&format!("{}_nonref", field.ident.as_ref().unwrap()), Span::call_site());
1011                                                                         if $to_c {
1012                                                                                 types.write_to_c_conversion_new_var(w, &nonref_ident, &field.ty, None, false);
1013                                                                         } else {
1014                                                                                 types.write_from_c_conversion_new_var(w, &nonref_ident, &field.ty, None);
1015                                                                         }
1016                                                                         write!(w, "\n\t\t\t\t").unwrap();
1017                                                                 }
1018                                                         } else {
1019                                                                 write!(w, "\n\t\t\t\t").unwrap();
1020                                                         }
1021                                                 }
1022                                         }
1023                                 } else { write!(w, " ").unwrap(); }
1024                                 write!(w, "{}{}::{}", if $to_c { "" } else { "native" }, e.ident, var.ident).unwrap();
1025                                 if let syn::Fields::Named(fields) = &var.fields {
1026                                         write!(w, " {{").unwrap();
1027                                         for field in fields.named.iter() {
1028                                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1029                                                 write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1030                                                 if $to_c {
1031                                                         types.write_to_c_conversion_inline_prefix(w, &field.ty, None, false);
1032                                                 } else {
1033                                                         types.write_from_c_conversion_prefix(w, &field.ty, None);
1034                                                 }
1035                                                 write!(w, "{}{}",
1036                                                         field.ident.as_ref().unwrap(),
1037                                                         if $ref { "_nonref" } else { "" }).unwrap();
1038                                                 if $to_c {
1039                                                         types.write_to_c_conversion_inline_suffix(w, &field.ty, None, false);
1040                                                 } else {
1041                                                         types.write_from_c_conversion_suffix(w, &field.ty, None);
1042                                                 }
1043                                                 write!(w, ",").unwrap();
1044                                         }
1045                                         writeln!(w, "\n\t\t\t\t}}").unwrap();
1046                                         write!(w, "\t\t\t}}").unwrap();
1047                                 }
1048                                 writeln!(w, ",").unwrap();
1049                         }
1050                         writeln!(w, "\t\t}}\n\t}}").unwrap();
1051                 }
1052         }
1053
1054         write_conv!(format!("to_native(&self) -> native{}", e.ident), false, true);
1055         write_conv!(format!("into_native(self) -> native{}", e.ident), false, false);
1056         write_conv!(format!("from_native(native: &native{}) -> Self", e.ident), true, true);
1057         write_conv!(format!("native_into(native: native{}) -> Self", e.ident), true, false);
1058         writeln!(w, "}}").unwrap();
1059
1060         if needs_free {
1061                 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", e.ident, e.ident).unwrap();
1062         }
1063         writeln!(w, "#[no_mangle]").unwrap();
1064         writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
1065         writeln!(w, "\torig.clone()").unwrap();
1066         writeln!(w, "}}").unwrap();
1067         write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free);
1068 }
1069
1070 fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &mut TypeResolver<'b, 'a>) {
1071         match export_status(&f.attrs) {
1072                 ExportStatus::Export => {},
1073                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1074         }
1075         writeln_docs(w, &f.attrs, "");
1076
1077         let mut gen_types = GenericTypes::new();
1078         if !gen_types.learn_generics(&f.sig.generics, types) { return; }
1079
1080         write!(w, "#[no_mangle]\npub extern \"C\" fn {}(", f.sig.ident).unwrap();
1081         write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
1082         write!(w, " {{\n\t").unwrap();
1083         write_method_var_decl_body(w, &f.sig, "", types, Some(&gen_types), false);
1084         write!(w, "{}::{}::{}(", types.orig_crate, types.module_path, f.sig.ident).unwrap();
1085         write_method_call_params(w, &f.sig, "", types, Some(&gen_types), "", false);
1086         writeln!(w, "\n}}\n").unwrap();
1087 }
1088
1089 // ********************************
1090 // *** File/Crate Walking Logic ***
1091 // ********************************
1092
1093 /// Simple utility to walk the modules in a crate - iterating over the modules (with file paths) in
1094 /// a single File.
1095 struct FileIter<'a, I: Iterator<Item = &'a syn::Item>> {
1096         in_dir: &'a str,
1097         path: &'a str,
1098         module: &'a str,
1099         item_iter: I,
1100 }
1101 impl<'a, I: Iterator<Item = &'a syn::Item>> Iterator for FileIter<'a, I> {
1102         type Item = (String, String, &'a syn::ItemMod);
1103         fn next(&mut self) -> std::option::Option<<Self as std::iter::Iterator>::Item> {
1104                 loop {
1105                         match self.item_iter.next() {
1106                                 Some(syn::Item::Mod(m)) => {
1107                                         if let syn::Visibility::Public(_) = m.vis {
1108                                                 match export_status(&m.attrs) {
1109                                                         ExportStatus::Export => {},
1110                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1111                                                 }
1112
1113                                                 let f_path = format!("{}/{}.rs", (self.path.as_ref() as &Path).parent().unwrap().display(), m.ident);
1114                                                 let new_mod = if self.module.is_empty() { format!("{}", m.ident) } else { format!("{}::{}", self.module, m.ident) };
1115                                                 if let Ok(_) = File::open(&format!("{}/{}", self.in_dir, f_path)) {
1116                                                         return Some((f_path, new_mod, m));
1117                                                 } else {
1118                                                         return Some((
1119                                                                 format!("{}/{}/mod.rs", (self.path.as_ref() as &Path).parent().unwrap().display(), m.ident),
1120                                                                 new_mod, m));
1121                                                 }
1122                                         }
1123                                 },
1124                                 Some(_) => {},
1125                                 None => return None,
1126                         }
1127                 }
1128         }
1129 }
1130 fn file_iter<'a>(file: &'a syn::File, in_dir: &'a str, path: &'a str, module: &'a str) ->
1131                 impl Iterator<Item = (String, String, &'a syn::ItemMod)> + 'a {
1132         FileIter { in_dir, path, module, item_iter: file.items.iter() }
1133 }
1134
1135 /// A struct containing the syn::File AST for each file in the crate.
1136 struct FullLibraryAST {
1137         files: HashMap<String, syn::File>,
1138 }
1139
1140 /// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
1141 /// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
1142 /// at `module` from C.
1143 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) {
1144         let syntax = if let Some(ast) = libast.files.get(module) { ast } else { return };
1145
1146         assert!(syntax.shebang.is_none()); // Not sure what this is, hope we dont have one
1147
1148         let new_file_path = format!("{}/{}", out_dir, path);
1149         let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
1150         let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1151                 .open(new_file_path).expect("Unable to open new src file");
1152
1153         assert_eq!(export_status(&syntax.attrs), ExportStatus::Export);
1154         writeln_docs(&mut out, &syntax.attrs, "");
1155
1156         if path.ends_with("/lib.rs") {
1157                 // Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
1158                 // and bitcoin hand-written modules.
1159                 writeln!(out, "#![allow(unknown_lints)]").unwrap();
1160                 writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
1161                 writeln!(out, "#![allow(non_snake_case)]").unwrap();
1162                 writeln!(out, "#![allow(unused_imports)]").unwrap();
1163                 writeln!(out, "#![allow(unused_variables)]").unwrap();
1164                 writeln!(out, "#![allow(unused_mut)]").unwrap();
1165                 writeln!(out, "#![allow(unused_parens)]").unwrap();
1166                 writeln!(out, "#![allow(unused_unsafe)]").unwrap();
1167                 writeln!(out, "#![allow(unused_braces)]").unwrap();
1168                 writeln!(out, "mod c_types;").unwrap();
1169                 writeln!(out, "mod bitcoin;").unwrap();
1170         } else {
1171                 writeln!(out, "\nuse std::ffi::c_void;\nuse bitcoin::hashes::Hash;\nuse crate::c_types::*;\n").unwrap();
1172         }
1173
1174         for (path, new_mod, m) in file_iter(&syntax, in_dir, path, &module) {
1175                 writeln_docs(&mut out, &m.attrs, "");
1176                 writeln!(out, "pub mod {};", m.ident).unwrap();
1177                 convert_file(libast, crate_types, in_dir, out_dir, &path,
1178                         orig_crate, &new_mod, header_file, cpp_header_file);
1179         }
1180
1181         eprintln!("Converting {} entries...", path);
1182
1183         let mut type_resolver = TypeResolver::new(orig_crate, module, crate_types);
1184
1185         // First pass over the items and fill in imports and file-declared objects in the type resolver
1186         for item in syntax.items.iter() {
1187                 match item {
1188                         syn::Item::Use(u) => type_resolver.process_use(&mut out, &u),
1189                         syn::Item::Struct(s) => {
1190                                 if let syn::Visibility::Public(_) = s.vis {
1191                                         declare_struct(&s, &mut type_resolver);
1192                                 }
1193                         },
1194                         syn::Item::Enum(e) => {
1195                                 if let syn::Visibility::Public(_) = e.vis {
1196                                         declare_enum(&e, &mut type_resolver);
1197                                 }
1198                         },
1199                         _ => {},
1200                 }
1201         }
1202
1203         for item in syntax.items.iter() {
1204                 match item {
1205                         syn::Item::Use(_) => {}, // Handled above
1206                         syn::Item::Static(_) => {},
1207                         syn::Item::Enum(e) => {
1208                                 if let syn::Visibility::Public(_) = e.vis {
1209                                         writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
1210                                 }
1211                         },
1212                         syn::Item::Impl(i) => {
1213                                 writeln_impl(&mut out, &i, &mut type_resolver);
1214                         },
1215                         syn::Item::Struct(s) => {
1216                                 if let syn::Visibility::Public(_) = s.vis {
1217                                         writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
1218                                 }
1219                         },
1220                         syn::Item::Trait(t) => {
1221                                 if let syn::Visibility::Public(_) = t.vis {
1222                                         writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
1223                                 }
1224                         },
1225                         syn::Item::Mod(_) => {}, // We don't have to do anything - the top loop handles these.
1226                         syn::Item::Const(c) => {
1227                                 // Re-export any primitive-type constants.
1228                                 if let syn::Visibility::Public(_) = c.vis {
1229                                         if let syn::Type::Path(p) = &*c.ty {
1230                                                 let resolved_path = type_resolver.resolve_path(&p.path, None);
1231                                                 if type_resolver.is_primitive(&resolved_path) {
1232                                                         writeln!(out, "\n#[no_mangle]").unwrap();
1233                                                         writeln!(out, "pub static {}: {} = {}::{}::{};", c.ident, resolved_path, orig_crate, module, c.ident).unwrap();
1234                                                 }
1235                                         }
1236                                 }
1237                         },
1238                         syn::Item::Type(t) => {
1239                                 if let syn::Visibility::Public(_) = t.vis {
1240                                         match export_status(&t.attrs) {
1241                                                 ExportStatus::Export => {},
1242                                                 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1243                                         }
1244
1245                                         let mut process_alias = true;
1246                                         for tok in t.generics.params.iter() {
1247                                                 if let syn::GenericParam::Lifetime(_) = tok {}
1248                                                 else { process_alias = false; }
1249                                         }
1250                                         if process_alias {
1251                                                 match &*t.ty {
1252                                                         syn::Type::Path(_) =>
1253                                                                 writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &t.generics, &t.attrs, &type_resolver, header_file, cpp_header_file),
1254                                                         _ => {}
1255                                                 }
1256                                         }
1257                                 }
1258                         },
1259                         syn::Item::Fn(f) => {
1260                                 if let syn::Visibility::Public(_) = f.vis {
1261                                         writeln_fn(&mut out, &f, &mut type_resolver);
1262                                 }
1263                         },
1264                         syn::Item::Macro(m) => {
1265                                 if m.ident.is_none() { // If its not a macro definition
1266                                         convert_macro(&mut out, &m.mac.path, &m.mac.tokens, &type_resolver);
1267                                 }
1268                         },
1269                         syn::Item::Verbatim(_) => {},
1270                         syn::Item::ExternCrate(_) => {},
1271                         _ => unimplemented!(),
1272                 }
1273         }
1274
1275         out.flush().unwrap();
1276 }
1277
1278 /// Load the AST for each file in the crate, filling the FullLibraryAST object
1279 fn load_ast(in_dir: &str, path: &str, module: String, ast_storage: &mut FullLibraryAST) {
1280         eprintln!("Loading {}{}...", in_dir, path);
1281
1282         let mut file = File::open(format!("{}/{}", in_dir, path)).expect("Unable to open file");
1283         let mut src = String::new();
1284         file.read_to_string(&mut src).expect("Unable to read file");
1285         let syntax = syn::parse_file(&src).expect("Unable to parse file");
1286
1287         assert_eq!(export_status(&syntax.attrs), ExportStatus::Export);
1288
1289         for (path, new_mod, _) in file_iter(&syntax, in_dir, path, &module) {
1290                 load_ast(in_dir, &path, new_mod, ast_storage);
1291         }
1292         ast_storage.files.insert(module, syntax);
1293 }
1294
1295 /// Insert ident -> absolute Path resolutions into imports from the given UseTree and path-prefix.
1296 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>) {
1297         match u {
1298                 syn::UseTree::Path(p) => {
1299                         path.push(syn::PathSegment { ident: p.ident.clone(), arguments: syn::PathArguments::None });
1300                         process_use_intern(&p.tree, path, imports);
1301                 },
1302                 syn::UseTree::Name(n) => {
1303                         path.push(syn::PathSegment { ident: n.ident.clone(), arguments: syn::PathArguments::None });
1304                         imports.insert(&n.ident, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path });
1305                 },
1306                 syn::UseTree::Group(g) => {
1307                         for i in g.items.iter() {
1308                                 process_use_intern(i, path.clone(), imports);
1309                         }
1310                 },
1311                 _ => {}
1312         }
1313 }
1314
1315 /// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern)
1316 fn resolve_imported_refs(imports: &HashMap<&syn::Ident, syn::Path>, mut ty: syn::Type) -> syn::Type {
1317         match &mut ty {
1318                 syn::Type::Path(p) => {
1319                         if let Some(ident) = p.path.get_ident() {
1320                                 if let Some(newpath) = imports.get(ident) {
1321                                         p.path = newpath.clone();
1322                                 }
1323                         } else { unimplemented!(); }
1324                 },
1325                 syn::Type::Reference(r) => {
1326                         r.elem = Box::new(resolve_imported_refs(imports, (*r.elem).clone()));
1327                 },
1328                 syn::Type::Slice(s) => {
1329                         s.elem = Box::new(resolve_imported_refs(imports, (*s.elem).clone()));
1330                 },
1331                 syn::Type::Tuple(t) => {
1332                         for e in t.elems.iter_mut() {
1333                                 *e = resolve_imported_refs(imports, e.clone());
1334                         }
1335                 },
1336                 _ => unimplemented!(),
1337         }
1338         ty
1339 }
1340
1341 /// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
1342 fn walk_ast<'a>(in_dir: &str, path: &str, module: String, ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
1343         let syntax = if let Some(ast) = ast_storage.files.get(&module) { ast } else { return };
1344         assert_eq!(export_status(&syntax.attrs), ExportStatus::Export);
1345
1346         for (path, new_mod, _) in file_iter(&syntax, in_dir, path, &module) {
1347                 walk_ast(in_dir, &path, new_mod, ast_storage, crate_types);
1348         }
1349
1350         let mut import_maps = HashMap::new();
1351
1352         for item in syntax.items.iter() {
1353                 match item {
1354                         syn::Item::Use(u) => {
1355                                 process_use_intern(&u.tree, syn::punctuated::Punctuated::new(), &mut import_maps);
1356                         },
1357                         syn::Item::Struct(s) => {
1358                                 if let syn::Visibility::Public(_) = s.vis {
1359                                         match export_status(&s.attrs) {
1360                                                 ExportStatus::Export => {},
1361                                                 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1362                                         }
1363                                         let struct_path = format!("{}::{}", module, s.ident);
1364                                         crate_types.opaques.insert(struct_path, &s.ident);
1365                                 }
1366                         },
1367                         syn::Item::Trait(t) => {
1368                                 if let syn::Visibility::Public(_) = t.vis {
1369                                         match export_status(&t.attrs) {
1370                                                 ExportStatus::Export => {},
1371                                                 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1372                                         }
1373                                         let trait_path = format!("{}::{}", module, t.ident);
1374                                         crate_types.traits.insert(trait_path, &t);
1375                                 }
1376                         },
1377                         syn::Item::Type(t) => {
1378                                 if let syn::Visibility::Public(_) = t.vis {
1379                                         match export_status(&t.attrs) {
1380                                                 ExportStatus::Export => {},
1381                                                 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1382                                         }
1383                                         let type_path = format!("{}::{}", module, t.ident);
1384                                         let mut process_alias = true;
1385                                         for tok in t.generics.params.iter() {
1386                                                 if let syn::GenericParam::Lifetime(_) = tok {}
1387                                                 else { process_alias = false; }
1388                                         }
1389                                         if process_alias {
1390                                                 match &*t.ty {
1391                                                         syn::Type::Path(_) => {
1392                                                                 // If its a path with no generics, assume we don't map the aliased type and map it opaque
1393                                                                 crate_types.opaques.insert(type_path, &t.ident);
1394                                                         },
1395                                                         _ => {
1396                                                                 crate_types.type_aliases.insert(type_path, resolve_imported_refs(&import_maps, (*t.ty).clone()));
1397                                                         }
1398                                                 }
1399                                         }
1400                                 }
1401                         },
1402                         syn::Item::Enum(e) if is_enum_opaque(e) => {
1403                                 if let syn::Visibility::Public(_) = e.vis {
1404                                         match export_status(&e.attrs) {
1405                                                 ExportStatus::Export => {},
1406                                                 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1407                                         }
1408                                         let enum_path = format!("{}::{}", module, e.ident);
1409                                         crate_types.opaques.insert(enum_path, &e.ident);
1410                                 }
1411                         },
1412                         syn::Item::Enum(e) => {
1413                                 if let syn::Visibility::Public(_) = e.vis {
1414                                         match export_status(&e.attrs) {
1415                                                 ExportStatus::Export => {},
1416                                                 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1417                                         }
1418                                         let enum_path = format!("{}::{}", module, e.ident);
1419                                         crate_types.mirrored_enums.insert(enum_path, &e);
1420                                 }
1421                         },
1422                         _ => {},
1423                 }
1424         }
1425 }
1426
1427 fn main() {
1428         let args: Vec<String> = env::args().collect();
1429         if args.len() != 7 {
1430                 eprintln!("Usage: source/dir target/dir source_crate_name derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
1431                 process::exit(1);
1432         }
1433
1434         let mut derived_templates = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1435                 .open(&args[4]).expect("Unable to open new header file");
1436         let mut header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1437                 .open(&args[5]).expect("Unable to open new header file");
1438         let mut cpp_header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1439                 .open(&args[6]).expect("Unable to open new header file");
1440
1441         writeln!(header_file, "#if defined(__GNUC__)\n#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
1442         writeln!(header_file, "#else\n#define MUST_USE_STRUCT\n#endif").unwrap();
1443         writeln!(header_file, "#if defined(__GNUC__)\n#define MUST_USE_RES __attribute__((warn_unused_result))").unwrap();
1444         writeln!(header_file, "#else\n#define MUST_USE_RES\n#endif").unwrap();
1445         writeln!(cpp_header_file, "#include <string.h>\nnamespace LDK {{").unwrap();
1446
1447         // First parse the full crate's ASTs, caching them so that we can hold references to the AST
1448         // objects in other datastructures:
1449         let mut libast = FullLibraryAST { files: HashMap::new() };
1450         load_ast(&args[1], "/lib.rs", "".to_string(), &mut libast);
1451
1452         // ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
1453         // when parsing other file ASTs...
1454         let mut libtypes = CrateTypes { traits: HashMap::new(), opaques: HashMap::new(), mirrored_enums: HashMap::new(),
1455                 type_aliases: HashMap::new(), templates_defined: HashMap::default(), template_file: &mut derived_templates };
1456         walk_ast(&args[1], "/lib.rs", "".to_string(), &libast, &mut libtypes);
1457
1458         // ... finally, do the actual file conversion/mapping, writing out types as we go.
1459         convert_file(&libast, &mut libtypes, &args[1], &args[2], "/lib.rs", &args[3], "", &mut header_file, &mut cpp_header_file);
1460
1461         // For container templates which we created while walking the crate, make sure we add C++
1462         // mapped types so that C++ users can utilize the auto-destructors available.
1463         for (ty, has_destructor) in libtypes.templates_defined.iter() {
1464                 write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor);
1465         }
1466         writeln!(cpp_header_file, "}}").unwrap();
1467
1468         header_file.flush().unwrap();
1469         cpp_header_file.flush().unwrap();
1470         derived_templates.flush().unwrap();
1471 }