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