a0acfc65dd6a27cc9e30a0f0167210526ca434bd
[ldk-c-bindings] / 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, hash_map, 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 }
521
522 /// Write out a simple "opaque" type (eg structs) which contain a pointer to the native Rust type
523 /// and a flag to indicate whether Drop'ing the mapped struct drops the underlying Rust type.
524 ///
525 /// Also writes out a _free function and a C++ wrapper which handles calling _free.
526 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) {
527         // If we directly read the original type by its original name, cbindgen hits
528         // https://github.com/eqrion/cbindgen/issues/286 Thus, instead, we import it as a temporary
529         // name and then reference it by that name, which works around the issue.
530         write!(w, "\nuse {}::{}::{} as native{}Import;\ntype native{} = native{}Import", types.orig_crate, types.module_path, ident, ident, ident, ident).unwrap();
531         maybe_write_generics(w, &generics, &types, true);
532         writeln!(w, ";\n").unwrap();
533         writeln!(extra_headers, "struct native{}Opaque;\ntypedef struct native{}Opaque LDKnative{};", ident, ident, ident).unwrap();
534         writeln_docs(w, &attrs, "");
535         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();
536         writeln!(w, "\t/// the Rust equivalent takes an Option, it may be set to null to indicate None.").unwrap();
537         writeln!(w, "\tpub inner: *mut native{},\n\tpub is_owned: bool,\n}}\n", ident).unwrap();
538         writeln!(w, "impl Drop for {} {{\n\tfn drop(&mut self) {{", struct_name).unwrap();
539         writeln!(w, "\t\tif self.is_owned && !<*mut native{}>::is_null(self.inner) {{", ident).unwrap();
540         writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(self.inner) }};\n\t\t}}\n\t}}\n}}").unwrap();
541         writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", struct_name, struct_name).unwrap();
542         writeln!(w, "#[allow(unused)]").unwrap();
543         writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
544         writeln!(w, "extern \"C\" fn {}_free_void(this_ptr: *mut c_void) {{", struct_name).unwrap();
545         writeln!(w, "\tunsafe {{ let _ = Box::from_raw(this_ptr as *mut native{}); }}\n}}", struct_name).unwrap();
546         writeln!(w, "#[allow(unused)]").unwrap();
547         writeln!(w, "/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy").unwrap();
548         writeln!(w, "impl {} {{", struct_name).unwrap();
549         writeln!(w, "\tpub(crate) fn take_inner(mut self) -> *mut native{} {{", struct_name).unwrap();
550         writeln!(w, "\t\tassert!(self.is_owned);").unwrap();
551         writeln!(w, "\t\tlet ret = self.inner;").unwrap();
552         writeln!(w, "\t\tself.inner = std::ptr::null_mut();").unwrap();
553         writeln!(w, "\t\tret").unwrap();
554         writeln!(w, "\t}}\n}}").unwrap();
555
556         write_cpp_wrapper(cpp_headers, &format!("{}", ident), true);
557 }
558
559 /// Writes out all the relevant mappings for a Rust struct, deferring to writeln_opaque to generate
560 /// the struct itself, and then writing getters and setters for public, understood-type fields and
561 /// a constructor if every field is public.
562 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) {
563         if export_status(&s.attrs) != ExportStatus::Export { return; }
564
565         let struct_name = &format!("{}", s.ident);
566         writeln_opaque(w, &s.ident, struct_name, &s.generics, &s.attrs, types, extra_headers, cpp_headers);
567
568         if let syn::Fields::Named(fields) = &s.fields {
569                 let mut gen_types = GenericTypes::new();
570                 assert!(gen_types.learn_generics(&s.generics, types));
571
572                 let mut all_fields_settable = true;
573                 for field in fields.named.iter() {
574                         if let syn::Visibility::Public(_) = field.vis {
575                                 let export = export_status(&field.attrs);
576                                 match export {
577                                         ExportStatus::Export => {},
578                                         ExportStatus::NoExport|ExportStatus::TestOnly => {
579                                                 all_fields_settable = false;
580                                                 continue
581                                         },
582                                 }
583
584                                 if let Some(ident) = &field.ident {
585                                         let ref_type = syn::Type::Reference(syn::TypeReference {
586                                                 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
587                                                 elem: Box::new(field.ty.clone()) });
588                                         if types.understood_c_type(&ref_type, Some(&gen_types)) {
589                                                 writeln_docs(w, &field.attrs, "");
590                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> ", struct_name, ident, struct_name).unwrap();
591                                                 types.write_c_type(w, &ref_type, Some(&gen_types), true);
592                                                 write!(w, " {{\n\tlet mut inner_val = &mut unsafe {{ &mut *this_ptr.inner }}.{};\n\t", ident).unwrap();
593                                                 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);
594                                                 if local_var { write!(w, "\n\t").unwrap(); }
595                                                 types.write_to_c_conversion_inline_prefix(w, &ref_type, Some(&gen_types), true);
596                                                 if local_var {
597                                                         write!(w, "inner_val").unwrap();
598                                                 } else {
599                                                         write!(w, "(*inner_val)").unwrap();
600                                                 }
601                                                 types.write_to_c_conversion_inline_suffix(w, &ref_type, Some(&gen_types), true);
602                                                 writeln!(w, "\n}}").unwrap();
603                                         }
604
605                                         if types.understood_c_type(&field.ty, Some(&gen_types)) {
606                                                 writeln_docs(w, &field.attrs, "");
607                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_set_{}(this_ptr: &mut {}, mut val: ", struct_name, ident, struct_name).unwrap();
608                                                 types.write_c_type(w, &field.ty, Some(&gen_types), false);
609                                                 write!(w, ") {{\n\t").unwrap();
610                                                 let local_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("val", Span::call_site()), &field.ty, Some(&gen_types));
611                                                 if local_var { write!(w, "\n\t").unwrap(); }
612                                                 write!(w, "unsafe {{ &mut *this_ptr.inner }}.{} = ", ident).unwrap();
613                                                 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
614                                                 write!(w, "val").unwrap();
615                                                 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
616                                                 writeln!(w, ";\n}}").unwrap();
617                                         } else { all_fields_settable = false; }
618                                 } else { all_fields_settable = false; }
619                         } else { all_fields_settable = false; }
620                 }
621
622                 if all_fields_settable {
623                         // Build a constructor!
624                         write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_new(", struct_name).unwrap();
625                         for (idx, field) in fields.named.iter().enumerate() {
626                                 if idx != 0 { write!(w, ", ").unwrap(); }
627                                 write!(w, "mut {}_arg: ", field.ident.as_ref().unwrap()).unwrap();
628                                 types.write_c_type(w, &field.ty, Some(&gen_types), false);
629                         }
630                         write!(w, ") -> {} {{\n\t", struct_name).unwrap();
631                         for field in fields.named.iter() {
632                                 let field_name = format!("{}_arg", field.ident.as_ref().unwrap());
633                                 if types.write_from_c_conversion_new_var(w, &syn::Ident::new(&field_name, Span::call_site()), &field.ty, Some(&gen_types)) {
634                                         write!(w, "\n\t").unwrap();
635                                 }
636                         }
637                         writeln!(w, "{} {{ inner: Box::into_raw(Box::new(native{} {{", struct_name, s.ident).unwrap();
638                         for field in fields.named.iter() {
639                                 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
640                                 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
641                                 write!(w, "{}_arg", field.ident.as_ref().unwrap()).unwrap();
642                                 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
643                                 writeln!(w, ",").unwrap();
644                         }
645                         writeln!(w, "\t}})), is_owned: true }}\n}}").unwrap();
646                 }
647         }
648 }
649
650 /// Prints a relevant conversion for impl *
651 ///
652 /// For simple impl Struct {}s, this just outputs the wrapper functions as Struct_fn_name() { .. }.
653 ///
654 /// For impl Trait for Struct{}s, this non-exported generates wrapper functions as
655 /// Trait_Struct_fn_name and a Struct_as_Trait(&struct) -> Trait function which returns a populated
656 /// Trait struct containing a pointer to the passed struct's inner field and the wrapper functions.
657 ///
658 /// A few non-crate Traits are hard-coded including Default.
659 fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut TypeResolver) {
660         match export_status(&i.attrs) {
661                 ExportStatus::Export => {},
662                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
663         }
664
665         if let syn::Type::Tuple(_) = &*i.self_ty {
666                 if types.understood_c_type(&*i.self_ty, None) {
667                         let mut gen_types = GenericTypes::new();
668                         if !gen_types.learn_generics(&i.generics, types) {
669                                 eprintln!("Not implementing anything for `impl (..)` due to not understood generics");
670                                 return;
671                         }
672
673                         if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
674                         if let Some(trait_path) = i.trait_.as_ref() {
675                                 if trait_path.0.is_some() { unimplemented!(); }
676                                 if types.understood_c_path(&trait_path.1) {
677                                         eprintln!("Not implementing anything for `impl Trait for (..)` - we only support manual defines");
678                                         return;
679                                 } else {
680                                         // Just do a manual implementation:
681                                         maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
682                                 }
683                         } else {
684                                 eprintln!("Not implementing anything for plain `impl (..)` block - we only support `impl Trait for (..)` blocks");
685                                 return;
686                         }
687                 }
688                 return;
689         }
690         if let &syn::Type::Path(ref p) = &*i.self_ty {
691                 if p.qself.is_some() { unimplemented!(); }
692                 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
693                         if let Some(resolved_path) = types.maybe_resolve_non_ignored_ident(&ident) {
694                                 let mut gen_types = GenericTypes::new();
695                                 if !gen_types.learn_generics(&i.generics, types) {
696                                         eprintln!("Not implementing anything for impl {} due to not understood generics", ident);
697                                         return;
698                                 }
699
700                                 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
701                                 if let Some(trait_path) = i.trait_.as_ref() {
702                                         if trait_path.0.is_some() { unimplemented!(); }
703                                         if types.understood_c_path(&trait_path.1) {
704                                                 let full_trait_path = types.resolve_path(&trait_path.1, None);
705                                                 let trait_obj = *types.crate_types.traits.get(&full_trait_path).unwrap();
706                                                 // We learn the associated types maping from the original trait object.
707                                                 // That's great, except that they are unresolved idents, so if we learn
708                                                 // mappings from a trai defined in a different file, we may mis-resolve or
709                                                 // fail to resolve the mapped types.
710                                                 gen_types.learn_associated_types(trait_obj, types);
711                                                 let mut impl_associated_types = HashMap::new();
712                                                 for item in i.items.iter() {
713                                                         match item {
714                                                                 syn::ImplItem::Type(t) => {
715                                                                         if let syn::Type::Path(p) = &t.ty {
716                                                                                 if let Some(id) = single_ident_generic_path_to_ident(&p.path) {
717                                                                                         impl_associated_types.insert(&t.ident, id);
718                                                                                 }
719                                                                         }
720                                                                 },
721                                                                 _ => {},
722                                                         }
723                                                 }
724
725                                                 let export = export_status(&trait_obj.attrs);
726                                                 match export {
727                                                         ExportStatus::Export => {},
728                                                         ExportStatus::NoExport|ExportStatus::TestOnly => return,
729                                                 }
730
731                                                 // For cases where we have a concrete native object which implements a
732                                                 // trait and need to return the C-mapped version of the trait, provide a
733                                                 // From<> implementation which does all the work to ensure free is handled
734                                                 // properly. This way we can call this method from deep in the
735                                                 // type-conversion logic without actually knowing the concrete native type.
736                                                 writeln!(w, "impl From<native{}> for crate::{} {{", ident, full_trait_path).unwrap();
737                                                 writeln!(w, "\tfn from(obj: native{}) -> Self {{", ident).unwrap();
738                                                 writeln!(w, "\t\tlet mut rust_obj = {} {{ inner: Box::into_raw(Box::new(obj)), is_owned: true }};", ident).unwrap();
739                                                 writeln!(w, "\t\tlet mut ret = {}_as_{}(&rust_obj);", ident, trait_obj.ident).unwrap();
740                                                 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();
741                                                 writeln!(w, "\t\trust_obj.inner = std::ptr::null_mut();").unwrap();
742                                                 writeln!(w, "\t\tret.free = Some({}_free_void);", ident).unwrap();
743                                                 writeln!(w, "\t\tret\n\t}}\n}}").unwrap();
744
745                                                 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_as_{}(this_arg: &{}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
746                                                 writeln!(w, "\tcrate::{} {{", full_trait_path).unwrap();
747                                                 writeln!(w, "\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
748                                                 writeln!(w, "\t\tfree: None,").unwrap();
749
750                                                 macro_rules! write_meth {
751                                                         ($m: expr, $trait: expr, $indent: expr) => {
752                                                                 let trait_method = $trait.items.iter().filter_map(|item| {
753                                                                         if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
754                                                                 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
755                                                                 match export_status(&trait_method.attrs) {
756                                                                         ExportStatus::Export => {},
757                                                                         ExportStatus::NoExport => {
758                                                                                 write!(w, "{}\t\t//XXX: Need to export {}\n", $indent, $m.sig.ident).unwrap();
759                                                                                 continue;
760                                                                         },
761                                                                         ExportStatus::TestOnly => continue,
762                                                                 }
763
764                                                                 let mut printed = false;
765                                                                 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
766                                                                         if let syn::Type::Reference(r) = &**rtype {
767                                                                                 write!(w, "\n\t\t{}{}: ", $indent, $m.sig.ident).unwrap();
768                                                                                 types.write_empty_rust_val(Some(&gen_types), w, &*r.elem);
769                                                                                 writeln!(w, ",\n{}\t\tset_{}: Some({}_{}_set_{}),", $indent, $m.sig.ident, ident, trait_obj.ident, $m.sig.ident).unwrap();
770                                                                                 printed = true;
771                                                                         }
772                                                                 }
773                                                                 if !printed {
774                                                                         write!(w, "{}\t\t{}: {}_{}_{},\n", $indent, $m.sig.ident, ident, trait_obj.ident, $m.sig.ident).unwrap();
775                                                                 }
776                                                         }
777                                                 }
778                                                 for item in trait_obj.items.iter() {
779                                                         match item {
780                                                                 syn::TraitItem::Method(m) => {
781                                                                         write_meth!(m, trait_obj, "");
782                                                                 },
783                                                                 _ => {},
784                                                         }
785                                                 }
786                                                 walk_supertraits!(trait_obj, Some(&types), (
787                                                         ("Clone", _) => {
788                                                                 writeln!(w, "\t\tclone: Some({}_clone_void),", ident).unwrap();
789                                                         },
790                                                         ("Sync", _) => {}, ("Send", _) => {},
791                                                         ("std::marker::Sync", _) => {}, ("std::marker::Send", _) => {},
792                                                         (s, t) => {
793                                                                 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
794                                                                         writeln!(w, "\t\t{}: crate::{} {{", t, s).unwrap();
795                                                                         writeln!(w, "\t\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
796                                                                         writeln!(w, "\t\t\tfree: None,").unwrap();
797                                                                         for item in supertrait_obj.items.iter() {
798                                                                                 match item {
799                                                                                         syn::TraitItem::Method(m) => {
800                                                                                                 write_meth!(m, supertrait_obj, "\t");
801                                                                                         },
802                                                                                         _ => {},
803                                                                                 }
804                                                                         }
805                                                                         write!(w, "\t\t}},\n").unwrap();
806                                                                 } else {
807                                                                         write_trait_impl_field_assign(w, s, ident);
808                                                                 }
809                                                         }
810                                                 ) );
811                                                 writeln!(w, "\t}}\n}}\n").unwrap();
812
813                                                 macro_rules! impl_meth {
814                                                         ($m: expr, $trait_path: expr, $trait: expr, $indent: expr) => {
815                                                                 let trait_method = $trait.items.iter().filter_map(|item| {
816                                                                         if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
817                                                                 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
818                                                                 match export_status(&trait_method.attrs) {
819                                                                         ExportStatus::Export => {},
820                                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
821                                                                 }
822
823                                                                 if let syn::ReturnType::Type(_, _) = &$m.sig.output {
824                                                                         writeln!(w, "#[must_use]").unwrap();
825                                                                 }
826                                                                 write!(w, "extern \"C\" fn {}_{}_{}(", ident, trait_obj.ident, $m.sig.ident).unwrap();
827                                                                 gen_types.push_ctx();
828                                                                 assert!(gen_types.learn_generics(&$m.sig.generics, types));
829                                                                 write_method_params(w, &$m.sig, "c_void", types, Some(&gen_types), true, true);
830                                                                 write!(w, " {{\n\t").unwrap();
831                                                                 write_method_var_decl_body(w, &$m.sig, "", types, Some(&gen_types), false);
832                                                                 let mut takes_self = false;
833                                                                 for inp in $m.sig.inputs.iter() {
834                                                                         if let syn::FnArg::Receiver(_) = inp {
835                                                                                 takes_self = true;
836                                                                         }
837                                                                 }
838
839                                                                 let mut t_gen_args = String::new();
840                                                                 for (idx, _) in $trait.generics.params.iter().enumerate() {
841                                                                         if idx != 0 { t_gen_args += ", " };
842                                                                         t_gen_args += "_"
843                                                                 }
844                                                                 if takes_self {
845                                                                         write!(w, "<native{} as {}::{}<{}>>::{}(unsafe {{ &mut *(this_arg as *mut native{}) }}, ", ident, types.orig_crate, $trait_path, t_gen_args, $m.sig.ident, ident).unwrap();
846                                                                 } else {
847                                                                         write!(w, "<native{} as {}::{}<{}>>::{}(", ident, types.orig_crate, $trait_path, t_gen_args, $m.sig.ident).unwrap();
848                                                                 }
849
850                                                                 let mut real_type = "".to_string();
851                                                                 match &$m.sig.output {
852                                                                         syn::ReturnType::Type(_, rtype) => {
853                                                                                 if let Some(mut remaining_path) = first_seg_self(&*rtype) {
854                                                                                         if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
855                                                                                                 real_type = format!("{}", impl_associated_types.get(associated_seg).unwrap());
856                                                                                         }
857                                                                                 }
858                                                                         },
859                                                                         _ => {},
860                                                                 }
861                                                                 write_method_call_params(w, &$m.sig, "", types, Some(&gen_types), &real_type, false);
862                                                                 gen_types.pop_ctx();
863                                                                 write!(w, "\n}}\n").unwrap();
864                                                                 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
865                                                                         if let syn::Type::Reference(r) = &**rtype {
866                                                                                 assert_eq!($m.sig.inputs.len(), 1); // Must only take self
867                                                                                 writeln!(w, "extern \"C\" fn {}_{}_set_{}(trait_self_arg: &{}) {{", ident, trait_obj.ident, $m.sig.ident, trait_obj.ident).unwrap();
868                                                                                 writeln!(w, "\t// This is a bit race-y in the general case, but for our specific use-cases today, we're safe").unwrap();
869                                                                                 writeln!(w, "\t// Specifically, we must ensure that the first time we're called it can never be in parallel").unwrap();
870                                                                                 write!(w, "\tif ").unwrap();
871                                                                                 types.write_empty_rust_val_check(Some(&gen_types), w, &*r.elem, &format!("trait_self_arg.{}", $m.sig.ident));
872                                                                                 writeln!(w, " {{").unwrap();
873                                                                                 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();
874                                                                                 writeln!(w, "\t}}").unwrap();
875                                                                                 writeln!(w, "}}").unwrap();
876                                                                         }
877                                                                 }
878                                                         }
879                                                 }
880
881                                                 for item in i.items.iter() {
882                                                         match item {
883                                                                 syn::ImplItem::Method(m) => {
884                                                                         impl_meth!(m, full_trait_path, trait_obj, "");
885                                                                 },
886                                                                 syn::ImplItem::Type(_) => {},
887                                                                 _ => unimplemented!(),
888                                                         }
889                                                 }
890                                                 walk_supertraits!(trait_obj, Some(&types), (
891                                                         (s, _) => {
892                                                                 if let Some(supertrait_obj) = types.crate_types.traits.get(s).cloned() {
893                                                                         for item in supertrait_obj.items.iter() {
894                                                                                 match item {
895                                                                                         syn::TraitItem::Method(m) => {
896                                                                                                 impl_meth!(m, s, supertrait_obj, "\t");
897                                                                                         },
898                                                                                         _ => {},
899                                                                                 }
900                                                                         }
901                                                                 }
902                                                         }
903                                                 ) );
904                                                 write!(w, "\n").unwrap();
905                                         } else if path_matches_nongeneric(&trait_path.1, &["From"]) {
906                                         } else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
907                                                 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
908                                                 write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
909                                                 write!(w, "}}\n").unwrap();
910                                         } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "PartialEq"]) {
911                                         } else if (path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) || path_matches_nongeneric(&trait_path.1, &["Clone"])) &&
912                                                         types.c_type_has_inner_from_path(&resolved_path) {
913                                                 writeln!(w, "impl Clone for {} {{", ident).unwrap();
914                                                 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
915                                                 writeln!(w, "\t\tSelf {{").unwrap();
916                                                 writeln!(w, "\t\t\tinner: if <*mut native{}>::is_null(self.inner) {{ std::ptr::null_mut() }} else {{", ident).unwrap();
917                                                 writeln!(w, "\t\t\t\tBox::into_raw(Box::new(unsafe {{ &*self.inner }}.clone())) }},").unwrap();
918                                                 writeln!(w, "\t\t\tis_owned: true,").unwrap();
919                                                 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
920                                                 writeln!(w, "#[allow(unused)]").unwrap();
921                                                 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
922                                                 writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", ident).unwrap();
923                                                 writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", ident).unwrap();
924                                                 writeln!(w, "}}").unwrap();
925                                                 writeln!(w, "#[no_mangle]").unwrap();
926                                                 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", ident, ident, ident).unwrap();
927                                                 writeln!(w, "\torig.clone()").unwrap();
928                                                 writeln!(w, "}}").unwrap();
929                                         } else {
930                                                 //XXX: implement for other things like ToString
931                                                 // If we have no generics, try a manual implementation:
932                                                 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
933                                         }
934                                 } else {
935                                         let declared_type = (*types.get_declared_type(&ident).unwrap()).clone();
936                                         for item in i.items.iter() {
937                                                 match item {
938                                                         syn::ImplItem::Method(m) => {
939                                                                 if let syn::Visibility::Public(_) = m.vis {
940                                                                         match export_status(&m.attrs) {
941                                                                                 ExportStatus::Export => {},
942                                                                                 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
943                                                                         }
944                                                                         if m.defaultness.is_some() { unimplemented!(); }
945                                                                         writeln_docs(w, &m.attrs, "");
946                                                                         if let syn::ReturnType::Type(_, _) = &m.sig.output {
947                                                                                 writeln!(w, "#[must_use]").unwrap();
948                                                                         }
949                                                                         write!(w, "#[no_mangle]\npub extern \"C\" fn {}_{}(", ident, m.sig.ident).unwrap();
950                                                                         let ret_type = match &declared_type {
951                                                                                 DeclType::MirroredEnum => format!("{}", ident),
952                                                                                 DeclType::StructImported => format!("{}", ident),
953                                                                                 _ => unimplemented!(),
954                                                                         };
955                                                                         gen_types.push_ctx();
956                                                                         assert!(gen_types.learn_generics(&m.sig.generics, types));
957                                                                         write_method_params(w, &m.sig, &ret_type, types, Some(&gen_types), false, true);
958                                                                         write!(w, " {{\n\t").unwrap();
959                                                                         write_method_var_decl_body(w, &m.sig, "", types, Some(&gen_types), false);
960                                                                         let mut takes_self = false;
961                                                                         let mut takes_mut_self = false;
962                                                                         for inp in m.sig.inputs.iter() {
963                                                                                 if let syn::FnArg::Receiver(r) = inp {
964                                                                                         takes_self = true;
965                                                                                         if r.mutability.is_some() { takes_mut_self = true; }
966                                                                                 }
967                                                                         }
968                                                                         if takes_mut_self {
969                                                                                 write!(w, "unsafe {{ &mut (*(this_arg.inner as *mut native{})) }}.{}(", ident, m.sig.ident).unwrap();
970                                                                         } else if takes_self {
971                                                                                 write!(w, "unsafe {{ &*this_arg.inner }}.{}(", m.sig.ident).unwrap();
972                                                                         } else {
973                                                                                 write!(w, "{}::{}::{}(", types.orig_crate, resolved_path, m.sig.ident).unwrap();
974                                                                         }
975                                                                         write_method_call_params(w, &m.sig, "", types, Some(&gen_types), &ret_type, false);
976                                                                         gen_types.pop_ctx();
977                                                                         writeln!(w, "\n}}\n").unwrap();
978                                                                 }
979                                                         },
980                                                         _ => {},
981                                                 }
982                                         }
983                                 }
984                         } else if let Some(resolved_path) = types.maybe_resolve_ident(&ident) {
985                                 if let Some(aliases) = types.crate_types.reverse_alias_map.get(&resolved_path).cloned() {
986                                         'alias_impls: for (alias, arguments) in aliases {
987                                                 let alias_resolved = types.resolve_path(&alias, None);
988                                                 for (idx, gen) in i.generics.params.iter().enumerate() {
989                                                         match gen {
990                                                                 syn::GenericParam::Type(type_param) => {
991                                                                         'bounds_check: for bound in type_param.bounds.iter() {
992                                                                                 if let syn::TypeParamBound::Trait(trait_bound) = bound {
993                                                                                         if let syn::PathArguments::AngleBracketed(ref t) = &arguments {
994                                                                                                 assert!(idx < t.args.len());
995                                                                                                 if let syn::GenericArgument::Type(syn::Type::Path(p)) = &t.args[idx] {
996                                                                                                         let generic_arg = types.resolve_path(&p.path, None);
997                                                                                                         let generic_bound = types.resolve_path(&trait_bound.path, None);
998                                                                                                         if let Some(traits_impld) = types.crate_types.trait_impls.get(&generic_arg) {
999                                                                                                                 for trait_impld in traits_impld {
1000                                                                                                                         if *trait_impld == generic_bound { continue 'bounds_check; }
1001                                                                                                                 }
1002                                                                                                                 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1003                                                                                                                 continue 'alias_impls;
1004                                                                                                         } else {
1005                                                                                                                 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1006                                                                                                                 continue 'alias_impls;
1007                                                                                                         }
1008                                                                                                 } else { unimplemented!(); }
1009                                                                                         } else { unimplemented!(); }
1010                                                                                 } else { unimplemented!(); }
1011                                                                         }
1012                                                                 },
1013                                                                 syn::GenericParam::Lifetime(_) => {},
1014                                                                 syn::GenericParam::Const(_) => unimplemented!(),
1015                                                         }
1016                                                 }
1017                                                 let aliased_impl = syn::ItemImpl {
1018                                                         attrs: i.attrs.clone(),
1019                                                         brace_token: syn::token::Brace(Span::call_site()),
1020                                                         defaultness: None,
1021                                                         generics: syn::Generics {
1022                                                                 lt_token: None,
1023                                                                 params: syn::punctuated::Punctuated::new(),
1024                                                                 gt_token: None,
1025                                                                 where_clause: None,
1026                                                         },
1027                                                         impl_token: syn::Token![impl](Span::call_site()),
1028                                                         items: i.items.clone(),
1029                                                         self_ty: Box::new(syn::Type::Path(syn::TypePath { qself: None, path: alias.clone() })),
1030                                                         trait_: i.trait_.clone(),
1031                                                         unsafety: None,
1032                                                 };
1033                                                 writeln_impl(w, &aliased_impl, types);
1034                                         }
1035                                 } else {
1036                                         eprintln!("Not implementing anything for {} due to it being marked not exported", ident);
1037                                 }
1038                         } else {
1039                                 eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub)", ident);
1040                         }
1041                 }
1042         }
1043 }
1044
1045
1046 /// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
1047 /// is unitary), we generate an equivalent enum with all types replaced with their C mapped
1048 /// versions followed by conversion functions which map between the Rust version and the C mapped
1049 /// version.
1050 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) {
1051         match export_status(&e.attrs) {
1052                 ExportStatus::Export => {},
1053                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1054         }
1055
1056         if is_enum_opaque(e) {
1057                 eprintln!("Skipping enum {} as it contains non-unit fields", e.ident);
1058                 writeln_opaque(w, &e.ident, &format!("{}", e.ident), &e.generics, &e.attrs, types, extra_headers, cpp_headers);
1059                 return;
1060         }
1061         writeln_docs(w, &e.attrs, "");
1062
1063         if e.generics.lt_token.is_some() {
1064                 unimplemented!();
1065         }
1066
1067         let mut needs_free = false;
1068
1069         writeln!(w, "#[must_use]\n#[derive(Clone)]\n#[repr(C)]\npub enum {} {{", e.ident).unwrap();
1070         for var in e.variants.iter() {
1071                 assert_eq!(export_status(&var.attrs), ExportStatus::Export); // We can't partially-export a mirrored enum
1072                 writeln_docs(w, &var.attrs, "\t");
1073                 write!(w, "\t{}", var.ident).unwrap();
1074                 if let syn::Fields::Named(fields) = &var.fields {
1075                         needs_free = true;
1076                         writeln!(w, " {{").unwrap();
1077                         for field in fields.named.iter() {
1078                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1079                                 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1080                                 types.write_c_type(w, &field.ty, None, false);
1081                                 writeln!(w, ",").unwrap();
1082                         }
1083                         write!(w, "\t}}").unwrap();
1084                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1085                         needs_free = true;
1086                         write!(w, "(").unwrap();
1087                         for (idx, field) in fields.unnamed.iter().enumerate() {
1088                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1089                                 types.write_c_type(w, &field.ty, None, false);
1090                                 if idx != fields.unnamed.len() - 1 {
1091                                         write!(w, ",").unwrap();
1092                                 }
1093                         }
1094                         write!(w, ")").unwrap();
1095                 }
1096                 if var.discriminant.is_some() { unimplemented!(); }
1097                 writeln!(w, ",").unwrap();
1098         }
1099         writeln!(w, "}}\nuse {}::{}::{} as native{};\nimpl {} {{", types.orig_crate, types.module_path, e.ident, e.ident, e.ident).unwrap();
1100
1101         macro_rules! write_conv {
1102                 ($fn_sig: expr, $to_c: expr, $ref: expr) => {
1103                         writeln!(w, "\t#[allow(unused)]\n\tpub(crate) fn {} {{\n\t\tmatch {} {{", $fn_sig, if $to_c { "native" } else { "self" }).unwrap();
1104                         for var in e.variants.iter() {
1105                                 write!(w, "\t\t\t{}{}::{} ", if $to_c { "native" } else { "" }, e.ident, var.ident).unwrap();
1106                                 if let syn::Fields::Named(fields) = &var.fields {
1107                                         write!(w, "{{").unwrap();
1108                                         for field in fields.named.iter() {
1109                                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1110                                                 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, field.ident.as_ref().unwrap()).unwrap();
1111                                         }
1112                                         write!(w, "}} ").unwrap();
1113                                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1114                                         write!(w, "(").unwrap();
1115                                         for (idx, field) in fields.unnamed.iter().enumerate() {
1116                                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1117                                                 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, ('a' as u8 + idx as u8) as char).unwrap();
1118                                         }
1119                                         write!(w, ") ").unwrap();
1120                                 }
1121                                 write!(w, "=>").unwrap();
1122
1123                                 macro_rules! handle_field_a {
1124                                         ($field: expr, $field_ident: expr) => { {
1125                                                 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1126                                                 let mut sink = ::std::io::sink();
1127                                                 let mut out: &mut dyn std::io::Write = if $ref { &mut sink } else { w };
1128                                                 let new_var = if $to_c {
1129                                                         types.write_to_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None, false)
1130                                                 } else {
1131                                                         types.write_from_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None)
1132                                                 };
1133                                                 if $ref || new_var {
1134                                                         if $ref {
1135                                                                 write!(w, "let mut {}_nonref = (*{}).clone();\n\t\t\t\t", $field_ident, $field_ident).unwrap();
1136                                                                 if new_var {
1137                                                                         let nonref_ident = syn::Ident::new(&format!("{}_nonref", $field_ident), Span::call_site());
1138                                                                         if $to_c {
1139                                                                                 types.write_to_c_conversion_new_var(w, &nonref_ident, &$field.ty, None, false);
1140                                                                         } else {
1141                                                                                 types.write_from_c_conversion_new_var(w, &nonref_ident, &$field.ty, None);
1142                                                                         }
1143                                                                         write!(w, "\n\t\t\t\t").unwrap();
1144                                                                 }
1145                                                         } else {
1146                                                                 write!(w, "\n\t\t\t\t").unwrap();
1147                                                         }
1148                                                 }
1149                                         } }
1150                                 }
1151                                 if let syn::Fields::Named(fields) = &var.fields {
1152                                         write!(w, " {{\n\t\t\t\t").unwrap();
1153                                         for field in fields.named.iter() {
1154                                                 handle_field_a!(field, field.ident.as_ref().unwrap());
1155                                         }
1156                                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1157                                         write!(w, " {{\n\t\t\t\t").unwrap();
1158                                         for (idx, field) in fields.unnamed.iter().enumerate() {
1159                                                 handle_field_a!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1160                                         }
1161                                 } else { write!(w, " ").unwrap(); }
1162
1163                                 write!(w, "{}{}::{}", if $to_c { "" } else { "native" }, e.ident, var.ident).unwrap();
1164
1165                                 macro_rules! handle_field_b {
1166                                         ($field: expr, $field_ident: expr) => { {
1167                                                 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1168                                                 if $to_c {
1169                                                         types.write_to_c_conversion_inline_prefix(w, &$field.ty, None, false);
1170                                                 } else {
1171                                                         types.write_from_c_conversion_prefix(w, &$field.ty, None);
1172                                                 }
1173                                                 write!(w, "{}{}", $field_ident,
1174                                                         if $ref { "_nonref" } else { "" }).unwrap();
1175                                                 if $to_c {
1176                                                         types.write_to_c_conversion_inline_suffix(w, &$field.ty, None, false);
1177                                                 } else {
1178                                                         types.write_from_c_conversion_suffix(w, &$field.ty, None);
1179                                                 }
1180                                                 write!(w, ",").unwrap();
1181                                         } }
1182                                 }
1183
1184                                 if let syn::Fields::Named(fields) = &var.fields {
1185                                         write!(w, " {{").unwrap();
1186                                         for field in fields.named.iter() {
1187                                                 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1188                                                 write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1189                                                 handle_field_b!(field, field.ident.as_ref().unwrap());
1190                                         }
1191                                         writeln!(w, "\n\t\t\t\t}}").unwrap();
1192                                         write!(w, "\t\t\t}}").unwrap();
1193                                 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1194                                         write!(w, " (").unwrap();
1195                                         for (idx, field) in fields.unnamed.iter().enumerate() {
1196                                                 write!(w, "\n\t\t\t\t\t").unwrap();
1197                                                 handle_field_b!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1198                                         }
1199                                         writeln!(w, "\n\t\t\t\t)").unwrap();
1200                                         write!(w, "\t\t\t}}").unwrap();
1201                                 }
1202                                 writeln!(w, ",").unwrap();
1203                         }
1204                         writeln!(w, "\t\t}}\n\t}}").unwrap();
1205                 }
1206         }
1207
1208         write_conv!(format!("to_native(&self) -> native{}", e.ident), false, true);
1209         write_conv!(format!("into_native(self) -> native{}", e.ident), false, false);
1210         write_conv!(format!("from_native(native: &native{}) -> Self", e.ident), true, true);
1211         write_conv!(format!("native_into(native: native{}) -> Self", e.ident), true, false);
1212         writeln!(w, "}}").unwrap();
1213
1214         if needs_free {
1215                 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", e.ident, e.ident).unwrap();
1216         }
1217         writeln!(w, "#[no_mangle]").unwrap();
1218         writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
1219         writeln!(w, "\torig.clone()").unwrap();
1220         writeln!(w, "}}").unwrap();
1221         write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free);
1222 }
1223
1224 fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &mut TypeResolver<'b, 'a>) {
1225         match export_status(&f.attrs) {
1226                 ExportStatus::Export => {},
1227                 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1228         }
1229         writeln_docs(w, &f.attrs, "");
1230
1231         let mut gen_types = GenericTypes::new();
1232         if !gen_types.learn_generics(&f.sig.generics, types) { return; }
1233
1234         write!(w, "#[no_mangle]\npub extern \"C\" fn {}(", f.sig.ident).unwrap();
1235         write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
1236         write!(w, " {{\n\t").unwrap();
1237         write_method_var_decl_body(w, &f.sig, "", types, Some(&gen_types), false);
1238         write!(w, "{}::{}::{}(", types.orig_crate, types.module_path, f.sig.ident).unwrap();
1239         write_method_call_params(w, &f.sig, "", types, Some(&gen_types), "", false);
1240         writeln!(w, "\n}}\n").unwrap();
1241 }
1242
1243 // ********************************
1244 // *** File/Crate Walking Logic ***
1245 // ********************************
1246 /// A public module
1247 struct ASTModule {
1248         pub attrs: Vec<syn::Attribute>,
1249         pub items: Vec<syn::Item>,
1250         pub submods: Vec<String>,
1251 }
1252 /// A struct containing the syn::File AST for each file in the crate.
1253 struct FullLibraryAST {
1254         modules: HashMap<String, ASTModule, NonRandomHash>,
1255 }
1256 impl FullLibraryAST {
1257         fn load_module(&mut self, module: String, attrs: Vec<syn::Attribute>, mut items: Vec<syn::Item>) {
1258                 let mut non_mod_items = Vec::with_capacity(items.len());
1259                 let mut submods = Vec::with_capacity(items.len());
1260                 for item in items.drain(..) {
1261                         match item {
1262                                 syn::Item::Mod(m) if m.content.is_some() => {
1263                                         if export_status(&m.attrs) == ExportStatus::Export {
1264                                                 if let syn::Visibility::Public(_) = m.vis {
1265                                                         let modident = format!("{}", m.ident);
1266                                                         let modname = if module != "" {
1267                                                                 module.clone() + "::" + &modident
1268                                                         } else {
1269                                                                 modident.clone()
1270                                                         };
1271                                                         self.load_module(modname, m.attrs, m.content.unwrap().1);
1272                                                         submods.push(modident);
1273                                                 } else {
1274                                                         non_mod_items.push(syn::Item::Mod(m));
1275                                                 }
1276                                         }
1277                                 },
1278                                 syn::Item::Mod(_) => panic!("--pretty=expanded output should never have non-body modules"),
1279                                 _ => { non_mod_items.push(item); }
1280                         }
1281                 }
1282                 self.modules.insert(module, ASTModule { attrs, items: non_mod_items, submods });
1283         }
1284
1285         pub fn load_lib(lib: syn::File) -> Self {
1286                 assert_eq!(export_status(&lib.attrs), ExportStatus::Export);
1287                 let mut res = Self { modules: HashMap::default() };
1288                 res.load_module("".to_owned(), lib.attrs, lib.items);
1289                 res
1290         }
1291 }
1292
1293 /// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
1294 /// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
1295 /// at `module` from C.
1296 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) {
1297         for (module, astmod) in libast.modules.iter() {
1298                 let ASTModule { ref attrs, ref items, ref submods } = astmod;
1299                 assert_eq!(export_status(&attrs), ExportStatus::Export);
1300
1301                 let new_file_path = if submods.is_empty() {
1302                         format!("{}/{}.rs", out_dir, module.replace("::", "/"))
1303                 } else if module != "" {
1304                         format!("{}/{}/mod.rs", out_dir, module.replace("::", "/"))
1305                 } else {
1306                         format!("{}/lib.rs", out_dir)
1307                 };
1308                 let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
1309                 let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1310                         .open(new_file_path).expect("Unable to open new src file");
1311
1312                 writeln_docs(&mut out, &attrs, "");
1313
1314                 if module == "" {
1315                         // Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
1316                         // and bitcoin hand-written modules.
1317                         writeln!(out, "#![allow(unknown_lints)]").unwrap();
1318                         writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
1319                         writeln!(out, "#![allow(non_snake_case)]").unwrap();
1320                         writeln!(out, "#![allow(unused_imports)]").unwrap();
1321                         writeln!(out, "#![allow(unused_variables)]").unwrap();
1322                         writeln!(out, "#![allow(unused_mut)]").unwrap();
1323                         writeln!(out, "#![allow(unused_parens)]").unwrap();
1324                         writeln!(out, "#![allow(unused_unsafe)]").unwrap();
1325                         writeln!(out, "#![allow(unused_braces)]").unwrap();
1326                         writeln!(out, "mod c_types;").unwrap();
1327                         writeln!(out, "mod bitcoin;").unwrap();
1328                 } else {
1329                         writeln!(out, "\nuse std::ffi::c_void;\nuse bitcoin::hashes::Hash;\nuse crate::c_types::*;\n").unwrap();
1330                 }
1331
1332                 for m in submods {
1333                         writeln!(out, "pub mod {};", m).unwrap();
1334                 }
1335
1336                 eprintln!("Converting {} entries...", module);
1337
1338                 let import_resolver = ImportResolver::new(module, items);
1339                 let mut type_resolver = TypeResolver::new(orig_crate, module, import_resolver, crate_types);
1340
1341                 for item in items.iter() {
1342                         match item {
1343                                 syn::Item::Use(_) => {}, // Handled above
1344                                 syn::Item::Static(_) => {},
1345                                 syn::Item::Enum(e) => {
1346                                         if let syn::Visibility::Public(_) = e.vis {
1347                                                 writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
1348                                         }
1349                                 },
1350                                 syn::Item::Impl(i) => {
1351                                         writeln_impl(&mut out, &i, &mut type_resolver);
1352                                 },
1353                                 syn::Item::Struct(s) => {
1354                                         if let syn::Visibility::Public(_) = s.vis {
1355                                                 writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
1356                                         }
1357                                 },
1358                                 syn::Item::Trait(t) => {
1359                                         if let syn::Visibility::Public(_) = t.vis {
1360                                                 writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
1361                                         }
1362                                 },
1363                                 syn::Item::Mod(_) => {}, // We don't have to do anything - the top loop handles these.
1364                                 syn::Item::Const(c) => {
1365                                         // Re-export any primitive-type constants.
1366                                         if let syn::Visibility::Public(_) = c.vis {
1367                                                 if let syn::Type::Path(p) = &*c.ty {
1368                                                         let resolved_path = type_resolver.resolve_path(&p.path, None);
1369                                                         if type_resolver.is_primitive(&resolved_path) {
1370                                                                 writeln!(out, "\n#[no_mangle]").unwrap();
1371                                                                 writeln!(out, "pub static {}: {} = {}::{}::{};", c.ident, resolved_path, orig_crate, module, c.ident).unwrap();
1372                                                         }
1373                                                 }
1374                                         }
1375                                 },
1376                                 syn::Item::Type(t) => {
1377                                         if let syn::Visibility::Public(_) = t.vis {
1378                                                 match export_status(&t.attrs) {
1379                                                         ExportStatus::Export => {},
1380                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1381                                                 }
1382
1383                                                 let mut process_alias = true;
1384                                                 for tok in t.generics.params.iter() {
1385                                                         if let syn::GenericParam::Lifetime(_) = tok {}
1386                                                         else { process_alias = false; }
1387                                                 }
1388                                                 if process_alias {
1389                                                         match &*t.ty {
1390                                                                 syn::Type::Path(_) =>
1391                                                                         writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &t.generics, &t.attrs, &type_resolver, header_file, cpp_header_file),
1392                                                                 _ => {}
1393                                                         }
1394                                                 }
1395                                         }
1396                                 },
1397                                 syn::Item::Fn(f) => {
1398                                         if let syn::Visibility::Public(_) = f.vis {
1399                                                 writeln_fn(&mut out, &f, &mut type_resolver);
1400                                         }
1401                                 },
1402                                 syn::Item::Macro(m) => {
1403                                         if m.ident.is_none() { // If its not a macro definition
1404                                                 convert_macro(&mut out, &m.mac.path, &m.mac.tokens, &type_resolver);
1405                                         }
1406                                 },
1407                                 syn::Item::Verbatim(_) => {},
1408                                 syn::Item::ExternCrate(_) => {},
1409                                 _ => unimplemented!(),
1410                         }
1411                 }
1412
1413                 out.flush().unwrap();
1414         }
1415 }
1416
1417 fn walk_private_mod<'a>(module: String, items: &'a syn::ItemMod, crate_types: &mut CrateTypes<'a>) {
1418         let import_resolver = ImportResolver::new(&module, &items.content.as_ref().unwrap().1);
1419         for item in items.content.as_ref().unwrap().1.iter() {
1420                 match item {
1421                         syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types),
1422                         syn::Item::Impl(i) => {
1423                                 if let &syn::Type::Path(ref p) = &*i.self_ty {
1424                                         if let Some(trait_path) = i.trait_.as_ref() {
1425                                                 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1426                                                         if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1427                                                                 match crate_types.trait_impls.entry(sp) {
1428                                                                         hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1429                                                                         hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1430                                                                 }
1431                                                         }
1432                                                 }
1433                                         }
1434                                 }
1435                         },
1436                         _ => {},
1437                 }
1438         }
1439 }
1440
1441 /// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
1442 fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
1443         for (module, astmod) in ast_storage.modules.iter() {
1444                 let ASTModule { ref attrs, ref items, submods: _ } = astmod;
1445                 assert_eq!(export_status(&attrs), ExportStatus::Export);
1446                 let import_resolver = ImportResolver::new(module, items);
1447
1448                 for item in items.iter() {
1449                         match item {
1450                                 syn::Item::Struct(s) => {
1451                                         if let syn::Visibility::Public(_) = s.vis {
1452                                                 match export_status(&s.attrs) {
1453                                                         ExportStatus::Export => {},
1454                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1455                                                 }
1456                                                 let struct_path = format!("{}::{}", module, s.ident);
1457                                                 crate_types.opaques.insert(struct_path, &s.ident);
1458                                         }
1459                                 },
1460                                 syn::Item::Trait(t) => {
1461                                         if let syn::Visibility::Public(_) = t.vis {
1462                                                 match export_status(&t.attrs) {
1463                                                         ExportStatus::Export => {},
1464                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1465                                                 }
1466                                                 let trait_path = format!("{}::{}", module, t.ident);
1467                                                 walk_supertraits!(t, None, (
1468                                                         ("Clone", _) => {
1469                                                                 crate_types.clonable_types.insert("crate::".to_owned() + &trait_path);
1470                                                         },
1471                                                         (_, _) => {}
1472                                                 ) );
1473                                                 crate_types.traits.insert(trait_path, &t);
1474                                         }
1475                                 },
1476                                 syn::Item::Type(t) => {
1477                                         if let syn::Visibility::Public(_) = t.vis {
1478                                                 match export_status(&t.attrs) {
1479                                                         ExportStatus::Export => {},
1480                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1481                                                 }
1482                                                 let type_path = format!("{}::{}", module, t.ident);
1483                                                 let mut process_alias = true;
1484                                                 for tok in t.generics.params.iter() {
1485                                                         if let syn::GenericParam::Lifetime(_) = tok {}
1486                                                         else { process_alias = false; }
1487                                                 }
1488                                                 if process_alias {
1489                                                         match &*t.ty {
1490                                                                 syn::Type::Path(p) => {
1491                                                                         // If its a path with no generics, assume we don't map the aliased type and map it opaque
1492                                                                         let mut segments = syn::punctuated::Punctuated::new();
1493                                                                         segments.push(syn::PathSegment {
1494                                                                                 ident: t.ident.clone(),
1495                                                                                 arguments: syn::PathArguments::None,
1496                                                                         });
1497                                                                         let path_obj = syn::Path { leading_colon: None, segments };
1498                                                                         let args_obj = p.path.segments.last().unwrap().arguments.clone();
1499                                                                         match crate_types.reverse_alias_map.entry(import_resolver.maybe_resolve_path(&p.path, None).unwrap()) {
1500                                                                                 hash_map::Entry::Occupied(mut e) => { e.get_mut().push((path_obj, args_obj)); },
1501                                                                                 hash_map::Entry::Vacant(e) => { e.insert(vec![(path_obj, args_obj)]); },
1502                                                                         }
1503
1504                                                                         crate_types.opaques.insert(type_path.clone(), &t.ident);
1505                                                                 },
1506                                                                 _ => {
1507                                                                         crate_types.type_aliases.insert(type_path, import_resolver.resolve_imported_refs((*t.ty).clone()));
1508                                                                 }
1509                                                         }
1510                                                 }
1511                                         }
1512                                 },
1513                                 syn::Item::Enum(e) if is_enum_opaque(e) => {
1514                                         if let syn::Visibility::Public(_) = e.vis {
1515                                                 match export_status(&e.attrs) {
1516                                                         ExportStatus::Export => {},
1517                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1518                                                 }
1519                                                 let enum_path = format!("{}::{}", module, e.ident);
1520                                                 crate_types.opaques.insert(enum_path, &e.ident);
1521                                         }
1522                                 },
1523                                 syn::Item::Enum(e) => {
1524                                         if let syn::Visibility::Public(_) = e.vis {
1525                                                 match export_status(&e.attrs) {
1526                                                         ExportStatus::Export => {},
1527                                                         ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1528                                                 }
1529                                                 let enum_path = format!("{}::{}", module, e.ident);
1530                                                 crate_types.mirrored_enums.insert(enum_path, &e);
1531                                         }
1532                                 },
1533                                 syn::Item::Impl(i) => {
1534                                         if let &syn::Type::Path(ref p) = &*i.self_ty {
1535                                                 if let Some(trait_path) = i.trait_.as_ref() {
1536                                                         if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) {
1537                                                                 if let Some(full_path) = import_resolver.maybe_resolve_path(&p.path, None) {
1538                                                                         crate_types.clonable_types.insert("crate::".to_owned() + &full_path);
1539                                                                 }
1540                                                         }
1541                                                         if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1542                                                                 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1543                                                                         match crate_types.trait_impls.entry(sp) {
1544                                                                                 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1545                                                                                 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1546                                                                         }
1547                                                                 }
1548                                                         }
1549                                                 }
1550                                         }
1551                                 },
1552                                 syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types),
1553                                 _ => {},
1554                         }
1555                 }
1556         }
1557 }
1558
1559 fn main() {
1560         let args: Vec<String> = env::args().collect();
1561         if args.len() != 6 {
1562                 eprintln!("Usage: target/dir source_crate_name derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
1563                 process::exit(1);
1564         }
1565
1566         let mut derived_templates = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1567                 .open(&args[3]).expect("Unable to open new header file");
1568         let mut header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1569                 .open(&args[4]).expect("Unable to open new header file");
1570         let mut cpp_header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1571                 .open(&args[5]).expect("Unable to open new header file");
1572
1573         writeln!(header_file, "#if defined(__GNUC__)").unwrap();
1574         writeln!(header_file, "#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
1575         writeln!(header_file, "#define MUST_USE_RES __attribute__((warn_unused_result))").unwrap();
1576         writeln!(header_file, "#else").unwrap();
1577         writeln!(header_file, "#define MUST_USE_STRUCT").unwrap();
1578         writeln!(header_file, "#define MUST_USE_RES").unwrap();
1579         writeln!(header_file, "#endif").unwrap();
1580         writeln!(header_file, "#if defined(__clang__)").unwrap();
1581         writeln!(header_file, "#define NONNULL_PTR _Nonnull").unwrap();
1582         writeln!(header_file, "#else").unwrap();
1583         writeln!(header_file, "#define NONNULL_PTR").unwrap();
1584         writeln!(header_file, "#endif").unwrap();
1585         writeln!(cpp_header_file, "#include <string.h>\nnamespace LDK {{").unwrap();
1586
1587         // First parse the full crate's ASTs, caching them so that we can hold references to the AST
1588         // objects in other datastructures:
1589         let mut lib_src = String::new();
1590         std::io::stdin().lock().read_to_string(&mut lib_src).unwrap();
1591         let lib_syntax = syn::parse_file(&lib_src).expect("Unable to parse file");
1592         let libast = FullLibraryAST::load_lib(lib_syntax);
1593
1594         // ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
1595         // when parsing other file ASTs...
1596         let mut libtypes = CrateTypes { traits: HashMap::new(), opaques: HashMap::new(), mirrored_enums: HashMap::new(),
1597                 type_aliases: HashMap::new(), reverse_alias_map: HashMap::new(), templates_defined: HashMap::default(),
1598                 template_file: &mut derived_templates,
1599                 clonable_types: HashSet::new(), trait_impls: HashMap::new() };
1600         walk_ast(&libast, &mut libtypes);
1601
1602         // ... finally, do the actual file conversion/mapping, writing out types as we go.
1603         convert_file(&libast, &mut libtypes, &args[1], &args[2], &mut header_file, &mut cpp_header_file);
1604
1605         // For container templates which we created while walking the crate, make sure we add C++
1606         // mapped types so that C++ users can utilize the auto-destructors available.
1607         for (ty, has_destructor) in libtypes.templates_defined.iter() {
1608                 write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor);
1609         }
1610         writeln!(cpp_header_file, "}}").unwrap();
1611
1612         header_file.flush().unwrap();
1613         cpp_header_file.flush().unwrap();
1614         derived_templates.flush().unwrap();
1615 }