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