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