Merge pull request #12 from TheBlueMatt/2021-04-incl-persister
[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                         "lightning::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                         "lightning::util::ser::Readable"|"lightning::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 == "lightning::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 == "lightning::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                 "lightning::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                 "lightning::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                 "lightning::util::ser::Writeable" => {
186                         writeln!(w, "impl {} 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, $type_resolver: 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, $type_resolver));
383                                                 write!(w, "\tfn {}", m.sig.ident).unwrap();
384                                                 $type_resolver.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 $type_resolver.skip_arg(&*arg.ty, Some(&meth_gen_types)) { "_" } else { "" }, ident.ident).unwrap();
409                                                                                 }
410                                                                                 _ => unimplemented!(),
411                                                                         }
412                                                                         $type_resolver.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                                                                 $type_resolver.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                                                                 $type_resolver.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                                                                 $type_resolver.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", $type_resolver, Some(&meth_gen_types), true);
445                                                 write!(w, "(self{}.{})(", $impl_accessor, m.sig.ident).unwrap();
446                                                 write_method_call_params(w, &m.sig, "\t", $type_resolver, 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, $type_resolver.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                                 let mut module_iter = s.rsplitn(2, "::");
504                                 module_iter.next().unwrap();
505                                 let supertrait_module = module_iter.next().unwrap();
506                                 let imports = ImportResolver::new(supertrait_module.splitn(2, "::").next().unwrap(), &types.crate_types.lib_ast.dependencies,
507                                         supertrait_module, &types.crate_types.lib_ast.modules.get(supertrait_module).unwrap().items);
508                                 let resolver = TypeResolver::new(&supertrait_module, imports, types.crate_types);
509                                 writeln!(w, "impl {} for {} {{", s, trait_name).unwrap();
510                                 impl_trait_for_c!(supertrait, format!(".{}", i), &resolver);
511                                 writeln!(w, "}}").unwrap();
512                                 walk_supertraits!(supertrait, Some(&types), (
513                                         ("Send", _) => writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap(),
514                                         ("Sync", _) => writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap(),
515                                         _ => unimplemented!()
516                                 ) );
517                         } else {
518                                 do_write_impl_trait(w, s, i, &trait_name);
519                         }
520                 }
521         ) );
522
523         // Finally, implement the original Rust trait for the newly created mapped trait.
524         writeln!(w, "\nuse {}::{} as rust{};", types.module_path, t.ident, trait_name).unwrap();
525         write!(w, "impl rust{}", t.ident).unwrap();
526         maybe_write_generics(w, &t.generics, types, false);
527         writeln!(w, " for {} {{", trait_name).unwrap();
528         impl_trait_for_c!(t, "", types);
529         writeln!(w, "}}\n").unwrap();
530         writeln!(w, "// We're essentially a pointer already, or at least a set of pointers, so allow us to be used").unwrap();
531         writeln!(w, "// directly as a Deref trait in higher-level structs:").unwrap();
532         writeln!(w, "impl std::ops::Deref for {} {{\n\ttype Target = Self;", trait_name).unwrap();
533         writeln!(w, "\tfn deref(&self) -> &Self {{\n\t\tself\n\t}}\n}}").unwrap();
534
535         writeln!(w, "/// Calls the free function if one is set").unwrap();
536         writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", trait_name, trait_name).unwrap();
537         writeln!(w, "impl Drop for {} {{", trait_name).unwrap();
538         writeln!(w, "\tfn drop(&mut self) {{").unwrap();
539         writeln!(w, "\t\tif let Some(f) = self.free {{").unwrap();
540         writeln!(w, "\t\t\tf(self.this_arg);").unwrap();
541         writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
542
543         write_cpp_wrapper(cpp_headers, &trait_name, true);
544 }
545
546 /// Write out a simple "opaque" type (eg structs) which contain a pointer to the native Rust type
547 /// and a flag to indicate whether Drop'ing the mapped struct drops the underlying Rust type.
548 ///
549 /// Also writes out a _free function and a C++ wrapper which handles calling _free.
550 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) {
551         // If we directly read the original type by its original name, cbindgen hits
552         // https://github.com/eqrion/cbindgen/issues/286 Thus, instead, we import it as a temporary
553         // name and then reference it by that name, which works around the issue.
554         write!(w, "\nuse {}::{} as native{}Import;\ntype native{} = native{}Import", types.module_path, ident, ident, ident, ident).unwrap();
555         maybe_write_generics(w, &generics, &types, true);
556         writeln!(w, ";\n").unwrap();
557         writeln!(extra_headers, "struct native{}Opaque;\ntypedef struct native{}Opaque LDKnative{};", ident, ident, ident).unwrap();
558         writeln_docs(w, &attrs, "");
559         writeln!(w, "#[must_use]\n#[repr(C)]\npub struct {} {{", struct_name).unwrap();
560         writeln!(w, "\t/// A pointer to the opaque Rust object.\n").unwrap();
561         writeln!(w, "\t/// Nearly everywhere, inner must be non-null, however in places where").unwrap();
562         writeln!(w, "\t/// the Rust equivalent takes an Option, it may be set to null to indicate None.").unwrap();
563         writeln!(w, "\tpub inner: *mut native{},", ident).unwrap();
564         writeln!(w, "\t/// Indicates that this is the only struct which contains the same pointer.\n").unwrap();
565         writeln!(w, "\t/// Rust functions which take ownership of an object provided via an argument require").unwrap();
566         writeln!(w, "\t/// this to be true and invalidate the object pointed to by inner.").unwrap();
567         writeln!(w, "\tpub is_owned: bool,").unwrap();
568         writeln!(w, "}}\n").unwrap();
569         writeln!(w, "impl Drop for {} {{\n\tfn drop(&mut self) {{", struct_name).unwrap();
570         writeln!(w, "\t\tif self.is_owned && !<*mut native{}>::is_null(self.inner) {{", ident).unwrap();
571         writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(self.inner) }};\n\t\t}}\n\t}}\n}}").unwrap();
572         writeln!(w, "/// Frees any resources used by the {}, if is_owned is set and inner is non-NULL.", struct_name).unwrap();
573         writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_obj: {}) {{ }}", struct_name, struct_name).unwrap();
574         writeln!(w, "#[allow(unused)]").unwrap();
575         writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
576         writeln!(w, "extern \"C\" fn {}_free_void(this_ptr: *mut c_void) {{", struct_name).unwrap();
577         writeln!(w, "\tunsafe {{ let _ = Box::from_raw(this_ptr as *mut native{}); }}\n}}", struct_name).unwrap();
578         writeln!(w, "#[allow(unused)]").unwrap();
579         writeln!(w, "/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy").unwrap();
580         writeln!(w, "impl {} {{", struct_name).unwrap();
581         writeln!(w, "\tpub(crate) fn take_inner(mut self) -> *mut native{} {{", struct_name).unwrap();
582         writeln!(w, "\t\tassert!(self.is_owned);").unwrap();
583         writeln!(w, "\t\tlet ret = self.inner;").unwrap();
584         writeln!(w, "\t\tself.inner = std::ptr::null_mut();").unwrap();
585         writeln!(w, "\t\tret").unwrap();
586         writeln!(w, "\t}}\n}}").unwrap();
587
588         write_cpp_wrapper(cpp_headers, &format!("{}", ident), true);
589 }
590
591 /// Writes out all the relevant mappings for a Rust struct, deferring to writeln_opaque to generate
592 /// the struct itself, and then writing getters and setters for public, understood-type fields and
593 /// a constructor if every field is public.
594 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) {
595         if export_status(&s.attrs) != ExportStatus::Export { return; }
596
597         let struct_name = &format!("{}", s.ident);
598         writeln_opaque(w, &s.ident, struct_name, &s.generics, &s.attrs, types, extra_headers, cpp_headers);
599
600         if let syn::Fields::Named(fields) = &s.fields {
601                 let mut gen_types = GenericTypes::new();
602                 assert!(gen_types.learn_generics(&s.generics, types));
603
604                 let mut all_fields_settable = true;
605                 for field in fields.named.iter() {
606                         if let syn::Visibility::Public(_) = field.vis {
607                                 let export = export_status(&field.attrs);
608                                 match export {
609                                         ExportStatus::Export => {},
610                                         ExportStatus::NoExport|ExportStatus::TestOnly => {
611                                                 all_fields_settable = false;
612                                                 continue
613                                         },
614                                 }
615
616                                 if let Some(ident) = &field.ident {
617                                         let ref_type = syn::Type::Reference(syn::TypeReference {
618                                                 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
619                                                 elem: Box::new(field.ty.clone()) });
620                                         if types.understood_c_type(&ref_type, Some(&gen_types)) {
621                                                 writeln_docs(w, &field.attrs, "");
622                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> ", struct_name, ident, struct_name).unwrap();
623                                                 types.write_c_type(w, &ref_type, Some(&gen_types), true);
624                                                 write!(w, " {{\n\tlet mut inner_val = &mut unsafe {{ &mut *this_ptr.inner }}.{};\n\t", ident).unwrap();
625                                                 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);
626                                                 if local_var { write!(w, "\n\t").unwrap(); }
627                                                 types.write_to_c_conversion_inline_prefix(w, &ref_type, Some(&gen_types), true);
628                                                 if local_var {
629                                                         write!(w, "inner_val").unwrap();
630                                                 } else {
631                                                         write!(w, "(*inner_val)").unwrap();
632                                                 }
633                                                 types.write_to_c_conversion_inline_suffix(w, &ref_type, Some(&gen_types), true);
634                                                 writeln!(w, "\n}}").unwrap();
635                                         }
636
637                                         if types.understood_c_type(&field.ty, Some(&gen_types)) {
638                                                 writeln_docs(w, &field.attrs, "");
639                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_set_{}(this_ptr: &mut {}, mut val: ", struct_name, ident, struct_name).unwrap();
640                                                 types.write_c_type(w, &field.ty, Some(&gen_types), false);
641                                                 write!(w, ") {{\n\t").unwrap();
642                                                 let local_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("val", Span::call_site()), &field.ty, Some(&gen_types));
643                                                 if local_var { write!(w, "\n\t").unwrap(); }
644                                                 write!(w, "unsafe {{ &mut *this_ptr.inner }}.{} = ", ident).unwrap();
645                                                 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
646                                                 write!(w, "val").unwrap();
647                                                 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
648                                                 writeln!(w, ";\n}}").unwrap();
649                                         } else { all_fields_settable = false; }
650                                 } else { all_fields_settable = false; }
651                         } else { all_fields_settable = false; }
652                 }
653
654                 if all_fields_settable {
655                         // Build a constructor!
656                         writeln!(w, "/// Constructs a new {} given each field", struct_name).unwrap();
657                         write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_new(", struct_name).unwrap();
658                         for (idx, field) in fields.named.iter().enumerate() {
659                                 if idx != 0 { write!(w, ", ").unwrap(); }
660                                 write!(w, "mut {}_arg: ", field.ident.as_ref().unwrap()).unwrap();
661                                 types.write_c_type(w, &field.ty, Some(&gen_types), false);
662                         }
663                         write!(w, ") -> {} {{\n\t", struct_name).unwrap();
664                         for field in fields.named.iter() {
665                                 let field_name = format!("{}_arg", field.ident.as_ref().unwrap());
666                                 if types.write_from_c_conversion_new_var(w, &syn::Ident::new(&field_name, Span::call_site()), &field.ty, Some(&gen_types)) {
667                                         write!(w, "\n\t").unwrap();
668                                 }
669                         }
670                         writeln!(w, "{} {{ inner: Box::into_raw(Box::new(native{} {{", struct_name, s.ident).unwrap();
671                         for field in fields.named.iter() {
672                                 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
673                                 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
674                                 write!(w, "{}_arg", field.ident.as_ref().unwrap()).unwrap();
675                                 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
676                                 writeln!(w, ",").unwrap();
677                         }
678                         writeln!(w, "\t}})), is_owned: true }}\n}}").unwrap();
679                 }
680         }
681 }
682
683 /// Prints a relevant conversion for impl *
684 ///
685 /// For simple impl Struct {}s, this just outputs the wrapper functions as Struct_fn_name() { .. }.
686 ///
687 /// For impl Trait for Struct{}s, this non-exported generates wrapper functions as
688 /// Trait_Struct_fn_name and a Struct_as_Trait(&struct) -> Trait function which returns a populated
689 /// Trait struct containing a pointer to the passed struct's inner field and the wrapper functions.
690 ///
691 /// A few non-crate Traits are hard-coded including Default.
692 fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut TypeResolver) {
693         match export_status(&i.attrs) {
694                 ExportStatus::Export => {},
695                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
696         }
697
698         if let syn::Type::Tuple(_) = &*i.self_ty {
699                 if types.understood_c_type(&*i.self_ty, None) {
700                         let mut gen_types = GenericTypes::new();
701                         if !gen_types.learn_generics(&i.generics, types) {
702                                 eprintln!("Not implementing anything for `impl (..)` due to not understood generics");
703                                 return;
704                         }
705
706                         if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
707                         if let Some(trait_path) = i.trait_.as_ref() {
708                                 if trait_path.0.is_some() { unimplemented!(); }
709                                 if types.understood_c_path(&trait_path.1) {
710                                         eprintln!("Not implementing anything for `impl Trait for (..)` - we only support manual defines");
711                                         return;
712                                 } else {
713                                         // Just do a manual implementation:
714                                         maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
715                                 }
716                         } else {
717                                 eprintln!("Not implementing anything for plain `impl (..)` block - we only support `impl Trait for (..)` blocks");
718                                 return;
719                         }
720                 }
721                 return;
722         }
723         if let &syn::Type::Path(ref p) = &*i.self_ty {
724                 if p.qself.is_some() { unimplemented!(); }
725                 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
726                         if let Some(resolved_path) = types.maybe_resolve_non_ignored_ident(&ident) {
727                                 let mut gen_types = GenericTypes::new();
728                                 if !gen_types.learn_generics(&i.generics, types) {
729                                         eprintln!("Not implementing anything for impl {} due to not understood generics", ident);
730                                         return;
731                                 }
732
733                                 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
734                                 if let Some(trait_path) = i.trait_.as_ref() {
735                                         if trait_path.0.is_some() { unimplemented!(); }
736                                         if types.understood_c_path(&trait_path.1) {
737                                                 let full_trait_path = types.resolve_path(&trait_path.1, None);
738                                                 let trait_obj = *types.crate_types.traits.get(&full_trait_path).unwrap();
739                                                 // We learn the associated types maping from the original trait object.
740                                                 // That's great, except that they are unresolved idents, so if we learn
741                                                 // mappings from a trai defined in a different file, we may mis-resolve or
742                                                 // fail to resolve the mapped types.
743                                                 gen_types.learn_associated_types(trait_obj, types);
744                                                 let mut impl_associated_types = HashMap::new();
745                                                 for item in i.items.iter() {
746                                                         match item {
747                                                                 syn::ImplItem::Type(t) => {
748                                                                         if let syn::Type::Path(p) = &t.ty {
749                                                                                 if let Some(id) = single_ident_generic_path_to_ident(&p.path) {
750                                                                                         impl_associated_types.insert(&t.ident, id);
751                                                                                 }
752                                                                         }
753                                                                 },
754                                                                 _ => {},
755                                                         }
756                                                 }
757
758                                                 let export = export_status(&trait_obj.attrs);
759                                                 match export {
760                                                         ExportStatus::Export => {},
761                                                         ExportStatus::NoExport|ExportStatus::TestOnly => return,
762                                                 }
763
764                                                 // For cases where we have a concrete native object which implements a
765                                                 // trait and need to return the C-mapped version of the trait, provide a
766                                                 // From<> implementation which does all the work to ensure free is handled
767                                                 // properly. This way we can call this method from deep in the
768                                                 // type-conversion logic without actually knowing the concrete native type.
769                                                 writeln!(w, "impl From<native{}> for crate::{} {{", ident, full_trait_path).unwrap();
770                                                 writeln!(w, "\tfn from(obj: native{}) -> Self {{", ident).unwrap();
771                                                 writeln!(w, "\t\tlet mut rust_obj = {} {{ inner: Box::into_raw(Box::new(obj)), is_owned: true }};", ident).unwrap();
772                                                 writeln!(w, "\t\tlet mut ret = {}_as_{}(&rust_obj);", ident, trait_obj.ident).unwrap();
773                                                 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();
774                                                 writeln!(w, "\t\trust_obj.inner = std::ptr::null_mut();").unwrap();
775                                                 writeln!(w, "\t\tret.free = Some({}_free_void);", ident).unwrap();
776                                                 writeln!(w, "\t\tret\n\t}}\n}}").unwrap();
777
778                                                 writeln!(w, "/// Constructs a new {} which calls the relevant methods on this_arg.", trait_obj.ident).unwrap();
779                                                 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();
780                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_as_{}(this_arg: &{}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
781                                                 writeln!(w, "\tcrate::{} {{", full_trait_path).unwrap();
782                                                 writeln!(w, "\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
783                                                 writeln!(w, "\t\tfree: None,").unwrap();
784
785                                                 macro_rules! write_meth {
786                                                         ($m: expr, $trait: expr, $indent: expr) => {
787                                                                 let trait_method = $trait.items.iter().filter_map(|item| {
788                                                                         if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
789                                                                 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
790                                                                 match export_status(&trait_method.attrs) {
791                                                                         ExportStatus::Export => {},
792                                                                         ExportStatus::NoExport => {
793                                                                                 write!(w, "{}\t\t//XXX: Need to export {}\n", $indent, $m.sig.ident).unwrap();
794                                                                                 continue;
795                                                                         },
796                                                                         ExportStatus::TestOnly => continue,
797                                                                 }
798
799                                                                 let mut printed = false;
800                                                                 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
801                                                                         if let syn::Type::Reference(r) = &**rtype {
802                                                                                 write!(w, "\n\t\t{}{}: ", $indent, $m.sig.ident).unwrap();
803                                                                                 types.write_empty_rust_val(Some(&gen_types), w, &*r.elem);
804                                                                                 writeln!(w, ",\n{}\t\tset_{}: Some({}_{}_set_{}),", $indent, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
805                                                                                 printed = true;
806                                                                         }
807                                                                 }
808                                                                 if !printed {
809                                                                         write!(w, "{}\t\t{}: {}_{}_{},\n", $indent, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
810                                                                 }
811                                                         }
812                                                 }
813                                                 for item in trait_obj.items.iter() {
814                                                         match item {
815                                                                 syn::TraitItem::Method(m) => {
816                                                                         write_meth!(m, trait_obj, "");
817                                                                 },
818                                                                 _ => {},
819                                                         }
820                                                 }
821                                                 let mut requires_clone = false;
822                                                 walk_supertraits!(trait_obj, Some(&types), (
823                                                         ("Clone", _) => requires_clone = true,
824                                                         (_, _) => {}
825                                                 ) );
826                                                 walk_supertraits!(trait_obj, Some(&types), (
827                                                         ("Clone", _) => {
828                                                                 writeln!(w, "\t\tclone: Some({}_clone_void),", ident).unwrap();
829                                                         },
830                                                         ("Sync", _) => {}, ("Send", _) => {},
831                                                         ("std::marker::Sync", _) => {}, ("std::marker::Send", _) => {},
832                                                         (s, t) => {
833                                                                 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
834                                                                         writeln!(w, "\t\t{}: crate::{} {{", t, s).unwrap();
835                                                                         writeln!(w, "\t\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
836                                                                         writeln!(w, "\t\t\tfree: None,").unwrap();
837                                                                         for item in supertrait_obj.items.iter() {
838                                                                                 match item {
839                                                                                         syn::TraitItem::Method(m) => {
840                                                                                                 write_meth!(m, supertrait_obj, "\t");
841                                                                                         },
842                                                                                         _ => {},
843                                                                                 }
844                                                                         }
845                                                                         write!(w, "\t\t}},\n").unwrap();
846                                                                         if !types.is_clonable(s) && requires_clone {
847                                                                                 writeln!(w, "\t\t{}_clone: {}_{}_clone,", t, ident, t).unwrap();
848                                                                         }
849                                                                 } else {
850                                                                         write_trait_impl_field_assign(w, s, ident);
851                                                                 }
852                                                         }
853                                                 ) );
854                                                 writeln!(w, "\t}}\n}}\n").unwrap();
855
856                                                 macro_rules! impl_meth {
857                                                         ($m: expr, $trait_path: expr, $trait: expr, $indent: expr) => {
858                                                                 let trait_method = $trait.items.iter().filter_map(|item| {
859                                                                         if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
860                                                                 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
861                                                                 match export_status(&trait_method.attrs) {
862                                                                         ExportStatus::Export => {},
863                                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
864                                                                 }
865
866                                                                 if let syn::ReturnType::Type(_, _) = &$m.sig.output {
867                                                                         writeln!(w, "#[must_use]").unwrap();
868                                                                 }
869                                                                 write!(w, "extern \"C\" fn {}_{}_{}(", ident, $trait.ident, $m.sig.ident).unwrap();
870                                                                 let mut meth_gen_types = gen_types.push_ctx();
871                                                                 assert!(meth_gen_types.learn_generics(&$m.sig.generics, types));
872                                                                 write_method_params(w, &$m.sig, "c_void", types, Some(&meth_gen_types), true, true);
873                                                                 write!(w, " {{\n\t").unwrap();
874                                                                 write_method_var_decl_body(w, &$m.sig, "", types, Some(&meth_gen_types), false);
875                                                                 let mut takes_self = false;
876                                                                 for inp in $m.sig.inputs.iter() {
877                                                                         if let syn::FnArg::Receiver(_) = inp {
878                                                                                 takes_self = true;
879                                                                         }
880                                                                 }
881
882                                                                 let mut t_gen_args = String::new();
883                                                                 for (idx, _) in $trait.generics.params.iter().enumerate() {
884                                                                         if idx != 0 { t_gen_args += ", " };
885                                                                         t_gen_args += "_"
886                                                                 }
887                                                                 if takes_self {
888                                                                         write!(w, "<native{} as {}<{}>>::{}(unsafe {{ &mut *(this_arg as *mut native{}) }}, ", ident, $trait_path, t_gen_args, $m.sig.ident, ident).unwrap();
889                                                                 } else {
890                                                                         write!(w, "<native{} as {}<{}>>::{}(", ident, $trait_path, t_gen_args, $m.sig.ident).unwrap();
891                                                                 }
892
893                                                                 let mut real_type = "".to_string();
894                                                                 match &$m.sig.output {
895                                                                         syn::ReturnType::Type(_, rtype) => {
896                                                                                 if let Some(mut remaining_path) = first_seg_self(&*rtype) {
897                                                                                         if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
898                                                                                                 real_type = format!("{}", impl_associated_types.get(associated_seg).unwrap());
899                                                                                         }
900                                                                                 }
901                                                                         },
902                                                                         _ => {},
903                                                                 }
904                                                                 write_method_call_params(w, &$m.sig, "", types, Some(&meth_gen_types), &real_type, false);
905                                                                 write!(w, "\n}}\n").unwrap();
906                                                                 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
907                                                                         if let syn::Type::Reference(r) = &**rtype {
908                                                                                 assert_eq!($m.sig.inputs.len(), 1); // Must only take self
909                                                                                 writeln!(w, "extern \"C\" fn {}_{}_set_{}(trait_self_arg: &{}) {{", ident, $trait.ident, $m.sig.ident, $trait.ident).unwrap();
910                                                                                 writeln!(w, "\t// This is a bit race-y in the general case, but for our specific use-cases today, we're safe").unwrap();
911                                                                                 writeln!(w, "\t// Specifically, we must ensure that the first time we're called it can never be in parallel").unwrap();
912                                                                                 write!(w, "\tif ").unwrap();
913                                                                                 types.write_empty_rust_val_check(Some(&meth_gen_types), w, &*r.elem, &format!("trait_self_arg.{}", $m.sig.ident));
914                                                                                 writeln!(w, " {{").unwrap();
915                                                                                 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();
916                                                                                 writeln!(w, "\t}}").unwrap();
917                                                                                 writeln!(w, "}}").unwrap();
918                                                                         }
919                                                                 }
920                                                         }
921                                                 }
922
923                                                 for item in i.items.iter() {
924                                                         match item {
925                                                                 syn::ImplItem::Method(m) => {
926                                                                         impl_meth!(m, full_trait_path, trait_obj, "");
927                                                                 },
928                                                                 syn::ImplItem::Type(_) => {},
929                                                                 _ => unimplemented!(),
930                                                         }
931                                                 }
932                                                 walk_supertraits!(trait_obj, Some(&types), (
933                                                         (s, t) => {
934                                                                 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
935                                                                         if !types.is_clonable(s) && requires_clone {
936                                                                                 writeln!(w, "extern \"C\" fn {}_{}_clone(orig: &crate::{}) -> crate::{} {{", ident, t, s, s).unwrap();
937                                                                                 writeln!(w, "\tcrate::{} {{", s).unwrap();
938                                                                                 writeln!(w, "\t\tthis_arg: orig.this_arg,").unwrap();
939                                                                                 writeln!(w, "\t\tfree: None,").unwrap();
940                                                                                 for item in supertrait_obj.items.iter() {
941                                                                                         match item {
942                                                                                                 syn::TraitItem::Method(m) => {
943                                                                                                         write_meth!(m, supertrait_obj, "");
944                                                                                                 },
945                                                                                                 _ => {},
946                                                                                         }
947                                                                                 }
948                                                                                 write!(w, "\t}}\n}}\n").unwrap();
949                                                                         }
950                                                                 }
951                                                         }
952                                                 ) );
953                                                 write!(w, "\n").unwrap();
954                                         } else if path_matches_nongeneric(&trait_path.1, &["From"]) {
955                                         } else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
956                                                 writeln!(w, "/// Creates a \"default\" {}. See struct and individual field documentaiton for details on which values are used.", ident).unwrap();
957                                                 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
958                                                 write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
959                                                 write!(w, "}}\n").unwrap();
960                                         } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "PartialEq"]) {
961                                         } else if (path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) || path_matches_nongeneric(&trait_path.1, &["Clone"])) &&
962                                                         types.c_type_has_inner_from_path(&resolved_path) {
963                                                 writeln!(w, "impl Clone for {} {{", ident).unwrap();
964                                                 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
965                                                 writeln!(w, "\t\tSelf {{").unwrap();
966                                                 writeln!(w, "\t\t\tinner: if <*mut native{}>::is_null(self.inner) {{ std::ptr::null_mut() }} else {{", ident).unwrap();
967                                                 writeln!(w, "\t\t\t\tBox::into_raw(Box::new(unsafe {{ &*self.inner }}.clone())) }},").unwrap();
968                                                 writeln!(w, "\t\t\tis_owned: true,").unwrap();
969                                                 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
970                                                 writeln!(w, "#[allow(unused)]").unwrap();
971                                                 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
972                                                 writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", ident).unwrap();
973                                                 writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", ident).unwrap();
974                                                 writeln!(w, "}}").unwrap();
975                                                 writeln!(w, "#[no_mangle]").unwrap();
976                                                 writeln!(w, "/// Creates a copy of the {}", ident).unwrap();
977                                                 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", ident, ident, ident).unwrap();
978                                                 writeln!(w, "\torig.clone()").unwrap();
979                                                 writeln!(w, "}}").unwrap();
980                                         } else {
981                                                 //XXX: implement for other things like ToString
982                                                 // If we have no generics, try a manual implementation:
983                                                 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
984                                         }
985                                 } else {
986                                         let declared_type = (*types.get_declared_type(&ident).unwrap()).clone();
987                                         for item in i.items.iter() {
988                                                 match item {
989                                                         syn::ImplItem::Method(m) => {
990                                                                 if let syn::Visibility::Public(_) = m.vis {
991                                                                         match export_status(&m.attrs) {
992                                                                                 ExportStatus::Export => {},
993                                                                                 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
994                                                                         }
995                                                                         if m.defaultness.is_some() { unimplemented!(); }
996                                                                         writeln_docs(w, &m.attrs, "");
997                                                                         if let syn::ReturnType::Type(_, _) = &m.sig.output {
998                                                                                 writeln!(w, "#[must_use]").unwrap();
999                                                                         }
1000                                                                         write!(w, "#[no_mangle]\npub extern \"C\" fn {}_{}(", ident, m.sig.ident).unwrap();
1001                                                                         let ret_type = match &declared_type {
1002                                                                                 DeclType::MirroredEnum => format!("{}", ident),
1003                                                                                 DeclType::StructImported => format!("{}", ident),
1004                                                                                 _ => unimplemented!(),
1005                                                                         };
1006                                                                         let mut meth_gen_types = gen_types.push_ctx();
1007                                                                         assert!(meth_gen_types.learn_generics(&m.sig.generics, types));
1008                                                                         write_method_params(w, &m.sig, &ret_type, types, Some(&meth_gen_types), false, true);
1009                                                                         write!(w, " {{\n\t").unwrap();
1010                                                                         write_method_var_decl_body(w, &m.sig, "", types, Some(&meth_gen_types), false);
1011                                                                         let mut takes_self = false;
1012                                                                         let mut takes_mut_self = false;
1013                                                                         for inp in m.sig.inputs.iter() {
1014                                                                                 if let syn::FnArg::Receiver(r) = inp {
1015                                                                                         takes_self = true;
1016                                                                                         if r.mutability.is_some() { takes_mut_self = true; }
1017                                                                                 }
1018                                                                         }
1019                                                                         if takes_mut_self {
1020                                                                                 write!(w, "unsafe {{ &mut (*(this_arg.inner as *mut native{})) }}.{}(", ident, m.sig.ident).unwrap();
1021                                                                         } else if takes_self {
1022                                                                                 write!(w, "unsafe {{ &*this_arg.inner }}.{}(", m.sig.ident).unwrap();
1023                                                                         } else {
1024                                                                                 write!(w, "{}::{}(", resolved_path, m.sig.ident).unwrap();
1025                                                                         }
1026                                                                         write_method_call_params(w, &m.sig, "", types, Some(&meth_gen_types), &ret_type, false);
1027                                                                         writeln!(w, "\n}}\n").unwrap();
1028                                                                 }
1029                                                         },
1030                                                         _ => {},
1031                                                 }
1032                                         }
1033                                 }
1034                         } else if let Some(resolved_path) = types.maybe_resolve_ident(&ident) {
1035                                 if let Some(aliases) = types.crate_types.reverse_alias_map.get(&resolved_path).cloned() {
1036                                         'alias_impls: for (alias, arguments) in aliases {
1037                                                 let alias_resolved = types.resolve_path(&alias, None);
1038                                                 for (idx, gen) in i.generics.params.iter().enumerate() {
1039                                                         match gen {
1040                                                                 syn::GenericParam::Type(type_param) => {
1041                                                                         'bounds_check: for bound in type_param.bounds.iter() {
1042                                                                                 if let syn::TypeParamBound::Trait(trait_bound) = bound {
1043                                                                                         if let syn::PathArguments::AngleBracketed(ref t) = &arguments {
1044                                                                                                 assert!(idx < t.args.len());
1045                                                                                                 if let syn::GenericArgument::Type(syn::Type::Path(p)) = &t.args[idx] {
1046                                                                                                         let generic_arg = types.resolve_path(&p.path, None);
1047                                                                                                         let generic_bound = types.resolve_path(&trait_bound.path, None);
1048                                                                                                         if let Some(traits_impld) = types.crate_types.trait_impls.get(&generic_arg) {
1049                                                                                                                 for trait_impld in traits_impld {
1050                                                                                                                         if *trait_impld == generic_bound { continue 'bounds_check; }
1051                                                                                                                 }
1052                                                                                                                 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1053                                                                                                                 continue 'alias_impls;
1054                                                                                                         } else {
1055                                                                                                                 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1056                                                                                                                 continue 'alias_impls;
1057                                                                                                         }
1058                                                                                                 } else { unimplemented!(); }
1059                                                                                         } else { unimplemented!(); }
1060                                                                                 } else { unimplemented!(); }
1061                                                                         }
1062                                                                 },
1063                                                                 syn::GenericParam::Lifetime(_) => {},
1064                                                                 syn::GenericParam::Const(_) => unimplemented!(),
1065                                                         }
1066                                                 }
1067                                                 let aliased_impl = syn::ItemImpl {
1068                                                         attrs: i.attrs.clone(),
1069                                                         brace_token: syn::token::Brace(Span::call_site()),
1070                                                         defaultness: None,
1071                                                         generics: syn::Generics {
1072                                                                 lt_token: None,
1073                                                                 params: syn::punctuated::Punctuated::new(),
1074                                                                 gt_token: None,
1075                                                                 where_clause: None,
1076                                                         },
1077                                                         impl_token: syn::Token![impl](Span::call_site()),
1078                                                         items: i.items.clone(),
1079                                                         self_ty: Box::new(syn::Type::Path(syn::TypePath { qself: None, path: alias.clone() })),
1080                                                         trait_: i.trait_.clone(),
1081                                                         unsafety: None,
1082                                                 };
1083                                                 writeln_impl(w, &aliased_impl, types);
1084                                         }
1085                                 } else {
1086                                         eprintln!("Not implementing anything for {} due to it being marked not exported", ident);
1087                                 }
1088                         } else {
1089                                 eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub)", ident);
1090                         }
1091                 }
1092         }
1093 }
1094
1095
1096 /// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
1097 /// is unitary), we generate an equivalent enum with all types replaced with their C mapped
1098 /// versions followed by conversion functions which map between the Rust version and the C mapped
1099 /// version.
1100 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) {
1101         match export_status(&e.attrs) {
1102                 ExportStatus::Export => {},
1103                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1104         }
1105
1106         if is_enum_opaque(e) {
1107                 eprintln!("Skipping enum {} as it contains non-unit fields", e.ident);
1108                 writeln_opaque(w, &e.ident, &format!("{}", e.ident), &e.generics, &e.attrs, types, extra_headers, cpp_headers);
1109                 return;
1110         }
1111         writeln_docs(w, &e.attrs, "");
1112
1113         if e.generics.lt_token.is_some() {
1114                 unimplemented!();
1115         }
1116
1117         let mut needs_free = false;
1118
1119         writeln!(w, "#[must_use]\n#[derive(Clone)]\n#[repr(C)]\npub enum {} {{", e.ident).unwrap();
1120         for var in e.variants.iter() {
1121                 assert_eq!(export_status(&var.attrs), ExportStatus::Export); // We can't partially-export a mirrored enum
1122                 writeln_docs(w, &var.attrs, "\t");
1123                 write!(w, "\t{}", var.ident).unwrap();
1124                 if let syn::Fields::Named(fields) = &var.fields {
1125                         needs_free = true;
1126                         writeln!(w, " {{").unwrap();
1127                         for field in fields.named.iter() {
1128                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1129                                 writeln_docs(w, &field.attrs, "\t\t");
1130                                 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1131                                 types.write_c_type(w, &field.ty, None, false);
1132                                 writeln!(w, ",").unwrap();
1133                         }
1134                         write!(w, "\t}}").unwrap();
1135                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1136                         needs_free = true;
1137                         write!(w, "(").unwrap();
1138                         for (idx, field) in fields.unnamed.iter().enumerate() {
1139                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1140                                 types.write_c_type(w, &field.ty, None, false);
1141                                 if idx != fields.unnamed.len() - 1 {
1142                                         write!(w, ",").unwrap();
1143                                 }
1144                         }
1145                         write!(w, ")").unwrap();
1146                 }
1147                 if var.discriminant.is_some() { unimplemented!(); }
1148                 writeln!(w, ",").unwrap();
1149         }
1150         writeln!(w, "}}\nuse {}::{} as native{};\nimpl {} {{", types.module_path, e.ident, e.ident, e.ident).unwrap();
1151
1152         macro_rules! write_conv {
1153                 ($fn_sig: expr, $to_c: expr, $ref: expr) => {
1154                         writeln!(w, "\t#[allow(unused)]\n\tpub(crate) fn {} {{\n\t\tmatch {} {{", $fn_sig, if $to_c { "native" } else { "self" }).unwrap();
1155                         for var in e.variants.iter() {
1156                                 write!(w, "\t\t\t{}{}::{} ", if $to_c { "native" } else { "" }, e.ident, var.ident).unwrap();
1157                                 if let syn::Fields::Named(fields) = &var.fields {
1158                                         write!(w, "{{").unwrap();
1159                                         for field in fields.named.iter() {
1160                                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1161                                                 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, field.ident.as_ref().unwrap()).unwrap();
1162                                         }
1163                                         write!(w, "}} ").unwrap();
1164                                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1165                                         write!(w, "(").unwrap();
1166                                         for (idx, field) in fields.unnamed.iter().enumerate() {
1167                                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1168                                                 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, ('a' as u8 + idx as u8) as char).unwrap();
1169                                         }
1170                                         write!(w, ") ").unwrap();
1171                                 }
1172                                 write!(w, "=>").unwrap();
1173
1174                                 macro_rules! handle_field_a {
1175                                         ($field: expr, $field_ident: expr) => { {
1176                                                 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1177                                                 let mut sink = ::std::io::sink();
1178                                                 let mut out: &mut dyn std::io::Write = if $ref { &mut sink } else { w };
1179                                                 let new_var = if $to_c {
1180                                                         types.write_to_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None, false)
1181                                                 } else {
1182                                                         types.write_from_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None)
1183                                                 };
1184                                                 if $ref || new_var {
1185                                                         if $ref {
1186                                                                 write!(w, "let mut {}_nonref = (*{}).clone();\n\t\t\t\t", $field_ident, $field_ident).unwrap();
1187                                                                 if new_var {
1188                                                                         let nonref_ident = syn::Ident::new(&format!("{}_nonref", $field_ident), Span::call_site());
1189                                                                         if $to_c {
1190                                                                                 types.write_to_c_conversion_new_var(w, &nonref_ident, &$field.ty, None, false);
1191                                                                         } else {
1192                                                                                 types.write_from_c_conversion_new_var(w, &nonref_ident, &$field.ty, None);
1193                                                                         }
1194                                                                         write!(w, "\n\t\t\t\t").unwrap();
1195                                                                 }
1196                                                         } else {
1197                                                                 write!(w, "\n\t\t\t\t").unwrap();
1198                                                         }
1199                                                 }
1200                                         } }
1201                                 }
1202                                 if let syn::Fields::Named(fields) = &var.fields {
1203                                         write!(w, " {{\n\t\t\t\t").unwrap();
1204                                         for field in fields.named.iter() {
1205                                                 handle_field_a!(field, field.ident.as_ref().unwrap());
1206                                         }
1207                                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1208                                         write!(w, " {{\n\t\t\t\t").unwrap();
1209                                         for (idx, field) in fields.unnamed.iter().enumerate() {
1210                                                 handle_field_a!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1211                                         }
1212                                 } else { write!(w, " ").unwrap(); }
1213
1214                                 write!(w, "{}{}::{}", if $to_c { "" } else { "native" }, e.ident, var.ident).unwrap();
1215
1216                                 macro_rules! handle_field_b {
1217                                         ($field: expr, $field_ident: expr) => { {
1218                                                 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1219                                                 if $to_c {
1220                                                         types.write_to_c_conversion_inline_prefix(w, &$field.ty, None, false);
1221                                                 } else {
1222                                                         types.write_from_c_conversion_prefix(w, &$field.ty, None);
1223                                                 }
1224                                                 write!(w, "{}{}", $field_ident,
1225                                                         if $ref { "_nonref" } else { "" }).unwrap();
1226                                                 if $to_c {
1227                                                         types.write_to_c_conversion_inline_suffix(w, &$field.ty, None, false);
1228                                                 } else {
1229                                                         types.write_from_c_conversion_suffix(w, &$field.ty, None);
1230                                                 }
1231                                                 write!(w, ",").unwrap();
1232                                         } }
1233                                 }
1234
1235                                 if let syn::Fields::Named(fields) = &var.fields {
1236                                         write!(w, " {{").unwrap();
1237                                         for field in fields.named.iter() {
1238                                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1239                                                 write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1240                                                 handle_field_b!(field, field.ident.as_ref().unwrap());
1241                                         }
1242                                         writeln!(w, "\n\t\t\t\t}}").unwrap();
1243                                         write!(w, "\t\t\t}}").unwrap();
1244                                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1245                                         write!(w, " (").unwrap();
1246                                         for (idx, field) in fields.unnamed.iter().enumerate() {
1247                                                 write!(w, "\n\t\t\t\t\t").unwrap();
1248                                                 handle_field_b!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1249                                         }
1250                                         writeln!(w, "\n\t\t\t\t)").unwrap();
1251                                         write!(w, "\t\t\t}}").unwrap();
1252                                 }
1253                                 writeln!(w, ",").unwrap();
1254                         }
1255                         writeln!(w, "\t\t}}\n\t}}").unwrap();
1256                 }
1257         }
1258
1259         write_conv!(format!("to_native(&self) -> native{}", e.ident), false, true);
1260         write_conv!(format!("into_native(self) -> native{}", e.ident), false, false);
1261         write_conv!(format!("from_native(native: &native{}) -> Self", e.ident), true, true);
1262         write_conv!(format!("native_into(native: native{}) -> Self", e.ident), true, false);
1263         writeln!(w, "}}").unwrap();
1264
1265         if needs_free {
1266                 writeln!(w, "/// Frees any resources used by the {}", e.ident).unwrap();
1267                 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", e.ident, e.ident).unwrap();
1268         }
1269         writeln!(w, "/// Creates a copy of the {}", e.ident).unwrap();
1270         writeln!(w, "#[no_mangle]").unwrap();
1271         writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
1272         writeln!(w, "\torig.clone()").unwrap();
1273         writeln!(w, "}}").unwrap();
1274         write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free);
1275 }
1276
1277 fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &mut TypeResolver<'b, 'a>) {
1278         match export_status(&f.attrs) {
1279                 ExportStatus::Export => {},
1280                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1281         }
1282         writeln_docs(w, &f.attrs, "");
1283
1284         let mut gen_types = GenericTypes::new();
1285         if !gen_types.learn_generics(&f.sig.generics, types) { return; }
1286
1287         write!(w, "#[no_mangle]\npub extern \"C\" fn {}(", f.sig.ident).unwrap();
1288         write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
1289         write!(w, " {{\n\t").unwrap();
1290         write_method_var_decl_body(w, &f.sig, "", types, Some(&gen_types), false);
1291         write!(w, "{}::{}(", types.module_path, f.sig.ident).unwrap();
1292         write_method_call_params(w, &f.sig, "", types, Some(&gen_types), "", false);
1293         writeln!(w, "\n}}\n").unwrap();
1294 }
1295
1296 // ********************************
1297 // *** File/Crate Walking Logic ***
1298 // ********************************
1299
1300 /// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
1301 /// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
1302 /// at `module` from C.
1303 fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &CrateTypes<'a>, out_dir: &str, header_file: &mut File, cpp_header_file: &mut File) {
1304         for (module, astmod) in libast.modules.iter() {
1305                 let orig_crate = module.splitn(2, "::").next().unwrap();
1306                 let ASTModule { ref attrs, ref items, ref submods } = astmod;
1307                 assert_eq!(export_status(&attrs), ExportStatus::Export);
1308
1309                 let new_file_path = if submods.is_empty() {
1310                         format!("{}/{}.rs", out_dir, module.replace("::", "/"))
1311                 } else if module != "" {
1312                         format!("{}/{}/mod.rs", out_dir, module.replace("::", "/"))
1313                 } else {
1314                         format!("{}/lib.rs", out_dir)
1315                 };
1316                 let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
1317                 let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1318                         .open(new_file_path).expect("Unable to open new src file");
1319
1320                 writeln!(out, "// This file is Copyright its original authors, visible in version control").unwrap();
1321                 writeln!(out, "// history and in the source files from which this was generated.").unwrap();
1322                 writeln!(out, "//").unwrap();
1323                 writeln!(out, "// This file is licensed under the license available in the LICENSE or LICENSE.md").unwrap();
1324                 writeln!(out, "// file in the root of this repository or, if no such file exists, the same").unwrap();
1325                 writeln!(out, "// license as that which applies to the original source files from which this").unwrap();
1326                 writeln!(out, "// source was automatically generated.").unwrap();
1327                 writeln!(out, "").unwrap();
1328
1329                 writeln_docs(&mut out, &attrs, "");
1330
1331                 if module == "" {
1332                         // Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
1333                         // and bitcoin hand-written modules.
1334                         writeln!(out, "//! C Bindings").unwrap();
1335                         writeln!(out, "#![allow(unknown_lints)]").unwrap();
1336                         writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
1337                         writeln!(out, "#![allow(non_snake_case)]").unwrap();
1338                         writeln!(out, "#![allow(unused_imports)]").unwrap();
1339                         writeln!(out, "#![allow(unused_variables)]").unwrap();
1340                         writeln!(out, "#![allow(unused_mut)]").unwrap();
1341                         writeln!(out, "#![allow(unused_parens)]").unwrap();
1342                         writeln!(out, "#![allow(unused_unsafe)]").unwrap();
1343                         writeln!(out, "#![allow(unused_braces)]").unwrap();
1344                         writeln!(out, "#![deny(missing_docs)]").unwrap();
1345                         writeln!(out, "pub mod c_types;").unwrap();
1346                         writeln!(out, "pub mod bitcoin;").unwrap();
1347                 } else {
1348                         writeln!(out, "\nuse std::ffi::c_void;\nuse bitcoin::hashes::Hash;\nuse crate::c_types::*;\n").unwrap();
1349                 }
1350
1351                 for m in submods {
1352                         writeln!(out, "pub mod {};", m).unwrap();
1353                 }
1354
1355                 eprintln!("Converting {} entries...", module);
1356
1357                 let import_resolver = ImportResolver::new(orig_crate, &libast.dependencies, module, items);
1358                 let mut type_resolver = TypeResolver::new(module, import_resolver, crate_types);
1359
1360                 for item in items.iter() {
1361                         match item {
1362                                 syn::Item::Use(_) => {}, // Handled above
1363                                 syn::Item::Static(_) => {},
1364                                 syn::Item::Enum(e) => {
1365                                         if let syn::Visibility::Public(_) = e.vis {
1366                                                 writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
1367                                         }
1368                                 },
1369                                 syn::Item::Impl(i) => {
1370                                         writeln_impl(&mut out, &i, &mut type_resolver);
1371                                 },
1372                                 syn::Item::Struct(s) => {
1373                                         if let syn::Visibility::Public(_) = s.vis {
1374                                                 writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
1375                                         }
1376                                 },
1377                                 syn::Item::Trait(t) => {
1378                                         if let syn::Visibility::Public(_) = t.vis {
1379                                                 writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
1380                                         }
1381                                 },
1382                                 syn::Item::Mod(_) => {}, // We don't have to do anything - the top loop handles these.
1383                                 syn::Item::Const(c) => {
1384                                         // Re-export any primitive-type constants.
1385                                         if let syn::Visibility::Public(_) = c.vis {
1386                                                 if let syn::Type::Path(p) = &*c.ty {
1387                                                         let resolved_path = type_resolver.resolve_path(&p.path, None);
1388                                                         if type_resolver.is_primitive(&resolved_path) {
1389                                                                 writeln_docs(&mut out, &c.attrs, "");
1390                                                                 writeln!(out, "\n#[no_mangle]").unwrap();
1391                                                                 writeln!(out, "pub static {}: {} = {}::{};", c.ident, resolved_path, module, c.ident).unwrap();
1392                                                         }
1393                                                 }
1394                                         }
1395                                 },
1396                                 syn::Item::Type(t) => {
1397                                         if let syn::Visibility::Public(_) = t.vis {
1398                                                 match export_status(&t.attrs) {
1399                                                         ExportStatus::Export => {},
1400                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1401                                                 }
1402
1403                                                 let mut process_alias = true;
1404                                                 for tok in t.generics.params.iter() {
1405                                                         if let syn::GenericParam::Lifetime(_) = tok {}
1406                                                         else { process_alias = false; }
1407                                                 }
1408                                                 if process_alias {
1409                                                         match &*t.ty {
1410                                                                 syn::Type::Path(_) =>
1411                                                                         writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &t.generics, &t.attrs, &type_resolver, header_file, cpp_header_file),
1412                                                                 _ => {}
1413                                                         }
1414                                                 }
1415                                         }
1416                                 },
1417                                 syn::Item::Fn(f) => {
1418                                         if let syn::Visibility::Public(_) = f.vis {
1419                                                 writeln_fn(&mut out, &f, &mut type_resolver);
1420                                         }
1421                                 },
1422                                 syn::Item::Macro(_) => {},
1423                                 syn::Item::Verbatim(_) => {},
1424                                 syn::Item::ExternCrate(_) => {},
1425                                 _ => unimplemented!(),
1426                         }
1427                 }
1428
1429                 out.flush().unwrap();
1430         }
1431 }
1432
1433 fn walk_private_mod<'a>(ast_storage: &'a FullLibraryAST, orig_crate: &str, module: String, items: &'a syn::ItemMod, crate_types: &mut CrateTypes<'a>) {
1434         let import_resolver = ImportResolver::new(orig_crate, &ast_storage.dependencies, &module, &items.content.as_ref().unwrap().1);
1435         for item in items.content.as_ref().unwrap().1.iter() {
1436                 match item {
1437                         syn::Item::Mod(m) => walk_private_mod(ast_storage, orig_crate, format!("{}::{}", module, m.ident), m, crate_types),
1438                         syn::Item::Impl(i) => {
1439                                 if let &syn::Type::Path(ref p) = &*i.self_ty {
1440                                         if let Some(trait_path) = i.trait_.as_ref() {
1441                                                 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1442                                                         if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1443                                                                 match crate_types.trait_impls.entry(sp) {
1444                                                                         hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1445                                                                         hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1446                                                                 }
1447                                                         }
1448                                                 }
1449                                         }
1450                                 }
1451                         },
1452                         _ => {},
1453                 }
1454         }
1455 }
1456
1457 /// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
1458 fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
1459         for (module, astmod) in ast_storage.modules.iter() {
1460                 let ASTModule { ref attrs, ref items, submods: _ } = astmod;
1461                 assert_eq!(export_status(&attrs), ExportStatus::Export);
1462                 let orig_crate = module.splitn(2, "::").next().unwrap();
1463                 let import_resolver = ImportResolver::new(orig_crate, &ast_storage.dependencies, module, items);
1464
1465                 for item in items.iter() {
1466                         match item {
1467                                 syn::Item::Struct(s) => {
1468                                         if let syn::Visibility::Public(_) = s.vis {
1469                                                 match export_status(&s.attrs) {
1470                                                         ExportStatus::Export => {},
1471                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1472                                                 }
1473                                                 let struct_path = format!("{}::{}", module, s.ident);
1474                                                 crate_types.opaques.insert(struct_path, &s.ident);
1475                                         }
1476                                 },
1477                                 syn::Item::Trait(t) => {
1478                                         if let syn::Visibility::Public(_) = t.vis {
1479                                                 match export_status(&t.attrs) {
1480                                                         ExportStatus::Export => {},
1481                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1482                                                 }
1483                                                 let trait_path = format!("{}::{}", module, t.ident);
1484                                                 walk_supertraits!(t, None, (
1485                                                         ("Clone", _) => {
1486                                                                 crate_types.set_clonable("crate::".to_owned() + &trait_path);
1487                                                         },
1488                                                         (_, _) => {}
1489                                                 ) );
1490                                                 crate_types.traits.insert(trait_path, &t);
1491                                         }
1492                                 },
1493                                 syn::Item::Type(t) => {
1494                                         if let syn::Visibility::Public(_) = t.vis {
1495                                                 match export_status(&t.attrs) {
1496                                                         ExportStatus::Export => {},
1497                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1498                                                 }
1499                                                 let type_path = format!("{}::{}", module, t.ident);
1500                                                 let mut process_alias = true;
1501                                                 for tok in t.generics.params.iter() {
1502                                                         if let syn::GenericParam::Lifetime(_) = tok {}
1503                                                         else { process_alias = false; }
1504                                                 }
1505                                                 if process_alias {
1506                                                         match &*t.ty {
1507                                                                 syn::Type::Path(p) => {
1508                                                                         // If its a path with no generics, assume we don't map the aliased type and map it opaque
1509                                                                         let mut segments = syn::punctuated::Punctuated::new();
1510                                                                         segments.push(syn::PathSegment {
1511                                                                                 ident: t.ident.clone(),
1512                                                                                 arguments: syn::PathArguments::None,
1513                                                                         });
1514                                                                         let path_obj = syn::Path { leading_colon: None, segments };
1515                                                                         let args_obj = p.path.segments.last().unwrap().arguments.clone();
1516                                                                         match crate_types.reverse_alias_map.entry(import_resolver.maybe_resolve_path(&p.path, None).unwrap()) {
1517                                                                                 hash_map::Entry::Occupied(mut e) => { e.get_mut().push((path_obj, args_obj)); },
1518                                                                                 hash_map::Entry::Vacant(e) => { e.insert(vec![(path_obj, args_obj)]); },
1519                                                                         }
1520
1521                                                                         crate_types.opaques.insert(type_path.clone(), &t.ident);
1522                                                                 },
1523                                                                 _ => {
1524                                                                         crate_types.type_aliases.insert(type_path, import_resolver.resolve_imported_refs((*t.ty).clone()));
1525                                                                 }
1526                                                         }
1527                                                 }
1528                                         }
1529                                 },
1530                                 syn::Item::Enum(e) if is_enum_opaque(e) => {
1531                                         if let syn::Visibility::Public(_) = e.vis {
1532                                                 match export_status(&e.attrs) {
1533                                                         ExportStatus::Export => {},
1534                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1535                                                 }
1536                                                 let enum_path = format!("{}::{}", module, e.ident);
1537                                                 crate_types.opaques.insert(enum_path, &e.ident);
1538                                         }
1539                                 },
1540                                 syn::Item::Enum(e) => {
1541                                         if let syn::Visibility::Public(_) = e.vis {
1542                                                 match export_status(&e.attrs) {
1543                                                         ExportStatus::Export => {},
1544                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1545                                                 }
1546                                                 let enum_path = format!("{}::{}", module, e.ident);
1547                                                 crate_types.mirrored_enums.insert(enum_path, &e);
1548                                         }
1549                                 },
1550                                 syn::Item::Impl(i) => {
1551                                         if let &syn::Type::Path(ref p) = &*i.self_ty {
1552                                                 if let Some(trait_path) = i.trait_.as_ref() {
1553                                                         if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) {
1554                                                                 if let Some(full_path) = import_resolver.maybe_resolve_path(&p.path, None) {
1555                                                                         crate_types.set_clonable("crate::".to_owned() + &full_path);
1556                                                                 }
1557                                                         }
1558                                                         if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1559                                                                 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1560                                                                         match crate_types.trait_impls.entry(sp) {
1561                                                                                 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1562                                                                                 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1563                                                                         }
1564                                                                 }
1565                                                         }
1566                                                 }
1567                                         }
1568                                 },
1569                                 syn::Item::Mod(m) => walk_private_mod(ast_storage, orig_crate, format!("{}::{}", module, m.ident), m, crate_types),
1570                                 _ => {},
1571                         }
1572                 }
1573         }
1574 }
1575
1576 fn main() {
1577         let args: Vec<String> = env::args().collect();
1578         if args.len() != 5 {
1579                 eprintln!("Usage: target/dir derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
1580                 process::exit(1);
1581         }
1582
1583         let mut derived_templates = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1584                 .open(&args[2]).expect("Unable to open new header file");
1585         let mut header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1586                 .open(&args[3]).expect("Unable to open new header file");
1587         let mut cpp_header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1588                 .open(&args[4]).expect("Unable to open new header file");
1589
1590         writeln!(header_file, "#if defined(__GNUC__)").unwrap();
1591         writeln!(header_file, "#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
1592         writeln!(header_file, "#define MUST_USE_RES __attribute__((warn_unused_result))").unwrap();
1593         writeln!(header_file, "#else").unwrap();
1594         writeln!(header_file, "#define MUST_USE_STRUCT").unwrap();
1595         writeln!(header_file, "#define MUST_USE_RES").unwrap();
1596         writeln!(header_file, "#endif").unwrap();
1597         writeln!(header_file, "#if defined(__clang__)").unwrap();
1598         writeln!(header_file, "#define NONNULL_PTR _Nonnull").unwrap();
1599         writeln!(header_file, "#else").unwrap();
1600         writeln!(header_file, "#define NONNULL_PTR").unwrap();
1601         writeln!(header_file, "#endif").unwrap();
1602         writeln!(cpp_header_file, "#include <string.h>\nnamespace LDK {{").unwrap();
1603
1604         // First parse the full crate's ASTs, caching them so that we can hold references to the AST
1605         // objects in other datastructures:
1606         let mut lib_src = String::new();
1607         std::io::stdin().lock().read_to_string(&mut lib_src).unwrap();
1608         let lib_syntax = syn::parse_file(&lib_src).expect("Unable to parse file");
1609         let libast = FullLibraryAST::load_lib(lib_syntax);
1610
1611         // ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
1612         // when parsing other file ASTs...
1613         let mut libtypes = CrateTypes::new(&mut derived_templates, &libast);
1614         walk_ast(&libast, &mut libtypes);
1615
1616         // ... finally, do the actual file conversion/mapping, writing out types as we go.
1617         convert_file(&libast, &libtypes, &args[1], &mut header_file, &mut cpp_header_file);
1618
1619         // For container templates which we created while walking the crate, make sure we add C++
1620         // mapped types so that C++ users can utilize the auto-destructors available.
1621         for (ty, has_destructor) in libtypes.templates_defined.borrow().iter() {
1622                 write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor);
1623         }
1624         writeln!(cpp_header_file, "}}").unwrap();
1625
1626         header_file.flush().unwrap();
1627         cpp_header_file.flush().unwrap();
1628         derived_templates.flush().unwrap();
1629 }