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