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