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