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