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