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