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