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