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