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