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