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