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