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