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