1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE>
5 // or the MIT license <LICENSE-MIT>, at your option.
6 // You may not use this file except in accordance with one or both of these
9 //! Converts a rust crate into a rust crate containing a number of C-exported wrapper functions and
10 //! classes (which is exportable using cbindgen).
11 //! In general, supports convering:
12 //! * structs as a pointer to the underlying type (either owned or not owned),
13 //! * traits as a void-ptr plus a jump table,
14 //! * enums as an equivalent enum with all the inner fields mapped to the mapped types,
15 //! * certain containers (tuples, slices, Vecs, Options, and Results currently) to a concrete
16 //! version of a defined container template.
18 //! It also generates relevant memory-management functions and free-standing functions with
19 //! parameters mapped.
21 use std::collections::{HashMap, hash_map, HashSet};
24 use std::io::{Read, Write};
27 use proc_macro2::{TokenTree, TokenStream, Span};
34 // *************************************
35 // *** Manually-expanded conversions ***
36 // *************************************
38 /// Because we don't expand macros, any code that we need to generated based on their contents has
39 /// to be completely manual. In this case its all just serialization, so its not too hard.
40 fn convert_macro<W: std::io::Write>(w: &mut W, macro_path: &syn::Path, stream: &TokenStream, types: &TypeResolver) {
41 assert_eq!(macro_path.segments.len(), 1);
42 match &format!("{}", macro_path.segments.iter().next().unwrap().ident) as &str {
43 "impl_writeable" | "impl_writeable_len_match" => {
44 let struct_for = if let TokenTree::Ident(i) = stream.clone().into_iter().next().unwrap() { i } else { unimplemented!(); };
45 if let Some(s) = types.maybe_resolve_ident(&struct_for) {
46 if !types.crate_types.opaques.get(&s).is_some() { return; }
47 writeln!(w, "#[no_mangle]").unwrap();
48 writeln!(w, "/// Serialize the {} into a byte array which can be read by {}_read", struct_for, struct_for).unwrap();
49 writeln!(w, "pub extern \"C\" fn {}_write(obj: &{}) -> crate::c_types::derived::CVec_u8Z {{", struct_for, struct_for).unwrap();
50 writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &(*(*obj).inner) }})").unwrap();
51 writeln!(w, "}}").unwrap();
52 writeln!(w, "#[no_mangle]").unwrap();
53 writeln!(w, "pub(crate) extern \"C\" fn {}_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {{", struct_for).unwrap();
54 writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &*(obj as *const native{}) }})", struct_for).unwrap();
55 writeln!(w, "}}").unwrap();
56 writeln!(w, "#[no_mangle]").unwrap();
57 writeln!(w, "/// Read a {} from a byte array, created by {}_write", struct_for, struct_for).unwrap();
58 writeln!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice) -> {} {{", struct_for, struct_for).unwrap();
59 writeln!(w, "\tif let Ok(res) = crate::c_types::deserialize_obj(ser) {{").unwrap();
60 writeln!(w, "\t\t{} {{ inner: Box::into_raw(Box::new(res)), is_owned: true }}", struct_for).unwrap();
61 writeln!(w, "\t}} else {{").unwrap();
62 writeln!(w, "\t\t{} {{ inner: std::ptr::null_mut(), is_owned: true }}", struct_for).unwrap();
63 writeln!(w, "\t}}\n}}").unwrap();
70 /// Convert "impl trait_path for for_ty { .. }" for manually-mapped types (ie (de)serialization)
71 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) {
72 if let Some(t) = types.maybe_resolve_path(&trait_path, Some(generics)) {
75 let mut has_inner = false;
76 if let syn::Type::Path(ref p) = for_ty {
77 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
78 for_obj = format!("{}", ident);
79 full_obj_path = for_obj.clone();
80 has_inner = types.c_type_has_inner_from_path(&types.resolve_path(&p.path, Some(generics)));
83 // We assume that anything that isn't a Path is somehow a generic that ends up in our
84 // derived-types module.
85 let mut for_obj_vec = Vec::new();
86 types.write_c_type(&mut for_obj_vec, for_ty, Some(generics), false);
87 full_obj_path = String::from_utf8(for_obj_vec).unwrap();
88 assert!(full_obj_path.starts_with(TypeResolver::generated_container_path()));
89 for_obj = full_obj_path[TypeResolver::generated_container_path().len() + 2..].into();
93 "util::ser::Writeable" => {
94 writeln!(w, "#[no_mangle]").unwrap();
95 writeln!(w, "/// Serialize the {} object into a byte array which can be read by {}_read", for_obj, for_obj).unwrap();
96 writeln!(w, "pub extern \"C\" fn {}_write(obj: &{}) -> crate::c_types::derived::CVec_u8Z {{", for_obj, full_obj_path).unwrap();
98 let ref_type = syn::Type::Reference(syn::TypeReference {
99 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
100 elem: Box::new(for_ty.clone()) });
101 assert!(!types.write_from_c_conversion_new_var(w, &syn::Ident::new("obj", Span::call_site()), &ref_type, Some(generics)));
103 write!(w, "\tcrate::c_types::serialize_obj(").unwrap();
104 types.write_from_c_conversion_prefix(w, &ref_type, Some(generics));
105 write!(w, "unsafe {{ &*obj }}").unwrap();
106 types.write_from_c_conversion_suffix(w, &ref_type, Some(generics));
107 writeln!(w, ")").unwrap();
109 writeln!(w, "}}").unwrap();
111 writeln!(w, "#[no_mangle]").unwrap();
112 writeln!(w, "pub(crate) extern \"C\" fn {}_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {{", for_obj).unwrap();
113 writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &*(obj as *const native{}) }})", for_obj).unwrap();
114 writeln!(w, "}}").unwrap();
117 "util::ser::Readable"|"util::ser::ReadableArgs" => {
118 // Create the Result<Object, DecodeError> syn::Type
119 let mut err_segs = syn::punctuated::Punctuated::new();
120 err_segs.push(syn::PathSegment { ident: syn::Ident::new("ln", Span::call_site()), arguments: syn::PathArguments::None });
121 err_segs.push(syn::PathSegment { ident: syn::Ident::new("msgs", Span::call_site()), arguments: syn::PathArguments::None });
122 err_segs.push(syn::PathSegment { ident: syn::Ident::new("DecodeError", Span::call_site()), arguments: syn::PathArguments::None });
123 let mut args = syn::punctuated::Punctuated::new();
124 args.push(syn::GenericArgument::Type(for_ty.clone()));
125 args.push(syn::GenericArgument::Type(syn::Type::Path(syn::TypePath {
126 qself: None, path: syn::Path {
127 leading_colon: Some(syn::Token![::](Span::call_site())), segments: err_segs,
130 let mut res_segs = syn::punctuated::Punctuated::new();
131 res_segs.push(syn::PathSegment {
132 ident: syn::Ident::new("Result", Span::call_site()),
133 arguments: syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
134 colon2_token: None, lt_token: syn::Token![<](Span::call_site()), args, gt_token: syn::Token![>](Span::call_site()),
137 let res_ty = syn::Type::Path(syn::TypePath { qself: None, path: syn::Path {
138 leading_colon: None, segments: res_segs } });
140 writeln!(w, "#[no_mangle]").unwrap();
141 writeln!(w, "/// Read a {} from a byte array, created by {}_write", for_obj, for_obj).unwrap();
142 write!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice", for_obj).unwrap();
144 let mut arg_conv = Vec::new();
145 if t == "util::ser::ReadableArgs" {
146 write!(w, ", arg: ").unwrap();
147 assert!(trait_path.leading_colon.is_none());
148 let args_seg = trait_path.segments.iter().last().unwrap();
149 assert_eq!(format!("{}", args_seg.ident), "ReadableArgs");
150 if let syn::PathArguments::AngleBracketed(args) = &args_seg.arguments {
151 assert_eq!(args.args.len(), 1);
152 if let syn::GenericArgument::Type(args_ty) = args.args.iter().next().unwrap() {
153 types.write_c_type(w, args_ty, Some(generics), false);
155 assert!(!types.write_from_c_conversion_new_var(&mut arg_conv, &syn::Ident::new("arg", Span::call_site()), &args_ty, Some(generics)));
157 write!(&mut arg_conv, "\tlet arg_conv = ").unwrap();
158 types.write_from_c_conversion_prefix(&mut arg_conv, &args_ty, Some(generics));
159 write!(&mut arg_conv, "arg").unwrap();
160 types.write_from_c_conversion_suffix(&mut arg_conv, &args_ty, Some(generics));
161 } else { unreachable!(); }
162 } else { unreachable!(); }
164 write!(w, ") -> ").unwrap();
165 types.write_c_type(w, &res_ty, Some(generics), false);
166 writeln!(w, " {{").unwrap();
168 if t == "util::ser::ReadableArgs" {
169 w.write(&arg_conv).unwrap();
170 write!(w, ";\n\tlet res: ").unwrap();
171 // At least in one case we need type annotations here, so provide them.
172 types.write_rust_type(w, Some(generics), &res_ty);
173 writeln!(w, " = crate::c_types::deserialize_obj_arg(ser, arg_conv);").unwrap();
175 writeln!(w, "\tlet res = crate::c_types::deserialize_obj(ser);").unwrap();
177 write!(w, "\t").unwrap();
178 if types.write_to_c_conversion_new_var(w, &syn::Ident::new("res", Span::call_site()), &res_ty, Some(generics), false) {
179 write!(w, "\n\t").unwrap();
181 types.write_to_c_conversion_inline_prefix(w, &res_ty, Some(generics), false);
182 write!(w, "res").unwrap();
183 types.write_to_c_conversion_inline_suffix(w, &res_ty, Some(generics), false);
184 writeln!(w, "\n}}").unwrap();
191 /// Convert "TraitA : TraitB" to a single function name and return type.
193 /// This is (obviously) somewhat over-specialized and only useful for TraitB's that only require a
194 /// single function (eg for serialization).
195 fn convert_trait_impl_field(trait_path: &str) -> (&'static str, String, &'static str) {
197 "util::ser::Writeable" => ("Serialize the object into a byte array", "write".to_owned(), "crate::c_types::derived::CVec_u8Z"),
198 _ => unimplemented!(),
202 /// Companion to convert_trait_impl_field, write an assignment for the function defined by it for
203 /// `for_obj` which implements the the trait at `trait_path`.
204 fn write_trait_impl_field_assign<W: std::io::Write>(w: &mut W, trait_path: &str, for_obj: &syn::Ident) {
206 "util::ser::Writeable" => {
207 writeln!(w, "\t\twrite: {}_write_void,", for_obj).unwrap();
209 _ => unimplemented!(),
213 /// Write out the impl block for a defined trait struct which has a supertrait
214 fn do_write_impl_trait<W: std::io::Write>(w: &mut W, trait_path: &str, trait_name: &syn::Ident, for_obj: &str) {
216 "util::events::MessageSendEventsProvider" => {
217 writeln!(w, "impl lightning::{} for {} {{", trait_path, for_obj).unwrap();
218 writeln!(w, "\tfn get_and_clear_pending_msg_events(&self) -> Vec<lightning::util::events::MessageSendEvent> {{").unwrap();
219 writeln!(w, "\t\t<crate::{} as lightning::{}>::get_and_clear_pending_msg_events(&self.{})", trait_path, trait_path, trait_name).unwrap();
220 writeln!(w, "\t}}\n}}").unwrap();
222 "util::ser::Writeable" => {
223 writeln!(w, "impl lightning::{} for {} {{", trait_path, for_obj).unwrap();
224 writeln!(w, "\tfn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {{").unwrap();
225 writeln!(w, "\t\tlet vec = (self.write)(self.this_arg);").unwrap();
226 writeln!(w, "\t\tw.write_all(vec.as_slice())").unwrap();
227 writeln!(w, "\t}}\n}}").unwrap();
233 // *******************************
234 // *** Per-Type Printing Logic ***
235 // *******************************
237 macro_rules! walk_supertraits { ($t: expr, $types: expr, ($( $pat: pat => $e: expr),*) ) => { {
238 if $t.colon_token.is_some() {
239 for st in $t.supertraits.iter() {
241 syn::TypeParamBound::Trait(supertrait) => {
242 if supertrait.paren_token.is_some() || supertrait.lifetimes.is_some() {
245 // First try to resolve path to find in-crate traits, but if that doesn't work
246 // assume its a prelude trait (eg Clone, etc) and just use the single ident.
247 let types_opt: Option<&TypeResolver> = $types;
248 if let Some(types) = types_opt {
249 if let Some(path) = types.maybe_resolve_path(&supertrait.path, None) {
250 match (&path as &str, &supertrait.path.segments.iter().last().unwrap().ident) {
256 if let Some(ident) = supertrait.path.get_ident() {
257 match (&format!("{}", ident) as &str, &ident) {
260 } else if types_opt.is_some() {
261 panic!("Supertrait unresolvable and not single-ident");
264 syn::TypeParamBound::Lifetime(_) => unimplemented!(),
270 /// Prints a C-mapped trait object containing a void pointer and a jump table for each function in
271 /// the original trait.
272 /// Implements the native Rust trait and relevant parent traits for the new C-mapped trait.
274 /// Finally, implements Deref<MappedTrait> for MappedTrait which allows its use in types which need
275 /// a concrete Deref to the Rust trait.
276 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) {
277 let trait_name = format!("{}", t.ident);
278 match export_status(&t.attrs) {
279 ExportStatus::Export => {},
280 ExportStatus::NoExport|ExportStatus::TestOnly => return,
282 writeln_docs(w, &t.attrs, "");
284 let mut gen_types = GenericTypes::new();
285 assert!(gen_types.learn_generics(&t.generics, types));
286 gen_types.learn_associated_types(&t, types);
288 writeln!(w, "#[repr(C)]\npub struct {} {{", trait_name).unwrap();
289 writeln!(w, "\t/// An opaque pointer which is passed to your function implementations as an argument.").unwrap();
290 writeln!(w, "\t/// This has no meaning in the LDK, and can be NULL or any other value.").unwrap();
291 writeln!(w, "\tpub this_arg: *mut c_void,").unwrap();
292 let mut generated_fields = Vec::new(); // Every field's (name, is_clonable) except this_arg, used in Clone generation
293 for item in t.items.iter() {
295 &syn::TraitItem::Method(ref m) => {
296 match export_status(&m.attrs) {
297 ExportStatus::NoExport => {
298 // NoExport in this context means we'll hit an unimplemented!() at runtime,
302 ExportStatus::Export => {},
303 ExportStatus::TestOnly => continue,
305 if m.default.is_some() { unimplemented!(); }
307 gen_types.push_ctx();
308 assert!(gen_types.learn_generics(&m.sig.generics, types));
310 writeln_docs(w, &m.attrs, "\t");
312 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
313 if let syn::Type::Reference(r) = &**rtype {
314 // We have to do quite a dance for trait functions which return references
315 // - they ultimately require us to have a native Rust object stored inside
316 // our concrete trait to return a reference to. However, users may wish to
317 // update the value to be returned each time the function is called (or, to
318 // make C copies of Rust impls equivalent, we have to be able to).
320 // Thus, we store a copy of the C-mapped type (which is just a pointer to
321 // the Rust type and a flag to indicate whether deallocation needs to
322 // happen) as well as provide an Option<>al function pointer which is
323 // called when the trait method is called which allows updating on the fly.
324 write!(w, "\tpub {}: ", m.sig.ident).unwrap();
325 generated_fields.push((format!("{}", m.sig.ident), true));
326 types.write_c_type(w, &*r.elem, Some(&gen_types), false);
327 writeln!(w, ",").unwrap();
328 writeln!(w, "\t/// Fill in the {} field as a reference to it will be given to Rust after this returns", m.sig.ident).unwrap();
329 writeln!(w, "\t/// Note that this takes a pointer to this object, not the this_ptr like other methods do").unwrap();
330 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();
331 writeln!(w, "\tpub set_{}: Option<extern \"C\" fn(&{})>,", m.sig.ident, trait_name).unwrap();
332 generated_fields.push((format!("set_{}", m.sig.ident), true));
333 // Note that cbindgen will now generate
334 // typedef struct Thing {..., set_thing: (const Thing*), ...} Thing;
335 // which does not compile since Thing is not defined before it is used.
336 writeln!(extra_headers, "struct LDK{};", trait_name).unwrap();
337 writeln!(extra_headers, "typedef struct LDK{} LDK{};", trait_name, trait_name).unwrap();
341 // Sadly, this currently doesn't do what we want, but it should be easy to get
342 // cbindgen to support it. See https://github.com/eqrion/cbindgen/issues/531
343 writeln!(w, "\t#[must_use]").unwrap();
346 write!(w, "\tpub {}: extern \"C\" fn (", m.sig.ident).unwrap();
347 generated_fields.push((format!("{}", m.sig.ident), true));
348 write_method_params(w, &m.sig, "c_void", types, Some(&gen_types), true, false);
349 writeln!(w, ",").unwrap();
353 &syn::TraitItem::Type(_) => {},
354 _ => unimplemented!(),
357 // Add functions which may be required for supertrait implementations.
358 let mut requires_clone = false;
359 walk_supertraits!(t, Some(&types), (
360 ("Clone", _) => requires_clone = true,
363 walk_supertraits!(t, Some(&types), (
365 writeln!(w, "\t/// Creates a copy of the object pointed to by this_arg, for a copy of this {}.", trait_name).unwrap();
366 writeln!(w, "\t/// Note that the ultimate copy of the {} will have all function pointers the same as the original.", trait_name).unwrap();
367 writeln!(w, "\t/// May be NULL if no action needs to be taken, the this_arg pointer will be copied into the new {}.", trait_name).unwrap();
368 writeln!(w, "\tpub clone: Option<extern \"C\" fn (this_arg: *const c_void) -> *mut c_void>,").unwrap();
369 generated_fields.push(("clone".to_owned(), true));
371 ("std::cmp::Eq", _) => {
372 writeln!(w, "\t/// Checks if two objects are equal given this object's this_arg pointer and another object.").unwrap();
373 writeln!(w, "\tpub eq: extern \"C\" fn (this_arg: *const c_void, other_arg: &{}) -> bool,", trait_name).unwrap();
374 writeln!(extra_headers, "typedef struct LDK{} LDK{};", trait_name, trait_name).unwrap();
375 generated_fields.push(("eq".to_owned(), true));
377 ("std::hash::Hash", _) => {
378 writeln!(w, "\t/// Calculate a succinct non-cryptographic hash for an object given its this_arg pointer.").unwrap();
379 writeln!(w, "\t/// This is used, for example, for inclusion of this object in a hash map.").unwrap();
380 writeln!(w, "\tpub hash: extern \"C\" fn (this_arg: *const c_void) -> u64,").unwrap();
381 generated_fields.push(("hash".to_owned(), true));
383 ("Send", _) => {}, ("Sync", _) => {},
385 generated_fields.push(if types.crate_types.traits.get(s).is_none() {
386 let (docs, name, ret) = convert_trait_impl_field(s);
387 writeln!(w, "\t/// {}", docs).unwrap();
388 writeln!(w, "\tpub {}: extern \"C\" fn (this_arg: *const c_void) -> {},", name, ret).unwrap();
389 (name, true) // Assume clonable
391 // For in-crate supertraits, just store a C-mapped copy of the supertrait as a member.
392 writeln!(w, "\t/// Implementation of {} for this object.", i).unwrap();
393 writeln!(w, "\tpub {}: crate::{},", i, s).unwrap();
394 let is_clonable = types.is_clonable(s);
395 if !is_clonable && requires_clone {
396 writeln!(w, "\t/// Creates a copy of the {}, for a copy of this {}.", i, trait_name).unwrap();
397 writeln!(w, "\t/// Because {} doesn't natively support copying itself, you have to provide a full copy implementation here.", i).unwrap();
398 writeln!(w, "\tpub {}_clone: extern \"C\" fn (orig_{}: &{}) -> {},", i, i, i, i).unwrap();
400 (format!("{}", i), is_clonable)
404 writeln!(w, "\t/// Frees any resources associated with this object given its this_arg pointer.").unwrap();
405 writeln!(w, "\t/// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.").unwrap();
406 writeln!(w, "\tpub free: Option<extern \"C\" fn(this_arg: *mut c_void)>,").unwrap();
407 generated_fields.push(("free".to_owned(), true));
408 writeln!(w, "}}").unwrap();
410 macro_rules! impl_trait_for_c {
411 ($t: expr, $impl_accessor: expr) => {
412 for item in $t.items.iter() {
414 syn::TraitItem::Method(m) => {
415 if let ExportStatus::TestOnly = export_status(&m.attrs) { continue; }
416 if m.default.is_some() { unimplemented!(); }
417 if m.sig.constness.is_some() || m.sig.asyncness.is_some() || m.sig.unsafety.is_some() ||
418 m.sig.abi.is_some() || m.sig.variadic.is_some() {
421 gen_types.push_ctx();
422 assert!(gen_types.learn_generics(&m.sig.generics, types));
423 write!(w, "\tfn {}", m.sig.ident).unwrap();
424 types.write_rust_generic_param(w, Some(&gen_types), m.sig.generics.params.iter());
425 write!(w, "(").unwrap();
426 for inp in m.sig.inputs.iter() {
428 syn::FnArg::Receiver(recv) => {
429 if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
430 write!(w, "&").unwrap();
431 if let Some(lft) = &recv.reference.as_ref().unwrap().1 {
432 write!(w, "'{} ", lft.ident).unwrap();
434 if recv.mutability.is_some() {
435 write!(w, "mut self").unwrap();
437 write!(w, "self").unwrap();
440 syn::FnArg::Typed(arg) => {
441 if !arg.attrs.is_empty() { unimplemented!(); }
443 syn::Pat::Ident(ident) => {
444 if !ident.attrs.is_empty() || ident.by_ref.is_some() ||
445 ident.mutability.is_some() || ident.subpat.is_some() {
448 write!(w, ", {}{}: ", if types.skip_arg(&*arg.ty, Some(&gen_types)) { "_" } else { "" }, ident.ident).unwrap();
450 _ => unimplemented!(),
452 types.write_rust_type(w, Some(&gen_types), &*arg.ty);
456 write!(w, ")").unwrap();
457 match &m.sig.output {
458 syn::ReturnType::Type(_, rtype) => {
459 write!(w, " -> ").unwrap();
460 types.write_rust_type(w, Some(&gen_types), &*rtype)
464 write!(w, " {{\n\t\t").unwrap();
465 match export_status(&m.attrs) {
466 ExportStatus::NoExport => {
471 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
472 if let syn::Type::Reference(r) = &**rtype {
473 assert_eq!(m.sig.inputs.len(), 1); // Must only take self!
474 writeln!(w, "if let Some(f) = self{}.set_{} {{", $impl_accessor, m.sig.ident).unwrap();
475 writeln!(w, "\t\t\t(f)(&self{});", $impl_accessor).unwrap();
476 write!(w, "\t\t}}\n\t\t").unwrap();
477 types.write_from_c_conversion_to_ref_prefix(w, &*r.elem, Some(&gen_types));
478 write!(w, "self{}.{}", $impl_accessor, m.sig.ident).unwrap();
479 types.write_from_c_conversion_to_ref_suffix(w, &*r.elem, Some(&gen_types));
480 writeln!(w, "\n\t}}").unwrap();
485 write_method_var_decl_body(w, &m.sig, "\t", types, Some(&gen_types), true);
486 write!(w, "(self{}.{})(", $impl_accessor, m.sig.ident).unwrap();
487 write_method_call_params(w, &m.sig, "\t", types, Some(&gen_types), "", true);
489 writeln!(w, "\n\t}}").unwrap();
492 &syn::TraitItem::Type(ref t) => {
493 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
494 let mut bounds_iter = t.bounds.iter();
495 match bounds_iter.next().unwrap() {
496 syn::TypeParamBound::Trait(tr) => {
497 writeln!(w, "\ttype {} = crate::{};", t.ident, types.resolve_path(&tr.path, Some(&gen_types))).unwrap();
499 _ => unimplemented!(),
501 if bounds_iter.next().is_some() { unimplemented!(); }
503 _ => unimplemented!(),
510 // Implement supertraits for the C-mapped struct.
511 walk_supertraits!(t, Some(&types), (
512 ("Send", _) => writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap(),
513 ("Sync", _) => writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap(),
514 ("std::cmp::Eq", _) => {
515 writeln!(w, "impl std::cmp::Eq for {} {{}}", trait_name).unwrap();
516 writeln!(w, "impl std::cmp::PartialEq for {} {{", trait_name).unwrap();
517 writeln!(w, "\tfn eq(&self, o: &Self) -> bool {{ (self.eq)(self.this_arg, o) }}\n}}").unwrap();
519 ("std::hash::Hash", _) => {
520 writeln!(w, "impl std::hash::Hash for {} {{", trait_name).unwrap();
521 writeln!(w, "\tfn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {{ hasher.write_u64((self.hash)(self.this_arg)) }}\n}}").unwrap();
524 writeln!(w, "#[no_mangle]").unwrap();
525 writeln!(w, "/// Creates a copy of a {}", trait_name).unwrap();
526 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", trait_name, trait_name, trait_name).unwrap();
527 writeln!(w, "\t{} {{", trait_name).unwrap();
528 writeln!(w, "\t\tthis_arg: if let Some(f) = orig.clone {{ (f)(orig.this_arg) }} else {{ orig.this_arg }},").unwrap();
529 for (field, clonable) in generated_fields.iter() {
531 writeln!(w, "\t\t{}: Clone::clone(&orig.{}),", field, field).unwrap();
533 writeln!(w, "\t\t{}: (orig.{}_clone)(&orig.{}),", field, field, field).unwrap();
534 writeln!(w, "\t\t{}_clone: orig.{}_clone,", field, field).unwrap();
537 writeln!(w, "\t}}\n}}").unwrap();
538 writeln!(w, "impl Clone for {} {{", trait_name).unwrap();
539 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
540 writeln!(w, "\t\t{}_clone(self)", trait_name).unwrap();
541 writeln!(w, "\t}}\n}}").unwrap();
544 if let Some(supertrait) = types.crate_types.traits.get(s) {
545 writeln!(w, "impl lightning::{} for {} {{", s, trait_name).unwrap(); // TODO: Drop hard-coded crate name here
546 impl_trait_for_c!(supertrait, format!(".{}", i));
547 writeln!(w, "}}").unwrap();
548 walk_supertraits!(supertrait, Some(&types), (
549 ("Send", _) => writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap(),
550 ("Sync", _) => writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap(),
551 _ => unimplemented!()
554 do_write_impl_trait(w, s, i, &trait_name);
559 // Finally, implement the original Rust trait for the newly created mapped trait.
560 writeln!(w, "\nuse {}::{}::{} as rust{};", types.orig_crate, types.module_path, t.ident, trait_name).unwrap();
561 write!(w, "impl rust{}", t.ident).unwrap();
562 maybe_write_generics(w, &t.generics, types, false);
563 writeln!(w, " for {} {{", trait_name).unwrap();
564 impl_trait_for_c!(t, "");
565 writeln!(w, "}}\n").unwrap();
566 writeln!(w, "// We're essentially a pointer already, or at least a set of pointers, so allow us to be used").unwrap();
567 writeln!(w, "// directly as a Deref trait in higher-level structs:").unwrap();
568 writeln!(w, "impl std::ops::Deref for {} {{\n\ttype Target = Self;", trait_name).unwrap();
569 writeln!(w, "\tfn deref(&self) -> &Self {{\n\t\tself\n\t}}\n}}").unwrap();
571 writeln!(w, "/// Calls the free function if one is set").unwrap();
572 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", trait_name, trait_name).unwrap();
573 writeln!(w, "impl Drop for {} {{", trait_name).unwrap();
574 writeln!(w, "\tfn drop(&mut self) {{").unwrap();
575 writeln!(w, "\t\tif let Some(f) = self.free {{").unwrap();
576 writeln!(w, "\t\t\tf(self.this_arg);").unwrap();
577 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
579 write_cpp_wrapper(cpp_headers, &trait_name, true);
582 /// Write out a simple "opaque" type (eg structs) which contain a pointer to the native Rust type
583 /// and a flag to indicate whether Drop'ing the mapped struct drops the underlying Rust type.
585 /// Also writes out a _free function and a C++ wrapper which handles calling _free.
586 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) {
587 // If we directly read the original type by its original name, cbindgen hits
588 // https://github.com/eqrion/cbindgen/issues/286 Thus, instead, we import it as a temporary
589 // name and then reference it by that name, which works around the issue.
590 write!(w, "\nuse {}::{}::{} as native{}Import;\ntype native{} = native{}Import", types.orig_crate, types.module_path, ident, ident, ident, ident).unwrap();
591 maybe_write_generics(w, &generics, &types, true);
592 writeln!(w, ";\n").unwrap();
593 writeln!(extra_headers, "struct native{}Opaque;\ntypedef struct native{}Opaque LDKnative{};", ident, ident, ident).unwrap();
594 writeln_docs(w, &attrs, "");
595 writeln!(w, "#[must_use]\n#[repr(C)]\npub struct {} {{", struct_name).unwrap();
596 writeln!(w, "\t/// A pointer to the opaque Rust object.\n").unwrap();
597 writeln!(w, "\t/// Nearly everywhere, inner must be non-null, however in places where").unwrap();
598 writeln!(w, "\t/// the Rust equivalent takes an Option, it may be set to null to indicate None.").unwrap();
599 writeln!(w, "\tpub inner: *mut native{},", ident).unwrap();
600 writeln!(w, "\t/// Indicates that this is the only struct which contains the same pointer.\n").unwrap();
601 writeln!(w, "\t/// Rust functions which take ownership of an object provided via an argument require").unwrap();
602 writeln!(w, "\t/// this to be true and invalidate the object pointed to by inner.").unwrap();
603 writeln!(w, "\tpub is_owned: bool,").unwrap();
604 writeln!(w, "}}\n").unwrap();
605 writeln!(w, "impl Drop for {} {{\n\tfn drop(&mut self) {{", struct_name).unwrap();
606 writeln!(w, "\t\tif self.is_owned && !<*mut native{}>::is_null(self.inner) {{", ident).unwrap();
607 writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(self.inner) }};\n\t\t}}\n\t}}\n}}").unwrap();
608 writeln!(w, "/// Frees any resources used by the {}, if is_owned is set and inner is non-NULL.", struct_name).unwrap();
609 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_obj: {}) {{ }}", struct_name, struct_name).unwrap();
610 writeln!(w, "#[allow(unused)]").unwrap();
611 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
612 writeln!(w, "extern \"C\" fn {}_free_void(this_ptr: *mut c_void) {{", struct_name).unwrap();
613 writeln!(w, "\tunsafe {{ let _ = Box::from_raw(this_ptr as *mut native{}); }}\n}}", struct_name).unwrap();
614 writeln!(w, "#[allow(unused)]").unwrap();
615 writeln!(w, "/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy").unwrap();
616 writeln!(w, "impl {} {{", struct_name).unwrap();
617 writeln!(w, "\tpub(crate) fn take_inner(mut self) -> *mut native{} {{", struct_name).unwrap();
618 writeln!(w, "\t\tassert!(self.is_owned);").unwrap();
619 writeln!(w, "\t\tlet ret = self.inner;").unwrap();
620 writeln!(w, "\t\tself.inner = std::ptr::null_mut();").unwrap();
621 writeln!(w, "\t\tret").unwrap();
622 writeln!(w, "\t}}\n}}").unwrap();
624 write_cpp_wrapper(cpp_headers, &format!("{}", ident), true);
627 /// Writes out all the relevant mappings for a Rust struct, deferring to writeln_opaque to generate
628 /// the struct itself, and then writing getters and setters for public, understood-type fields and
629 /// a constructor if every field is public.
630 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) {
631 if export_status(&s.attrs) != ExportStatus::Export { return; }
633 let struct_name = &format!("{}", s.ident);
634 writeln_opaque(w, &s.ident, struct_name, &s.generics, &s.attrs, types, extra_headers, cpp_headers);
636 if let syn::Fields::Named(fields) = &s.fields {
637 let mut gen_types = GenericTypes::new();
638 assert!(gen_types.learn_generics(&s.generics, types));
640 let mut all_fields_settable = true;
641 for field in fields.named.iter() {
642 if let syn::Visibility::Public(_) = field.vis {
643 let export = export_status(&field.attrs);
645 ExportStatus::Export => {},
646 ExportStatus::NoExport|ExportStatus::TestOnly => {
647 all_fields_settable = false;
652 if let Some(ident) = &field.ident {
653 let ref_type = syn::Type::Reference(syn::TypeReference {
654 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
655 elem: Box::new(field.ty.clone()) });
656 if types.understood_c_type(&ref_type, Some(&gen_types)) {
657 writeln_docs(w, &field.attrs, "");
658 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> ", struct_name, ident, struct_name).unwrap();
659 types.write_c_type(w, &ref_type, Some(&gen_types), true);
660 write!(w, " {{\n\tlet mut inner_val = &mut unsafe {{ &mut *this_ptr.inner }}.{};\n\t", ident).unwrap();
661 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);
662 if local_var { write!(w, "\n\t").unwrap(); }
663 types.write_to_c_conversion_inline_prefix(w, &ref_type, Some(&gen_types), true);
665 write!(w, "inner_val").unwrap();
667 write!(w, "(*inner_val)").unwrap();
669 types.write_to_c_conversion_inline_suffix(w, &ref_type, Some(&gen_types), true);
670 writeln!(w, "\n}}").unwrap();
673 if types.understood_c_type(&field.ty, Some(&gen_types)) {
674 writeln_docs(w, &field.attrs, "");
675 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_set_{}(this_ptr: &mut {}, mut val: ", struct_name, ident, struct_name).unwrap();
676 types.write_c_type(w, &field.ty, Some(&gen_types), false);
677 write!(w, ") {{\n\t").unwrap();
678 let local_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("val", Span::call_site()), &field.ty, Some(&gen_types));
679 if local_var { write!(w, "\n\t").unwrap(); }
680 write!(w, "unsafe {{ &mut *this_ptr.inner }}.{} = ", ident).unwrap();
681 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
682 write!(w, "val").unwrap();
683 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
684 writeln!(w, ";\n}}").unwrap();
685 } else { all_fields_settable = false; }
686 } else { all_fields_settable = false; }
687 } else { all_fields_settable = false; }
690 if all_fields_settable {
691 // Build a constructor!
692 writeln!(w, "/// Constructs a new {} given each field", struct_name).unwrap();
693 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_new(", struct_name).unwrap();
694 for (idx, field) in fields.named.iter().enumerate() {
695 if idx != 0 { write!(w, ", ").unwrap(); }
696 write!(w, "mut {}_arg: ", field.ident.as_ref().unwrap()).unwrap();
697 types.write_c_type(w, &field.ty, Some(&gen_types), false);
699 write!(w, ") -> {} {{\n\t", struct_name).unwrap();
700 for field in fields.named.iter() {
701 let field_name = format!("{}_arg", field.ident.as_ref().unwrap());
702 if types.write_from_c_conversion_new_var(w, &syn::Ident::new(&field_name, Span::call_site()), &field.ty, Some(&gen_types)) {
703 write!(w, "\n\t").unwrap();
706 writeln!(w, "{} {{ inner: Box::into_raw(Box::new(native{} {{", struct_name, s.ident).unwrap();
707 for field in fields.named.iter() {
708 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
709 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
710 write!(w, "{}_arg", field.ident.as_ref().unwrap()).unwrap();
711 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
712 writeln!(w, ",").unwrap();
714 writeln!(w, "\t}})), is_owned: true }}\n}}").unwrap();
719 /// Prints a relevant conversion for impl *
721 /// For simple impl Struct {}s, this just outputs the wrapper functions as Struct_fn_name() { .. }.
723 /// For impl Trait for Struct{}s, this non-exported generates wrapper functions as
724 /// Trait_Struct_fn_name and a Struct_as_Trait(&struct) -> Trait function which returns a populated
725 /// Trait struct containing a pointer to the passed struct's inner field and the wrapper functions.
727 /// A few non-crate Traits are hard-coded including Default.
728 fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut TypeResolver) {
729 match export_status(&i.attrs) {
730 ExportStatus::Export => {},
731 ExportStatus::NoExport|ExportStatus::TestOnly => return,
734 if let syn::Type::Tuple(_) = &*i.self_ty {
735 if types.understood_c_type(&*i.self_ty, None) {
736 let mut gen_types = GenericTypes::new();
737 if !gen_types.learn_generics(&i.generics, types) {
738 eprintln!("Not implementing anything for `impl (..)` due to not understood generics");
742 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
743 if let Some(trait_path) = i.trait_.as_ref() {
744 if trait_path.0.is_some() { unimplemented!(); }
745 if types.understood_c_path(&trait_path.1) {
746 eprintln!("Not implementing anything for `impl Trait for (..)` - we only support manual defines");
749 // Just do a manual implementation:
750 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
753 eprintln!("Not implementing anything for plain `impl (..)` block - we only support `impl Trait for (..)` blocks");
759 if let &syn::Type::Path(ref p) = &*i.self_ty {
760 if p.qself.is_some() { unimplemented!(); }
761 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
762 if let Some(resolved_path) = types.maybe_resolve_non_ignored_ident(&ident) {
763 let mut gen_types = GenericTypes::new();
764 if !gen_types.learn_generics(&i.generics, types) {
765 eprintln!("Not implementing anything for impl {} due to not understood generics", ident);
769 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
770 if let Some(trait_path) = i.trait_.as_ref() {
771 if trait_path.0.is_some() { unimplemented!(); }
772 if types.understood_c_path(&trait_path.1) {
773 let full_trait_path = types.resolve_path(&trait_path.1, None);
774 let trait_obj = *types.crate_types.traits.get(&full_trait_path).unwrap();
775 // We learn the associated types maping from the original trait object.
776 // That's great, except that they are unresolved idents, so if we learn
777 // mappings from a trai defined in a different file, we may mis-resolve or
778 // fail to resolve the mapped types.
779 gen_types.learn_associated_types(trait_obj, types);
780 let mut impl_associated_types = HashMap::new();
781 for item in i.items.iter() {
783 syn::ImplItem::Type(t) => {
784 if let syn::Type::Path(p) = &t.ty {
785 if let Some(id) = single_ident_generic_path_to_ident(&p.path) {
786 impl_associated_types.insert(&t.ident, id);
794 let export = export_status(&trait_obj.attrs);
796 ExportStatus::Export => {},
797 ExportStatus::NoExport|ExportStatus::TestOnly => return,
800 // For cases where we have a concrete native object which implements a
801 // trait and need to return the C-mapped version of the trait, provide a
802 // From<> implementation which does all the work to ensure free is handled
803 // properly. This way we can call this method from deep in the
804 // type-conversion logic without actually knowing the concrete native type.
805 writeln!(w, "impl From<native{}> for crate::{} {{", ident, full_trait_path).unwrap();
806 writeln!(w, "\tfn from(obj: native{}) -> Self {{", ident).unwrap();
807 writeln!(w, "\t\tlet mut rust_obj = {} {{ inner: Box::into_raw(Box::new(obj)), is_owned: true }};", ident).unwrap();
808 writeln!(w, "\t\tlet mut ret = {}_as_{}(&rust_obj);", ident, trait_obj.ident).unwrap();
809 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();
810 writeln!(w, "\t\trust_obj.inner = std::ptr::null_mut();").unwrap();
811 writeln!(w, "\t\tret.free = Some({}_free_void);", ident).unwrap();
812 writeln!(w, "\t\tret\n\t}}\n}}").unwrap();
814 writeln!(w, "/// Constructs a new {} which calls the relevant methods on this_arg.", trait_obj.ident).unwrap();
815 writeln!(w, "/// This copies the `inner` pointer in this_arg and thus the returned {} must be freed before this_arg is", trait_obj.ident).unwrap();
816 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_as_{}(this_arg: &{}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
817 writeln!(w, "\tcrate::{} {{", full_trait_path).unwrap();
818 writeln!(w, "\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
819 writeln!(w, "\t\tfree: None,").unwrap();
821 macro_rules! write_meth {
822 ($m: expr, $trait: expr, $indent: expr) => {
823 let trait_method = $trait.items.iter().filter_map(|item| {
824 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
825 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
826 match export_status(&trait_method.attrs) {
827 ExportStatus::Export => {},
828 ExportStatus::NoExport => {
829 write!(w, "{}\t\t//XXX: Need to export {}\n", $indent, $m.sig.ident).unwrap();
832 ExportStatus::TestOnly => continue,
835 let mut printed = false;
836 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
837 if let syn::Type::Reference(r) = &**rtype {
838 write!(w, "\n\t\t{}{}: ", $indent, $m.sig.ident).unwrap();
839 types.write_empty_rust_val(Some(&gen_types), w, &*r.elem);
840 writeln!(w, ",\n{}\t\tset_{}: Some({}_{}_set_{}),", $indent, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
845 write!(w, "{}\t\t{}: {}_{}_{},\n", $indent, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
849 for item in trait_obj.items.iter() {
851 syn::TraitItem::Method(m) => {
852 write_meth!(m, trait_obj, "");
857 let mut requires_clone = false;
858 walk_supertraits!(trait_obj, Some(&types), (
859 ("Clone", _) => requires_clone = true,
862 walk_supertraits!(trait_obj, Some(&types), (
864 writeln!(w, "\t\tclone: Some({}_clone_void),", ident).unwrap();
866 ("Sync", _) => {}, ("Send", _) => {},
867 ("std::marker::Sync", _) => {}, ("std::marker::Send", _) => {},
869 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
870 writeln!(w, "\t\t{}: crate::{} {{", t, s).unwrap();
871 writeln!(w, "\t\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
872 writeln!(w, "\t\t\tfree: None,").unwrap();
873 for item in supertrait_obj.items.iter() {
875 syn::TraitItem::Method(m) => {
876 write_meth!(m, supertrait_obj, "\t");
881 write!(w, "\t\t}},\n").unwrap();
882 if !types.is_clonable(s) && requires_clone {
883 writeln!(w, "\t\t{}_clone: {}_{}_clone,", t, ident, t).unwrap();
886 write_trait_impl_field_assign(w, s, ident);
890 writeln!(w, "\t}}\n}}\n").unwrap();
892 macro_rules! impl_meth {
893 ($m: expr, $trait_path: expr, $trait: expr, $indent: expr) => {
894 let trait_method = $trait.items.iter().filter_map(|item| {
895 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
896 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
897 match export_status(&trait_method.attrs) {
898 ExportStatus::Export => {},
899 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
902 if let syn::ReturnType::Type(_, _) = &$m.sig.output {
903 writeln!(w, "#[must_use]").unwrap();
905 write!(w, "extern \"C\" fn {}_{}_{}(", ident, $trait.ident, $m.sig.ident).unwrap();
906 gen_types.push_ctx();
907 assert!(gen_types.learn_generics(&$m.sig.generics, types));
908 write_method_params(w, &$m.sig, "c_void", types, Some(&gen_types), true, true);
909 write!(w, " {{\n\t").unwrap();
910 write_method_var_decl_body(w, &$m.sig, "", types, Some(&gen_types), false);
911 let mut takes_self = false;
912 for inp in $m.sig.inputs.iter() {
913 if let syn::FnArg::Receiver(_) = inp {
918 let mut t_gen_args = String::new();
919 for (idx, _) in $trait.generics.params.iter().enumerate() {
920 if idx != 0 { t_gen_args += ", " };
924 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();
926 write!(w, "<native{} as {}::{}<{}>>::{}(", ident, types.orig_crate, $trait_path, t_gen_args, $m.sig.ident).unwrap();
929 let mut real_type = "".to_string();
930 match &$m.sig.output {
931 syn::ReturnType::Type(_, rtype) => {
932 if let Some(mut remaining_path) = first_seg_self(&*rtype) {
933 if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
934 real_type = format!("{}", impl_associated_types.get(associated_seg).unwrap());
940 write_method_call_params(w, &$m.sig, "", types, Some(&gen_types), &real_type, false);
942 write!(w, "\n}}\n").unwrap();
943 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
944 if let syn::Type::Reference(r) = &**rtype {
945 assert_eq!($m.sig.inputs.len(), 1); // Must only take self
946 writeln!(w, "extern \"C\" fn {}_{}_set_{}(trait_self_arg: &{}) {{", ident, $trait.ident, $m.sig.ident, $trait.ident).unwrap();
947 writeln!(w, "\t// This is a bit race-y in the general case, but for our specific use-cases today, we're safe").unwrap();
948 writeln!(w, "\t// Specifically, we must ensure that the first time we're called it can never be in parallel").unwrap();
949 write!(w, "\tif ").unwrap();
950 types.write_empty_rust_val_check(Some(&gen_types), w, &*r.elem, &format!("trait_self_arg.{}", $m.sig.ident));
951 writeln!(w, " {{").unwrap();
952 writeln!(w, "\t\tunsafe {{ &mut *(trait_self_arg as *const {} as *mut {}) }}.{} = {}_{}_{}(trait_self_arg.this_arg);", $trait.ident, $trait.ident, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
953 writeln!(w, "\t}}").unwrap();
954 writeln!(w, "}}").unwrap();
960 for item in i.items.iter() {
962 syn::ImplItem::Method(m) => {
963 impl_meth!(m, full_trait_path, trait_obj, "");
965 syn::ImplItem::Type(_) => {},
966 _ => unimplemented!(),
969 walk_supertraits!(trait_obj, Some(&types), (
971 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
972 if !types.is_clonable(s) && requires_clone {
973 writeln!(w, "extern \"C\" fn {}_{}_clone(orig: &crate::{}) -> crate::{} {{", ident, t, s, s).unwrap();
974 writeln!(w, "\tcrate::{} {{", s).unwrap();
975 writeln!(w, "\t\tthis_arg: orig.this_arg,").unwrap();
976 writeln!(w, "\t\tfree: None,").unwrap();
977 for item in supertrait_obj.items.iter() {
979 syn::TraitItem::Method(m) => {
980 write_meth!(m, supertrait_obj, "");
985 write!(w, "\t}}\n}}\n").unwrap();
990 write!(w, "\n").unwrap();
991 } else if path_matches_nongeneric(&trait_path.1, &["From"]) {
992 } else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
993 writeln!(w, "/// Creates a \"default\" {}. See struct and individual field documentaiton for details on which values are used.", ident).unwrap();
994 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
995 write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
996 write!(w, "}}\n").unwrap();
997 } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "PartialEq"]) {
998 } else if (path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) || path_matches_nongeneric(&trait_path.1, &["Clone"])) &&
999 types.c_type_has_inner_from_path(&resolved_path) {
1000 writeln!(w, "impl Clone for {} {{", ident).unwrap();
1001 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
1002 writeln!(w, "\t\tSelf {{").unwrap();
1003 writeln!(w, "\t\t\tinner: if <*mut native{}>::is_null(self.inner) {{ std::ptr::null_mut() }} else {{", ident).unwrap();
1004 writeln!(w, "\t\t\t\tBox::into_raw(Box::new(unsafe {{ &*self.inner }}.clone())) }},").unwrap();
1005 writeln!(w, "\t\t\tis_owned: true,").unwrap();
1006 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
1007 writeln!(w, "#[allow(unused)]").unwrap();
1008 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
1009 writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", ident).unwrap();
1010 writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", ident).unwrap();
1011 writeln!(w, "}}").unwrap();
1012 writeln!(w, "#[no_mangle]").unwrap();
1013 writeln!(w, "/// Creates a copy of the {}", ident).unwrap();
1014 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", ident, ident, ident).unwrap();
1015 writeln!(w, "\torig.clone()").unwrap();
1016 writeln!(w, "}}").unwrap();
1018 //XXX: implement for other things like ToString
1019 // If we have no generics, try a manual implementation:
1020 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
1023 let declared_type = (*types.get_declared_type(&ident).unwrap()).clone();
1024 for item in i.items.iter() {
1026 syn::ImplItem::Method(m) => {
1027 if let syn::Visibility::Public(_) = m.vis {
1028 match export_status(&m.attrs) {
1029 ExportStatus::Export => {},
1030 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1032 if m.defaultness.is_some() { unimplemented!(); }
1033 writeln_docs(w, &m.attrs, "");
1034 if let syn::ReturnType::Type(_, _) = &m.sig.output {
1035 writeln!(w, "#[must_use]").unwrap();
1037 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_{}(", ident, m.sig.ident).unwrap();
1038 let ret_type = match &declared_type {
1039 DeclType::MirroredEnum => format!("{}", ident),
1040 DeclType::StructImported => format!("{}", ident),
1041 _ => unimplemented!(),
1043 gen_types.push_ctx();
1044 assert!(gen_types.learn_generics(&m.sig.generics, types));
1045 write_method_params(w, &m.sig, &ret_type, types, Some(&gen_types), false, true);
1046 write!(w, " {{\n\t").unwrap();
1047 write_method_var_decl_body(w, &m.sig, "", types, Some(&gen_types), false);
1048 let mut takes_self = false;
1049 let mut takes_mut_self = false;
1050 for inp in m.sig.inputs.iter() {
1051 if let syn::FnArg::Receiver(r) = inp {
1053 if r.mutability.is_some() { takes_mut_self = true; }
1057 write!(w, "unsafe {{ &mut (*(this_arg.inner as *mut native{})) }}.{}(", ident, m.sig.ident).unwrap();
1058 } else if takes_self {
1059 write!(w, "unsafe {{ &*this_arg.inner }}.{}(", m.sig.ident).unwrap();
1061 write!(w, "{}::{}::{}(", types.orig_crate, resolved_path, m.sig.ident).unwrap();
1063 write_method_call_params(w, &m.sig, "", types, Some(&gen_types), &ret_type, false);
1064 gen_types.pop_ctx();
1065 writeln!(w, "\n}}\n").unwrap();
1072 } else if let Some(resolved_path) = types.maybe_resolve_ident(&ident) {
1073 if let Some(aliases) = types.crate_types.reverse_alias_map.get(&resolved_path).cloned() {
1074 'alias_impls: for (alias, arguments) in aliases {
1075 let alias_resolved = types.resolve_path(&alias, None);
1076 for (idx, gen) in i.generics.params.iter().enumerate() {
1078 syn::GenericParam::Type(type_param) => {
1079 'bounds_check: for bound in type_param.bounds.iter() {
1080 if let syn::TypeParamBound::Trait(trait_bound) = bound {
1081 if let syn::PathArguments::AngleBracketed(ref t) = &arguments {
1082 assert!(idx < t.args.len());
1083 if let syn::GenericArgument::Type(syn::Type::Path(p)) = &t.args[idx] {
1084 let generic_arg = types.resolve_path(&p.path, None);
1085 let generic_bound = types.resolve_path(&trait_bound.path, None);
1086 if let Some(traits_impld) = types.crate_types.trait_impls.get(&generic_arg) {
1087 for trait_impld in traits_impld {
1088 if *trait_impld == generic_bound { continue 'bounds_check; }
1090 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1091 continue 'alias_impls;
1093 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1094 continue 'alias_impls;
1096 } else { unimplemented!(); }
1097 } else { unimplemented!(); }
1098 } else { unimplemented!(); }
1101 syn::GenericParam::Lifetime(_) => {},
1102 syn::GenericParam::Const(_) => unimplemented!(),
1105 let aliased_impl = syn::ItemImpl {
1106 attrs: i.attrs.clone(),
1107 brace_token: syn::token::Brace(Span::call_site()),
1109 generics: syn::Generics {
1111 params: syn::punctuated::Punctuated::new(),
1115 impl_token: syn::Token![impl](Span::call_site()),
1116 items: i.items.clone(),
1117 self_ty: Box::new(syn::Type::Path(syn::TypePath { qself: None, path: alias.clone() })),
1118 trait_: i.trait_.clone(),
1121 writeln_impl(w, &aliased_impl, types);
1124 eprintln!("Not implementing anything for {} due to it being marked not exported", ident);
1127 eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub)", ident);
1134 /// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
1135 /// is unitary), we generate an equivalent enum with all types replaced with their C mapped
1136 /// versions followed by conversion functions which map between the Rust version and the C mapped
1138 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) {
1139 match export_status(&e.attrs) {
1140 ExportStatus::Export => {},
1141 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1144 if is_enum_opaque(e) {
1145 eprintln!("Skipping enum {} as it contains non-unit fields", e.ident);
1146 writeln_opaque(w, &e.ident, &format!("{}", e.ident), &e.generics, &e.attrs, types, extra_headers, cpp_headers);
1149 writeln_docs(w, &e.attrs, "");
1151 if e.generics.lt_token.is_some() {
1155 let mut needs_free = false;
1157 writeln!(w, "#[must_use]\n#[derive(Clone)]\n#[repr(C)]\npub enum {} {{", e.ident).unwrap();
1158 for var in e.variants.iter() {
1159 assert_eq!(export_status(&var.attrs), ExportStatus::Export); // We can't partially-export a mirrored enum
1160 writeln_docs(w, &var.attrs, "\t");
1161 write!(w, "\t{}", var.ident).unwrap();
1162 if let syn::Fields::Named(fields) = &var.fields {
1164 writeln!(w, " {{").unwrap();
1165 for field in fields.named.iter() {
1166 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1167 writeln_docs(w, &field.attrs, "\t\t");
1168 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1169 types.write_c_type(w, &field.ty, None, false);
1170 writeln!(w, ",").unwrap();
1172 write!(w, "\t}}").unwrap();
1173 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1175 write!(w, "(").unwrap();
1176 for (idx, field) in fields.unnamed.iter().enumerate() {
1177 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1178 types.write_c_type(w, &field.ty, None, false);
1179 if idx != fields.unnamed.len() - 1 {
1180 write!(w, ",").unwrap();
1183 write!(w, ")").unwrap();
1185 if var.discriminant.is_some() { unimplemented!(); }
1186 writeln!(w, ",").unwrap();
1188 writeln!(w, "}}\nuse {}::{}::{} as native{};\nimpl {} {{", types.orig_crate, types.module_path, e.ident, e.ident, e.ident).unwrap();
1190 macro_rules! write_conv {
1191 ($fn_sig: expr, $to_c: expr, $ref: expr) => {
1192 writeln!(w, "\t#[allow(unused)]\n\tpub(crate) fn {} {{\n\t\tmatch {} {{", $fn_sig, if $to_c { "native" } else { "self" }).unwrap();
1193 for var in e.variants.iter() {
1194 write!(w, "\t\t\t{}{}::{} ", if $to_c { "native" } else { "" }, e.ident, var.ident).unwrap();
1195 if let syn::Fields::Named(fields) = &var.fields {
1196 write!(w, "{{").unwrap();
1197 for field in fields.named.iter() {
1198 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1199 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, field.ident.as_ref().unwrap()).unwrap();
1201 write!(w, "}} ").unwrap();
1202 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1203 write!(w, "(").unwrap();
1204 for (idx, field) in fields.unnamed.iter().enumerate() {
1205 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1206 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, ('a' as u8 + idx as u8) as char).unwrap();
1208 write!(w, ") ").unwrap();
1210 write!(w, "=>").unwrap();
1212 macro_rules! handle_field_a {
1213 ($field: expr, $field_ident: expr) => { {
1214 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1215 let mut sink = ::std::io::sink();
1216 let mut out: &mut dyn std::io::Write = if $ref { &mut sink } else { w };
1217 let new_var = if $to_c {
1218 types.write_to_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None, false)
1220 types.write_from_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None)
1222 if $ref || new_var {
1224 write!(w, "let mut {}_nonref = (*{}).clone();\n\t\t\t\t", $field_ident, $field_ident).unwrap();
1226 let nonref_ident = syn::Ident::new(&format!("{}_nonref", $field_ident), Span::call_site());
1228 types.write_to_c_conversion_new_var(w, &nonref_ident, &$field.ty, None, false);
1230 types.write_from_c_conversion_new_var(w, &nonref_ident, &$field.ty, None);
1232 write!(w, "\n\t\t\t\t").unwrap();
1235 write!(w, "\n\t\t\t\t").unwrap();
1240 if let syn::Fields::Named(fields) = &var.fields {
1241 write!(w, " {{\n\t\t\t\t").unwrap();
1242 for field in fields.named.iter() {
1243 handle_field_a!(field, field.ident.as_ref().unwrap());
1245 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1246 write!(w, " {{\n\t\t\t\t").unwrap();
1247 for (idx, field) in fields.unnamed.iter().enumerate() {
1248 handle_field_a!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1250 } else { write!(w, " ").unwrap(); }
1252 write!(w, "{}{}::{}", if $to_c { "" } else { "native" }, e.ident, var.ident).unwrap();
1254 macro_rules! handle_field_b {
1255 ($field: expr, $field_ident: expr) => { {
1256 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1258 types.write_to_c_conversion_inline_prefix(w, &$field.ty, None, false);
1260 types.write_from_c_conversion_prefix(w, &$field.ty, None);
1262 write!(w, "{}{}", $field_ident,
1263 if $ref { "_nonref" } else { "" }).unwrap();
1265 types.write_to_c_conversion_inline_suffix(w, &$field.ty, None, false);
1267 types.write_from_c_conversion_suffix(w, &$field.ty, None);
1269 write!(w, ",").unwrap();
1273 if let syn::Fields::Named(fields) = &var.fields {
1274 write!(w, " {{").unwrap();
1275 for field in fields.named.iter() {
1276 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1277 write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1278 handle_field_b!(field, field.ident.as_ref().unwrap());
1280 writeln!(w, "\n\t\t\t\t}}").unwrap();
1281 write!(w, "\t\t\t}}").unwrap();
1282 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1283 write!(w, " (").unwrap();
1284 for (idx, field) in fields.unnamed.iter().enumerate() {
1285 write!(w, "\n\t\t\t\t\t").unwrap();
1286 handle_field_b!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1288 writeln!(w, "\n\t\t\t\t)").unwrap();
1289 write!(w, "\t\t\t}}").unwrap();
1291 writeln!(w, ",").unwrap();
1293 writeln!(w, "\t\t}}\n\t}}").unwrap();
1297 write_conv!(format!("to_native(&self) -> native{}", e.ident), false, true);
1298 write_conv!(format!("into_native(self) -> native{}", e.ident), false, false);
1299 write_conv!(format!("from_native(native: &native{}) -> Self", e.ident), true, true);
1300 write_conv!(format!("native_into(native: native{}) -> Self", e.ident), true, false);
1301 writeln!(w, "}}").unwrap();
1304 writeln!(w, "/// Frees any resources used by the {}", e.ident).unwrap();
1305 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", e.ident, e.ident).unwrap();
1307 writeln!(w, "/// Creates a copy of the {}", e.ident).unwrap();
1308 writeln!(w, "#[no_mangle]").unwrap();
1309 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
1310 writeln!(w, "\torig.clone()").unwrap();
1311 writeln!(w, "}}").unwrap();
1312 write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free);
1315 fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &mut TypeResolver<'b, 'a>) {
1316 match export_status(&f.attrs) {
1317 ExportStatus::Export => {},
1318 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1320 writeln_docs(w, &f.attrs, "");
1322 let mut gen_types = GenericTypes::new();
1323 if !gen_types.learn_generics(&f.sig.generics, types) { return; }
1325 write!(w, "#[no_mangle]\npub extern \"C\" fn {}(", f.sig.ident).unwrap();
1326 write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
1327 write!(w, " {{\n\t").unwrap();
1328 write_method_var_decl_body(w, &f.sig, "", types, Some(&gen_types), false);
1329 write!(w, "{}::{}::{}(", types.orig_crate, types.module_path, f.sig.ident).unwrap();
1330 write_method_call_params(w, &f.sig, "", types, Some(&gen_types), "", false);
1331 writeln!(w, "\n}}\n").unwrap();
1334 // ********************************
1335 // *** File/Crate Walking Logic ***
1336 // ********************************
1339 pub attrs: Vec<syn::Attribute>,
1340 pub items: Vec<syn::Item>,
1341 pub submods: Vec<String>,
1343 /// A struct containing the syn::File AST for each file in the crate.
1344 struct FullLibraryAST {
1345 modules: HashMap<String, ASTModule, NonRandomHash>,
1347 impl FullLibraryAST {
1348 fn load_module(&mut self, module: String, attrs: Vec<syn::Attribute>, mut items: Vec<syn::Item>) {
1349 let mut non_mod_items = Vec::with_capacity(items.len());
1350 let mut submods = Vec::with_capacity(items.len());
1351 for item in items.drain(..) {
1353 syn::Item::Mod(m) if m.content.is_some() => {
1354 if export_status(&m.attrs) == ExportStatus::Export {
1355 if let syn::Visibility::Public(_) = m.vis {
1356 let modident = format!("{}", m.ident);
1357 let modname = if module != "" {
1358 module.clone() + "::" + &modident
1362 self.load_module(modname, m.attrs, m.content.unwrap().1);
1363 submods.push(modident);
1365 non_mod_items.push(syn::Item::Mod(m));
1369 syn::Item::Mod(_) => panic!("--pretty=expanded output should never have non-body modules"),
1370 _ => { non_mod_items.push(item); }
1373 self.modules.insert(module, ASTModule { attrs, items: non_mod_items, submods });
1376 pub fn load_lib(lib: syn::File) -> Self {
1377 assert_eq!(export_status(&lib.attrs), ExportStatus::Export);
1378 let mut res = Self { modules: HashMap::default() };
1379 res.load_module("".to_owned(), lib.attrs, lib.items);
1384 /// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
1385 /// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
1386 /// at `module` from C.
1387 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) {
1388 for (module, astmod) in libast.modules.iter() {
1389 let ASTModule { ref attrs, ref items, ref submods } = astmod;
1390 assert_eq!(export_status(&attrs), ExportStatus::Export);
1392 let new_file_path = if submods.is_empty() {
1393 format!("{}/{}.rs", out_dir, module.replace("::", "/"))
1394 } else if module != "" {
1395 format!("{}/{}/mod.rs", out_dir, module.replace("::", "/"))
1397 format!("{}/lib.rs", out_dir)
1399 let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
1400 let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1401 .open(new_file_path).expect("Unable to open new src file");
1403 writeln!(out, "// This file is Copyright its original authors, visible in version control").unwrap();
1404 writeln!(out, "// history and in the source files from which this was generated.").unwrap();
1405 writeln!(out, "//").unwrap();
1406 writeln!(out, "// This file is licensed under the license available in the LICENSE or LICENSE.md").unwrap();
1407 writeln!(out, "// file in the root of this repository or, if no such file exists, the same").unwrap();
1408 writeln!(out, "// license as that which applies to the original source files from which this").unwrap();
1409 writeln!(out, "// source was automatically generated.").unwrap();
1410 writeln!(out, "").unwrap();
1412 writeln_docs(&mut out, &attrs, "");
1415 // Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
1416 // and bitcoin hand-written modules.
1417 writeln!(out, "#![allow(unknown_lints)]").unwrap();
1418 writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
1419 writeln!(out, "#![allow(non_snake_case)]").unwrap();
1420 writeln!(out, "#![allow(unused_imports)]").unwrap();
1421 writeln!(out, "#![allow(unused_variables)]").unwrap();
1422 writeln!(out, "#![allow(unused_mut)]").unwrap();
1423 writeln!(out, "#![allow(unused_parens)]").unwrap();
1424 writeln!(out, "#![allow(unused_unsafe)]").unwrap();
1425 writeln!(out, "#![allow(unused_braces)]").unwrap();
1426 writeln!(out, "#![deny(missing_docs)]").unwrap();
1427 writeln!(out, "pub mod c_types;").unwrap();
1428 writeln!(out, "pub mod bitcoin;").unwrap();
1430 writeln!(out, "\nuse std::ffi::c_void;\nuse bitcoin::hashes::Hash;\nuse crate::c_types::*;\n").unwrap();
1434 writeln!(out, "pub mod {};", m).unwrap();
1437 eprintln!("Converting {} entries...", module);
1439 let import_resolver = ImportResolver::new(module, items);
1440 let mut type_resolver = TypeResolver::new(orig_crate, module, import_resolver, crate_types);
1442 for item in items.iter() {
1444 syn::Item::Use(_) => {}, // Handled above
1445 syn::Item::Static(_) => {},
1446 syn::Item::Enum(e) => {
1447 if let syn::Visibility::Public(_) = e.vis {
1448 writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
1451 syn::Item::Impl(i) => {
1452 writeln_impl(&mut out, &i, &mut type_resolver);
1454 syn::Item::Struct(s) => {
1455 if let syn::Visibility::Public(_) = s.vis {
1456 writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
1459 syn::Item::Trait(t) => {
1460 if let syn::Visibility::Public(_) = t.vis {
1461 writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
1464 syn::Item::Mod(_) => {}, // We don't have to do anything - the top loop handles these.
1465 syn::Item::Const(c) => {
1466 // Re-export any primitive-type constants.
1467 if let syn::Visibility::Public(_) = c.vis {
1468 if let syn::Type::Path(p) = &*c.ty {
1469 let resolved_path = type_resolver.resolve_path(&p.path, None);
1470 if type_resolver.is_primitive(&resolved_path) {
1471 writeln_docs(&mut out, &c.attrs, "");
1472 writeln!(out, "\n#[no_mangle]").unwrap();
1473 writeln!(out, "pub static {}: {} = {}::{}::{};", c.ident, resolved_path, orig_crate, module, c.ident).unwrap();
1478 syn::Item::Type(t) => {
1479 if let syn::Visibility::Public(_) = t.vis {
1480 match export_status(&t.attrs) {
1481 ExportStatus::Export => {},
1482 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1485 let mut process_alias = true;
1486 for tok in t.generics.params.iter() {
1487 if let syn::GenericParam::Lifetime(_) = tok {}
1488 else { process_alias = false; }
1492 syn::Type::Path(_) =>
1493 writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &t.generics, &t.attrs, &type_resolver, header_file, cpp_header_file),
1499 syn::Item::Fn(f) => {
1500 if let syn::Visibility::Public(_) = f.vis {
1501 writeln_fn(&mut out, &f, &mut type_resolver);
1504 syn::Item::Macro(m) => {
1505 if m.ident.is_none() { // If its not a macro definition
1506 convert_macro(&mut out, &m.mac.path, &m.mac.tokens, &type_resolver);
1509 syn::Item::Verbatim(_) => {},
1510 syn::Item::ExternCrate(_) => {},
1511 _ => unimplemented!(),
1515 out.flush().unwrap();
1519 fn walk_private_mod<'a>(module: String, items: &'a syn::ItemMod, crate_types: &mut CrateTypes<'a>) {
1520 let import_resolver = ImportResolver::new(&module, &items.content.as_ref().unwrap().1);
1521 for item in items.content.as_ref().unwrap().1.iter() {
1523 syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types),
1524 syn::Item::Impl(i) => {
1525 if let &syn::Type::Path(ref p) = &*i.self_ty {
1526 if let Some(trait_path) = i.trait_.as_ref() {
1527 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1528 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1529 match crate_types.trait_impls.entry(sp) {
1530 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1531 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1543 /// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
1544 fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
1545 for (module, astmod) in ast_storage.modules.iter() {
1546 let ASTModule { ref attrs, ref items, submods: _ } = astmod;
1547 assert_eq!(export_status(&attrs), ExportStatus::Export);
1548 let import_resolver = ImportResolver::new(module, items);
1550 for item in items.iter() {
1552 syn::Item::Struct(s) => {
1553 if let syn::Visibility::Public(_) = s.vis {
1554 match export_status(&s.attrs) {
1555 ExportStatus::Export => {},
1556 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1558 let struct_path = format!("{}::{}", module, s.ident);
1559 crate_types.opaques.insert(struct_path, &s.ident);
1562 syn::Item::Trait(t) => {
1563 if let syn::Visibility::Public(_) = t.vis {
1564 match export_status(&t.attrs) {
1565 ExportStatus::Export => {},
1566 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1568 let trait_path = format!("{}::{}", module, t.ident);
1569 walk_supertraits!(t, None, (
1571 crate_types.clonable_types.insert("crate::".to_owned() + &trait_path);
1575 crate_types.traits.insert(trait_path, &t);
1578 syn::Item::Type(t) => {
1579 if let syn::Visibility::Public(_) = t.vis {
1580 match export_status(&t.attrs) {
1581 ExportStatus::Export => {},
1582 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1584 let type_path = format!("{}::{}", module, t.ident);
1585 let mut process_alias = true;
1586 for tok in t.generics.params.iter() {
1587 if let syn::GenericParam::Lifetime(_) = tok {}
1588 else { process_alias = false; }
1592 syn::Type::Path(p) => {
1593 // If its a path with no generics, assume we don't map the aliased type and map it opaque
1594 let mut segments = syn::punctuated::Punctuated::new();
1595 segments.push(syn::PathSegment {
1596 ident: t.ident.clone(),
1597 arguments: syn::PathArguments::None,
1599 let path_obj = syn::Path { leading_colon: None, segments };
1600 let args_obj = p.path.segments.last().unwrap().arguments.clone();
1601 match crate_types.reverse_alias_map.entry(import_resolver.maybe_resolve_path(&p.path, None).unwrap()) {
1602 hash_map::Entry::Occupied(mut e) => { e.get_mut().push((path_obj, args_obj)); },
1603 hash_map::Entry::Vacant(e) => { e.insert(vec![(path_obj, args_obj)]); },
1606 crate_types.opaques.insert(type_path.clone(), &t.ident);
1609 crate_types.type_aliases.insert(type_path, import_resolver.resolve_imported_refs((*t.ty).clone()));
1615 syn::Item::Enum(e) if is_enum_opaque(e) => {
1616 if let syn::Visibility::Public(_) = e.vis {
1617 match export_status(&e.attrs) {
1618 ExportStatus::Export => {},
1619 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1621 let enum_path = format!("{}::{}", module, e.ident);
1622 crate_types.opaques.insert(enum_path, &e.ident);
1625 syn::Item::Enum(e) => {
1626 if let syn::Visibility::Public(_) = e.vis {
1627 match export_status(&e.attrs) {
1628 ExportStatus::Export => {},
1629 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1631 let enum_path = format!("{}::{}", module, e.ident);
1632 crate_types.mirrored_enums.insert(enum_path, &e);
1635 syn::Item::Impl(i) => {
1636 if let &syn::Type::Path(ref p) = &*i.self_ty {
1637 if let Some(trait_path) = i.trait_.as_ref() {
1638 if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) {
1639 if let Some(full_path) = import_resolver.maybe_resolve_path(&p.path, None) {
1640 crate_types.clonable_types.insert("crate::".to_owned() + &full_path);
1643 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1644 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1645 match crate_types.trait_impls.entry(sp) {
1646 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1647 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1654 syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types),
1662 let args: Vec<String> = env::args().collect();
1663 if args.len() != 6 {
1664 eprintln!("Usage: target/dir source_crate_name derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
1668 let mut derived_templates = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1669 .open(&args[3]).expect("Unable to open new header file");
1670 let mut header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1671 .open(&args[4]).expect("Unable to open new header file");
1672 let mut cpp_header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1673 .open(&args[5]).expect("Unable to open new header file");
1675 writeln!(header_file, "#if defined(__GNUC__)").unwrap();
1676 writeln!(header_file, "#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
1677 writeln!(header_file, "#define MUST_USE_RES __attribute__((warn_unused_result))").unwrap();
1678 writeln!(header_file, "#else").unwrap();
1679 writeln!(header_file, "#define MUST_USE_STRUCT").unwrap();
1680 writeln!(header_file, "#define MUST_USE_RES").unwrap();
1681 writeln!(header_file, "#endif").unwrap();
1682 writeln!(header_file, "#if defined(__clang__)").unwrap();
1683 writeln!(header_file, "#define NONNULL_PTR _Nonnull").unwrap();
1684 writeln!(header_file, "#else").unwrap();
1685 writeln!(header_file, "#define NONNULL_PTR").unwrap();
1686 writeln!(header_file, "#endif").unwrap();
1687 writeln!(cpp_header_file, "#include <string.h>\nnamespace LDK {{").unwrap();
1689 // First parse the full crate's ASTs, caching them so that we can hold references to the AST
1690 // objects in other datastructures:
1691 let mut lib_src = String::new();
1692 std::io::stdin().lock().read_to_string(&mut lib_src).unwrap();
1693 let lib_syntax = syn::parse_file(&lib_src).expect("Unable to parse file");
1694 let libast = FullLibraryAST::load_lib(lib_syntax);
1696 // ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
1697 // when parsing other file ASTs...
1698 let mut libtypes = CrateTypes { traits: HashMap::new(), opaques: HashMap::new(), mirrored_enums: HashMap::new(),
1699 type_aliases: HashMap::new(), reverse_alias_map: HashMap::new(), templates_defined: HashMap::default(),
1700 template_file: &mut derived_templates,
1701 clonable_types: HashSet::new(), trait_impls: HashMap::new() };
1702 walk_ast(&libast, &mut libtypes);
1704 // ... finally, do the actual file conversion/mapping, writing out types as we go.
1705 convert_file(&libast, &mut libtypes, &args[1], &args[2], &mut header_file, &mut cpp_header_file);
1707 // For container templates which we created while walking the crate, make sure we add C++
1708 // mapped types so that C++ users can utilize the auto-destructors available.
1709 for (ty, has_destructor) in libtypes.templates_defined.iter() {
1710 write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor);
1712 writeln!(cpp_header_file, "}}").unwrap();
1714 header_file.flush().unwrap();
1715 cpp_header_file.flush().unwrap();
1716 derived_templates.flush().unwrap();