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