Support supertraits-of-supertraits
[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, HashSet};
22 use std::env;
23 use std::fs::File;
24 use std::io::{Read, Write};
25 use std::iter::FromIterator;
26 use std::process;
27
28 use proc_macro2::Span;
29 use quote::format_ident;
30 use syn::parse_quote;
31
32 mod types;
33 mod blocks;
34 use types::*;
35 use blocks::*;
36
37 const DEFAULT_IMPORTS: &'static str = "
38 use alloc::str::FromStr;
39 use core::ffi::c_void;
40 use core::convert::Infallible;
41 use bitcoin::hashes::Hash;
42 use crate::c_types::*;
43 #[cfg(feature=\"no-std\")]
44 use alloc::{vec::Vec, boxed::Box};
45 ";
46
47
48 /// str.rsplit_once but with an older MSRV
49 fn rsplit_once<'a>(inp: &'a str, pattern: &str) -> Option<(&'a str, &'a str)> {
50         let mut iter = inp.rsplitn(2, pattern);
51         let second_entry = iter.next().unwrap();
52         Some((iter.next().unwrap(), second_entry))
53 }
54
55 // *************************************
56 // *** Manually-expanded conversions ***
57 // *************************************
58
59 /// Convert "impl trait_path for for_ty { .. }" for manually-mapped types (ie (de)serialization)
60 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) {
61         if let Some(t) = types.maybe_resolve_path(&trait_path, Some(generics)) {
62                 let for_obj;
63                 let full_obj_path;
64                 let mut has_inner = false;
65                 if let syn::Type::Path(ref p) = for_ty {
66                         let resolved_path = types.resolve_path(&p.path, Some(generics));
67                         for_obj = format!("{}", p.path.segments.last().unwrap().ident);
68                         full_obj_path = format!("crate::{}", resolved_path);
69                         has_inner = types.c_type_has_inner_from_path(&resolved_path);
70                 } else {
71                         // We assume that anything that isn't a Path is somehow a generic that ends up in our
72                         // derived-types module.
73                         let mut for_obj_vec = Vec::new();
74                         types.write_c_type(&mut for_obj_vec, for_ty, Some(generics), false);
75                         full_obj_path = String::from_utf8(for_obj_vec).unwrap();
76                         assert!(full_obj_path.starts_with(TypeResolver::generated_container_path()));
77                         for_obj = full_obj_path[TypeResolver::generated_container_path().len() + 2..].into();
78                 }
79
80                 match &t as &str {
81                         "lightning::util::ser::Writeable" => {
82                                 writeln!(w, "#[no_mangle]").unwrap();
83                                 writeln!(w, "/// Serialize the {} object into a byte array which can be read by {}_read", for_obj, for_obj).unwrap();
84                                 writeln!(w, "pub extern \"C\" fn {}_write(obj: &{}) -> crate::c_types::derived::CVec_u8Z {{", for_obj, full_obj_path).unwrap();
85
86                                 let ref_type: syn::Type = syn::parse_quote!(&#for_ty);
87                                 assert!(!types.write_from_c_conversion_new_var(w, &format_ident!("obj"), &ref_type, Some(generics)));
88
89                                 write!(w, "\tcrate::c_types::serialize_obj(").unwrap();
90                                 types.write_from_c_conversion_prefix(w, &ref_type, Some(generics));
91                                 write!(w, "unsafe {{ &*obj }}").unwrap();
92                                 types.write_from_c_conversion_suffix(w, &ref_type, Some(generics));
93                                 writeln!(w, ")").unwrap();
94
95                                 writeln!(w, "}}").unwrap();
96                                 if has_inner {
97                                         writeln!(w, "#[no_mangle]").unwrap();
98                                         writeln!(w, "pub(crate) extern \"C\" fn {}_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {{", for_obj).unwrap();
99                                         writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &*(obj as *const native{}) }})", for_obj).unwrap();
100                                         writeln!(w, "}}").unwrap();
101                                 }
102                         },
103                         "lightning::util::ser::Readable"|"lightning::util::ser::ReadableArgs"|"lightning::util::ser::MaybeReadable" => {
104                                 // Create the Result<Object, DecodeError> syn::Type
105                                 let mut res_ty: syn::Type = parse_quote!(Result<#for_ty, lightning::ln::msgs::DecodeError>);
106
107                                 writeln!(w, "#[no_mangle]").unwrap();
108                                 writeln!(w, "/// Read a {} from a byte array, created by {}_write", for_obj, for_obj).unwrap();
109                                 write!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice", for_obj).unwrap();
110
111                                 let mut arg_conv = Vec::new();
112                                 if t == "lightning::util::ser::ReadableArgs" {
113                                         assert!(trait_path.leading_colon.is_none());
114                                         let args_seg = trait_path.segments.iter().last().unwrap();
115                                         assert_eq!(format!("{}", args_seg.ident), "ReadableArgs");
116                                         if let syn::PathArguments::AngleBracketed(args) = &args_seg.arguments {
117                                                 assert_eq!(args.args.len(), 1);
118                                                 if let syn::GenericArgument::Type(args_ty) = args.args.iter().next().unwrap() {
119                                                         macro_rules! write_arg_conv {
120                                                                 ($ty: expr, $arg_name: expr) => {
121                                                                         write!(w, ", {}: ", $arg_name).unwrap();
122                                                                         types.write_c_type(w, $ty, Some(generics), false);
123
124                                                                         write!(&mut arg_conv, "\t").unwrap();
125                                                                         if types.write_from_c_conversion_new_var(&mut arg_conv, &format_ident!("{}", $arg_name), &$ty, Some(generics)) {
126                                                                                 write!(&mut arg_conv, "\n\t").unwrap();
127                                                                         }
128
129                                                                         write!(&mut arg_conv, "let {}_conv = ", $arg_name).unwrap();
130                                                                         types.write_from_c_conversion_prefix(&mut arg_conv, &$ty, Some(generics));
131                                                                         write!(&mut arg_conv, "{}", $arg_name).unwrap();
132                                                                         types.write_from_c_conversion_suffix(&mut arg_conv, &$ty, Some(generics));
133                                                                         write!(&mut arg_conv, ";\n").unwrap();
134                                                                 }
135                                                         }
136
137                                                         if let syn::Type::Tuple(tup) = args_ty {
138                                                                 // Crack open tuples and make them separate arguments instead of
139                                                                 // converting the full tuple. This makes it substantially easier to
140                                                                 // reason about things like references in the tuple fields.
141                                                                 let mut arg_conv_res = Vec::new();
142                                                                 for (idx, elem) in tup.elems.iter().enumerate() {
143                                                                         let arg_name = format!("arg_{}", ('a' as u8 + idx as u8) as char);
144                                                                         write_arg_conv!(elem, arg_name);
145                                                                         write!(&mut arg_conv_res, "{}_conv{}", arg_name, if idx != tup.elems.len() - 1 { ", " } else { "" }).unwrap();
146                                                                 }
147                                                                 writeln!(&mut arg_conv, "\tlet arg_conv = ({});", String::from_utf8(arg_conv_res).unwrap()).unwrap();
148                                                         } else {
149                                                                 write_arg_conv!(args_ty, "arg");
150                                                         }
151                                                 } else { unreachable!(); }
152                                         } else { unreachable!(); }
153                                 } else if t == "lightning::util::ser::MaybeReadable" {
154                                         res_ty = parse_quote!(Result<Option<#for_ty>, lightning::ln::msgs::DecodeError>);
155                                 }
156                                 write!(w, ") -> ").unwrap();
157                                 types.write_c_type(w, &res_ty, Some(generics), false);
158                                 writeln!(w, " {{").unwrap();
159
160                                 if t == "lightning::util::ser::ReadableArgs" {
161                                         w.write(&arg_conv).unwrap();
162                                 }
163
164                                 write!(w, "\tlet res: ").unwrap();
165                                 // At least in one case we need type annotations here, so provide them.
166                                 types.write_rust_type(w, Some(generics), &res_ty, false);
167
168                                 if t == "lightning::util::ser::ReadableArgs" {
169                                         writeln!(w, " = crate::c_types::deserialize_obj_arg(ser, arg_conv);").unwrap();
170                                 } else if t == "lightning::util::ser::MaybeReadable" {
171                                         writeln!(w, " = crate::c_types::maybe_deserialize_obj(ser);").unwrap();
172                                 } else {
173                                         writeln!(w, " = crate::c_types::deserialize_obj(ser);").unwrap();
174                                 }
175                                 write!(w, "\t").unwrap();
176                                 if types.write_to_c_conversion_new_var(w, &format_ident!("res"), &res_ty, Some(generics), false) {
177                                         write!(w, "\n\t").unwrap();
178                                 }
179                                 types.write_to_c_conversion_inline_prefix(w, &res_ty, Some(generics), false);
180                                 write!(w, "res").unwrap();
181                                 types.write_to_c_conversion_inline_suffix(w, &res_ty, Some(generics), false);
182                                 writeln!(w, "\n}}").unwrap();
183                         },
184                         _ => {},
185                 }
186         }
187 }
188
189 /// Convert "TraitA : TraitB" to a single function name and return type.
190 ///
191 /// This is (obviously) somewhat over-specialized and only useful for TraitB's that only require a
192 /// single function (eg for serialization).
193 fn convert_trait_impl_field(trait_path: &str) -> (&'static str, String, &'static str) {
194         match trait_path {
195                 "lightning::util::ser::Writeable" => ("Serialize the object into a byte array", "write".to_owned(), "crate::c_types::derived::CVec_u8Z"),
196                 _ => unimplemented!(),
197         }
198 }
199
200 /// Companion to convert_trait_impl_field, write an assignment for the function defined by it for
201 /// `for_obj` which implements the the trait at `trait_path`.
202 fn write_trait_impl_field_assign<W: std::io::Write>(w: &mut W, trait_path: &str, for_obj: &syn::Ident) {
203         match trait_path {
204                 "lightning::util::ser::Writeable" => {
205                         writeln!(w, "\t\twrite: {}_write_void,", for_obj).unwrap();
206                 },
207                 _ => unimplemented!(),
208         }
209 }
210
211 /// Write out the impl block for a defined trait struct which has a supertrait
212 fn do_write_impl_trait<W: std::io::Write>(w: &mut W, trait_path: &str, _trait_name: &syn::Ident, for_obj: &str) {
213         match trait_path {
214                 "lightning::util::ser::Writeable" => {
215                         writeln!(w, "impl {} for {} {{", trait_path, for_obj).unwrap();
216                         writeln!(w, "\tfn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> {{").unwrap();
217                         writeln!(w, "\t\tlet vec = (self.write)(self.this_arg);").unwrap();
218                         writeln!(w, "\t\tw.write_all(vec.as_slice())").unwrap();
219                         writeln!(w, "\t}}\n}}").unwrap();
220                 },
221                 _ => panic!(),
222         }
223 }
224
225 /// Returns true if an instance of the given type must never exist
226 fn is_type_unconstructable(path: &str) -> bool {
227         path == "core::convert::Infallible" || path == "crate::c_types::NotConstructable"
228 }
229
230 // *******************************
231 // *** Per-Type Printing Logic ***
232 // *******************************
233
234 macro_rules! walk_supertraits { ($t: expr, $types: expr, ($( $($pat: pat)|* => $e: expr),*) ) => { {
235         if $t.colon_token.is_some() {
236                 for st in $t.supertraits.iter() {
237                         match st {
238                                 syn::TypeParamBound::Trait(supertrait) => {
239                                         if supertrait.paren_token.is_some() || supertrait.lifetimes.is_some() {
240                                                 unimplemented!();
241                                         }
242                                         // First try to resolve path to find in-crate traits, but if that doesn't work
243                                         // assume its a prelude trait (eg Clone, etc) and just use the single ident.
244                                         let types_opt: Option<&TypeResolver> = $types;
245                                         if let Some(types) = types_opt {
246                                                 if let Some(path) = types.maybe_resolve_path(&supertrait.path, None) {
247                                                         let last_seg = supertrait.path.segments.iter().last().unwrap();
248                                                         match (&path as &str, &last_seg.ident, &last_seg.arguments) {
249                                                                 $( $($pat)|* => $e, )*
250                                                         }
251                                                         continue;
252                                                 }
253                                         }
254                                         if let Some(ident) = supertrait.path.get_ident() {
255                                                 match (&format!("{}", ident) as &str, &ident, &syn::PathArguments::None) {
256                                                         $( $($pat)|* => $e, )*
257                                                 }
258                                         } else if types_opt.is_some() {
259                                                 panic!("Supertrait unresolvable and not single-ident");
260                                         }
261                                 },
262                                 syn::TypeParamBound::Lifetime(_) => unimplemented!(),
263                         }
264                 }
265         }
266 } } }
267
268 macro_rules! get_module_type_resolver {
269         ($module: expr, $crate_libs: expr, $crate_types: expr) => { {
270                 let module: &str = &$module;
271                 let mut module_iter = module.rsplitn(2, "::");
272                 module_iter.next().unwrap();
273                 let module = module_iter.next().unwrap();
274                 let imports = ImportResolver::new(module.splitn(2, "::").next().unwrap(), &$crate_types.lib_ast,
275                                 module, &$crate_types.lib_ast.modules.get(module).unwrap().items);
276                 TypeResolver::new(module, imports, $crate_types)
277         } }
278 }
279
280 /// Prints a C-mapped trait object containing a void pointer and a jump table for each function in
281 /// the original trait.
282 /// Implements the native Rust trait and relevant parent traits for the new C-mapped trait.
283 ///
284 /// Finally, implements Deref<MappedTrait> for MappedTrait which allows its use in types which need
285 /// a concrete Deref to the Rust trait.
286 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) {
287         let trait_name = format!("{}", t.ident);
288         let implementable;
289         match export_status(&t.attrs) {
290                 ExportStatus::Export => { implementable = true; }
291                 ExportStatus::NotImplementable => { implementable = false; },
292                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
293         }
294         writeln_docs(w, &t.attrs, "");
295
296         let mut gen_types = GenericTypes::new(Some(format!("{}::{}", types.module_path, trait_name)));
297
298         // Add functions which may be required for supertrait implementations.
299         // Due to borrow checker limitations, we only support one in-crate supertrait here.
300         let supertrait_name;
301         let supertrait_resolver;
302         walk_supertraits!(t, Some(&types), (
303                 (s, _i, _) => {
304                         if let Some(supertrait) = types.crate_types.traits.get(s) {
305                                 supertrait_name = s.to_string();
306                                 supertrait_resolver = get_module_type_resolver!(supertrait_name, types.crate_libs, types.crate_types);
307                                 gen_types.learn_associated_types(&supertrait, &supertrait_resolver);
308                                 break;
309                         }
310                 }
311         ) );
312
313         assert!(gen_types.learn_generics(&t.generics, types));
314         gen_types.learn_associated_types(&t, types);
315
316         writeln!(w, "#[repr(C)]\npub struct {} {{", trait_name).unwrap();
317         writeln!(w, "\t/// An opaque pointer which is passed to your function implementations as an argument.").unwrap();
318         writeln!(w, "\t/// This has no meaning in the LDK, and can be NULL or any other value.").unwrap();
319         writeln!(w, "\tpub this_arg: *mut c_void,").unwrap();
320         // We store every field's (name, Option<clone_fn>, docs) except this_arg, used in Clone generation
321         // docs is only set if its a function which should be callable on the object itself in C++
322         let mut generated_fields = Vec::new();
323         for item in t.items.iter() {
324                 match item {
325                         &syn::TraitItem::Method(ref m) => {
326                                 match export_status(&m.attrs) {
327                                         ExportStatus::NoExport => {
328                                                 // NoExport in this context means we'll hit an unimplemented!() at runtime,
329                                                 // so bail out.
330                                                 unimplemented!();
331                                         },
332                                         ExportStatus::Export => {},
333                                         ExportStatus::TestOnly => continue,
334                                         ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
335                                 }
336
337                                 let mut meth_gen_types = gen_types.push_ctx();
338                                 assert!(meth_gen_types.learn_generics(&m.sig.generics, types));
339
340                                 writeln_fn_docs(w, &m.attrs, "\t", types, Some(&meth_gen_types), m.sig.inputs.iter(), &m.sig.output);
341
342                                 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
343                                         if let syn::Type::Reference(r) = &**rtype {
344                                                 // We have to do quite a dance for trait functions which return references
345                                                 // - they ultimately require us to have a native Rust object stored inside
346                                                 // our concrete trait to return a reference to. However, users may wish to
347                                                 // update the value to be returned each time the function is called (or, to
348                                                 // make C copies of Rust impls equivalent, we have to be able to).
349                                                 //
350                                                 // Thus, we store a copy of the C-mapped type (which is just a pointer to
351                                                 // the Rust type and a flag to indicate whether deallocation needs to
352                                                 // happen) as well as provide an Option<>al function pointer which is
353                                                 // called when the trait method is called which allows updating on the fly.
354                                                 write!(w, "\tpub {}: ", m.sig.ident).unwrap();
355                                                 generated_fields.push((format!("{}", m.sig.ident), None, None));
356                                                 types.write_c_type(w, &*r.elem, Some(&meth_gen_types), false);
357                                                 writeln!(w, ",").unwrap();
358                                                 writeln!(w, "\t/// Fill in the {} field as a reference to it will be given to Rust after this returns", m.sig.ident).unwrap();
359                                                 writeln!(w, "\t/// Note that this takes a pointer to this object, not the this_ptr like other methods do").unwrap();
360                                                 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();
361                                                 writeln!(w, "\tpub set_{}: Option<extern \"C\" fn(&{})>,", m.sig.ident, trait_name).unwrap();
362                                                 generated_fields.push((format!("set_{}", m.sig.ident), None, None));
363                                                 // Note that cbindgen will now generate
364                                                 // typedef struct Thing {..., set_thing: (const struct Thing*), ...} Thing;
365                                                 // which does not compile since Thing is not defined before it is used.
366                                                 writeln!(extra_headers, "struct LDK{};", trait_name).unwrap();
367                                                 continue;
368                                         }
369                                         // Sadly, this currently doesn't do what we want, but it should be easy to get
370                                         // cbindgen to support it. See https://github.com/eqrion/cbindgen/issues/531
371                                         writeln!(w, "\t#[must_use]").unwrap();
372                                 }
373
374                                 let mut cpp_docs = Vec::new();
375                                 writeln_fn_docs(&mut cpp_docs, &m.attrs, "\t * ", types, Some(&meth_gen_types), m.sig.inputs.iter(), &m.sig.output);
376                                 let docs_string = "\t/**\n".to_owned() + &String::from_utf8(cpp_docs).unwrap().replace("///", "") + "\t */\n";
377
378                                 write!(w, "\tpub {}: extern \"C\" fn (", m.sig.ident).unwrap();
379                                 generated_fields.push((format!("{}", m.sig.ident), None, Some(docs_string)));
380                                 write_method_params(w, &m.sig, "c_void", types, Some(&meth_gen_types), true, false);
381                                 writeln!(w, ",").unwrap();
382                         },
383                         &syn::TraitItem::Type(_) => {},
384                         _ => unimplemented!(),
385                 }
386         }
387         // Add functions which may be required for supertrait implementations.
388         walk_supertraits!(t, Some(&types), (
389                 ("Clone", _, _) => {
390                         writeln!(w, "\t/// Called, if set, after this {} has been cloned into a duplicate object.", trait_name).unwrap();
391                         writeln!(w, "\t/// The new {} is provided, and should be mutated as needed to perform a", trait_name).unwrap();
392                         writeln!(w, "\t/// deep copy of the object pointed to by this_arg or avoid any double-freeing.").unwrap();
393                         writeln!(w, "\tpub cloned: Option<extern \"C\" fn (new_{}: &mut {})>,", trait_name, trait_name).unwrap();
394                         generated_fields.push(("cloned".to_owned(), None, None));
395                 },
396                 ("std::cmp::Eq", _, _)|("core::cmp::Eq", _, _) => {
397                         let eq_docs = "Checks if two objects are equal given this object's this_arg pointer and another object.";
398                         writeln!(w, "\t/// {}", eq_docs).unwrap();
399                         writeln!(w, "\tpub eq: extern \"C\" fn (this_arg: *const c_void, other_arg: &{}) -> bool,", trait_name).unwrap();
400                         generated_fields.push(("eq".to_owned(), None, Some(format!("\t/** {} */\n", eq_docs))));
401                 },
402                 ("std::hash::Hash", _, _)|("core::hash::Hash", _, _) => {
403                         let hash_docs_a = "Calculate a succinct non-cryptographic hash for an object given its this_arg pointer.";
404                         let hash_docs_b = "This is used, for example, for inclusion of this object in a hash map.";
405                         writeln!(w, "\t/// {}", hash_docs_a).unwrap();
406                         writeln!(w, "\t/// {}", hash_docs_b).unwrap();
407                         writeln!(w, "\tpub hash: extern \"C\" fn (this_arg: *const c_void) -> u64,").unwrap();
408                         generated_fields.push(("hash".to_owned(), None,
409                                 Some(format!("\t/**\n\t * {}\n\t * {}\n\t */\n", hash_docs_a, hash_docs_b))));
410                 },
411                 ("Send", _, _) => {}, ("Sync", _, _) => {},
412                 ("std::fmt::Debug", _, _)|("core::fmt::Debug", _, _) => {
413                         let debug_docs = "Return a human-readable \"debug\" string describing this object";
414                         writeln!(w, "\t/// {}", debug_docs).unwrap();
415                         writeln!(w, "\tpub debug_str: extern \"C\" fn (this_arg: *const c_void) -> crate::c_types::Str,").unwrap();
416                         generated_fields.push(("debug_str".to_owned(), None,
417                                 Some(format!("\t/**\n\t * {}\n\t */\n", debug_docs))));
418                 },
419                 (s, i, _) => {
420                         // TODO: Both of the below should expose supertrait methods in C++, but doing so is
421                         // nontrivial.
422                         generated_fields.push(if types.crate_types.traits.get(s).is_none() {
423                                 let (docs, name, ret) = convert_trait_impl_field(s);
424                                 writeln!(w, "\t/// {}", docs).unwrap();
425                                 writeln!(w, "\tpub {}: extern \"C\" fn (this_arg: *const c_void) -> {},", name, ret).unwrap();
426                                 (name, None, None) // Assume clonable
427                         } else {
428                                 // For in-crate supertraits, just store a C-mapped copy of the supertrait as a member.
429                                 writeln!(w, "\t/// Implementation of {} for this object.", i).unwrap();
430                                 let is_clonable = types.is_clonable(s);
431                                 writeln!(w, "\tpub {}: crate::{},", i, s).unwrap();
432                                 (format!("{}", i), if !is_clonable {
433                                         Some(format!("crate::{}_clone_fields", s))
434                                 } else { None }, None)
435                         });
436                 }
437         ) );
438         writeln!(w, "\t/// Frees any resources associated with this object given its this_arg pointer.").unwrap();
439         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();
440         writeln!(w, "\tpub free: Option<extern \"C\" fn(this_arg: *mut c_void)>,").unwrap();
441         generated_fields.push(("free".to_owned(), None, None));
442         writeln!(w, "}}").unwrap();
443
444         macro_rules! impl_trait_for_c {
445                 ($t: expr, $impl_accessor: expr, $type_resolver: expr, $generic_impls: expr) => {
446                         let mut trait_gen_types = gen_types.push_ctx();
447                         assert!(trait_gen_types.learn_generics_with_impls(&$t.generics, $generic_impls, $type_resolver));
448                         for item in $t.items.iter() {
449                                 match item {
450                                         syn::TraitItem::Method(m) => {
451                                                 if let ExportStatus::TestOnly = export_status(&m.attrs) { continue; }
452                                                 if m.sig.constness.is_some() || m.sig.asyncness.is_some() || m.sig.unsafety.is_some() ||
453                                                                 m.sig.abi.is_some() || m.sig.variadic.is_some() {
454                                                         panic!("1");
455                                                 }
456                                                 let mut meth_gen_types = trait_gen_types.push_ctx();
457                                                 assert!(meth_gen_types.learn_generics(&m.sig.generics, $type_resolver));
458                                                 // Note that we do *not* use the method generics when printing "native"
459                                                 // rust parts - if the method is generic, we need to print a generic
460                                                 // method.
461                                                 write!(w, "\tfn {}", m.sig.ident).unwrap();
462                                                 $type_resolver.write_rust_generic_param(w, Some(&gen_types), m.sig.generics.params.iter());
463                                                 write!(w, "(").unwrap();
464                                                 for inp in m.sig.inputs.iter() {
465                                                         match inp {
466                                                                 syn::FnArg::Receiver(recv) => {
467                                                                         if !recv.attrs.is_empty() || recv.reference.is_none() { panic!("2"); }
468                                                                         write!(w, "&").unwrap();
469                                                                         if let Some(lft) = &recv.reference.as_ref().unwrap().1 {
470                                                                                 write!(w, "'{} ", lft.ident).unwrap();
471                                                                         }
472                                                                         if recv.mutability.is_some() {
473                                                                                 write!(w, "mut self").unwrap();
474                                                                         } else {
475                                                                                 write!(w, "self").unwrap();
476                                                                         }
477                                                                 },
478                                                                 syn::FnArg::Typed(arg) => {
479                                                                         if !arg.attrs.is_empty() { panic!("3"); }
480                                                                         match &*arg.pat {
481                                                                                 syn::Pat::Ident(ident) => {
482                                                                                         if !ident.attrs.is_empty() || ident.by_ref.is_some() ||
483                                                                                                         ident.mutability.is_some() || ident.subpat.is_some() {
484                                                                                                 panic!("4");
485                                                                                         }
486                                                                                         write!(w, ", mut {}{}: ", if $type_resolver.skip_arg(&*arg.ty, Some(&meth_gen_types)) { "_" } else { "" }, ident.ident).unwrap();
487                                                                                 }
488                                                                                 _ => panic!("5"),
489                                                                         }
490                                                                         $type_resolver.write_rust_type(w, Some(&gen_types), &*arg.ty, false);
491                                                                 }
492                                                         }
493                                                 }
494                                                 write!(w, ")").unwrap();
495                                                 match &m.sig.output {
496                                                         syn::ReturnType::Type(_, rtype) => {
497                                                                 write!(w, " -> ").unwrap();
498                                                                 $type_resolver.write_rust_type(w, Some(&gen_types), &*rtype, false)
499                                                         },
500                                                         _ => {},
501                                                 }
502                                                 write!(w, " {{\n\t\t").unwrap();
503                                                 match export_status(&m.attrs) {
504                                                         ExportStatus::NoExport => {
505                                                                 panic!("6");
506                                                         },
507                                                         _ => {},
508                                                 }
509                                                 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
510                                                         if let syn::Type::Reference(r) = &**rtype {
511                                                                 assert_eq!(m.sig.inputs.len(), 1); // Must only take self!
512                                                                 writeln!(w, "if let Some(f) = self{}.set_{} {{", $impl_accessor, m.sig.ident).unwrap();
513                                                                 writeln!(w, "\t\t\t(f)(&self{});", $impl_accessor).unwrap();
514                                                                 write!(w, "\t\t}}\n\t\t").unwrap();
515                                                                 $type_resolver.write_from_c_conversion_to_ref_prefix(w, &*r.elem, Some(&meth_gen_types));
516                                                                 write!(w, "self{}.{}", $impl_accessor, m.sig.ident).unwrap();
517                                                                 $type_resolver.write_from_c_conversion_to_ref_suffix(w, &*r.elem, Some(&meth_gen_types));
518                                                                 writeln!(w, "\n\t}}").unwrap();
519                                                                 continue;
520                                                         }
521                                                 }
522                                                 write_method_var_decl_body(w, &m.sig, "\t", $type_resolver, Some(&meth_gen_types), true);
523                                                 write!(w, "(self{}.{})(", $impl_accessor, m.sig.ident).unwrap();
524                                                 let mut args = Vec::new();
525                                                 write_method_call_params(&mut args, &m.sig, "\t", $type_resolver, Some(&meth_gen_types), "", true);
526                                                 w.write_all(String::from_utf8(args).unwrap().replace("self", &format!("self{}", $impl_accessor)).as_bytes()).unwrap();
527
528                                                 writeln!(w, "\n\t}}").unwrap();
529                                         },
530                                         &syn::TraitItem::Type(ref t) => {
531                                                 if t.default.is_some() || t.generics.lt_token.is_some() { panic!("10"); }
532                                                 let mut bounds_iter = t.bounds.iter();
533                                                 loop {
534                                                         match bounds_iter.next().unwrap() {
535                                                                 syn::TypeParamBound::Trait(tr) => {
536                                                                         writeln!(w, "\ttype {} = crate::{};", t.ident, $type_resolver.resolve_path(&tr.path, Some(&gen_types))).unwrap();
537                                                                         for bound in bounds_iter {
538                                                                                 if let syn::TypeParamBound::Trait(_) = bound { panic!("11"); }
539                                                                         }
540                                                                         break;
541                                                                 },
542                                                                 syn::TypeParamBound::Lifetime(_) => {},
543                                                         }
544                                                 }
545                                         },
546                                         _ => panic!("12"),
547                                 }
548                         }
549                 }
550         }
551
552         writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap();
553         writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap();
554
555         writeln!(w, "#[no_mangle]").unwrap();
556         writeln!(w, "pub(crate) extern \"C\" fn {}_clone_fields(orig: &{}) -> {} {{", trait_name, trait_name, trait_name).unwrap();
557         writeln!(w, "\t{} {{", trait_name).unwrap();
558         writeln!(w, "\t\tthis_arg: orig.this_arg,").unwrap();
559         for (field, clone_fn, _) in generated_fields.iter() {
560                 if let Some(f) = clone_fn {
561                         // If the field isn't clonable, blindly assume its a trait and hope for the best.
562                         writeln!(w, "\t\t{}: {}(&orig.{}),", field, f, field).unwrap();
563                 } else {
564                         writeln!(w, "\t\t{}: Clone::clone(&orig.{}),", field, field).unwrap();
565                 }
566         }
567         writeln!(w, "\t}}\n}}").unwrap();
568
569         // Implement supertraits for the C-mapped struct.
570         walk_supertraits!(t, Some(&types), (
571                 ("std::cmp::Eq", _, _)|("core::cmp::Eq", _, _) => {
572                         writeln!(w, "impl core::cmp::Eq for {} {{}}", trait_name).unwrap();
573                         writeln!(w, "impl core::cmp::PartialEq for {} {{", trait_name).unwrap();
574                         writeln!(w, "\tfn eq(&self, o: &Self) -> bool {{ (self.eq)(self.this_arg, o) }}\n}}").unwrap();
575                 },
576                 ("std::hash::Hash", _, _)|("core::hash::Hash", _, _) => {
577                         writeln!(w, "impl core::hash::Hash for {} {{", trait_name).unwrap();
578                         writeln!(w, "\tfn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {{ hasher.write_u64((self.hash)(self.this_arg)) }}\n}}").unwrap();
579                 },
580                 ("Send", _, _) => {}, ("Sync", _, _) => {},
581                 ("Clone", _, _) => {
582                         writeln!(w, "#[no_mangle]").unwrap();
583                         writeln!(w, "/// Creates a copy of a {}", trait_name).unwrap();
584                         writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", trait_name, trait_name, trait_name).unwrap();
585                         writeln!(w, "\tlet mut res = {}_clone_fields(orig);", trait_name).unwrap();
586                         writeln!(w, "\tif let Some(f) = orig.cloned {{ (f)(&mut res) }};").unwrap();
587                         writeln!(w, "\tres\n}}").unwrap();
588                         writeln!(w, "impl Clone for {} {{", trait_name).unwrap();
589                         writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
590                         writeln!(w, "\t\t{}_clone(self)", trait_name).unwrap();
591                         writeln!(w, "\t}}\n}}").unwrap();
592                 },
593                 ("std::fmt::Debug", _, _)|("core::fmt::Debug", _, _) => {
594                         writeln!(w, "impl core::fmt::Debug for {} {{", trait_name).unwrap();
595                         writeln!(w, "\tfn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {{").unwrap();
596                         writeln!(w, "\t\tf.write_str((self.debug_str)(self.this_arg).into_str())").unwrap();
597                         writeln!(w, "\t}}").unwrap();
598                         writeln!(w, "}}").unwrap();
599                 },
600                 (s, i, generic_args) => {
601                         if let Some(supertrait) = types.crate_types.traits.get(s) {
602                                 let resolver = get_module_type_resolver!(s, types.crate_libs, types.crate_types);
603                                 macro_rules! impl_supertrait {
604                                         ($s: expr, $supertrait: expr, $i: expr, $generic_args: expr) => {
605                                                 let resolver = get_module_type_resolver!($s, types.crate_libs, types.crate_types);
606
607                                                 // Blindly assume that the same imports where `supertrait` is defined are also
608                                                 // imported here. This will almost certainly break at some point, but it should be
609                                                 // a compilation failure when it does so.
610                                                 write!(w, "impl").unwrap();
611                                                 maybe_write_lifetime_generics(w, &$supertrait.generics, types);
612                                                 write!(w, " {}", $s).unwrap();
613                                                 maybe_write_generics(w, &$supertrait.generics, $generic_args, types, false);
614                                                 writeln!(w, " for {} {{", trait_name).unwrap();
615
616                                                 impl_trait_for_c!($supertrait, format!(".{}", $i), &resolver, $generic_args);
617                                                 writeln!(w, "}}").unwrap();
618                                         }
619                                 }
620                                 impl_supertrait!(s, supertrait, i, generic_args);
621                                 walk_supertraits!(supertrait, Some(&resolver), (
622                                         (s, supertrait_i, generic_args) => {
623                                                 if let Some(supertrait) = types.crate_types.traits.get(s) {
624                                                         impl_supertrait!(s, supertrait, format!("{}.{}", i, supertrait_i), generic_args);
625                                                 }
626                                         }
627                                 ) );
628                         } else {
629                                 do_write_impl_trait(w, s, i, &trait_name);
630                         }
631                 }
632         ) );
633
634         // Finally, implement the original Rust trait for the newly created mapped trait.
635         writeln!(w, "\nuse {}::{} as rust{};", types.module_path, t.ident, trait_name).unwrap();
636         if implementable {
637                 write!(w, "impl").unwrap();
638                 maybe_write_lifetime_generics(w, &t.generics, types);
639                 write!(w, " rust{}", t.ident).unwrap();
640                 maybe_write_generics(w, &t.generics, &syn::PathArguments::None, types, false);
641                 writeln!(w, " for {} {{", trait_name).unwrap();
642                 impl_trait_for_c!(t, "", types, &syn::PathArguments::None);
643                 writeln!(w, "}}\n").unwrap();
644                 writeln!(w, "// We're essentially a pointer already, or at least a set of pointers, so allow us to be used").unwrap();
645                 writeln!(w, "// directly as a Deref trait in higher-level structs:").unwrap();
646                 writeln!(w, "impl core::ops::Deref for {} {{\n\ttype Target = Self;", trait_name).unwrap();
647                 writeln!(w, "\tfn deref(&self) -> &Self {{\n\t\tself\n\t}}\n}}").unwrap();
648         }
649
650         writeln!(w, "/// Calls the free function if one is set").unwrap();
651         writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", trait_name, trait_name).unwrap();
652         writeln!(w, "impl Drop for {} {{", trait_name).unwrap();
653         writeln!(w, "\tfn drop(&mut self) {{").unwrap();
654         writeln!(w, "\t\tif let Some(f) = self.free {{").unwrap();
655         writeln!(w, "\t\t\tf(self.this_arg);").unwrap();
656         writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
657
658         write_cpp_wrapper(cpp_headers, &trait_name, true, Some(generated_fields.drain(..)
659                 .filter_map(|(name, _, docs)| if let Some(docs) = docs { Some((name, docs)) } else { None }).collect()));
660 }
661
662 /// Write out a simple "opaque" type (eg structs) which contain a pointer to the native Rust type
663 /// and a flag to indicate whether Drop'ing the mapped struct drops the underlying Rust type.
664 ///
665 /// Also writes out a _free function and a C++ wrapper which handles calling _free.
666 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) {
667         // If we directly read the original type by its original name, cbindgen hits
668         // https://github.com/eqrion/cbindgen/issues/286 Thus, instead, we import it as a temporary
669         // name and then reference it by that name, which works around the issue.
670         write!(w, "\nuse {}::{} as native{}Import;\npub(crate) type native{} = native{}Import", types.module_path, ident, ident, ident, ident).unwrap();
671         maybe_write_generics(w, &generics, &syn::PathArguments::None, &types, true);
672         writeln!(w, ";\n").unwrap();
673         writeln!(extra_headers, "struct native{}Opaque;\ntypedef struct native{}Opaque LDKnative{};", ident, ident, ident).unwrap();
674         writeln_docs(w, &attrs, "");
675         writeln!(w, "#[must_use]\n#[repr(C)]\npub struct {} {{", struct_name).unwrap();
676         writeln!(w, "\t/// A pointer to the opaque Rust object.\n").unwrap();
677         writeln!(w, "\t/// Nearly everywhere, inner must be non-null, however in places where").unwrap();
678         writeln!(w, "\t/// the Rust equivalent takes an Option, it may be set to null to indicate None.").unwrap();
679         writeln!(w, "\tpub inner: *mut native{},", ident).unwrap();
680         writeln!(w, "\t/// Indicates that this is the only struct which contains the same pointer.\n").unwrap();
681         writeln!(w, "\t/// Rust functions which take ownership of an object provided via an argument require").unwrap();
682         writeln!(w, "\t/// this to be true and invalidate the object pointed to by inner.").unwrap();
683         writeln!(w, "\tpub is_owned: bool,").unwrap();
684         writeln!(w, "}}\n").unwrap();
685         writeln!(w, "impl Drop for {} {{\n\tfn drop(&mut self) {{", struct_name).unwrap();
686         writeln!(w, "\t\tif self.is_owned && !<*mut native{}>::is_null(self.inner) {{", ident).unwrap();
687         writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(ObjOps::untweak_ptr(self.inner)) }};\n\t\t}}\n\t}}\n}}").unwrap();
688         writeln!(w, "/// Frees any resources used by the {}, if is_owned is set and inner is non-NULL.", struct_name).unwrap();
689         writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_obj: {}) {{ }}", struct_name, struct_name).unwrap();
690         writeln!(w, "#[allow(unused)]").unwrap();
691         writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
692         writeln!(w, "pub(crate) extern \"C\" fn {}_free_void(this_ptr: *mut c_void) {{", struct_name).unwrap();
693         writeln!(w, "\tlet _ = unsafe {{ Box::from_raw(this_ptr as *mut native{}) }};\n}}", struct_name).unwrap();
694         writeln!(w, "#[allow(unused)]").unwrap();
695         writeln!(w, "impl {} {{", struct_name).unwrap();
696         writeln!(w, "\tpub(crate) fn get_native_ref(&self) -> &'static native{} {{", struct_name).unwrap();
697         writeln!(w, "\t\tunsafe {{ &*ObjOps::untweak_ptr(self.inner) }}").unwrap();
698         writeln!(w, "\t}}").unwrap();
699         writeln!(w, "\tpub(crate) fn get_native_mut_ref(&self) -> &'static mut native{} {{", struct_name).unwrap();
700         writeln!(w, "\t\tunsafe {{ &mut *ObjOps::untweak_ptr(self.inner) }}").unwrap();
701         writeln!(w, "\t}}").unwrap();
702         writeln!(w, "\t/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy").unwrap();
703         writeln!(w, "\tpub(crate) fn take_inner(mut self) -> *mut native{} {{", struct_name).unwrap();
704         writeln!(w, "\t\tassert!(self.is_owned);").unwrap();
705         writeln!(w, "\t\tlet ret = ObjOps::untweak_ptr(self.inner);").unwrap();
706         writeln!(w, "\t\tself.inner = core::ptr::null_mut();").unwrap();
707         writeln!(w, "\t\tret").unwrap();
708         writeln!(w, "\t}}\n}}").unwrap();
709
710         write_cpp_wrapper(cpp_headers, &format!("{}", ident), true, None);
711 }
712
713 /// Writes out all the relevant mappings for a Rust struct, deferring to writeln_opaque to generate
714 /// the struct itself, and then writing getters and setters for public, understood-type fields and
715 /// a constructor if every field is public.
716 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) {
717         if export_status(&s.attrs) != ExportStatus::Export { return; }
718
719         let struct_name = &format!("{}", s.ident);
720         writeln_opaque(w, &s.ident, struct_name, &s.generics, &s.attrs, types, extra_headers, cpp_headers);
721
722         let mut self_path_segs = syn::punctuated::Punctuated::new();
723         self_path_segs.push(s.ident.clone().into());
724         let self_path = syn::Path { leading_colon: None, segments: self_path_segs};
725         let mut gen_types = GenericTypes::new(Some(types.resolve_path(&self_path, None)));
726         assert!(gen_types.learn_generics(&s.generics, types));
727
728         let mut all_fields_settable = true;
729         macro_rules! define_field {
730                 ($new_name: expr, $real_name: expr, $field: expr) => {
731                         if let syn::Visibility::Public(_) = $field.vis {
732                                 let export = export_status(&$field.attrs);
733                                 match export {
734                                         ExportStatus::Export => {},
735                                         ExportStatus::NoExport|ExportStatus::TestOnly => {
736                                                 all_fields_settable = false;
737                                                 continue
738                                         },
739                                         ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
740                                 }
741
742                                 if let Some(ref_type) = types.create_ownable_reference(&$field.ty, Some(&gen_types)) {
743                                         if types.understood_c_type(&ref_type, Some(&gen_types)) {
744                                                 writeln_arg_docs(w, &$field.attrs, "", types, Some(&gen_types), vec![].drain(..), Some(&ref_type));
745                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> ", struct_name, $new_name, struct_name).unwrap();
746                                                 types.write_c_type(w, &ref_type, Some(&gen_types), true);
747                                                 write!(w, " {{\n\tlet mut inner_val = &mut this_ptr.get_native_mut_ref().{};\n\t", $real_name).unwrap();
748                                                 let local_var = types.write_to_c_conversion_from_ownable_ref_new_var(w, &format_ident!("inner_val"), &ref_type, Some(&gen_types));
749                                                 if local_var { write!(w, "\n\t").unwrap(); }
750                                                 types.write_to_c_conversion_inline_prefix(w, &ref_type, Some(&gen_types), true);
751                                                 write!(w, "inner_val").unwrap();
752                                                 types.write_to_c_conversion_inline_suffix(w, &ref_type, Some(&gen_types), true);
753                                                 writeln!(w, "\n}}").unwrap();
754                                         } else {
755                                                 // If the type isn't reference-able, but is clonable, export a getter that just clones
756                                                 if types.understood_c_type(&$field.ty, Some(&gen_types)) {
757                                                         let mut v = Vec::new();
758                                                         types.write_c_type(&mut v, &$field.ty, Some(&gen_types), true);
759                                                         let s = String::from_utf8(v).unwrap();
760                                                         if types.is_clonable(&s) {
761                                                                 writeln_arg_docs(w, &$field.attrs, "", types, Some(&gen_types), vec![].drain(..), Some(&$field.ty));
762                                                                 writeln!(w, "///\n/// Returns a copy of the field.").unwrap();
763                                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> {}", struct_name, $new_name, struct_name, s).unwrap();
764                                                                 write!(w, " {{\n\tlet mut inner_val = this_ptr.get_native_mut_ref().{}.clone();\n\t", $real_name).unwrap();
765                                                                 let local_var = types.write_to_c_conversion_new_var(w, &format_ident!("inner_val"), &$field.ty, Some(&gen_types), true);
766                                                                 if local_var { write!(w, "\n\t").unwrap(); }
767                                                                 types.write_to_c_conversion_inline_prefix(w, &$field.ty, Some(&gen_types), true);
768                                                                 write!(w, "inner_val").unwrap();
769                                                                 types.write_to_c_conversion_inline_suffix(w, &$field.ty, Some(&gen_types), true);
770                                                                 writeln!(w, "\n}}").unwrap();
771                                                         }
772                                                 }
773                                         }
774                                 }
775
776                                 if types.understood_c_type(&$field.ty, Some(&gen_types)) {
777                                         writeln_arg_docs(w, &$field.attrs, "", types, Some(&gen_types), vec![("val".to_owned(), &$field.ty)].drain(..), None);
778                                         write!(w, "#[no_mangle]\npub extern \"C\" fn {}_set_{}(this_ptr: &mut {}, mut val: ", struct_name, $new_name, struct_name).unwrap();
779                                         types.write_c_type(w, &$field.ty, Some(&gen_types), false);
780                                         write!(w, ") {{\n\t").unwrap();
781                                         let local_var = types.write_from_c_conversion_new_var(w, &format_ident!("val"), &$field.ty, Some(&gen_types));
782                                         if local_var { write!(w, "\n\t").unwrap(); }
783                                         write!(w, "unsafe {{ &mut *ObjOps::untweak_ptr(this_ptr.inner) }}.{} = ", $real_name).unwrap();
784                                         types.write_from_c_conversion_prefix(w, &$field.ty, Some(&gen_types));
785                                         write!(w, "val").unwrap();
786                                         types.write_from_c_conversion_suffix(w, &$field.ty, Some(&gen_types));
787                                         writeln!(w, ";\n}}").unwrap();
788                                 } else { all_fields_settable = false; }
789                         } else { all_fields_settable = false; }
790                 }
791         }
792
793         match &s.fields {
794                 syn::Fields::Named(fields) => {
795                         for field in fields.named.iter() {
796                                 if let Some(ident) = &field.ident {
797                                         define_field!(ident, ident, field);
798                                 } else { all_fields_settable = false; }
799                         }
800                 }
801                 syn::Fields::Unnamed(fields) => {
802                         for (idx, field) in fields.unnamed.iter().enumerate() {
803                                 define_field!(('a' as u8 + idx as u8) as char, ('0' as u8 + idx as u8) as char, field);
804                         }
805                 }
806                 _ => unimplemented!()
807         }
808
809         if all_fields_settable {
810                 // Build a constructor!
811                 writeln!(w, "/// Constructs a new {} given each field", struct_name).unwrap();
812                 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_new(", struct_name).unwrap();
813
814                 match &s.fields {
815                         syn::Fields::Named(fields) => {
816                                 for (idx, field) in fields.named.iter().enumerate() {
817                                         if idx != 0 { write!(w, ", ").unwrap(); }
818                                         write!(w, "mut {}_arg: ", field.ident.as_ref().unwrap()).unwrap();
819                                         types.write_c_type(w, &field.ty, Some(&gen_types), false);
820                                 }
821                         }
822                         syn::Fields::Unnamed(fields) => {
823                                 for (idx, field) in fields.unnamed.iter().enumerate() {
824                                         if idx != 0 { write!(w, ", ").unwrap(); }
825                                         write!(w, "mut {}_arg: ", ('a' as u8 + idx as u8) as char).unwrap();
826                                         types.write_c_type(w, &field.ty, Some(&gen_types), false);
827                                 }
828                         }
829                         _ => unreachable!()
830                 }
831                 write!(w, ") -> {} {{\n\t", struct_name).unwrap();
832                 match &s.fields {
833                         syn::Fields::Named(fields) => {
834                                 for field in fields.named.iter() {
835                                         let field_ident = format_ident!("{}_arg", field.ident.as_ref().unwrap());
836                                         if types.write_from_c_conversion_new_var(w, &field_ident, &field.ty, Some(&gen_types)) {
837                                                 write!(w, "\n\t").unwrap();
838                                         }
839                                 }
840                         },
841                         syn::Fields::Unnamed(fields) => {
842                                 for (idx, field) in fields.unnamed.iter().enumerate() {
843                                         let field_ident = format_ident!("{}_arg", ('a' as u8 + idx as u8) as char);
844                                         if types.write_from_c_conversion_new_var(w, &field_ident, &field.ty, Some(&gen_types)) {
845                                                 write!(w, "\n\t").unwrap();
846                                         }
847                                 }
848                         },
849                         _ => unreachable!()
850                 }
851                 write!(w, "{} {{ inner: ObjOps::heap_alloc(", struct_name).unwrap();
852                 match &s.fields {
853                         syn::Fields::Named(fields) => {
854                                 writeln!(w, "native{} {{", s.ident).unwrap();
855                                 for field in fields.named.iter() {
856                                         write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
857                                         types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
858                                         write!(w, "{}_arg", field.ident.as_ref().unwrap()).unwrap();
859                                         types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
860                                         writeln!(w, ",").unwrap();
861                                 }
862                                 write!(w, "\t}}").unwrap();
863                         },
864                         syn::Fields::Unnamed(fields) => {
865                                 assert!(!s.generics.params.iter()
866                                         .any(|gen| if let syn::GenericParam::Lifetime(_) = gen { false } else { true }));
867                                 writeln!(w, "{} (", types.maybe_resolve_ident(&s.ident).unwrap()).unwrap();
868                                 for (idx, field) in fields.unnamed.iter().enumerate() {
869                                         write!(w, "\t\t").unwrap();
870                                         types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
871                                         write!(w, "{}_arg", ('a' as u8 + idx as u8) as char).unwrap();
872                                         types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
873                                         writeln!(w, ",").unwrap();
874                                 }
875                                 write!(w, "\t)").unwrap();
876                         },
877                         _ => unreachable!()
878                 }
879                 writeln!(w, "), is_owned: true }}\n}}").unwrap();
880         }
881 }
882
883 /// Prints a relevant conversion for impl *
884 ///
885 /// For simple impl Struct {}s, this just outputs the wrapper functions as Struct_fn_name() { .. }.
886 ///
887 /// For impl Trait for Struct{}s, this non-exported generates wrapper functions as
888 /// Trait_Struct_fn_name and a Struct_as_Trait(&struct) -> Trait function which returns a populated
889 /// Trait struct containing a pointer to the passed struct's inner field and the wrapper functions.
890 ///
891 /// A few non-crate Traits are hard-coded including Default.
892 fn writeln_impl<W: std::io::Write>(w: &mut W, w_uses: &mut HashSet<String, NonRandomHash>, i: &syn::ItemImpl, types: &mut TypeResolver) {
893         match export_status(&i.attrs) {
894                 ExportStatus::Export => {},
895                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
896                 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
897         }
898
899         if let syn::Type::Tuple(_) = &*i.self_ty {
900                 if types.understood_c_type(&*i.self_ty, None) {
901                         let mut gen_types = GenericTypes::new(None);
902                         if !gen_types.learn_generics(&i.generics, types) {
903                                 eprintln!("Not implementing anything for `impl (..)` due to not understood generics");
904                                 return;
905                         }
906
907                         if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
908                         if let Some(trait_path) = i.trait_.as_ref() {
909                                 if trait_path.0.is_some() { unimplemented!(); }
910                                 if types.understood_c_path(&trait_path.1) {
911                                         eprintln!("Not implementing anything for `impl Trait for (..)` - we only support manual defines");
912                                         return;
913                                 } else {
914                                         // Just do a manual implementation:
915                                         maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
916                                 }
917                         } else {
918                                 eprintln!("Not implementing anything for plain `impl (..)` block - we only support `impl Trait for (..)` blocks");
919                                 return;
920                         }
921                 }
922                 return;
923         }
924         if let &syn::Type::Path(ref p) = &*i.self_ty {
925                 if p.qself.is_some() { unimplemented!(); }
926                 let ident = &p.path.segments.last().unwrap().ident;
927                 if let Some(resolved_path) = types.maybe_resolve_path(&p.path, None) {
928                         if types.crate_types.opaques.contains_key(&resolved_path) || types.crate_types.mirrored_enums.contains_key(&resolved_path) ||
929                                 // At least for core::infallible::Infallible we need to support mapping an
930                                 // out-of-crate trait implementation.
931                                 (types.understood_c_path(&p.path) && first_seg_is_stdlib(resolved_path.split("::").next().unwrap())) {
932                                 if !types.understood_c_path(&p.path) {
933                                         eprintln!("Not implementing anything for impl {} as the type is not understood (probably C-not exported)", ident);
934                                         return;
935                                 }
936
937                                 let mut gen_types = GenericTypes::new(Some(resolved_path.clone()));
938                                 if !gen_types.learn_generics(&i.generics, types) {
939                                         eprintln!("Not implementing anything for impl {} due to not understood generics", ident);
940                                         return;
941                                 }
942
943                                 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
944                                 if let Some(trait_path) = i.trait_.as_ref() {
945                                         if trait_path.0.is_some() { unimplemented!(); }
946                                         if types.understood_c_path(&trait_path.1) {
947                                                 let full_trait_path = types.resolve_path(&trait_path.1, None);
948                                                 let trait_obj = *types.crate_types.traits.get(&full_trait_path).unwrap();
949
950                                                 let supertrait_name;
951                                                 let supertrait_resolver;
952                                                 walk_supertraits!(trait_obj, Some(&types), (
953                                                         (s, _i, _) => {
954                                                                 if let Some(supertrait) = types.crate_types.traits.get(s) {
955                                                                         supertrait_name = s.to_string();
956                                                                         supertrait_resolver = get_module_type_resolver!(supertrait_name, types.crate_libs, types.crate_types);
957                                                                         gen_types.learn_associated_types(&supertrait, &supertrait_resolver);
958                                                                         break;
959                                                                 }
960                                                         }
961                                                 ) );
962                                                 // We learn the associated types maping from the original trait object.
963                                                 // That's great, except that they are unresolved idents, so if we learn
964                                                 // mappings from a trai defined in a different file, we may mis-resolve or
965                                                 // fail to resolve the mapped types. Thus, we have to construct a new
966                                                 // resolver for the module that the trait was defined in here first.
967                                                 let mut trait_resolver = get_module_type_resolver!(full_trait_path, types.crate_libs, types.crate_types);
968                                                 gen_types.learn_associated_types(trait_obj, &trait_resolver);
969                                                 let mut impl_associated_types = HashMap::new();
970                                                 for item in i.items.iter() {
971                                                         match item {
972                                                                 syn::ImplItem::Type(t) => {
973                                                                         if let syn::Type::Path(p) = &t.ty {
974                                                                                 if let Some(id) = single_ident_generic_path_to_ident(&p.path) {
975                                                                                         impl_associated_types.insert(&t.ident, id);
976                                                                                 }
977                                                                         }
978                                                                 },
979                                                                 _ => {},
980                                                         }
981                                                 }
982
983                                                 let export = export_status(&trait_obj.attrs);
984                                                 match export {
985                                                         ExportStatus::Export|ExportStatus::NotImplementable => {},
986                                                         ExportStatus::NoExport|ExportStatus::TestOnly => return,
987                                                 }
988
989                                                 // For cases where we have a concrete native object which implements a
990                                                 // trait and need to return the C-mapped version of the trait, provide a
991                                                 // From<> implementation which does all the work to ensure free is handled
992                                                 // properly. This way we can call this method from deep in the
993                                                 // type-conversion logic without actually knowing the concrete native type.
994                                                 if !resolved_path.starts_with(types.module_path) {
995                                                         if !first_seg_is_stdlib(resolved_path.split("::").next().unwrap()) {
996                                                                 w_uses.insert(format!("use crate::{}::native{} as native{};", resolved_path.rsplitn(2, "::").skip(1).next().unwrap(), ident, ident));
997                                                                 w_uses.insert(format!("use crate::{};", resolved_path));
998                                                                 w_uses.insert(format!("use crate::{}_free_void;", resolved_path));
999                                                         } else {
1000                                                                 w_uses.insert(format!("use {} as native{};", resolved_path, ident));
1001                                                         }
1002                                                 }
1003                                                 writeln!(w, "impl From<native{}> for crate::{} {{", ident, full_trait_path).unwrap();
1004                                                 writeln!(w, "\tfn from(obj: native{}) -> Self {{", ident).unwrap();
1005                                                 if is_type_unconstructable(&resolved_path) {
1006                                                         writeln!(w, "\t\tunreachable!();").unwrap();
1007                                                 } else {
1008                                                         writeln!(w, "\t\tlet mut rust_obj = {} {{ inner: ObjOps::heap_alloc(obj), is_owned: true }};", ident).unwrap();
1009                                                         writeln!(w, "\t\tlet mut ret = {}_as_{}(&rust_obj);", ident, trait_obj.ident).unwrap();
1010                                                         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();
1011                                                         writeln!(w, "\t\trust_obj.inner = core::ptr::null_mut();").unwrap();
1012                                                         writeln!(w, "\t\tret.free = Some({}_free_void);", ident).unwrap();
1013                                                         writeln!(w, "\t\tret").unwrap();
1014                                                 }
1015                                                 writeln!(w, "\t}}\n}}").unwrap();
1016                                                 if is_type_unconstructable(&resolved_path) {
1017                                                         // We don't bother with Struct_as_Trait conversion for types which must
1018                                                         // never be instantiated, so just return early.
1019                                                         return;
1020                                                 }
1021
1022                                                 writeln!(w, "/// Constructs a new {} which calls the relevant methods on this_arg.", trait_obj.ident).unwrap();
1023                                                 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();
1024                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_as_{}(this_arg: &{}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
1025                                                 writeln!(w, "\tcrate::{} {{", full_trait_path).unwrap();
1026                                                 writeln!(w, "\t\tthis_arg: unsafe {{ ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }},").unwrap();
1027                                                 writeln!(w, "\t\tfree: None,").unwrap();
1028
1029                                                 macro_rules! write_meth {
1030                                                         ($m: expr, $trait: expr, $indent: expr) => {
1031                                                                 let trait_method = $trait.items.iter().filter_map(|item| {
1032                                                                         if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
1033                                                                 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
1034                                                                 match export_status(&trait_method.attrs) {
1035                                                                         ExportStatus::Export => {},
1036                                                                         ExportStatus::NoExport => {
1037                                                                                 write!(w, "{}\t\t//XXX: Need to export {}\n", $indent, $m.sig.ident).unwrap();
1038                                                                                 continue;
1039                                                                         },
1040                                                                         ExportStatus::TestOnly => continue,
1041                                                                         ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1042                                                                 }
1043
1044                                                                 let mut printed = false;
1045                                                                 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
1046                                                                         if let syn::Type::Reference(r) = &**rtype {
1047                                                                                 write!(w, "\n\t\t{}{}: ", $indent, $m.sig.ident).unwrap();
1048                                                                                 types.write_empty_rust_val(Some(&gen_types), w, &*r.elem);
1049                                                                                 writeln!(w, ",\n{}\t\tset_{}: Some({}_{}_set_{}),", $indent, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
1050                                                                                 printed = true;
1051                                                                         }
1052                                                                 }
1053                                                                 if !printed {
1054                                                                         write!(w, "{}\t\t{}: {}_{}_{},\n", $indent, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
1055                                                                 }
1056                                                         }
1057                                                 }
1058                                                 for item in trait_obj.items.iter() {
1059                                                         match item {
1060                                                                 syn::TraitItem::Method(m) => {
1061                                                                         write_meth!(m, trait_obj, "");
1062                                                                 },
1063                                                                 _ => {},
1064                                                         }
1065                                                 }
1066                                                 let mut requires_clone = false;
1067                                                 walk_supertraits!(trait_obj, Some(&types), (
1068                                                         ("Clone", _, _) => {
1069                                                                 requires_clone = true;
1070                                                                 writeln!(w, "\t\tcloned: Some({}_{}_cloned),", trait_obj.ident, ident).unwrap();
1071                                                         },
1072                                                         ("Sync", _, _) => {}, ("Send", _, _) => {},
1073                                                         ("std::marker::Sync", _, _) => {}, ("std::marker::Send", _, _) => {},
1074                                                         ("core::fmt::Debug", _, _) => {},
1075                                                         (s, t, _) => {
1076                                                                 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
1077                                                                         macro_rules! write_impl_fields {
1078                                                                                 ($s: expr, $supertrait_obj: expr, $t: expr, $pfx: expr, $resolver: expr) => {
1079                                                                                         writeln!(w, "{}\t{}: crate::{} {{", $pfx, $t, $s).unwrap();
1080                                                                                         writeln!(w, "{}\t\tthis_arg: unsafe {{ ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }},", $pfx).unwrap();
1081                                                                                         writeln!(w, "{}\t\tfree: None,", $pfx).unwrap();
1082                                                                                         for item in $supertrait_obj.items.iter() {
1083                                                                                                 match item {
1084                                                                                                         syn::TraitItem::Method(m) => {
1085                                                                                                                 write_meth!(m, $supertrait_obj, $pfx);
1086                                                                                                         },
1087                                                                                                         _ => {},
1088                                                                                                 }
1089                                                                                         }
1090                                                                                 walk_supertraits!($supertrait_obj, Some(&$resolver), (
1091                                                                                         ("Clone", _, _) => {
1092                                                                                                 writeln!(w, "{}\tcloned: Some({}_{}_cloned),", $pfx, $supertrait_obj.ident, ident).unwrap();
1093                                                                                         },
1094                                                                                         (_, _, _) => {}
1095                                                                                 ) );
1096                                                                                 }
1097                                                                         }
1098                                                                         write_impl_fields!(s, supertrait_obj, t, "\t", types);
1099
1100                                                                         let resolver = get_module_type_resolver!(s, types.crate_libs, types.crate_types);
1101                                                                         walk_supertraits!(supertrait_obj, Some(&resolver), (
1102                                                                                 (s, t, _) => {
1103                                                                                         if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
1104                                                                                                 write_impl_fields!(s, supertrait_obj, t, "\t\t", resolver);
1105                                                                                                 write!(w, "\t\t\t}},\n").unwrap();
1106                                                                                         }
1107                                                                                 }
1108                                                                         ) );
1109                                                                         write!(w, "\t\t}},\n").unwrap();
1110                                                                 } else {
1111                                                                         write_trait_impl_field_assign(w, s, ident);
1112                                                                 }
1113                                                         }
1114                                                 ) );
1115                                                 writeln!(w, "\t}}\n}}\n").unwrap();
1116
1117                                                 macro_rules! impl_meth {
1118                                                         ($m: expr, $trait_meth: expr, $trait_path: expr, $trait: expr, $indent: expr, $types: expr) => {
1119                                                                 let trait_method = $trait.items.iter().filter_map(|item| {
1120                                                                         if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
1121                                                                 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
1122                                                                 match export_status(&trait_method.attrs) {
1123                                                                         ExportStatus::Export => {},
1124                                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1125                                                                         ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1126                                                                 }
1127
1128                                                                 if let syn::ReturnType::Type(_, _) = &$m.sig.output {
1129                                                                         writeln!(w, "#[must_use]").unwrap();
1130                                                                 }
1131                                                                 write!(w, "extern \"C\" fn {}_{}_{}(", ident, $trait.ident, $m.sig.ident).unwrap();
1132                                                                 let mut meth_gen_types = gen_types.push_ctx();
1133                                                                 assert!(meth_gen_types.learn_generics(&$m.sig.generics, $types));
1134                                                                 let mut uncallable_function = false;
1135                                                                 for inp in $m.sig.inputs.iter() {
1136                                                                         match inp {
1137                                                                                 syn::FnArg::Typed(arg) => {
1138                                                                                         if $types.skip_arg(&*arg.ty, Some(&meth_gen_types)) { continue; }
1139                                                                                         let mut c_type = Vec::new();
1140                                                                                         $types.write_c_type(&mut c_type, &*arg.ty, Some(&meth_gen_types), false);
1141                                                                                         if is_type_unconstructable(&String::from_utf8(c_type).unwrap()) {
1142                                                                                                 uncallable_function = true;
1143                                                                                         }
1144                                                                                 }
1145                                                                                 _ => {}
1146                                                                         }
1147                                                                 }
1148                                                                 write_method_params(w, &$trait_meth.sig, "c_void", &mut trait_resolver, Some(&meth_gen_types), true, true);
1149                                                                 write!(w, " {{\n\t").unwrap();
1150                                                                 if uncallable_function {
1151                                                                         write!(w, "unreachable!();").unwrap();
1152                                                                 } else {
1153                                                                         write_method_var_decl_body(w, &$trait_meth.sig, "", &mut trait_resolver, Some(&meth_gen_types), false);
1154                                                                         let mut takes_self = false;
1155                                                                         for inp in $m.sig.inputs.iter() {
1156                                                                                 if let syn::FnArg::Receiver(_) = inp {
1157                                                                                         takes_self = true;
1158                                                                                 }
1159                                                                         }
1160
1161                                                                         let mut t_gen_args = String::new();
1162                                                                         for (idx, _) in $trait.generics.params.iter().enumerate() {
1163                                                                                 if idx != 0 { t_gen_args += ", " };
1164                                                                                 t_gen_args += "_"
1165                                                                         }
1166                                                                         // rustc doesn't like <_> if the _ is actually a lifetime, so
1167                                                                         // if all the parameters are lifetimes just skip it.
1168                                                                         let mut nonlifetime_param = false;
1169                                                                         for param in $trait.generics.params.iter() {
1170                                                                                 if let syn::GenericParam::Lifetime(_) = param {}
1171                                                                                 else { nonlifetime_param = true; }
1172                                                                         }
1173                                                                         if !nonlifetime_param { t_gen_args = String::new(); }
1174                                                                         if takes_self {
1175                                                                                 write!(w, "<native{} as {}<{}>>::{}(unsafe {{ &mut *(this_arg as *mut native{}) }}, ", ident, $trait_path, t_gen_args, $m.sig.ident, ident).unwrap();
1176                                                                         } else {
1177                                                                                 write!(w, "<native{} as {}<{}>>::{}(", ident, $trait_path, t_gen_args, $m.sig.ident).unwrap();
1178                                                                         }
1179
1180                                                                         let mut real_type = "".to_string();
1181                                                                         match &$m.sig.output {
1182                                                                                 syn::ReturnType::Type(_, rtype) => {
1183                                                                                         if let Some(mut remaining_path) = first_seg_self(&*rtype) {
1184                                                                                                 if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
1185                                                                                                         real_type = format!("{}", impl_associated_types.get(associated_seg).unwrap());
1186                                                                                                 }
1187                                                                                         }
1188                                                                                 },
1189                                                                                 _ => {},
1190                                                                         }
1191                                                                         write_method_call_params(w, &$trait_meth.sig, "", &mut trait_resolver, Some(&meth_gen_types), &real_type, false);
1192                                                                 }
1193                                                                 write!(w, "\n}}\n").unwrap();
1194                                                                 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
1195                                                                         if let syn::Type::Reference(r) = &**rtype {
1196                                                                                 assert_eq!($m.sig.inputs.len(), 1); // Must only take self
1197                                                                                 writeln!(w, "extern \"C\" fn {}_{}_set_{}(trait_self_arg: &{}) {{", ident, $trait.ident, $m.sig.ident, $trait.ident).unwrap();
1198                                                                                 writeln!(w, "\t// This is a bit race-y in the general case, but for our specific use-cases today, we're safe").unwrap();
1199                                                                                 writeln!(w, "\t// Specifically, we must ensure that the first time we're called it can never be in parallel").unwrap();
1200                                                                                 write!(w, "\tif ").unwrap();
1201                                                                                 $types.write_empty_rust_val_check(Some(&meth_gen_types), w, &*r.elem, &format!("trait_self_arg.{}", $m.sig.ident));
1202                                                                                 writeln!(w, " {{").unwrap();
1203                                                                                 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();
1204                                                                                 writeln!(w, "\t}}").unwrap();
1205                                                                                 writeln!(w, "}}").unwrap();
1206                                                                         }
1207                                                                 }
1208                                                         }
1209                                                 }
1210
1211                                                 'impl_item_loop: for trait_item in trait_obj.items.iter() {
1212                                                         match trait_item {
1213                                                                 syn::TraitItem::Method(meth) => {
1214                                                                         for item in i.items.iter() {
1215                                                                                 match item {
1216                                                                                         syn::ImplItem::Method(m) => {
1217                                                                                                 if meth.sig.ident == m.sig.ident {
1218                                                                                                         impl_meth!(m, meth, full_trait_path, trait_obj, "", types);
1219                                                                                                         continue 'impl_item_loop;
1220                                                                                                 }
1221                                                                                         },
1222                                                                                         syn::ImplItem::Type(_) => {},
1223                                                                                         _ => unimplemented!(),
1224                                                                                 }
1225                                                                         }
1226                                                                         assert!(meth.default.is_some());
1227                                                                         let old_gen_types = gen_types;
1228                                                                         gen_types = GenericTypes::new(Some(resolved_path.clone()));
1229                                                                         impl_meth!(meth, meth, full_trait_path, trait_obj, "", &mut trait_resolver);
1230                                                                         gen_types = old_gen_types;
1231                                                                 },
1232                                                                 _ => {},
1233                                                         }
1234                                                 }
1235                                                 if requires_clone {
1236                                                         writeln!(w, "extern \"C\" fn {}_{}_cloned(new_obj: &mut crate::{}) {{", trait_obj.ident, ident, full_trait_path).unwrap();
1237                                                         writeln!(w, "\tnew_obj.this_arg = {}_clone_void(new_obj.this_arg);", ident).unwrap();
1238                                                         writeln!(w, "\tnew_obj.free = Some({}_free_void);", ident).unwrap();
1239                                                         walk_supertraits!(trait_obj, Some(&types), (
1240                                                                 (s, t, _) => {
1241                                                                         if types.crate_types.traits.get(s).is_some() {
1242                                                                                 assert!(!types.is_clonable(s)); // We don't currently support cloning with a clonable supertrait
1243                                                                                 writeln!(w, "\tnew_obj.{}.this_arg = new_obj.this_arg;", t).unwrap();
1244                                                                                 writeln!(w, "\tnew_obj.{}.free = None;", t).unwrap();
1245                                                                         }
1246                                                                 }
1247                                                         ) );
1248                                                         writeln!(w, "}}").unwrap();
1249                                                 }
1250                                                 write!(w, "\n").unwrap();
1251                                                 return;
1252                                         }
1253                                         if is_type_unconstructable(&resolved_path) {
1254                                                 // Don't bother exposing trait implementations for objects which cannot be
1255                                                 // instantiated.
1256                                                 return;
1257                                         }
1258                                         if path_matches_nongeneric(&trait_path.1, &["From"]) {
1259                                         } else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
1260                                                 writeln!(w, "/// Creates a \"default\" {}. See struct and individual field documentaiton for details on which values are used.", ident).unwrap();
1261                                                 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
1262                                                 write!(w, "\t{} {{ inner: ObjOps::heap_alloc(Default::default()), is_owned: true }}\n", ident).unwrap();
1263                                                 write!(w, "}}\n").unwrap();
1264                                         } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "PartialEq"]) {
1265                                         } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "Eq"]) {
1266                                                 writeln!(w, "/// Checks if two {}s contain equal inner contents.", ident).unwrap();
1267                                                 writeln!(w, "/// This ignores pointers and is_owned flags and looks at the values in fields.").unwrap();
1268                                                 if types.c_type_has_inner_from_path(&resolved_path) {
1269                                                         writeln!(w, "/// Two objects with NULL inner values will be considered \"equal\" here.").unwrap();
1270                                                 }
1271                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_eq(a: &{}, b: &{}) -> bool {{\n", ident, ident, ident).unwrap();
1272                                                 if types.c_type_has_inner_from_path(&resolved_path) {
1273                                                         write!(w, "\tif a.inner == b.inner {{ return true; }}\n").unwrap();
1274                                                         write!(w, "\tif a.inner.is_null() || b.inner.is_null() {{ return false; }}\n").unwrap();
1275                                                 }
1276
1277                                                 let path = &p.path;
1278                                                 let ref_type: syn::Type = syn::parse_quote!(&#path);
1279                                                 assert!(!types.write_to_c_conversion_new_var(w, &format_ident!("a"), &*i.self_ty, Some(&gen_types), false), "We don't support new var conversions when comparing equality");
1280
1281                                                 write!(w, "\tif ").unwrap();
1282                                                 types.write_from_c_conversion_prefix(w, &ref_type, Some(&gen_types));
1283                                                 write!(w, "a").unwrap();
1284                                                 types.write_from_c_conversion_suffix(w, &ref_type, Some(&gen_types));
1285                                                 write!(w, " == ").unwrap();
1286                                                 types.write_from_c_conversion_prefix(w, &ref_type, Some(&gen_types));
1287                                                 write!(w, "b").unwrap();
1288                                                 types.write_from_c_conversion_suffix(w, &ref_type, Some(&gen_types));
1289
1290                                                 writeln!(w, " {{ true }} else {{ false }}\n}}").unwrap();
1291                                         } else if path_matches_nongeneric(&trait_path.1, &["core", "hash", "Hash"]) {
1292                                                 writeln!(w, "/// Checks if two {}s contain equal inner contents.", ident).unwrap();
1293                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_hash(o: &{}) -> u64 {{\n", ident, ident).unwrap();
1294                                                 if types.c_type_has_inner_from_path(&resolved_path) {
1295                                                         write!(w, "\tif o.inner.is_null() {{ return 0; }}\n").unwrap();
1296                                                 }
1297
1298                                                 let path = &p.path;
1299                                                 let ref_type: syn::Type = syn::parse_quote!(&#path);
1300                                                 assert!(!types.write_to_c_conversion_new_var(w, &format_ident!("a"), &*i.self_ty, Some(&gen_types), false), "We don't support new var conversions when comparing equality");
1301
1302                                                 writeln!(w, "\t// Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core").unwrap();
1303                                                 writeln!(w, "\t#[allow(deprecated)]").unwrap();
1304                                                 writeln!(w, "\tlet mut hasher = core::hash::SipHasher::new();").unwrap();
1305                                                 write!(w, "\tcore::hash::Hash::hash(").unwrap();
1306                                                 types.write_from_c_conversion_prefix(w, &ref_type, Some(&gen_types));
1307                                                 write!(w, "o").unwrap();
1308                                                 types.write_from_c_conversion_suffix(w, &ref_type, Some(&gen_types));
1309                                                 writeln!(w, ", &mut hasher);").unwrap();
1310                                                 writeln!(w, "\tcore::hash::Hasher::finish(&hasher)\n}}").unwrap();
1311                                         } else if (path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) || path_matches_nongeneric(&trait_path.1, &["Clone"])) &&
1312                                                         types.c_type_has_inner_from_path(&resolved_path) {
1313                                                 writeln!(w, "impl Clone for {} {{", ident).unwrap();
1314                                                 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
1315                                                 writeln!(w, "\t\tSelf {{").unwrap();
1316                                                 writeln!(w, "\t\t\tinner: if <*mut native{}>::is_null(self.inner) {{ core::ptr::null_mut() }} else {{", ident).unwrap();
1317                                                 writeln!(w, "\t\t\t\tObjOps::heap_alloc(unsafe {{ &*ObjOps::untweak_ptr(self.inner) }}.clone()) }},").unwrap();
1318                                                 writeln!(w, "\t\t\tis_owned: true,").unwrap();
1319                                                 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
1320                                                 writeln!(w, "#[allow(unused)]").unwrap();
1321                                                 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
1322                                                 writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", ident).unwrap();
1323                                                 writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", ident).unwrap();
1324                                                 writeln!(w, "}}").unwrap();
1325                                                 writeln!(w, "#[no_mangle]").unwrap();
1326                                                 writeln!(w, "/// Creates a copy of the {}", ident).unwrap();
1327                                                 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", ident, ident, ident).unwrap();
1328                                                 writeln!(w, "\torig.clone()").unwrap();
1329                                                 writeln!(w, "}}").unwrap();
1330                                         } else if path_matches_nongeneric(&trait_path.1, &["FromStr"]) {
1331                                                 let mut err_opt = None;
1332                                                 for item in i.items.iter() {
1333                                                         match item {
1334                                                                 syn::ImplItem::Type(ty) if format!("{}", ty.ident) == "Err" => {
1335                                                                         err_opt = Some(&ty.ty);
1336                                                                 },
1337                                                                 _ => {}
1338                                                         }
1339                                                 }
1340                                                 let err_ty = err_opt.unwrap();
1341                                                 if let Some(container) = types.get_c_mangled_container_type(vec![&*i.self_ty, &err_ty], Some(&gen_types), "Result") {
1342                                                         writeln!(w, "#[no_mangle]").unwrap();
1343                                                         writeln!(w, "/// Read a {} object from a string", ident).unwrap();
1344                                                         writeln!(w, "pub extern \"C\" fn {}_from_str(s: crate::c_types::Str) -> {} {{", ident, container).unwrap();
1345                                                         writeln!(w, "\tmatch {}::from_str(s.into_str()) {{", resolved_path).unwrap();
1346
1347                                                         writeln!(w, "\t\tOk(r) => {{").unwrap();
1348                                                         let new_var = types.write_to_c_conversion_new_var(w, &format_ident!("r"), &*i.self_ty, Some(&gen_types), false);
1349                                                         write!(w, "\t\t\tcrate::c_types::CResultTempl::ok(\n\t\t\t\t").unwrap();
1350                                                         types.write_to_c_conversion_inline_prefix(w, &*i.self_ty, Some(&gen_types), false);
1351                                                         write!(w, "{}r", if new_var { "local_" } else { "" }).unwrap();
1352                                                         types.write_to_c_conversion_inline_suffix(w, &*i.self_ty, Some(&gen_types), false);
1353                                                         writeln!(w, "\n\t\t\t)\n\t\t}},").unwrap();
1354
1355                                                         writeln!(w, "\t\tErr(e) => {{").unwrap();
1356                                                         let new_var = types.write_to_c_conversion_new_var(w, &format_ident!("e"), &err_ty, Some(&gen_types), false);
1357                                                         write!(w, "\t\t\tcrate::c_types::CResultTempl::err(\n\t\t\t\t").unwrap();
1358                                                         types.write_to_c_conversion_inline_prefix(w, &err_ty, Some(&gen_types), false);
1359                                                         write!(w, "{}e", if new_var { "local_" } else { "" }).unwrap();
1360                                                         types.write_to_c_conversion_inline_suffix(w, &err_ty, Some(&gen_types), false);
1361                                                         writeln!(w, "\n\t\t\t)\n\t\t}},").unwrap();
1362
1363                                                         writeln!(w, "\t}}.into()\n}}").unwrap();
1364                                                 }
1365                                         } else if path_matches_nongeneric(&trait_path.1, &["Display"]) {
1366                                                 writeln!(w, "#[no_mangle]").unwrap();
1367                                                 writeln!(w, "/// Get the string representation of a {} object", ident).unwrap();
1368                                                 writeln!(w, "pub extern \"C\" fn {}_to_str(o: &crate::{}) -> Str {{", ident, resolved_path).unwrap();
1369
1370                                                 let self_ty = &i.self_ty;
1371                                                 let ref_type: syn::Type = syn::parse_quote!(&#self_ty);
1372                                                 let new_var = types.write_from_c_conversion_new_var(w, &format_ident!("o"), &ref_type, Some(&gen_types));
1373                                                 write!(w, "\talloc::format!(\"{{}}\", ").unwrap();
1374                                                 types.write_from_c_conversion_prefix(w, &ref_type, Some(&gen_types));
1375                                                 write!(w, "{}o", if new_var { "local_" } else { "" }).unwrap();
1376                                                 types.write_from_c_conversion_suffix(w, &ref_type, Some(&gen_types));
1377                                                 writeln!(w, ").into()").unwrap();
1378
1379                                                 writeln!(w, "}}").unwrap();
1380                                         } else {
1381                                                 //XXX: implement for other things like ToString
1382                                                 // If we have no generics, try a manual implementation:
1383                                                 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
1384                                         }
1385                                 } else {
1386                                         let is_opaque = types.crate_types.opaques.contains_key(&resolved_path);
1387                                         let is_mirrored_enum = types.crate_types.mirrored_enums.contains_key(&resolved_path);
1388                                         for item in i.items.iter() {
1389                                                 match item {
1390                                                         syn::ImplItem::Method(m) => {
1391                                                                 if let syn::Visibility::Public(_) = m.vis {
1392                                                                         match export_status(&m.attrs) {
1393                                                                                 ExportStatus::Export => {},
1394                                                                                 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1395                                                                                 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1396                                                                         }
1397                                                                         if m.sig.asyncness.is_some() { continue; }
1398                                                                         let mut meth_gen_types = gen_types.push_ctx();
1399                                                                         assert!(meth_gen_types.learn_generics(&m.sig.generics, types));
1400                                                                         if m.defaultness.is_some() { unimplemented!(); }
1401                                                                         writeln_fn_docs(w, &m.attrs, "", types, Some(&meth_gen_types), m.sig.inputs.iter(), &m.sig.output);
1402                                                                         if let syn::ReturnType::Type(_, _) = &m.sig.output {
1403                                                                                 writeln!(w, "#[must_use]").unwrap();
1404                                                                         }
1405                                                                         write!(w, "#[no_mangle]\npub extern \"C\" fn {}_{}(", ident, m.sig.ident).unwrap();
1406                                                                         let ret_type = format!("crate::{}", resolved_path);
1407                                                                         write_method_params(w, &m.sig, &ret_type, types, Some(&meth_gen_types), false, true);
1408                                                                         write!(w, " {{\n\t").unwrap();
1409                                                                         write_method_var_decl_body(w, &m.sig, "", types, Some(&meth_gen_types), false);
1410                                                                         let mut takes_self = false;
1411                                                                         let mut takes_mut_self = false;
1412                                                                         let mut takes_owned_self = false;
1413                                                                         for inp in m.sig.inputs.iter() {
1414                                                                                 if let syn::FnArg::Receiver(r) = inp {
1415                                                                                         takes_self = true;
1416                                                                                         if r.mutability.is_some() { takes_mut_self = true; }
1417                                                                                         if r.reference.is_none() { takes_owned_self = true; }
1418                                                                                 }
1419                                                                         }
1420                                                                         if !takes_mut_self && !takes_self {
1421                                                                                 write!(w, "{}::{}(", resolved_path, m.sig.ident).unwrap();
1422                                                                         } else {
1423                                                                                 if is_mirrored_enum {
1424                                                                                         write!(w, "this_arg.to_native().{}(", m.sig.ident).unwrap();
1425                                                                                 } else if is_opaque {
1426                                                                                         if takes_owned_self {
1427                                                                                                 write!(w, "(*unsafe {{ Box::from_raw(this_arg.take_inner()) }}).{}(", m.sig.ident).unwrap();
1428                                                                                         } else if takes_mut_self {
1429                                                                                                 write!(w, "unsafe {{ &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::{}::native{})) }}.{}(", rsplit_once(&resolved_path, "::").unwrap().0, ident, m.sig.ident).unwrap();
1430                                                                                         } else {
1431                                                                                                 write!(w, "unsafe {{ &*ObjOps::untweak_ptr(this_arg.inner) }}.{}(", m.sig.ident).unwrap();
1432                                                                                         }
1433                                                                                 } else {
1434                                                                                         unimplemented!();
1435                                                                                 }
1436                                                                         }
1437                                                                         write_method_call_params(w, &m.sig, "", types, Some(&meth_gen_types), &ret_type, false);
1438                                                                         writeln!(w, "\n}}\n").unwrap();
1439                                                                 }
1440                                                         },
1441                                                         _ => {},
1442                                                 }
1443                                         }
1444                                 }
1445                         } else if let Some(resolved_path) = types.maybe_resolve_ident(&ident) {
1446                                 create_alias_for_impl(resolved_path, i, types, move |aliased_impl, types| writeln_impl(w, w_uses, &aliased_impl, types));
1447                         } else {
1448                                 eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub)", ident);
1449                         }
1450                 }
1451         }
1452 }
1453
1454 fn create_alias_for_impl<F: FnMut(syn::ItemImpl, &mut TypeResolver)>(resolved_path: String, i: &syn::ItemImpl, types: &mut TypeResolver, mut callback: F) {
1455         if let Some(aliases) = types.crate_types.reverse_alias_map.get(&resolved_path).cloned() {
1456                 let mut gen_types = Some(GenericTypes::new(Some(resolved_path.clone())));
1457                 if !gen_types.as_mut().unwrap().learn_generics(&i.generics, types) {
1458                         gen_types = None;
1459                 }
1460                 let alias_module = rsplit_once(&resolved_path, "::").unwrap().0;
1461
1462                 'alias_impls: for (alias_resolved, arguments) in aliases {
1463                         let mut new_ty_generics = Vec::new();
1464                         let mut new_ty_bounds = Vec::new();
1465                         let mut need_generics = false;
1466
1467                         let alias_resolver_override;
1468                         let alias_resolver = if alias_module != types.module_path {
1469                                 alias_resolver_override = ImportResolver::new(types.types.crate_name, &types.crate_types.lib_ast,
1470                                         alias_module, &types.crate_types.lib_ast.modules.get(alias_module).unwrap().items);
1471                                 &alias_resolver_override
1472                         } else { &types.types };
1473                         let mut where_clause = syn::WhereClause { where_token: syn::Token![where](Span::call_site()),
1474                                 predicates: syn::punctuated::Punctuated::new()
1475                         };
1476                         for (idx, gen) in i.generics.params.iter().enumerate() {
1477                                 match gen {
1478                                         syn::GenericParam::Type(type_param) => {
1479                                                 'bounds_check: for bound in type_param.bounds.iter() {
1480                                                         if let syn::TypeParamBound::Trait(trait_bound) = bound {
1481                                                                 if let syn::PathArguments::AngleBracketed(ref t) = &arguments {
1482                                                                         assert!(idx < t.args.len());
1483                                                                         if let syn::GenericArgument::Type(syn::Type::Path(p)) = &t.args[idx] {
1484                                                                                 let generic_bound = types.maybe_resolve_path(&trait_bound.path, None)
1485                                                                                         .unwrap_or_else(|| format!("{}::{}", types.module_path, single_ident_generic_path_to_ident(&trait_bound.path).unwrap()));
1486
1487                                                                                 if let Some(generic_arg) = alias_resolver.maybe_resolve_path(&p.path, None) {
1488                                                                                         new_ty_generics.push((type_param.ident.clone(), syn::Type::Path(p.clone())));
1489                                                                                         if let Some(traits_impld) = types.crate_types.trait_impls.get(&generic_arg) {
1490                                                                                                 for trait_impld in traits_impld {
1491                                                                                                         if *trait_impld == generic_bound { continue 'bounds_check; }
1492                                                                                                 }
1493                                                                                                 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1494                                                                                                 continue 'alias_impls;
1495                                                                                         } else {
1496                                                                                                 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1497                                                                                                 continue 'alias_impls;
1498                                                                                         }
1499                                                                                 } else if gen_types.is_some() {
1500                                                                                         let resp =  types.maybe_resolve_path(&p.path, gen_types.as_ref());
1501                                                                                         if generic_bound == "core::ops::Deref" && resp.is_some() {
1502                                                                                                 new_ty_bounds.push((type_param.ident.clone(),
1503                                                                                                         string_path_to_syn_path("core::ops::Deref")));
1504                                                                                                 let mut bounds = syn::punctuated::Punctuated::new();
1505                                                                                                 bounds.push(syn::TypeParamBound::Trait(syn::TraitBound {
1506                                                                                                         paren_token: None,
1507                                                                                                         modifier: syn::TraitBoundModifier::None,
1508                                                                                                         lifetimes: None,
1509                                                                                                         path: string_path_to_syn_path(&types.resolve_path(&p.path, gen_types.as_ref())),
1510                                                                                                 }));
1511                                                                                                 let mut path = string_path_to_syn_path(&format!("{}::Target", type_param.ident));
1512                                                                                                 path.leading_colon = None;
1513                                                                                                 where_clause.predicates.push(syn::WherePredicate::Type(syn::PredicateType {
1514                                                                                                         lifetimes: None,
1515                                                                                                         bounded_ty: syn::Type::Path(syn::TypePath { qself: None, path }),
1516                                                                                                         colon_token: syn::Token![:](Span::call_site()),
1517                                                                                                         bounds,
1518                                                                                                 }));
1519                                                                                         } else {
1520                                                                                                 new_ty_generics.push((type_param.ident.clone(),
1521                                                                                                         gen_types.as_ref().resolve_type(&syn::Type::Path(p.clone())).clone()));
1522                                                                                         }
1523                                                                                         need_generics = true;
1524                                                                                 } else {
1525                                                                                         unimplemented!();
1526                                                                                 }
1527                                                                         } else { unimplemented!(); }
1528                                                                 } else { unimplemented!(); }
1529                                                         } else { unimplemented!(); }
1530                                                 }
1531                                         },
1532                                         syn::GenericParam::Lifetime(_) => {},
1533                                         syn::GenericParam::Const(_) => unimplemented!(),
1534                                 }
1535                         }
1536                         let mut params = syn::punctuated::Punctuated::new();
1537                         let alias = string_path_to_syn_path(&alias_resolved);
1538                         let real_aliased =
1539                                 if need_generics {
1540                                         let alias_generics = types.crate_types.opaques.get(&alias_resolved).unwrap().1;
1541
1542                                         // If we need generics on the alias, create impl generic bounds...
1543                                         assert_eq!(new_ty_generics.len() + new_ty_bounds.len(), i.generics.params.len());
1544                                         let mut args = syn::punctuated::Punctuated::new();
1545                                         for (ident, param) in new_ty_generics.drain(..) {
1546                                                 // TODO: We blindly assume that generics in the type alias and
1547                                                 // the aliased type have the same names, which we really shouldn't.
1548                                                 if alias_generics.params.iter().any(|generic|
1549                                                         if let syn::GenericParam::Type(t) = generic { t.ident == ident } else { false })
1550                                                 {
1551                                                         args.push(parse_quote!(#ident));
1552                                                 }
1553                                                 params.push(syn::GenericParam::Type(syn::TypeParam {
1554                                                         attrs: Vec::new(),
1555                                                         ident,
1556                                                         colon_token: None,
1557                                                         bounds: syn::punctuated::Punctuated::new(),
1558                                                         eq_token: Some(syn::token::Eq(Span::call_site())),
1559                                                         default: Some(param),
1560                                                 }));
1561                                         }
1562                                         for (ident, param) in new_ty_bounds.drain(..) {
1563                                                 // TODO: We blindly assume that generics in the type alias and
1564                                                 // the aliased type have the same names, which we really shouldn't.
1565                                                 if alias_generics.params.iter().any(|generic|
1566                                                         if let syn::GenericParam::Type(t) = generic { t.ident == ident } else { false })
1567                                                 {
1568                                                         args.push(parse_quote!(#ident));
1569                                                 }
1570                                                 params.push(syn::GenericParam::Type(syn::TypeParam {
1571                                                         attrs: Vec::new(),
1572                                                         ident,
1573                                                         colon_token: Some(syn::token::Colon(Span::call_site())),
1574                                                         bounds: syn::punctuated::Punctuated::from_iter(
1575                                                                 Some(syn::TypeParamBound::Trait(syn::TraitBound {
1576                                                                         path: param, paren_token: None, lifetimes: None,
1577                                                                         modifier: syn::TraitBoundModifier::None,
1578                                                                 }))
1579                                                         ),
1580                                                         eq_token: None,
1581                                                         default: None,
1582                                                 }));
1583                                         }
1584                                         // ... and swap the last segment of the impl self_ty to use the generic bounds.
1585                                         let mut res = alias.clone();
1586                                         res.segments.last_mut().unwrap().arguments = syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
1587                                                 colon2_token: None,
1588                                                 lt_token: syn::token::Lt(Span::call_site()),
1589                                                 args,
1590                                                 gt_token: syn::token::Gt(Span::call_site()),
1591                                         });
1592                                         res
1593                                 } else { alias.clone() };
1594                         callback(syn::ItemImpl {
1595                                 attrs: i.attrs.clone(),
1596                                 brace_token: syn::token::Brace(Span::call_site()),
1597                                 defaultness: None,
1598                                 generics: syn::Generics {
1599                                         lt_token: None,
1600                                         params,
1601                                         gt_token: None,
1602                                         where_clause: Some(where_clause),
1603                                 },
1604                                 impl_token: syn::Token![impl](Span::call_site()),
1605                                 items: i.items.clone(),
1606                                 self_ty: Box::new(syn::Type::Path(syn::TypePath { qself: None, path: real_aliased })),
1607                                 trait_: i.trait_.clone(),
1608                                 unsafety: None,
1609                         }, types);
1610                 }
1611         } else {
1612                 eprintln!("Not implementing anything for {} due to it being marked not exported", resolved_path);
1613         }
1614 }
1615
1616 /// Replaces upper case charachters with underscore followed by lower case except the first
1617 /// charachter and repeated upper case characthers (which are only made lower case).
1618 fn camel_to_snake_case(camel: &str) -> String {
1619         let mut res = "".to_string();
1620         let mut last_upper = -1;
1621         for (idx, c) in camel.chars().enumerate() {
1622                 if c.is_uppercase() {
1623                         if last_upper != idx as isize - 1 { res.push('_'); }
1624                         res.push(c.to_lowercase().next().unwrap());
1625                         last_upper = idx as isize;
1626                 } else {
1627                         res.push(c);
1628                 }
1629         }
1630         res
1631 }
1632
1633
1634 /// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
1635 /// is unitary), we generate an equivalent enum with all types replaced with their C mapped
1636 /// versions followed by conversion functions which map between the Rust version and the C mapped
1637 /// version.
1638 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) {
1639         match export_status(&e.attrs) {
1640                 ExportStatus::Export => {},
1641                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1642                 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1643         }
1644
1645         if is_enum_opaque(e) {
1646                 eprintln!("Skipping enum {} as it contains non-unit fields", e.ident);
1647                 writeln_opaque(w, &e.ident, &format!("{}", e.ident), &e.generics, &e.attrs, types, extra_headers, cpp_headers);
1648                 return;
1649         }
1650         writeln_docs(w, &e.attrs, "");
1651
1652         let mut gen_types = GenericTypes::new(None);
1653         assert!(gen_types.learn_generics(&e.generics, types));
1654
1655         let mut needs_free = false;
1656         let mut constr = Vec::new();
1657         let mut is_clonable = true;
1658
1659         for var in e.variants.iter() {
1660                 if let syn::Fields::Named(fields) = &var.fields {
1661                         needs_free = true;
1662                         for field in fields.named.iter() {
1663                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1664
1665                                 let mut ty_checks = Vec::new();
1666                                 types.write_c_type(&mut ty_checks, &field.ty, Some(&gen_types), false);
1667                                 if !types.is_clonable(&String::from_utf8(ty_checks).unwrap()) {
1668                                         is_clonable = false;
1669                                 }
1670                         }
1671                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1672                         for field in fields.unnamed.iter() {
1673                                 let mut ty_checks = Vec::new();
1674                                 types.write_c_type(&mut ty_checks, &field.ty, Some(&gen_types), false);
1675                                 let ty = String::from_utf8(ty_checks).unwrap();
1676                                 if ty != "" && !types.is_clonable(&ty) {
1677                                         is_clonable = false;
1678                                 }
1679                         }
1680                 }
1681         }
1682
1683         if is_clonable {
1684                 writeln!(w, "#[derive(Clone)]").unwrap();
1685                 types.crate_types.set_clonable(format!("{}::{}", types.module_path, e.ident));
1686         }
1687         writeln!(w, "#[must_use]\n#[repr(C)]\npub enum {} {{", e.ident).unwrap();
1688         for var in e.variants.iter() {
1689                 assert_eq!(export_status(&var.attrs), ExportStatus::Export); // We can't partially-export a mirrored enum
1690                 writeln_docs(w, &var.attrs, "\t");
1691                 write!(w, "\t{}", var.ident).unwrap();
1692                 writeln!(&mut constr, "#[no_mangle]\n/// Utility method to constructs a new {}-variant {}", var.ident, e.ident).unwrap();
1693                 let constr_name = camel_to_snake_case(&format!("{}", var.ident));
1694                 write!(&mut constr, "pub extern \"C\" fn {}_{}(", e.ident, constr_name).unwrap();
1695                 let mut empty_tuple_variant = false;
1696                 if let syn::Fields::Named(fields) = &var.fields {
1697                         needs_free = true;
1698                         writeln!(w, " {{").unwrap();
1699                         for (idx, field) in fields.named.iter().enumerate() {
1700                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1701                                 writeln_field_docs(w, &field.attrs, "\t\t", types, Some(&gen_types), &field.ty);
1702                                 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1703                                 write!(&mut constr, "{}{}: ", if idx != 0 { ", " } else { "" }, field.ident.as_ref().unwrap()).unwrap();
1704                                 types.write_c_type(w, &field.ty, Some(&gen_types), true);
1705                                 types.write_c_type(&mut constr, &field.ty, Some(&gen_types), true);
1706                                 writeln!(w, ",").unwrap();
1707                         }
1708                         write!(w, "\t}}").unwrap();
1709                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1710                         if fields.unnamed.len() == 1 {
1711                                 let mut empty_check = Vec::new();
1712                                 types.write_c_type(&mut empty_check, &fields.unnamed[0].ty, Some(&gen_types), true);
1713                                 if empty_check.is_empty() {
1714                                         empty_tuple_variant = true;
1715                                 }
1716                         }
1717                         if !empty_tuple_variant {
1718                                 needs_free = true;
1719                                 writeln!(w, "(").unwrap();
1720                                 for (idx, field) in fields.unnamed.iter().enumerate() {
1721                                         if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1722                                         writeln_field_docs(w, &field.attrs, "\t\t", types, Some(&gen_types), &field.ty);
1723                                         write!(w, "\t\t").unwrap();
1724                                         types.write_c_type(w, &field.ty, Some(&gen_types), true);
1725
1726                                         write!(&mut constr, "{}: ", ('a' as u8 + idx as u8) as char).unwrap();
1727                                         types.write_c_type(&mut constr, &field.ty, Some(&gen_types), false);
1728                                         if idx != fields.unnamed.len() - 1 {
1729                                                 writeln!(w, ",").unwrap();
1730                                                 write!(&mut constr, ",").unwrap();
1731                                         }
1732                                 }
1733                                 write!(w, ")").unwrap();
1734                         }
1735                 }
1736                 if var.discriminant.is_some() { unimplemented!(); }
1737                 write!(&mut constr, ") -> {} {{\n\t{}::{}", e.ident, e.ident, var.ident).unwrap();
1738                 if let syn::Fields::Named(fields) = &var.fields {
1739                         writeln!(&mut constr, " {{").unwrap();
1740                         for field in fields.named.iter() {
1741                                 writeln!(&mut constr, "\t\t{},", field.ident.as_ref().unwrap()).unwrap();
1742                         }
1743                         writeln!(&mut constr, "\t}}").unwrap();
1744                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1745                         if !empty_tuple_variant {
1746                                 write!(&mut constr, "(").unwrap();
1747                                 for (idx, field) in fields.unnamed.iter().enumerate() {
1748                                         let mut ref_c_ty = Vec::new();
1749                                         let mut nonref_c_ty = Vec::new();
1750                                         types.write_c_type(&mut ref_c_ty, &field.ty, Some(&gen_types), false);
1751                                         types.write_c_type(&mut nonref_c_ty, &field.ty, Some(&gen_types), true);
1752
1753                                         if ref_c_ty != nonref_c_ty {
1754                                                 // We blindly assume references in field types are always opaque types, and
1755                                                 // print out an opaque reference -> owned reference conversion here.
1756                                                 write!(&mut constr, "{} {{ inner: {}.inner, is_owned: false }}, ", String::from_utf8(nonref_c_ty).unwrap(), ('a' as u8 + idx as u8) as char).unwrap();
1757                                         } else {
1758                                                 write!(&mut constr, "{}, ", ('a' as u8 + idx as u8) as char).unwrap();
1759                                         }
1760                                 }
1761                                 writeln!(&mut constr, ")").unwrap();
1762                         } else {
1763                                 writeln!(&mut constr, "").unwrap();
1764                         }
1765                 }
1766                 writeln!(&mut constr, "}}").unwrap();
1767                 writeln!(w, ",").unwrap();
1768         }
1769         writeln!(w, "}}\nuse {}::{} as {}Import;", types.module_path, e.ident, e.ident).unwrap();
1770         write!(w, "pub(crate) type native{} = {}Import", e.ident, e.ident).unwrap();
1771         maybe_write_generics(w, &e.generics, &syn::PathArguments::None, &types, true);
1772         writeln!(w, ";\n\nimpl {} {{", e.ident).unwrap();
1773
1774         macro_rules! write_conv {
1775                 ($fn_sig: expr, $to_c: expr, $ref: expr) => {
1776                         writeln!(w, "\t#[allow(unused)]\n\tpub(crate) fn {} {{\n\t\tmatch {} {{", $fn_sig, if $to_c { "native" } else { "self" }).unwrap();
1777                         for var in e.variants.iter() {
1778                                 write!(w, "\t\t\t{}{}::{} ", if $to_c { "native" } else { "" }, e.ident, var.ident).unwrap();
1779                                 let mut empty_tuple_variant = false;
1780                                 if let syn::Fields::Named(fields) = &var.fields {
1781                                         write!(w, "{{").unwrap();
1782                                         for field in fields.named.iter() {
1783                                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1784                                                 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, field.ident.as_ref().unwrap()).unwrap();
1785                                         }
1786                                         write!(w, "}} ").unwrap();
1787                                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1788                                         if fields.unnamed.len() == 1 {
1789                                                 let mut empty_check = Vec::new();
1790                                                 types.write_c_type(&mut empty_check, &fields.unnamed[0].ty, Some(&gen_types), true);
1791                                                 if empty_check.is_empty() {
1792                                                         empty_tuple_variant = true;
1793                                                 }
1794                                         }
1795                                         if !empty_tuple_variant || $to_c {
1796                                                 write!(w, "(").unwrap();
1797                                                 for (idx, field) in fields.unnamed.iter().enumerate() {
1798                                                         if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1799                                                         write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, ('a' as u8 + idx as u8) as char).unwrap();
1800                                                 }
1801                                                 write!(w, ") ").unwrap();
1802                                         }
1803                                 }
1804                                 write!(w, "=>").unwrap();
1805
1806                                 macro_rules! handle_field_a {
1807                                         ($field: expr, $field_ident: expr) => { {
1808                                                 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1809                                                 let mut sink = ::std::io::sink();
1810                                                 let mut out: &mut dyn std::io::Write = if $ref { &mut sink } else { w };
1811                                                 let new_var = if $to_c {
1812                                                         types.write_to_c_conversion_new_var(&mut out, $field_ident, &$field.ty, Some(&gen_types), true)
1813                                                 } else {
1814                                                         types.write_from_c_conversion_new_var(&mut out, $field_ident, &$field.ty, Some(&gen_types))
1815                                                 };
1816                                                 if $ref || new_var {
1817                                                         if $ref {
1818                                                                 write!(w, "let mut {}_nonref = Clone::clone({});\n\t\t\t\t", $field_ident, $field_ident).unwrap();
1819                                                                 if new_var {
1820                                                                         let nonref_ident = format_ident!("{}_nonref", $field_ident);
1821                                                                         if $to_c {
1822                                                                                 types.write_to_c_conversion_new_var(w, &nonref_ident, &$field.ty, Some(&gen_types), true);
1823                                                                         } else {
1824                                                                                 types.write_from_c_conversion_new_var(w, &nonref_ident, &$field.ty, Some(&gen_types));
1825                                                                         }
1826                                                                         write!(w, "\n\t\t\t\t").unwrap();
1827                                                                 }
1828                                                         } else {
1829                                                                 write!(w, "\n\t\t\t\t").unwrap();
1830                                                         }
1831                                                 }
1832                                         } }
1833                                 }
1834                                 if let syn::Fields::Named(fields) = &var.fields {
1835                                         write!(w, " {{\n\t\t\t\t").unwrap();
1836                                         for field in fields.named.iter() {
1837                                                 handle_field_a!(field, field.ident.as_ref().unwrap());
1838                                         }
1839                                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1840                                         write!(w, " {{\n\t\t\t\t").unwrap();
1841                                         for (idx, field) in fields.unnamed.iter().enumerate() {
1842                                                 if !empty_tuple_variant {
1843                                                         handle_field_a!(field, &format_ident!("{}", ('a' as u8 + idx as u8) as char));
1844                                                 }
1845                                         }
1846                                 } else { write!(w, " ").unwrap(); }
1847
1848                                 write!(w, "{}{}::{}", if $to_c { "" } else { "native" }, e.ident, var.ident).unwrap();
1849
1850                                 macro_rules! handle_field_b {
1851                                         ($field: expr, $field_ident: expr) => { {
1852                                                 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1853                                                 if $to_c {
1854                                                         types.write_to_c_conversion_inline_prefix(w, &$field.ty, Some(&gen_types), true);
1855                                                 } else {
1856                                                         types.write_from_c_conversion_prefix(w, &$field.ty, Some(&gen_types));
1857                                                 }
1858                                                 write!(w, "{}{}", $field_ident,
1859                                                         if $ref { "_nonref" } else { "" }).unwrap();
1860                                                 if $to_c {
1861                                                         types.write_to_c_conversion_inline_suffix(w, &$field.ty, Some(&gen_types), true);
1862                                                 } else {
1863                                                         types.write_from_c_conversion_suffix(w, &$field.ty, Some(&gen_types));
1864                                                 }
1865                                                 write!(w, ",").unwrap();
1866                                         } }
1867                                 }
1868
1869                                 if let syn::Fields::Named(fields) = &var.fields {
1870                                         write!(w, " {{").unwrap();
1871                                         for field in fields.named.iter() {
1872                                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1873                                                 write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1874                                                 handle_field_b!(field, field.ident.as_ref().unwrap());
1875                                         }
1876                                         writeln!(w, "\n\t\t\t\t}}").unwrap();
1877                                         write!(w, "\t\t\t}}").unwrap();
1878                                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1879                                         if !empty_tuple_variant || !$to_c {
1880                                                 write!(w, " (").unwrap();
1881                                                 for (idx, field) in fields.unnamed.iter().enumerate() {
1882                                                         write!(w, "\n\t\t\t\t\t").unwrap();
1883                                                         handle_field_b!(field, &format_ident!("{}", ('a' as u8 + idx as u8) as char));
1884                                                 }
1885                                                 writeln!(w, "\n\t\t\t\t)").unwrap();
1886                                         }
1887                                         write!(w, "\t\t\t}}").unwrap();
1888                                 }
1889                                 writeln!(w, ",").unwrap();
1890                         }
1891                         writeln!(w, "\t\t}}\n\t}}").unwrap();
1892                 }
1893         }
1894
1895         if is_clonable {
1896                 write_conv!(format!("to_native(&self) -> native{}", e.ident), false, true);
1897         }
1898         write_conv!(format!("into_native(self) -> native{}", e.ident), false, false);
1899         if is_clonable {
1900                 write_conv!(format!("from_native(native: &native{}) -> Self", e.ident), true, true);
1901         }
1902         write_conv!(format!("native_into(native: native{}) -> Self", e.ident), true, false);
1903         writeln!(w, "}}").unwrap();
1904
1905         if needs_free {
1906                 writeln!(w, "/// Frees any resources used by the {}", e.ident).unwrap();
1907                 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", e.ident, e.ident).unwrap();
1908         }
1909         if is_clonable {
1910                 writeln!(w, "/// Creates a copy of the {}", e.ident).unwrap();
1911                 writeln!(w, "#[no_mangle]").unwrap();
1912                 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
1913                 writeln!(w, "\torig.clone()").unwrap();
1914                 writeln!(w, "}}").unwrap();
1915         }
1916         w.write_all(&constr).unwrap();
1917         write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free, None);
1918 }
1919
1920 fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &mut TypeResolver<'b, 'a>) {
1921         match export_status(&f.attrs) {
1922                 ExportStatus::Export => {},
1923                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1924                 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1925         }
1926         let mut gen_types = GenericTypes::new(None);
1927         if !gen_types.learn_generics(&f.sig.generics, types) { return; }
1928
1929         writeln_fn_docs(w, &f.attrs, "", types, Some(&gen_types), f.sig.inputs.iter(), &f.sig.output);
1930
1931         write!(w, "#[no_mangle]\npub extern \"C\" fn {}(", f.sig.ident).unwrap();
1932
1933
1934         write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
1935         write!(w, " {{\n\t").unwrap();
1936         write_method_var_decl_body(w, &f.sig, "", types, Some(&gen_types), false);
1937         write!(w, "{}::{}", types.module_path, f.sig.ident).unwrap();
1938
1939         let mut function_generic_args = Vec::new();
1940         maybe_write_generics(&mut function_generic_args, &f.sig.generics, &syn::PathArguments::None, types, true);
1941         if !function_generic_args.is_empty() {
1942                 write!(w, "::{}", String::from_utf8(function_generic_args).unwrap()).unwrap();
1943         }
1944         write!(w, "(").unwrap();
1945
1946         write_method_call_params(w, &f.sig, "", types, Some(&gen_types), "", false);
1947         writeln!(w, "\n}}\n").unwrap();
1948 }
1949
1950 // ********************************
1951 // *** File/Crate Walking Logic ***
1952 // ********************************
1953
1954 fn convert_priv_mod<'a, 'b: 'a, W: std::io::Write>(w: &mut W, w_uses: &mut HashSet<String, NonRandomHash>, libast: &'b FullLibraryAST, crate_types: &CrateTypes<'b>, out_dir: &str, mod_path: &str, module: &'b syn::ItemMod) {
1955         // We want to ignore all items declared in this module (as they are not pub), but we still need
1956         // to give the ImportResolver any use statements, so we copy them here.
1957         let mut use_items = Vec::new();
1958         for item in module.content.as_ref().unwrap().1.iter() {
1959                 if let syn::Item::Use(_) = item {
1960                         use_items.push(item);
1961                 }
1962         }
1963         let import_resolver = ImportResolver::from_borrowed_items(mod_path.splitn(2, "::").next().unwrap(), libast, mod_path, &use_items);
1964         let mut types = TypeResolver::new(mod_path, import_resolver, crate_types);
1965
1966         writeln!(w, "mod {} {{\n{}", module.ident, DEFAULT_IMPORTS).unwrap();
1967         for item in module.content.as_ref().unwrap().1.iter() {
1968                 match item {
1969                         syn::Item::Mod(m) => convert_priv_mod(w, w_uses, libast, crate_types, out_dir, &format!("{}::{}", mod_path, module.ident), m),
1970                         syn::Item::Impl(i) => {
1971                                 writeln_impl(w, w_uses, i, &mut types);
1972                         },
1973                         _ => {},
1974                 }
1975         }
1976         writeln!(w, "}}").unwrap();
1977 }
1978
1979 /// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
1980 /// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
1981 /// at `module` from C.
1982 fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &CrateTypes<'a>, out_dir: &str, header_file: &mut File, cpp_header_file: &mut File) {
1983         for (module, astmod) in libast.modules.iter() {
1984                 let orig_crate = module.splitn(2, "::").next().unwrap();
1985                 let ASTModule { ref attrs, ref items, ref submods } = astmod;
1986                 assert_eq!(export_status(&attrs), ExportStatus::Export);
1987
1988                 let new_file_path = if submods.is_empty() {
1989                         format!("{}/{}.rs", out_dir, module.replace("::", "/"))
1990                 } else if module != "" {
1991                         format!("{}/{}/mod.rs", out_dir, module.replace("::", "/"))
1992                 } else {
1993                         format!("{}/lib.rs", out_dir)
1994                 };
1995                 let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
1996                 let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1997                         .open(new_file_path).expect("Unable to open new src file");
1998                 let mut out_uses = HashSet::default();
1999
2000                 writeln!(out, "// This file is Copyright its original authors, visible in version control").unwrap();
2001                 writeln!(out, "// history and in the source files from which this was generated.").unwrap();
2002                 writeln!(out, "//").unwrap();
2003                 writeln!(out, "// This file is licensed under the license available in the LICENSE or LICENSE.md").unwrap();
2004                 writeln!(out, "// file in the root of this repository or, if no such file exists, the same").unwrap();
2005                 writeln!(out, "// license as that which applies to the original source files from which this").unwrap();
2006                 writeln!(out, "// source was automatically generated.").unwrap();
2007                 writeln!(out, "").unwrap();
2008
2009                 writeln_docs(&mut out, &attrs, "");
2010
2011                 if module == "" {
2012                         // Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
2013                         // and bitcoin hand-written modules.
2014                         writeln!(out, "//! C Bindings").unwrap();
2015                         writeln!(out, "#![allow(unknown_lints)]").unwrap();
2016                         writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
2017                         writeln!(out, "#![allow(non_snake_case)]").unwrap();
2018                         writeln!(out, "#![allow(unused_imports)]").unwrap();
2019                         writeln!(out, "#![allow(unused_variables)]").unwrap();
2020                         writeln!(out, "#![allow(unused_mut)]").unwrap();
2021                         writeln!(out, "#![allow(unused_parens)]").unwrap();
2022                         writeln!(out, "#![allow(unused_unsafe)]").unwrap();
2023                         writeln!(out, "#![allow(unused_braces)]").unwrap();
2024                         // TODO: We need to map deny(missing_docs) in the source crate(s)
2025                         //writeln!(out, "#![deny(missing_docs)]").unwrap();
2026
2027                         writeln!(out, "#![cfg_attr(not(feature = \"std\"), no_std)]").unwrap();
2028                         writeln!(out, "#[cfg(not(any(feature = \"std\", feature = \"no-std\")))]").unwrap();
2029                         writeln!(out, "compile_error!(\"at least one of the `std` or `no-std` features must be enabled\");").unwrap();
2030                         writeln!(out, "extern crate alloc;").unwrap();
2031
2032                         writeln!(out, "pub mod version;").unwrap();
2033                         writeln!(out, "pub mod c_types;").unwrap();
2034                         writeln!(out, "pub mod bitcoin;").unwrap();
2035                 } else {
2036                         writeln!(out, "{}", DEFAULT_IMPORTS).unwrap();
2037                 }
2038
2039                 for m in submods {
2040                         writeln!(out, "pub mod {};", m).unwrap();
2041                 }
2042
2043                 eprintln!("Converting {} entries...", module);
2044
2045                 let import_resolver = ImportResolver::new(orig_crate, libast, module, items);
2046                 let mut type_resolver = TypeResolver::new(module, import_resolver, crate_types);
2047
2048                 for item in items.iter() {
2049                         match item {
2050                                 syn::Item::Use(_) => {}, // Handled above
2051                                 syn::Item::Static(_) => {},
2052                                 syn::Item::Enum(e) => {
2053                                         if let syn::Visibility::Public(_) = e.vis {
2054                                                 writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
2055                                         }
2056                                 },
2057                                 syn::Item::Impl(i) => {
2058                                         writeln_impl(&mut out, &mut out_uses, &i, &mut type_resolver);
2059                                 },
2060                                 syn::Item::Struct(s) => {
2061                                         if let syn::Visibility::Public(_) = s.vis {
2062                                                 writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
2063                                         }
2064                                 },
2065                                 syn::Item::Trait(t) => {
2066                                         if let syn::Visibility::Public(_) = t.vis {
2067                                                 writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
2068                                         }
2069                                 },
2070                                 syn::Item::Mod(m) => {
2071                                         convert_priv_mod(&mut out, &mut out_uses, libast, crate_types, out_dir, &format!("{}::{}", module, m.ident), m);
2072                                 },
2073                                 syn::Item::Const(c) => {
2074                                         // Re-export any primitive-type constants.
2075                                         if let syn::Visibility::Public(_) = c.vis {
2076                                                 if let syn::Type::Path(p) = &*c.ty {
2077                                                         let resolved_path = type_resolver.resolve_path(&p.path, None);
2078                                                         if type_resolver.is_primitive(&resolved_path) {
2079                                                                 writeln_field_docs(&mut out, &c.attrs, "", &mut type_resolver, None, &*c.ty);
2080                                                                 writeln!(out, "\n#[no_mangle]").unwrap();
2081                                                                 writeln!(out, "pub static {}: {} = {}::{};", c.ident, resolved_path, module, c.ident).unwrap();
2082                                                         }
2083                                                 }
2084                                         }
2085                                 },
2086                                 syn::Item::Type(t) => {
2087                                         if let syn::Visibility::Public(_) = t.vis {
2088                                                 match export_status(&t.attrs) {
2089                                                         ExportStatus::Export => {},
2090                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
2091                                                         ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
2092                                                 }
2093
2094                                                 match &*t.ty {
2095                                                         syn::Type::Path(p) => {
2096                                                                 let real_ty = type_resolver.resolve_path(&p.path, None);
2097                                                                 let real_generic_bounds = type_resolver.crate_types.opaques.get(&real_ty).map(|t| t.1).or(
2098                                                                         type_resolver.crate_types.priv_structs.get(&real_ty).map(|r| *r)).unwrap();
2099                                                                 let mut resolved_generics = t.generics.clone();
2100
2101                                                                 // Assume blindly that the bounds in the struct definition where
2102                                                                 // clause matches any equivalent bounds on the type alias.
2103                                                                 assert!(resolved_generics.where_clause.is_none());
2104                                                                 resolved_generics.where_clause = real_generic_bounds.where_clause.clone();
2105
2106                                                                 if let syn::PathArguments::AngleBracketed(real_generics) = &p.path.segments.last().unwrap().arguments {
2107                                                                         for (real_idx, real_param) in real_generics.args.iter().enumerate() {
2108                                                                                 if let syn::GenericArgument::Type(syn::Type::Path(real_param_path)) = real_param {
2109                                                                                         for param in resolved_generics.params.iter_mut() {
2110                                                                                                 if let syn::GenericParam::Type(type_param) = param {
2111                                                                                                         if Some(&type_param.ident) == real_param_path.path.get_ident() {
2112                                                                                                                 if let syn::GenericParam::Type(real_type_param) = &real_generic_bounds.params[real_idx] {
2113                                                                                                                         type_param.bounds = real_type_param.bounds.clone();
2114                                                                                                                         type_param.default = real_type_param.default.clone();
2115
2116                                                                                                                 }
2117                                                                                                         }
2118                                                                                                 }
2119                                                                                         }
2120                                                                                 }
2121                                                                         }
2122                                                                 }
2123
2124                                                                 writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &resolved_generics, &t.attrs, &type_resolver, header_file, cpp_header_file)},
2125                                                         _ => {}
2126                                                 }
2127                                         }
2128                                 },
2129                                 syn::Item::Fn(f) => {
2130                                         if let syn::Visibility::Public(_) = f.vis {
2131                                                 writeln_fn(&mut out, &f, &mut type_resolver);
2132                                         }
2133                                 },
2134                                 syn::Item::Macro(_) => {},
2135                                 syn::Item::Verbatim(_) => {},
2136                                 syn::Item::ExternCrate(_) => {},
2137                                 _ => unimplemented!(),
2138                         }
2139                 }
2140
2141                 for use_stmt in out_uses {
2142                         writeln!(out, "{}", use_stmt).unwrap();
2143                 }
2144
2145                 out.flush().unwrap();
2146         }
2147 }
2148
2149
2150 /// Walk the FullLibraryAST, determining if impl aliases need to be marked cloneable.
2151 fn walk_ast_second_pass<'a>(ast_storage: &'a FullLibraryAST, crate_types: &CrateTypes<'a>) {
2152         for (module, astmod) in ast_storage.modules.iter() {
2153                 let orig_crate = module.splitn(2, "::").next().unwrap();
2154                 let ASTModule { ref attrs, ref items, .. } = astmod;
2155                 assert_eq!(export_status(&attrs), ExportStatus::Export);
2156
2157                 let import_resolver = ImportResolver::new(orig_crate, ast_storage, module, items);
2158                 let mut types = TypeResolver::new(module, import_resolver, crate_types);
2159
2160                 for item in items.iter() {
2161                         match item {
2162                                 syn::Item::Impl(i) => {
2163                                         match export_status(&i.attrs) {
2164                                                 ExportStatus::Export => {},
2165                                                 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
2166                                                 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
2167                                         }
2168                                         if let Some(trait_path) = i.trait_.as_ref() {
2169                                                 if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) ||
2170                                                    path_matches_nongeneric(&trait_path.1, &["Clone"])
2171                                                 {
2172                                                         if let &syn::Type::Path(ref p) = &*i.self_ty {
2173                                                                 if let Some(resolved_path) = types.maybe_resolve_path(&p.path, None) {
2174                                                                         create_alias_for_impl(resolved_path, i, &mut types, |aliased_impl, types| {
2175                                                                                 if let &syn::Type::Path(ref p) = &*aliased_impl.self_ty {
2176                                                                                         if let Some(resolved_aliased_path) = types.maybe_resolve_path(&p.path, None) {
2177                                                                                                 crate_types.set_clonable("crate::".to_owned() + &resolved_aliased_path);
2178                                                                                         }
2179                                                                                 }
2180                                                                         });
2181                                                                 }
2182                                                         }
2183                                                 }
2184                                         }
2185                                 }
2186                                 _ => {}
2187                         }
2188                 }
2189         }
2190 }
2191
2192 fn walk_private_mod<'a>(ast_storage: &'a FullLibraryAST, orig_crate: &str, module: String, items: &'a syn::ItemMod, crate_types: &mut CrateTypes<'a>) {
2193         let import_resolver = ImportResolver::new(orig_crate, ast_storage, &module, &items.content.as_ref().unwrap().1);
2194         for item in items.content.as_ref().unwrap().1.iter() {
2195                 match item {
2196                         syn::Item::Mod(m) => walk_private_mod(ast_storage, orig_crate, format!("{}::{}", module, m.ident), m, crate_types),
2197                         syn::Item::Impl(i) => {
2198                                 if let &syn::Type::Path(ref p) = &*i.self_ty {
2199                                         if let Some(trait_path) = i.trait_.as_ref() {
2200                                                 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
2201                                                         if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
2202                                                                 match crate_types.trait_impls.entry(sp) {
2203                                                                         hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
2204                                                                         hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
2205                                                                 }
2206                                                         }
2207                                                 }
2208                                         }
2209                                 }
2210                         },
2211                         _ => {},
2212                 }
2213         }
2214 }
2215
2216 /// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
2217 fn walk_ast_first_pass<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
2218         for (module, astmod) in ast_storage.modules.iter() {
2219                 let ASTModule { ref attrs, ref items, submods: _ } = astmod;
2220                 assert_eq!(export_status(&attrs), ExportStatus::Export);
2221                 let orig_crate = module.splitn(2, "::").next().unwrap();
2222                 let import_resolver = ImportResolver::new(orig_crate, ast_storage, module, items);
2223
2224                 for item in items.iter() {
2225                         match item {
2226                                 syn::Item::Struct(s) => {
2227                                         if let syn::Visibility::Public(_) = s.vis {
2228                                                 let struct_path = format!("{}::{}", module, s.ident);
2229                                                 match export_status(&s.attrs) {
2230                                                         ExportStatus::Export => {},
2231                                                         ExportStatus::NoExport|ExportStatus::TestOnly => {
2232                                                                 crate_types.priv_structs.insert(struct_path, &s.generics);
2233                                                                 continue
2234                                                         },
2235                                                         ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
2236                                                 }
2237                                                 crate_types.opaques.insert(struct_path, (&s.ident, &s.generics));
2238                                         }
2239                                 },
2240                                 syn::Item::Trait(t) => {
2241                                         if let syn::Visibility::Public(_) = t.vis {
2242                                                 match export_status(&t.attrs) {
2243                                                         ExportStatus::Export|ExportStatus::NotImplementable => {},
2244                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
2245                                                 }
2246                                                 let trait_path = format!("{}::{}", module, t.ident);
2247                                                 walk_supertraits!(t, None, (
2248                                                         ("Clone", _, _) => {
2249                                                                 crate_types.set_clonable("crate::".to_owned() + &trait_path);
2250                                                         },
2251                                                         (_, _, _) => {}
2252                                                 ) );
2253                                                 crate_types.traits.insert(trait_path, &t);
2254                                         }
2255                                 },
2256                                 syn::Item::Type(t) => {
2257                                         if let syn::Visibility::Public(_) = t.vis {
2258                                                 match export_status(&t.attrs) {
2259                                                         ExportStatus::Export => {},
2260                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
2261                                                         ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
2262                                                 }
2263                                                 let type_path = format!("{}::{}", module, t.ident);
2264                                                 match &*t.ty {
2265                                                         syn::Type::Path(p) => {
2266                                                                 // If its a path with no generics, assume we don't map the aliased type and map it opaque
2267                                                                 let args_obj = p.path.segments.last().unwrap().arguments.clone();
2268                                                                 match crate_types.reverse_alias_map.entry(import_resolver.maybe_resolve_path(&p.path, None).unwrap()) {
2269                                                                         hash_map::Entry::Occupied(mut e) => { e.get_mut().push((type_path.clone(), args_obj)); },
2270                                                                         hash_map::Entry::Vacant(e) => { e.insert(vec![(type_path.clone(), args_obj)]); },
2271                                                                 }
2272
2273                                                                 crate_types.opaques.insert(type_path, (&t.ident, &t.generics));
2274                                                         },
2275                                                         _ => {
2276                                                                 crate_types.type_aliases.insert(type_path, import_resolver.resolve_imported_refs((*t.ty).clone()));
2277                                                         }
2278                                                 }
2279                                         }
2280                                 },
2281                                 syn::Item::Enum(e) if is_enum_opaque(e) => {
2282                                         if let syn::Visibility::Public(_) = e.vis {
2283                                                 match export_status(&e.attrs) {
2284                                                         ExportStatus::Export => {},
2285                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
2286                                                         ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
2287                                                 }
2288                                                 let enum_path = format!("{}::{}", module, e.ident);
2289                                                 crate_types.opaques.insert(enum_path, (&e.ident, &e.generics));
2290                                         }
2291                                 },
2292                                 syn::Item::Enum(e) => {
2293                                         if let syn::Visibility::Public(_) = e.vis {
2294                                                 match export_status(&e.attrs) {
2295                                                         ExportStatus::Export => {},
2296                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
2297                                                         ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
2298                                                 }
2299                                                 let enum_path = format!("{}::{}", module, e.ident);
2300                                                 crate_types.mirrored_enums.insert(enum_path, &e);
2301                                         }
2302                                 },
2303                                 syn::Item::Impl(i) => {
2304                                         if let &syn::Type::Path(ref p) = &*i.self_ty {
2305                                                 if let Some(trait_path) = i.trait_.as_ref() {
2306                                                         if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) ||
2307                                                            path_matches_nongeneric(&trait_path.1, &["Clone"]) {
2308                                                                 if let Some(full_path) = import_resolver.maybe_resolve_path(&p.path, None) {
2309                                                                         crate_types.set_clonable("crate::".to_owned() + &full_path);
2310                                                                 }
2311                                                         }
2312                                                         if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
2313                                                                 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
2314                                                                         match crate_types.trait_impls.entry(sp) {
2315                                                                                 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
2316                                                                                 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
2317                                                                         }
2318                                                                 }
2319                                                         }
2320                                                 }
2321                                         }
2322                                 },
2323                                 syn::Item::Mod(m) => walk_private_mod(ast_storage, orig_crate, format!("{}::{}", module, m.ident), m, crate_types),
2324                                 _ => {},
2325                         }
2326                 }
2327         }
2328 }
2329
2330 fn main() {
2331         let args: Vec<String> = env::args().collect();
2332         if args.len() != 5 {
2333                 eprintln!("Usage: target/dir derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
2334                 process::exit(1);
2335         }
2336
2337         let mut derived_templates = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
2338                 .open(&args[2]).expect("Unable to open new header file");
2339         writeln!(&mut derived_templates, "{}", DEFAULT_IMPORTS).unwrap();
2340         let mut header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
2341                 .open(&args[3]).expect("Unable to open new header file");
2342         let mut cpp_header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
2343                 .open(&args[4]).expect("Unable to open new header file");
2344
2345         writeln!(header_file, "#if defined(__GNUC__)").unwrap();
2346         writeln!(header_file, "#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
2347         writeln!(header_file, "#define MUST_USE_RES __attribute__((warn_unused_result))").unwrap();
2348         writeln!(header_file, "#else").unwrap();
2349         writeln!(header_file, "#define MUST_USE_STRUCT").unwrap();
2350         writeln!(header_file, "#define MUST_USE_RES").unwrap();
2351         writeln!(header_file, "#endif").unwrap();
2352         writeln!(header_file, "#if defined(__clang__)").unwrap();
2353         writeln!(header_file, "#define NONNULL_PTR _Nonnull").unwrap();
2354         writeln!(header_file, "#else").unwrap();
2355         writeln!(header_file, "#define NONNULL_PTR").unwrap();
2356         writeln!(header_file, "#endif").unwrap();
2357         writeln!(cpp_header_file, "#include <string.h>\nnamespace LDK {{").unwrap();
2358
2359         // Write a few manually-defined types into the C++ header file
2360         write_cpp_wrapper(&mut cpp_header_file, "Str", true, None);
2361
2362         // First parse the full crate's ASTs, caching them so that we can hold references to the AST
2363         // objects in other datastructures:
2364         let mut lib_src = String::new();
2365         std::io::stdin().lock().read_to_string(&mut lib_src).unwrap();
2366         let lib_syntax = syn::parse_file(&lib_src).expect("Unable to parse file");
2367         let libast = FullLibraryAST::load_lib(lib_syntax);
2368
2369         // ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
2370         // when parsing other file ASTs...
2371         let mut libtypes = CrateTypes::new(&mut derived_templates, &libast);
2372         walk_ast_first_pass(&libast, &mut libtypes);
2373
2374         // ... using the generated data, determine a few additional fields, specifically which type
2375         // aliases are to be clone-able...
2376         walk_ast_second_pass(&libast, &libtypes);
2377
2378         // ... finally, do the actual file conversion/mapping, writing out types as we go.
2379         convert_file(&libast, &libtypes, &args[1], &mut header_file, &mut cpp_header_file);
2380
2381         // For container templates which we created while walking the crate, make sure we add C++
2382         // mapped types so that C++ users can utilize the auto-destructors available.
2383         for (ty, has_destructor) in libtypes.templates_defined.borrow().iter() {
2384                 write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor, None);
2385         }
2386         writeln!(cpp_header_file, "}}").unwrap();
2387
2388         header_file.flush().unwrap();
2389         cpp_header_file.flush().unwrap();
2390         derived_templates.flush().unwrap();
2391 }