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