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