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