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