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.
10 //! It also generates relevant memory-management functions and free-standing functions with
11 //! parameters mapped.
13 use std::collections::{HashMap, HashSet};
16 use std::io::{Read, Write};
19 use proc_macro2::{TokenTree, TokenStream, Span};
26 // *************************************
27 // *** Manually-expanded conversions ***
28 // *************************************
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();
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)) {
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)));
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();
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();
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)));
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();
98 writeln!(w, "}}").unwrap();
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();
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,
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()),
126 let res_ty = syn::Type::Path(syn::TypePath { qself: None, path: syn::Path {
127 leading_colon: None, segments: res_segs } });
129 writeln!(w, "#[no_mangle]").unwrap();
130 write!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice", for_obj).unwrap();
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);
143 assert!(!types.write_from_c_conversion_new_var(&mut arg_conv, &syn::Ident::new("arg", Span::call_site()), &args_ty, Some(generics)));
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!(); }
152 write!(w, ") -> ").unwrap();
153 types.write_c_type(w, &res_ty, Some(generics), false);
154 writeln!(w, " {{").unwrap();
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();
163 writeln!(w, "\tlet res = crate::c_types::deserialize_obj(ser);").unwrap();
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();
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();
179 /// Convert "TraitA : TraitB" to a single function name and return type.
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) {
185 "util::ser::Writeable" => ("write".to_owned(), "crate::c_types::derived::CVec_u8Z"),
186 _ => unimplemented!(),
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) {
194 "util::ser::Writeable" => {
195 writeln!(w, "\t\twrite: {}_write_void,", for_obj).unwrap();
197 _ => unimplemented!(),
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) {
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();
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();
221 // *******************************
222 // *** Per-Type Printing Logic ***
223 // *******************************
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() {
229 syn::TypeParamBound::Trait(supertrait) => {
230 if supertrait.paren_token.is_some() || supertrait.lifetimes.is_some() {
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) {
244 if let Some(ident) = supertrait.path.get_ident() {
245 match (&format!("{}", ident) as &str, &ident) {
248 } else if types_opt.is_some() {
249 panic!("Supertrait unresolvable and not single-ident");
252 syn::TypeParamBound::Lifetime(_) => unimplemented!(),
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.
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,
270 writeln_docs(w, &t.attrs, "");
272 let mut gen_types = GenericTypes::new();
273 assert!(gen_types.learn_generics(&t.generics, types));
274 gen_types.learn_associated_types(&t, types);
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() {
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,
288 ExportStatus::Export => {},
289 ExportStatus::TestOnly => continue,
291 if m.default.is_some() { unimplemented!(); }
293 gen_types.push_ctx();
294 assert!(gen_types.learn_generics(&m.sig.generics, types));
296 writeln_docs(w, &m.attrs, "\t");
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).
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();
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();
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();
339 &syn::TraitItem::Type(_) => {},
340 _ => unimplemented!(),
343 // Add functions which may be required for supertrait implementations.
344 walk_supertraits!(t, Some(&types), (
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());
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());
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());
358 ("Send", _) => {}, ("Sync", _) => {},
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();
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();
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();
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();
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();
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();
402 do_write_impl_trait(w, s, i, &trait_name);
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() {
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() {
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() {
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();
433 if recv.mutability.is_some() {
434 write!(w, "mut self").unwrap();
436 write!(w, "self").unwrap();
439 syn::FnArg::Typed(arg) => {
440 if !arg.attrs.is_empty() { unimplemented!(); }
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() {
447 write!(w, ", {}{}: ", if types.skip_arg(&*arg.ty, Some(&gen_types)) { "_" } else { "" }, ident.ident).unwrap();
449 _ => unimplemented!(),
451 types.write_rust_type(w, Some(&gen_types), &*arg.ty);
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)
463 write!(w, " {{\n\t\t").unwrap();
464 match export_status(&m.attrs) {
465 ExportStatus::NoExport => {
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();
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);
488 writeln!(w, "\n\t}}").unwrap();
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();
498 _ => unimplemented!(),
500 if bounds_iter.next().is_some() { unimplemented!(); }
502 _ => unimplemented!(),
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();
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();
519 write_cpp_wrapper(cpp_headers, &trait_name, true);
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.
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 && !self.inner.is_null() {{").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();
556 write_cpp_wrapper(cpp_headers, &format!("{}", ident), true);
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; }
565 let struct_name = &format!("{}", s.ident);
566 writeln_opaque(w, &s.ident, struct_name, &s.generics, &s.attrs, types, extra_headers, cpp_headers);
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));
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);
577 ExportStatus::Export => {},
578 ExportStatus::NoExport|ExportStatus::TestOnly => {
579 all_fields_settable = false;
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);
597 write!(w, "inner_val").unwrap();
599 write!(w, "(*inner_val)").unwrap();
601 types.write_to_c_conversion_inline_suffix(w, &ref_type, Some(&gen_types), true);
602 writeln!(w, "\n}}").unwrap();
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; }
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);
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();
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();
645 writeln!(w, "\t}})), is_owned: true }}\n}}").unwrap();
650 /// Prints a relevant conversion for impl *
652 /// For simple impl Struct {}s, this just outputs the wrapper functions as Struct_fn_name() { .. }.
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.
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,
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");
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");
680 // Just do a manual implementation:
681 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
684 eprintln!("Not implementing anything for plain `impl (..)` block - we only support `impl Trait for (..)` blocks");
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);
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() {
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);
725 let export = export_status(&trait_obj.attrs);
727 ExportStatus::Export => {},
728 ExportStatus::NoExport|ExportStatus::TestOnly => return,
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();
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();
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();
761 ExportStatus::TestOnly => continue,
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();
774 write!(w, "{}\t\t{}: {}_{}_{},\n", $indent, $m.sig.ident, ident, trait_obj.ident, $m.sig.ident).unwrap();
778 for item in trait_obj.items.iter() {
780 syn::TraitItem::Method(m) => {
781 write_meth!(m, trait_obj, "");
786 walk_supertraits!(trait_obj, Some(&types), (
788 writeln!(w, "\t\tclone: Some({}_clone_void),", ident).unwrap();
790 ("Sync", _) => {}, ("Send", _) => {},
791 ("std::marker::Sync", _) => {}, ("std::marker::Send", _) => {},
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() {
799 syn::TraitItem::Method(m) => {
800 write_meth!(m, supertrait_obj, "\t");
805 write!(w, "\t\t}},\n").unwrap();
807 write_trait_impl_field_assign(w, s, ident);
811 write!(w, "\t}}\n}}\nuse {}::{} as {}TraitImport;\n", types.orig_crate, full_trait_path, trait_obj.ident).unwrap();
813 macro_rules! impl_meth {
814 ($m: 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,
823 if let syn::ReturnType::Type(_, _) = &$m.sig.output {
824 writeln!(w, "#[must_use]").unwrap();
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 {
839 write!(w, "unsafe {{ &mut *(this_arg as *mut native{}) }}.{}(", ident, $m.sig.ident).unwrap();
841 write!(w, "{}::{}::{}(", types.orig_crate, resolved_path, $m.sig.ident).unwrap();
844 let mut real_type = "".to_string();
845 match &$m.sig.output {
846 syn::ReturnType::Type(_, rtype) => {
847 if let Some(mut remaining_path) = first_seg_self(&*rtype) {
848 if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
849 real_type = format!("{}", impl_associated_types.get(associated_seg).unwrap());
855 write_method_call_params(w, &$m.sig, "", types, Some(&gen_types), &real_type, false);
857 write!(w, "\n}}\n").unwrap();
858 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
859 if let syn::Type::Reference(r) = &**rtype {
860 assert_eq!($m.sig.inputs.len(), 1); // Must only take self
861 writeln!(w, "extern \"C\" fn {}_{}_set_{}(trait_self_arg: &{}) {{", ident, trait_obj.ident, $m.sig.ident, trait_obj.ident).unwrap();
862 writeln!(w, "\t// This is a bit race-y in the general case, but for our specific use-cases today, we're safe").unwrap();
863 writeln!(w, "\t// Specifically, we must ensure that the first time we're called it can never be in parallel").unwrap();
864 write!(w, "\tif ").unwrap();
865 types.write_empty_rust_val_check(Some(&gen_types), w, &*r.elem, &format!("trait_self_arg.{}", $m.sig.ident));
866 writeln!(w, " {{").unwrap();
867 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();
868 writeln!(w, "\t}}").unwrap();
869 writeln!(w, "}}").unwrap();
875 for item in i.items.iter() {
877 syn::ImplItem::Method(m) => {
878 impl_meth!(m, trait_obj, "");
880 syn::ImplItem::Type(_) => {},
881 _ => unimplemented!(),
884 walk_supertraits!(trait_obj, Some(&types), (
886 if let Some(supertrait_obj) = types.crate_types.traits.get(s).cloned() {
887 writeln!(w, "use {}::{} as native{}Trait;", types.orig_crate, s, t).unwrap();
888 for item in supertrait_obj.items.iter() {
890 syn::TraitItem::Method(m) => {
891 impl_meth!(m, supertrait_obj, "\t");
899 write!(w, "\n").unwrap();
900 } else if path_matches_nongeneric(&trait_path.1, &["From"]) {
901 } else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
902 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
903 write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
904 write!(w, "}}\n").unwrap();
905 } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "PartialEq"]) {
906 } else if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) && types.c_type_has_inner_from_path(&resolved_path) {
907 writeln!(w, "impl Clone for {} {{", ident).unwrap();
908 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
909 writeln!(w, "\t\tSelf {{").unwrap();
910 writeln!(w, "\t\t\tinner: if self.inner.is_null() {{ std::ptr::null_mut() }} else {{").unwrap();
911 writeln!(w, "\t\t\t\tBox::into_raw(Box::new(unsafe {{ &*self.inner }}.clone())) }},").unwrap();
912 writeln!(w, "\t\t\tis_owned: true,").unwrap();
913 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
914 writeln!(w, "#[allow(unused)]").unwrap();
915 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
916 writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", ident).unwrap();
917 writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", ident).unwrap();
918 writeln!(w, "}}").unwrap();
919 writeln!(w, "#[no_mangle]").unwrap();
920 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", ident, ident, ident).unwrap();
921 writeln!(w, "\torig.clone()").unwrap();
922 writeln!(w, "}}").unwrap();
924 //XXX: implement for other things like ToString
925 // If we have no generics, try a manual implementation:
926 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
929 let declared_type = (*types.get_declared_type(&ident).unwrap()).clone();
930 for item in i.items.iter() {
932 syn::ImplItem::Method(m) => {
933 if let syn::Visibility::Public(_) = m.vis {
934 match export_status(&m.attrs) {
935 ExportStatus::Export => {},
936 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
938 if m.defaultness.is_some() { unimplemented!(); }
939 writeln_docs(w, &m.attrs, "");
940 if let syn::ReturnType::Type(_, _) = &m.sig.output {
941 writeln!(w, "#[must_use]").unwrap();
943 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_{}(", ident, m.sig.ident).unwrap();
944 let ret_type = match &declared_type {
945 DeclType::MirroredEnum => format!("{}", ident),
946 DeclType::StructImported => format!("{}", ident),
947 _ => unimplemented!(),
949 gen_types.push_ctx();
950 assert!(gen_types.learn_generics(&m.sig.generics, types));
951 write_method_params(w, &m.sig, &ret_type, types, Some(&gen_types), false, true);
952 write!(w, " {{\n\t").unwrap();
953 write_method_var_decl_body(w, &m.sig, "", types, Some(&gen_types), false);
954 let mut takes_self = false;
955 let mut takes_mut_self = false;
956 for inp in m.sig.inputs.iter() {
957 if let syn::FnArg::Receiver(r) = inp {
959 if r.mutability.is_some() { takes_mut_self = true; }
963 write!(w, "unsafe {{ &mut (*(this_arg.inner as *mut native{})) }}.{}(", ident, m.sig.ident).unwrap();
964 } else if takes_self {
965 write!(w, "unsafe {{ &*this_arg.inner }}.{}(", m.sig.ident).unwrap();
967 write!(w, "{}::{}::{}(", types.orig_crate, resolved_path, m.sig.ident).unwrap();
969 write_method_call_params(w, &m.sig, "", types, Some(&gen_types), &ret_type, false);
971 writeln!(w, "\n}}\n").unwrap();
979 eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub or its marked not exported)", ident);
986 /// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
987 /// is unitary), we generate an equivalent enum with all types replaced with their C mapped
988 /// versions followed by conversion functions which map between the Rust version and the C mapped
990 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) {
991 match export_status(&e.attrs) {
992 ExportStatus::Export => {},
993 ExportStatus::NoExport|ExportStatus::TestOnly => return,
996 if is_enum_opaque(e) {
997 eprintln!("Skipping enum {} as it contains non-unit fields", e.ident);
998 writeln_opaque(w, &e.ident, &format!("{}", e.ident), &e.generics, &e.attrs, types, extra_headers, cpp_headers);
1001 writeln_docs(w, &e.attrs, "");
1003 if e.generics.lt_token.is_some() {
1007 let mut needs_free = false;
1009 writeln!(w, "#[must_use]\n#[derive(Clone)]\n#[repr(C)]\npub enum {} {{", e.ident).unwrap();
1010 for var in e.variants.iter() {
1011 assert_eq!(export_status(&var.attrs), ExportStatus::Export); // We can't partially-export a mirrored enum
1012 writeln_docs(w, &var.attrs, "\t");
1013 write!(w, "\t{}", var.ident).unwrap();
1014 if let syn::Fields::Named(fields) = &var.fields {
1016 writeln!(w, " {{").unwrap();
1017 for field in fields.named.iter() {
1018 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1019 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1020 types.write_c_type(w, &field.ty, None, false);
1021 writeln!(w, ",").unwrap();
1023 write!(w, "\t}}").unwrap();
1025 if var.discriminant.is_some() { unimplemented!(); }
1026 writeln!(w, ",").unwrap();
1028 writeln!(w, "}}\nuse {}::{}::{} as native{};\nimpl {} {{", types.orig_crate, types.module_path, e.ident, e.ident, e.ident).unwrap();
1030 macro_rules! write_conv {
1031 ($fn_sig: expr, $to_c: expr, $ref: expr) => {
1032 writeln!(w, "\t#[allow(unused)]\n\tpub(crate) fn {} {{\n\t\tmatch {} {{", $fn_sig, if $to_c { "native" } else { "self" }).unwrap();
1033 for var in e.variants.iter() {
1034 write!(w, "\t\t\t{}{}::{} ", if $to_c { "native" } else { "" }, e.ident, var.ident).unwrap();
1035 if let syn::Fields::Named(fields) = &var.fields {
1036 write!(w, "{{").unwrap();
1037 for field in fields.named.iter() {
1038 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1039 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, field.ident.as_ref().unwrap()).unwrap();
1041 write!(w, "}} ").unwrap();
1043 write!(w, "=>").unwrap();
1044 if let syn::Fields::Named(fields) = &var.fields {
1045 write!(w, " {{\n\t\t\t\t").unwrap();
1046 for field in fields.named.iter() {
1047 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1048 let mut sink = ::std::io::sink();
1049 let mut out: &mut dyn std::io::Write = if $ref { &mut sink } else { w };
1050 let new_var = if $to_c {
1051 types.write_to_c_conversion_new_var(&mut out, field.ident.as_ref().unwrap(), &field.ty, None, false)
1053 types.write_from_c_conversion_new_var(&mut out, field.ident.as_ref().unwrap(), &field.ty, None)
1055 if $ref || new_var {
1057 write!(w, "let mut {}_nonref = (*{}).clone();\n\t\t\t\t", field.ident.as_ref().unwrap(), field.ident.as_ref().unwrap()).unwrap();
1059 let nonref_ident = syn::Ident::new(&format!("{}_nonref", field.ident.as_ref().unwrap()), Span::call_site());
1061 types.write_to_c_conversion_new_var(w, &nonref_ident, &field.ty, None, false);
1063 types.write_from_c_conversion_new_var(w, &nonref_ident, &field.ty, None);
1065 write!(w, "\n\t\t\t\t").unwrap();
1068 write!(w, "\n\t\t\t\t").unwrap();
1072 } else { write!(w, " ").unwrap(); }
1073 write!(w, "{}{}::{}", if $to_c { "" } else { "native" }, e.ident, var.ident).unwrap();
1074 if let syn::Fields::Named(fields) = &var.fields {
1075 write!(w, " {{").unwrap();
1076 for field in fields.named.iter() {
1077 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1078 write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1080 types.write_to_c_conversion_inline_prefix(w, &field.ty, None, false);
1082 types.write_from_c_conversion_prefix(w, &field.ty, None);
1085 field.ident.as_ref().unwrap(),
1086 if $ref { "_nonref" } else { "" }).unwrap();
1088 types.write_to_c_conversion_inline_suffix(w, &field.ty, None, false);
1090 types.write_from_c_conversion_suffix(w, &field.ty, None);
1092 write!(w, ",").unwrap();
1094 writeln!(w, "\n\t\t\t\t}}").unwrap();
1095 write!(w, "\t\t\t}}").unwrap();
1097 writeln!(w, ",").unwrap();
1099 writeln!(w, "\t\t}}\n\t}}").unwrap();
1103 write_conv!(format!("to_native(&self) -> native{}", e.ident), false, true);
1104 write_conv!(format!("into_native(self) -> native{}", e.ident), false, false);
1105 write_conv!(format!("from_native(native: &native{}) -> Self", e.ident), true, true);
1106 write_conv!(format!("native_into(native: native{}) -> Self", e.ident), true, false);
1107 writeln!(w, "}}").unwrap();
1110 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", e.ident, e.ident).unwrap();
1112 writeln!(w, "#[no_mangle]").unwrap();
1113 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
1114 writeln!(w, "\torig.clone()").unwrap();
1115 writeln!(w, "}}").unwrap();
1116 write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free);
1119 fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &mut TypeResolver<'b, 'a>) {
1120 match export_status(&f.attrs) {
1121 ExportStatus::Export => {},
1122 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1124 writeln_docs(w, &f.attrs, "");
1126 let mut gen_types = GenericTypes::new();
1127 if !gen_types.learn_generics(&f.sig.generics, types) { return; }
1129 write!(w, "#[no_mangle]\npub extern \"C\" fn {}(", f.sig.ident).unwrap();
1130 write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
1131 write!(w, " {{\n\t").unwrap();
1132 write_method_var_decl_body(w, &f.sig, "", types, Some(&gen_types), false);
1133 write!(w, "{}::{}::{}(", types.orig_crate, types.module_path, f.sig.ident).unwrap();
1134 write_method_call_params(w, &f.sig, "", types, Some(&gen_types), "", false);
1135 writeln!(w, "\n}}\n").unwrap();
1138 // ********************************
1139 // *** File/Crate Walking Logic ***
1140 // ********************************
1143 pub attrs: Vec<syn::Attribute>,
1144 pub items: Vec<syn::Item>,
1145 pub submods: Vec<String>,
1147 /// A struct containing the syn::File AST for each file in the crate.
1148 struct FullLibraryAST {
1149 modules: HashMap<String, ASTModule, NonRandomHash>,
1151 impl FullLibraryAST {
1152 fn load_module(&mut self, module: String, attrs: Vec<syn::Attribute>, mut items: Vec<syn::Item>) {
1153 let mut non_mod_items = Vec::with_capacity(items.len());
1154 let mut submods = Vec::with_capacity(items.len());
1155 for item in items.drain(..) {
1157 syn::Item::Mod(m) if m.content.is_some() => {
1158 if export_status(&m.attrs) == ExportStatus::Export {
1159 if let syn::Visibility::Public(_) = m.vis {
1160 let modident = format!("{}", m.ident);
1161 let modname = if module != "" {
1162 module.clone() + "::" + &modident
1166 self.load_module(modname, m.attrs, m.content.unwrap().1);
1167 submods.push(modident);
1169 non_mod_items.push(syn::Item::Mod(m));
1173 syn::Item::Mod(_) => panic!("--pretty=expanded output should never have non-body modules"),
1174 _ => { non_mod_items.push(item); }
1177 self.modules.insert(module, ASTModule { attrs, items: non_mod_items, submods });
1180 pub fn load_lib(lib: syn::File) -> Self {
1181 assert_eq!(export_status(&lib.attrs), ExportStatus::Export);
1182 let mut res = Self { modules: HashMap::default() };
1183 res.load_module("".to_owned(), lib.attrs, lib.items);
1188 /// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
1189 /// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
1190 /// at `module` from C.
1191 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) {
1192 for (module, astmod) in libast.modules.iter() {
1193 let ASTModule { ref attrs, ref items, ref submods } = astmod;
1194 assert_eq!(export_status(&attrs), ExportStatus::Export);
1196 let new_file_path = if submods.is_empty() {
1197 format!("{}/{}.rs", out_dir, module.replace("::", "/"))
1198 } else if module != "" {
1199 format!("{}/{}/mod.rs", out_dir, module.replace("::", "/"))
1201 format!("{}/lib.rs", out_dir)
1203 let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
1204 let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1205 .open(new_file_path).expect("Unable to open new src file");
1207 writeln_docs(&mut out, &attrs, "");
1210 // Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
1211 // and bitcoin hand-written modules.
1212 writeln!(out, "#![allow(unknown_lints)]").unwrap();
1213 writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
1214 writeln!(out, "#![allow(non_snake_case)]").unwrap();
1215 writeln!(out, "#![allow(unused_imports)]").unwrap();
1216 writeln!(out, "#![allow(unused_variables)]").unwrap();
1217 writeln!(out, "#![allow(unused_mut)]").unwrap();
1218 writeln!(out, "#![allow(unused_parens)]").unwrap();
1219 writeln!(out, "#![allow(unused_unsafe)]").unwrap();
1220 writeln!(out, "#![allow(unused_braces)]").unwrap();
1221 writeln!(out, "mod c_types;").unwrap();
1222 writeln!(out, "mod bitcoin;").unwrap();
1224 writeln!(out, "\nuse std::ffi::c_void;\nuse bitcoin::hashes::Hash;\nuse crate::c_types::*;\n").unwrap();
1228 writeln!(out, "pub mod {};", m).unwrap();
1231 eprintln!("Converting {} entries...", module);
1233 let import_resolver = ImportResolver::new(module, items);
1234 let mut type_resolver = TypeResolver::new(orig_crate, module, import_resolver, crate_types);
1236 for item in items.iter() {
1238 syn::Item::Use(_) => {}, // Handled above
1239 syn::Item::Static(_) => {},
1240 syn::Item::Enum(e) => {
1241 if let syn::Visibility::Public(_) = e.vis {
1242 writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
1245 syn::Item::Impl(i) => {
1246 writeln_impl(&mut out, &i, &mut type_resolver);
1248 syn::Item::Struct(s) => {
1249 if let syn::Visibility::Public(_) = s.vis {
1250 writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
1253 syn::Item::Trait(t) => {
1254 if let syn::Visibility::Public(_) = t.vis {
1255 writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
1258 syn::Item::Mod(_) => {}, // We don't have to do anything - the top loop handles these.
1259 syn::Item::Const(c) => {
1260 // Re-export any primitive-type constants.
1261 if let syn::Visibility::Public(_) = c.vis {
1262 if let syn::Type::Path(p) = &*c.ty {
1263 let resolved_path = type_resolver.resolve_path(&p.path, None);
1264 if type_resolver.is_primitive(&resolved_path) {
1265 writeln!(out, "\n#[no_mangle]").unwrap();
1266 writeln!(out, "pub static {}: {} = {}::{}::{};", c.ident, resolved_path, orig_crate, module, c.ident).unwrap();
1271 syn::Item::Type(t) => {
1272 if let syn::Visibility::Public(_) = t.vis {
1273 match export_status(&t.attrs) {
1274 ExportStatus::Export => {},
1275 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1278 let mut process_alias = true;
1279 for tok in t.generics.params.iter() {
1280 if let syn::GenericParam::Lifetime(_) = tok {}
1281 else { process_alias = false; }
1285 syn::Type::Path(_) =>
1286 writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &t.generics, &t.attrs, &type_resolver, header_file, cpp_header_file),
1292 syn::Item::Fn(f) => {
1293 if let syn::Visibility::Public(_) = f.vis {
1294 writeln_fn(&mut out, &f, &mut type_resolver);
1297 syn::Item::Macro(m) => {
1298 if m.ident.is_none() { // If its not a macro definition
1299 convert_macro(&mut out, &m.mac.path, &m.mac.tokens, &type_resolver);
1302 syn::Item::Verbatim(_) => {},
1303 syn::Item::ExternCrate(_) => {},
1304 _ => unimplemented!(),
1308 out.flush().unwrap();
1312 /// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
1313 fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
1314 for (module, astmod) in ast_storage.modules.iter() {
1315 let ASTModule { ref attrs, ref items, submods: _ } = astmod;
1316 assert_eq!(export_status(&attrs), ExportStatus::Export);
1317 let import_resolver = ImportResolver::new(module, items);
1319 for item in items.iter() {
1321 syn::Item::Struct(s) => {
1322 if let syn::Visibility::Public(_) = s.vis {
1323 match export_status(&s.attrs) {
1324 ExportStatus::Export => {},
1325 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1327 let struct_path = format!("{}::{}", module, s.ident);
1328 crate_types.opaques.insert(struct_path, &s.ident);
1331 syn::Item::Trait(t) => {
1332 if let syn::Visibility::Public(_) = t.vis {
1333 match export_status(&t.attrs) {
1334 ExportStatus::Export => {},
1335 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1337 let trait_path = format!("{}::{}", module, t.ident);
1338 walk_supertraits!(t, None, (
1340 crate_types.clonable_types.insert("crate::".to_owned() + &trait_path);
1344 crate_types.traits.insert(trait_path, &t);
1347 syn::Item::Type(t) => {
1348 if let syn::Visibility::Public(_) = t.vis {
1349 match export_status(&t.attrs) {
1350 ExportStatus::Export => {},
1351 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1353 let type_path = format!("{}::{}", module, t.ident);
1354 let mut process_alias = true;
1355 for tok in t.generics.params.iter() {
1356 if let syn::GenericParam::Lifetime(_) = tok {}
1357 else { process_alias = false; }
1361 syn::Type::Path(_) => {
1362 // If its a path with no generics, assume we don't map the aliased type and map it opaque
1363 crate_types.opaques.insert(type_path, &t.ident);
1366 crate_types.type_aliases.insert(type_path, import_resolver.resolve_imported_refs((*t.ty).clone()));
1372 syn::Item::Enum(e) if is_enum_opaque(e) => {
1373 if let syn::Visibility::Public(_) = e.vis {
1374 match export_status(&e.attrs) {
1375 ExportStatus::Export => {},
1376 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1378 let enum_path = format!("{}::{}", module, e.ident);
1379 crate_types.opaques.insert(enum_path, &e.ident);
1382 syn::Item::Enum(e) => {
1383 if let syn::Visibility::Public(_) = e.vis {
1384 match export_status(&e.attrs) {
1385 ExportStatus::Export => {},
1386 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1388 let enum_path = format!("{}::{}", module, e.ident);
1389 crate_types.mirrored_enums.insert(enum_path, &e);
1392 syn::Item::Impl(i) => {
1393 if let &syn::Type::Path(ref p) = &*i.self_ty {
1394 if let Some(trait_path) = i.trait_.as_ref() {
1395 if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) {
1396 if let Some(full_path) = import_resolver.maybe_resolve_path(&p.path, None) {
1397 crate_types.clonable_types.insert("crate::".to_owned() + &full_path);
1410 let args: Vec<String> = env::args().collect();
1411 if args.len() != 6 {
1412 eprintln!("Usage: target/dir source_crate_name derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
1416 let mut derived_templates = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1417 .open(&args[3]).expect("Unable to open new header file");
1418 let mut header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1419 .open(&args[4]).expect("Unable to open new header file");
1420 let mut cpp_header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1421 .open(&args[5]).expect("Unable to open new header file");
1423 writeln!(header_file, "#if defined(__GNUC__)").unwrap();
1424 writeln!(header_file, "#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
1425 writeln!(header_file, "#define MUST_USE_RES __attribute__((warn_unused_result))").unwrap();
1426 writeln!(header_file, "#else").unwrap();
1427 writeln!(header_file, "#define MUST_USE_STRUCT").unwrap();
1428 writeln!(header_file, "#define MUST_USE_RES").unwrap();
1429 writeln!(header_file, "#endif").unwrap();
1430 writeln!(header_file, "#if defined(__clang__)").unwrap();
1431 writeln!(header_file, "#define NONNULL_PTR _Nonnull").unwrap();
1432 writeln!(header_file, "#else").unwrap();
1433 writeln!(header_file, "#define NONNULL_PTR").unwrap();
1434 writeln!(header_file, "#endif").unwrap();
1435 writeln!(cpp_header_file, "#include <string.h>\nnamespace LDK {{").unwrap();
1437 // First parse the full crate's ASTs, caching them so that we can hold references to the AST
1438 // objects in other datastructures:
1439 let mut lib_src = String::new();
1440 std::io::stdin().lock().read_to_string(&mut lib_src).unwrap();
1441 let lib_syntax = syn::parse_file(&lib_src).expect("Unable to parse file");
1442 let libast = FullLibraryAST::load_lib(lib_syntax);
1444 // ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
1445 // when parsing other file ASTs...
1446 let mut libtypes = CrateTypes { traits: HashMap::new(), opaques: HashMap::new(), mirrored_enums: HashMap::new(),
1447 type_aliases: HashMap::new(), templates_defined: HashMap::default(), template_file: &mut derived_templates,
1448 clonable_types: HashSet::new() };
1449 walk_ast(&libast, &mut libtypes);
1451 // ... finally, do the actual file conversion/mapping, writing out types as we go.
1452 convert_file(&libast, &mut libtypes, &args[1], &args[2], &mut header_file, &mut cpp_header_file);
1454 // For container templates which we created while walking the crate, make sure we add C++
1455 // mapped types so that C++ users can utilize the auto-destructors available.
1456 for (ty, has_destructor) in libtypes.templates_defined.iter() {
1457 write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor);
1459 writeln!(cpp_header_file, "}}").unwrap();
1461 header_file.flush().unwrap();
1462 cpp_header_file.flush().unwrap();
1463 derived_templates.flush().unwrap();