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 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));
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));
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));
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 walk_supertraits!(t, Some(&types), (
360 writeln!(w, "\t/// Creates a copy of the object pointed to by this_arg, for a copy of this {}.", trait_name).unwrap();
361 writeln!(w, "\t/// Note that the ultimate copy of the {} will have all function pointers the same as the original.", trait_name).unwrap();
362 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();
363 writeln!(w, "\tpub clone: Option<extern \"C\" fn (this_arg: *const c_void) -> *mut c_void>,").unwrap();
364 generated_fields.push("clone".to_owned());
366 ("std::cmp::Eq", _) => {
367 writeln!(w, "\t/// Checks if two objects are equal given this object's this_arg pointer and another object.").unwrap();
368 writeln!(w, "\tpub eq: extern \"C\" fn (this_arg: *const c_void, other_arg: &{}) -> bool,", trait_name).unwrap();
369 writeln!(extra_headers, "typedef struct LDK{} LDK{};", trait_name, trait_name).unwrap();
370 generated_fields.push("eq".to_owned());
372 ("std::hash::Hash", _) => {
373 writeln!(w, "\t/// Calculate a succinct non-cryptographic hash for an object given its this_arg pointer.").unwrap();
374 writeln!(w, "\t/// This is used, for example, for inclusion of this object in a hash map.").unwrap();
375 writeln!(w, "\tpub hash: extern \"C\" fn (this_arg: *const c_void) -> u64,").unwrap();
376 generated_fields.push("hash".to_owned());
378 ("Send", _) => {}, ("Sync", _) => {},
380 generated_fields.push(if types.crate_types.traits.get(s).is_none() {
381 let (docs, name, ret) = convert_trait_impl_field(s);
382 writeln!(w, "\t/// {}", docs).unwrap();
383 writeln!(w, "\tpub {}: extern \"C\" fn (this_arg: *const c_void) -> {},", name, ret).unwrap();
386 // For in-crate supertraits, just store a C-mapped copy of the supertrait as a member.
387 writeln!(w, "/// Implementation of {} for this object.", i).unwrap();
388 writeln!(w, "\tpub {}: crate::{},", i, s).unwrap();
393 writeln!(w, "\t/// Frees any resources associated with this object given its this_arg pointer.").unwrap();
394 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();
395 writeln!(w, "\tpub free: Option<extern \"C\" fn(this_arg: *mut c_void)>,").unwrap();
396 generated_fields.push("free".to_owned());
397 writeln!(w, "}}").unwrap();
398 // Implement supertraits for the C-mapped struct.
399 walk_supertraits!(t, Some(&types), (
400 ("Send", _) => writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap(),
401 ("Sync", _) => writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap(),
402 ("std::cmp::Eq", _) => {
403 writeln!(w, "impl std::cmp::Eq for {} {{}}", trait_name).unwrap();
404 writeln!(w, "impl std::cmp::PartialEq for {} {{", trait_name).unwrap();
405 writeln!(w, "\tfn eq(&self, o: &Self) -> bool {{ (self.eq)(self.this_arg, o) }}\n}}").unwrap();
407 ("std::hash::Hash", _) => {
408 writeln!(w, "impl std::hash::Hash for {} {{", trait_name).unwrap();
409 writeln!(w, "\tfn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {{ hasher.write_u64((self.hash)(self.this_arg)) }}\n}}").unwrap();
412 writeln!(w, "#[no_mangle]").unwrap();
413 writeln!(w, "/// Creates a copy of a {}", trait_name).unwrap();
414 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", trait_name, trait_name, trait_name).unwrap();
415 writeln!(w, "\t{} {{", trait_name).unwrap();
416 writeln!(w, "\t\tthis_arg: if let Some(f) = orig.clone {{ (f)(orig.this_arg) }} else {{ orig.this_arg }},").unwrap();
417 for field in generated_fields.iter() {
418 writeln!(w, "\t\t{}: orig.{}.clone(),", field, field).unwrap();
420 writeln!(w, "\t}}\n}}").unwrap();
421 writeln!(w, "impl Clone for {} {{", trait_name).unwrap();
422 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
423 writeln!(w, "\t\t{}_clone(self)", trait_name).unwrap();
424 writeln!(w, "\t}}\n}}").unwrap();
427 do_write_impl_trait(w, s, i, &trait_name);
431 // Finally, implement the original Rust trait for the newly created mapped trait.
432 writeln!(w, "\nuse {}::{}::{} as rust{};", types.orig_crate, types.module_path, t.ident, trait_name).unwrap();
433 write!(w, "impl rust{}", t.ident).unwrap();
434 maybe_write_generics(w, &t.generics, types, false);
435 writeln!(w, " for {} {{", trait_name).unwrap();
436 for item in t.items.iter() {
438 syn::TraitItem::Method(m) => {
439 if let ExportStatus::TestOnly = export_status(&m.attrs) { continue; }
440 if m.default.is_some() { unimplemented!(); }
441 if m.sig.constness.is_some() || m.sig.asyncness.is_some() || m.sig.unsafety.is_some() ||
442 m.sig.abi.is_some() || m.sig.variadic.is_some() {
445 gen_types.push_ctx();
446 assert!(gen_types.learn_generics(&m.sig.generics, types));
447 write!(w, "\tfn {}", m.sig.ident).unwrap();
448 types.write_rust_generic_param(w, Some(&gen_types), m.sig.generics.params.iter());
449 write!(w, "(").unwrap();
450 for inp in m.sig.inputs.iter() {
452 syn::FnArg::Receiver(recv) => {
453 if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
454 write!(w, "&").unwrap();
455 if let Some(lft) = &recv.reference.as_ref().unwrap().1 {
456 write!(w, "'{} ", lft.ident).unwrap();
458 if recv.mutability.is_some() {
459 write!(w, "mut self").unwrap();
461 write!(w, "self").unwrap();
464 syn::FnArg::Typed(arg) => {
465 if !arg.attrs.is_empty() { unimplemented!(); }
467 syn::Pat::Ident(ident) => {
468 if !ident.attrs.is_empty() || ident.by_ref.is_some() ||
469 ident.mutability.is_some() || ident.subpat.is_some() {
472 write!(w, ", {}{}: ", if types.skip_arg(&*arg.ty, Some(&gen_types)) { "_" } else { "" }, ident.ident).unwrap();
474 _ => unimplemented!(),
476 types.write_rust_type(w, Some(&gen_types), &*arg.ty);
480 write!(w, ")").unwrap();
481 match &m.sig.output {
482 syn::ReturnType::Type(_, rtype) => {
483 write!(w, " -> ").unwrap();
484 types.write_rust_type(w, Some(&gen_types), &*rtype)
488 write!(w, " {{\n\t\t").unwrap();
489 match export_status(&m.attrs) {
490 ExportStatus::NoExport => {
495 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
496 if let syn::Type::Reference(r) = &**rtype {
497 assert_eq!(m.sig.inputs.len(), 1); // Must only take self!
498 writeln!(w, "if let Some(f) = self.set_{} {{", m.sig.ident).unwrap();
499 writeln!(w, "\t\t\t(f)(self);").unwrap();
500 write!(w, "\t\t}}\n\t\t").unwrap();
501 types.write_from_c_conversion_to_ref_prefix(w, &*r.elem, Some(&gen_types));
502 write!(w, "self.{}", m.sig.ident).unwrap();
503 types.write_from_c_conversion_to_ref_suffix(w, &*r.elem, Some(&gen_types));
504 writeln!(w, "\n\t}}").unwrap();
509 write_method_var_decl_body(w, &m.sig, "\t", types, Some(&gen_types), true);
510 write!(w, "(self.{})(", m.sig.ident).unwrap();
511 write_method_call_params(w, &m.sig, "\t", types, Some(&gen_types), "", true);
513 writeln!(w, "\n\t}}").unwrap();
516 &syn::TraitItem::Type(ref t) => {
517 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
518 let mut bounds_iter = t.bounds.iter();
519 match bounds_iter.next().unwrap() {
520 syn::TypeParamBound::Trait(tr) => {
521 writeln!(w, "\ttype {} = crate::{};", t.ident, types.resolve_path(&tr.path, Some(&gen_types))).unwrap();
523 _ => unimplemented!(),
525 if bounds_iter.next().is_some() { unimplemented!(); }
527 _ => unimplemented!(),
530 writeln!(w, "}}\n").unwrap();
531 writeln!(w, "// We're essentially a pointer already, or at least a set of pointers, so allow us to be used").unwrap();
532 writeln!(w, "// directly as a Deref trait in higher-level structs:").unwrap();
533 writeln!(w, "impl std::ops::Deref for {} {{\n\ttype Target = Self;", trait_name).unwrap();
534 writeln!(w, "\tfn deref(&self) -> &Self {{\n\t\tself\n\t}}\n}}").unwrap();
536 writeln!(w, "/// Calls the free function if one is set").unwrap();
537 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", trait_name, trait_name).unwrap();
538 writeln!(w, "impl Drop for {} {{", trait_name).unwrap();
539 writeln!(w, "\tfn drop(&mut self) {{").unwrap();
540 writeln!(w, "\t\tif let Some(f) = self.free {{").unwrap();
541 writeln!(w, "\t\t\tf(self.this_arg);").unwrap();
542 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
544 write_cpp_wrapper(cpp_headers, &trait_name, true);
547 /// Write out a simple "opaque" type (eg structs) which contain a pointer to the native Rust type
548 /// and a flag to indicate whether Drop'ing the mapped struct drops the underlying Rust type.
550 /// Also writes out a _free function and a C++ wrapper which handles calling _free.
551 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) {
552 // If we directly read the original type by its original name, cbindgen hits
553 // https://github.com/eqrion/cbindgen/issues/286 Thus, instead, we import it as a temporary
554 // name and then reference it by that name, which works around the issue.
555 write!(w, "\nuse {}::{}::{} as native{}Import;\ntype native{} = native{}Import", types.orig_crate, types.module_path, ident, ident, ident, ident).unwrap();
556 maybe_write_generics(w, &generics, &types, true);
557 writeln!(w, ";\n").unwrap();
558 writeln!(extra_headers, "struct native{}Opaque;\ntypedef struct native{}Opaque LDKnative{};", ident, ident, ident).unwrap();
559 writeln_docs(w, &attrs, "");
560 writeln!(w, "#[must_use]\n#[repr(C)]\npub struct {} {{", struct_name).unwrap();
561 writeln!(w, "\t/// A pointer to the opaque Rust object.\n").unwrap();
562 writeln!(w, "\t/// Nearly everywhere, inner must be non-null, however in places where").unwrap();
563 writeln!(w, "\t/// the Rust equivalent takes an Option, it may be set to null to indicate None.").unwrap();
564 writeln!(w, "\tpub inner: *mut native{},", ident).unwrap();
565 writeln!(w, "\t/// Indicates that this is the only struct which contains the same pointer.\n").unwrap();
566 writeln!(w, "\t/// Rust functions which take ownership of an object provided via an argument require").unwrap();
567 writeln!(w, "\t/// this to be true and invalidate the object pointed to by inner.").unwrap();
568 writeln!(w, "\tpub is_owned: bool,").unwrap();
569 writeln!(w, "}}\n").unwrap();
570 writeln!(w, "impl Drop for {} {{\n\tfn drop(&mut self) {{", struct_name).unwrap();
571 writeln!(w, "\t\tif self.is_owned && !<*mut native{}>::is_null(self.inner) {{", ident).unwrap();
572 writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(self.inner) }};\n\t\t}}\n\t}}\n}}").unwrap();
573 writeln!(w, "/// Frees any resources used by the {}, if is_owned is set and inner is non-NULL.", struct_name).unwrap();
574 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_obj: {}) {{ }}", struct_name, struct_name).unwrap();
575 writeln!(w, "#[allow(unused)]").unwrap();
576 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
577 writeln!(w, "extern \"C\" fn {}_free_void(this_ptr: *mut c_void) {{", struct_name).unwrap();
578 writeln!(w, "\tunsafe {{ let _ = Box::from_raw(this_ptr as *mut native{}); }}\n}}", struct_name).unwrap();
579 writeln!(w, "#[allow(unused)]").unwrap();
580 writeln!(w, "/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy").unwrap();
581 writeln!(w, "impl {} {{", struct_name).unwrap();
582 writeln!(w, "\tpub(crate) fn take_inner(mut self) -> *mut native{} {{", struct_name).unwrap();
583 writeln!(w, "\t\tassert!(self.is_owned);").unwrap();
584 writeln!(w, "\t\tlet ret = self.inner;").unwrap();
585 writeln!(w, "\t\tself.inner = std::ptr::null_mut();").unwrap();
586 writeln!(w, "\t\tret").unwrap();
587 writeln!(w, "\t}}\n}}").unwrap();
589 write_cpp_wrapper(cpp_headers, &format!("{}", ident), true);
592 /// Writes out all the relevant mappings for a Rust struct, deferring to writeln_opaque to generate
593 /// the struct itself, and then writing getters and setters for public, understood-type fields and
594 /// a constructor if every field is public.
595 fn writeln_struct<'a, 'b, W: std::io::Write>(w: &mut W, s: &'a syn::ItemStruct, types: &mut TypeResolver<'b, 'a>, extra_headers: &mut File, cpp_headers: &mut File) {
596 if export_status(&s.attrs) != ExportStatus::Export { return; }
598 let struct_name = &format!("{}", s.ident);
599 writeln_opaque(w, &s.ident, struct_name, &s.generics, &s.attrs, types, extra_headers, cpp_headers);
601 if let syn::Fields::Named(fields) = &s.fields {
602 let mut gen_types = GenericTypes::new();
603 assert!(gen_types.learn_generics(&s.generics, types));
605 let mut all_fields_settable = true;
606 for field in fields.named.iter() {
607 if let syn::Visibility::Public(_) = field.vis {
608 let export = export_status(&field.attrs);
610 ExportStatus::Export => {},
611 ExportStatus::NoExport|ExportStatus::TestOnly => {
612 all_fields_settable = false;
617 if let Some(ident) = &field.ident {
618 let ref_type = syn::Type::Reference(syn::TypeReference {
619 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
620 elem: Box::new(field.ty.clone()) });
621 if types.understood_c_type(&ref_type, Some(&gen_types)) {
622 writeln_docs(w, &field.attrs, "");
623 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> ", struct_name, ident, struct_name).unwrap();
624 types.write_c_type(w, &ref_type, Some(&gen_types), true);
625 write!(w, " {{\n\tlet mut inner_val = &mut unsafe {{ &mut *this_ptr.inner }}.{};\n\t", ident).unwrap();
626 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);
627 if local_var { write!(w, "\n\t").unwrap(); }
628 types.write_to_c_conversion_inline_prefix(w, &ref_type, Some(&gen_types), true);
630 write!(w, "inner_val").unwrap();
632 write!(w, "(*inner_val)").unwrap();
634 types.write_to_c_conversion_inline_suffix(w, &ref_type, Some(&gen_types), true);
635 writeln!(w, "\n}}").unwrap();
638 if types.understood_c_type(&field.ty, Some(&gen_types)) {
639 writeln_docs(w, &field.attrs, "");
640 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_set_{}(this_ptr: &mut {}, mut val: ", struct_name, ident, struct_name).unwrap();
641 types.write_c_type(w, &field.ty, Some(&gen_types), false);
642 write!(w, ") {{\n\t").unwrap();
643 let local_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("val", Span::call_site()), &field.ty, Some(&gen_types));
644 if local_var { write!(w, "\n\t").unwrap(); }
645 write!(w, "unsafe {{ &mut *this_ptr.inner }}.{} = ", ident).unwrap();
646 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
647 write!(w, "val").unwrap();
648 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
649 writeln!(w, ";\n}}").unwrap();
650 } else { all_fields_settable = false; }
651 } else { all_fields_settable = false; }
652 } else { all_fields_settable = false; }
655 if all_fields_settable {
656 // Build a constructor!
657 writeln!(w, "/// Constructs a new {} given each field", struct_name).unwrap();
658 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_new(", struct_name).unwrap();
659 for (idx, field) in fields.named.iter().enumerate() {
660 if idx != 0 { write!(w, ", ").unwrap(); }
661 write!(w, "mut {}_arg: ", field.ident.as_ref().unwrap()).unwrap();
662 types.write_c_type(w, &field.ty, Some(&gen_types), false);
664 write!(w, ") -> {} {{\n\t", struct_name).unwrap();
665 for field in fields.named.iter() {
666 let field_name = format!("{}_arg", field.ident.as_ref().unwrap());
667 if types.write_from_c_conversion_new_var(w, &syn::Ident::new(&field_name, Span::call_site()), &field.ty, Some(&gen_types)) {
668 write!(w, "\n\t").unwrap();
671 writeln!(w, "{} {{ inner: Box::into_raw(Box::new(native{} {{", struct_name, s.ident).unwrap();
672 for field in fields.named.iter() {
673 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
674 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
675 write!(w, "{}_arg", field.ident.as_ref().unwrap()).unwrap();
676 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
677 writeln!(w, ",").unwrap();
679 writeln!(w, "\t}})), is_owned: true }}\n}}").unwrap();
684 /// Prints a relevant conversion for impl *
686 /// For simple impl Struct {}s, this just outputs the wrapper functions as Struct_fn_name() { .. }.
688 /// For impl Trait for Struct{}s, this non-exported generates wrapper functions as
689 /// Trait_Struct_fn_name and a Struct_as_Trait(&struct) -> Trait function which returns a populated
690 /// Trait struct containing a pointer to the passed struct's inner field and the wrapper functions.
692 /// A few non-crate Traits are hard-coded including Default.
693 fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut TypeResolver) {
694 match export_status(&i.attrs) {
695 ExportStatus::Export => {},
696 ExportStatus::NoExport|ExportStatus::TestOnly => return,
699 if let syn::Type::Tuple(_) = &*i.self_ty {
700 if types.understood_c_type(&*i.self_ty, None) {
701 let mut gen_types = GenericTypes::new();
702 if !gen_types.learn_generics(&i.generics, types) {
703 eprintln!("Not implementing anything for `impl (..)` due to not understood generics");
707 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
708 if let Some(trait_path) = i.trait_.as_ref() {
709 if trait_path.0.is_some() { unimplemented!(); }
710 if types.understood_c_path(&trait_path.1) {
711 eprintln!("Not implementing anything for `impl Trait for (..)` - we only support manual defines");
714 // Just do a manual implementation:
715 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
718 eprintln!("Not implementing anything for plain `impl (..)` block - we only support `impl Trait for (..)` blocks");
724 if let &syn::Type::Path(ref p) = &*i.self_ty {
725 if p.qself.is_some() { unimplemented!(); }
726 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
727 if let Some(resolved_path) = types.maybe_resolve_non_ignored_ident(&ident) {
728 let mut gen_types = GenericTypes::new();
729 if !gen_types.learn_generics(&i.generics, types) {
730 eprintln!("Not implementing anything for impl {} due to not understood generics", ident);
734 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
735 if let Some(trait_path) = i.trait_.as_ref() {
736 if trait_path.0.is_some() { unimplemented!(); }
737 if types.understood_c_path(&trait_path.1) {
738 let full_trait_path = types.resolve_path(&trait_path.1, None);
739 let trait_obj = *types.crate_types.traits.get(&full_trait_path).unwrap();
740 // We learn the associated types maping from the original trait object.
741 // That's great, except that they are unresolved idents, so if we learn
742 // mappings from a trai defined in a different file, we may mis-resolve or
743 // fail to resolve the mapped types.
744 gen_types.learn_associated_types(trait_obj, types);
745 let mut impl_associated_types = HashMap::new();
746 for item in i.items.iter() {
748 syn::ImplItem::Type(t) => {
749 if let syn::Type::Path(p) = &t.ty {
750 if let Some(id) = single_ident_generic_path_to_ident(&p.path) {
751 impl_associated_types.insert(&t.ident, id);
759 let export = export_status(&trait_obj.attrs);
761 ExportStatus::Export => {},
762 ExportStatus::NoExport|ExportStatus::TestOnly => return,
765 // For cases where we have a concrete native object which implements a
766 // trait and need to return the C-mapped version of the trait, provide a
767 // From<> implementation which does all the work to ensure free is handled
768 // properly. This way we can call this method from deep in the
769 // type-conversion logic without actually knowing the concrete native type.
770 writeln!(w, "impl From<native{}> for crate::{} {{", ident, full_trait_path).unwrap();
771 writeln!(w, "\tfn from(obj: native{}) -> Self {{", ident).unwrap();
772 writeln!(w, "\t\tlet mut rust_obj = {} {{ inner: Box::into_raw(Box::new(obj)), is_owned: true }};", ident).unwrap();
773 writeln!(w, "\t\tlet mut ret = {}_as_{}(&rust_obj);", ident, trait_obj.ident).unwrap();
774 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();
775 writeln!(w, "\t\trust_obj.inner = std::ptr::null_mut();").unwrap();
776 writeln!(w, "\t\tret.free = Some({}_free_void);", ident).unwrap();
777 writeln!(w, "\t\tret\n\t}}\n}}").unwrap();
779 writeln!(w, "/// Constructs a new {} which calls the relevant methods on this_arg.", trait_obj.ident).unwrap();
780 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();
781 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_as_{}(this_arg: &{}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
782 writeln!(w, "\tcrate::{} {{", full_trait_path).unwrap();
783 writeln!(w, "\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
784 writeln!(w, "\t\tfree: None,").unwrap();
786 macro_rules! write_meth {
787 ($m: expr, $trait: expr, $indent: expr) => {
788 let trait_method = $trait.items.iter().filter_map(|item| {
789 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
790 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
791 match export_status(&trait_method.attrs) {
792 ExportStatus::Export => {},
793 ExportStatus::NoExport => {
794 write!(w, "{}\t\t//XXX: Need to export {}\n", $indent, $m.sig.ident).unwrap();
797 ExportStatus::TestOnly => continue,
800 let mut printed = false;
801 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
802 if let syn::Type::Reference(r) = &**rtype {
803 write!(w, "\n\t\t{}{}: ", $indent, $m.sig.ident).unwrap();
804 types.write_empty_rust_val(Some(&gen_types), w, &*r.elem);
805 writeln!(w, ",\n{}\t\tset_{}: Some({}_{}_set_{}),", $indent, $m.sig.ident, ident, trait_obj.ident, $m.sig.ident).unwrap();
810 write!(w, "{}\t\t{}: {}_{}_{},\n", $indent, $m.sig.ident, ident, trait_obj.ident, $m.sig.ident).unwrap();
814 for item in trait_obj.items.iter() {
816 syn::TraitItem::Method(m) => {
817 write_meth!(m, trait_obj, "");
822 walk_supertraits!(trait_obj, Some(&types), (
824 writeln!(w, "\t\tclone: Some({}_clone_void),", ident).unwrap();
826 ("Sync", _) => {}, ("Send", _) => {},
827 ("std::marker::Sync", _) => {}, ("std::marker::Send", _) => {},
829 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
830 writeln!(w, "\t\t{}: crate::{} {{", t, s).unwrap();
831 writeln!(w, "\t\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
832 writeln!(w, "\t\t\tfree: None,").unwrap();
833 for item in supertrait_obj.items.iter() {
835 syn::TraitItem::Method(m) => {
836 write_meth!(m, supertrait_obj, "\t");
841 write!(w, "\t\t}},\n").unwrap();
843 write_trait_impl_field_assign(w, s, ident);
847 writeln!(w, "\t}}\n}}\n").unwrap();
849 macro_rules! impl_meth {
850 ($m: expr, $trait_path: expr, $trait: expr, $indent: expr) => {
851 let trait_method = $trait.items.iter().filter_map(|item| {
852 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
853 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
854 match export_status(&trait_method.attrs) {
855 ExportStatus::Export => {},
856 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
859 if let syn::ReturnType::Type(_, _) = &$m.sig.output {
860 writeln!(w, "#[must_use]").unwrap();
862 write!(w, "extern \"C\" fn {}_{}_{}(", ident, trait_obj.ident, $m.sig.ident).unwrap();
863 gen_types.push_ctx();
864 assert!(gen_types.learn_generics(&$m.sig.generics, types));
865 write_method_params(w, &$m.sig, "c_void", types, Some(&gen_types), true, true);
866 write!(w, " {{\n\t").unwrap();
867 write_method_var_decl_body(w, &$m.sig, "", types, Some(&gen_types), false);
868 let mut takes_self = false;
869 for inp in $m.sig.inputs.iter() {
870 if let syn::FnArg::Receiver(_) = inp {
875 let mut t_gen_args = String::new();
876 for (idx, _) in $trait.generics.params.iter().enumerate() {
877 if idx != 0 { t_gen_args += ", " };
881 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();
883 write!(w, "<native{} as {}::{}<{}>>::{}(", ident, types.orig_crate, $trait_path, t_gen_args, $m.sig.ident).unwrap();
886 let mut real_type = "".to_string();
887 match &$m.sig.output {
888 syn::ReturnType::Type(_, rtype) => {
889 if let Some(mut remaining_path) = first_seg_self(&*rtype) {
890 if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
891 real_type = format!("{}", impl_associated_types.get(associated_seg).unwrap());
897 write_method_call_params(w, &$m.sig, "", types, Some(&gen_types), &real_type, false);
899 write!(w, "\n}}\n").unwrap();
900 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
901 if let syn::Type::Reference(r) = &**rtype {
902 assert_eq!($m.sig.inputs.len(), 1); // Must only take self
903 writeln!(w, "extern \"C\" fn {}_{}_set_{}(trait_self_arg: &{}) {{", ident, trait_obj.ident, $m.sig.ident, trait_obj.ident).unwrap();
904 writeln!(w, "\t// This is a bit race-y in the general case, but for our specific use-cases today, we're safe").unwrap();
905 writeln!(w, "\t// Specifically, we must ensure that the first time we're called it can never be in parallel").unwrap();
906 write!(w, "\tif ").unwrap();
907 types.write_empty_rust_val_check(Some(&gen_types), w, &*r.elem, &format!("trait_self_arg.{}", $m.sig.ident));
908 writeln!(w, " {{").unwrap();
909 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();
910 writeln!(w, "\t}}").unwrap();
911 writeln!(w, "}}").unwrap();
917 for item in i.items.iter() {
919 syn::ImplItem::Method(m) => {
920 impl_meth!(m, full_trait_path, trait_obj, "");
922 syn::ImplItem::Type(_) => {},
923 _ => unimplemented!(),
926 walk_supertraits!(trait_obj, Some(&types), (
928 if let Some(supertrait_obj) = types.crate_types.traits.get(s).cloned() {
929 for item in supertrait_obj.items.iter() {
931 syn::TraitItem::Method(m) => {
932 impl_meth!(m, s, supertrait_obj, "\t");
940 write!(w, "\n").unwrap();
941 } else if path_matches_nongeneric(&trait_path.1, &["From"]) {
942 } else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
943 writeln!(w, "/// Creates a \"default\" {}. See struct and individual field documentaiton for details on which values are used.", ident).unwrap();
944 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
945 write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
946 write!(w, "}}\n").unwrap();
947 } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "PartialEq"]) {
948 } else if (path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) || path_matches_nongeneric(&trait_path.1, &["Clone"])) &&
949 types.c_type_has_inner_from_path(&resolved_path) {
950 writeln!(w, "impl Clone for {} {{", ident).unwrap();
951 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
952 writeln!(w, "\t\tSelf {{").unwrap();
953 writeln!(w, "\t\t\tinner: if <*mut native{}>::is_null(self.inner) {{ std::ptr::null_mut() }} else {{", ident).unwrap();
954 writeln!(w, "\t\t\t\tBox::into_raw(Box::new(unsafe {{ &*self.inner }}.clone())) }},").unwrap();
955 writeln!(w, "\t\t\tis_owned: true,").unwrap();
956 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
957 writeln!(w, "#[allow(unused)]").unwrap();
958 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
959 writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", ident).unwrap();
960 writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", ident).unwrap();
961 writeln!(w, "}}").unwrap();
962 writeln!(w, "#[no_mangle]").unwrap();
963 writeln!(w, "/// Creates a copy of the {}", ident).unwrap();
964 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", ident, ident, ident).unwrap();
965 writeln!(w, "\torig.clone()").unwrap();
966 writeln!(w, "}}").unwrap();
968 //XXX: implement for other things like ToString
969 // If we have no generics, try a manual implementation:
970 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
973 let declared_type = (*types.get_declared_type(&ident).unwrap()).clone();
974 for item in i.items.iter() {
976 syn::ImplItem::Method(m) => {
977 if let syn::Visibility::Public(_) = m.vis {
978 match export_status(&m.attrs) {
979 ExportStatus::Export => {},
980 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
982 if m.defaultness.is_some() { unimplemented!(); }
983 writeln_docs(w, &m.attrs, "");
984 if let syn::ReturnType::Type(_, _) = &m.sig.output {
985 writeln!(w, "#[must_use]").unwrap();
987 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_{}(", ident, m.sig.ident).unwrap();
988 let ret_type = match &declared_type {
989 DeclType::MirroredEnum => format!("{}", ident),
990 DeclType::StructImported => format!("{}", ident),
991 _ => unimplemented!(),
993 gen_types.push_ctx();
994 assert!(gen_types.learn_generics(&m.sig.generics, types));
995 write_method_params(w, &m.sig, &ret_type, types, Some(&gen_types), false, true);
996 write!(w, " {{\n\t").unwrap();
997 write_method_var_decl_body(w, &m.sig, "", types, Some(&gen_types), false);
998 let mut takes_self = false;
999 let mut takes_mut_self = false;
1000 for inp in m.sig.inputs.iter() {
1001 if let syn::FnArg::Receiver(r) = inp {
1003 if r.mutability.is_some() { takes_mut_self = true; }
1007 write!(w, "unsafe {{ &mut (*(this_arg.inner as *mut native{})) }}.{}(", ident, m.sig.ident).unwrap();
1008 } else if takes_self {
1009 write!(w, "unsafe {{ &*this_arg.inner }}.{}(", m.sig.ident).unwrap();
1011 write!(w, "{}::{}::{}(", types.orig_crate, resolved_path, m.sig.ident).unwrap();
1013 write_method_call_params(w, &m.sig, "", types, Some(&gen_types), &ret_type, false);
1014 gen_types.pop_ctx();
1015 writeln!(w, "\n}}\n").unwrap();
1022 } else if let Some(resolved_path) = types.maybe_resolve_ident(&ident) {
1023 if let Some(aliases) = types.crate_types.reverse_alias_map.get(&resolved_path).cloned() {
1024 'alias_impls: for (alias, arguments) in aliases {
1025 let alias_resolved = types.resolve_path(&alias, None);
1026 for (idx, gen) in i.generics.params.iter().enumerate() {
1028 syn::GenericParam::Type(type_param) => {
1029 'bounds_check: for bound in type_param.bounds.iter() {
1030 if let syn::TypeParamBound::Trait(trait_bound) = bound {
1031 if let syn::PathArguments::AngleBracketed(ref t) = &arguments {
1032 assert!(idx < t.args.len());
1033 if let syn::GenericArgument::Type(syn::Type::Path(p)) = &t.args[idx] {
1034 let generic_arg = types.resolve_path(&p.path, None);
1035 let generic_bound = types.resolve_path(&trait_bound.path, None);
1036 if let Some(traits_impld) = types.crate_types.trait_impls.get(&generic_arg) {
1037 for trait_impld in traits_impld {
1038 if *trait_impld == generic_bound { continue 'bounds_check; }
1040 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1041 continue 'alias_impls;
1043 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1044 continue 'alias_impls;
1046 } else { unimplemented!(); }
1047 } else { unimplemented!(); }
1048 } else { unimplemented!(); }
1051 syn::GenericParam::Lifetime(_) => {},
1052 syn::GenericParam::Const(_) => unimplemented!(),
1055 let aliased_impl = syn::ItemImpl {
1056 attrs: i.attrs.clone(),
1057 brace_token: syn::token::Brace(Span::call_site()),
1059 generics: syn::Generics {
1061 params: syn::punctuated::Punctuated::new(),
1065 impl_token: syn::Token![impl](Span::call_site()),
1066 items: i.items.clone(),
1067 self_ty: Box::new(syn::Type::Path(syn::TypePath { qself: None, path: alias.clone() })),
1068 trait_: i.trait_.clone(),
1071 writeln_impl(w, &aliased_impl, types);
1074 eprintln!("Not implementing anything for {} due to it being marked not exported", ident);
1077 eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub)", ident);
1084 /// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
1085 /// is unitary), we generate an equivalent enum with all types replaced with their C mapped
1086 /// versions followed by conversion functions which map between the Rust version and the C mapped
1088 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) {
1089 match export_status(&e.attrs) {
1090 ExportStatus::Export => {},
1091 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1094 if is_enum_opaque(e) {
1095 eprintln!("Skipping enum {} as it contains non-unit fields", e.ident);
1096 writeln_opaque(w, &e.ident, &format!("{}", e.ident), &e.generics, &e.attrs, types, extra_headers, cpp_headers);
1099 writeln_docs(w, &e.attrs, "");
1101 if e.generics.lt_token.is_some() {
1105 let mut needs_free = false;
1107 writeln!(w, "#[must_use]\n#[derive(Clone)]\n#[repr(C)]\npub enum {} {{", e.ident).unwrap();
1108 for var in e.variants.iter() {
1109 assert_eq!(export_status(&var.attrs), ExportStatus::Export); // We can't partially-export a mirrored enum
1110 writeln_docs(w, &var.attrs, "\t");
1111 write!(w, "\t{}", var.ident).unwrap();
1112 if let syn::Fields::Named(fields) = &var.fields {
1114 writeln!(w, " {{").unwrap();
1115 for field in fields.named.iter() {
1116 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1117 writeln_docs(w, &field.attrs, "\t\t");
1118 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1119 types.write_c_type(w, &field.ty, None, false);
1120 writeln!(w, ",").unwrap();
1122 write!(w, "\t}}").unwrap();
1123 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1125 write!(w, "(").unwrap();
1126 for (idx, field) in fields.unnamed.iter().enumerate() {
1127 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1128 types.write_c_type(w, &field.ty, None, false);
1129 if idx != fields.unnamed.len() - 1 {
1130 write!(w, ",").unwrap();
1133 write!(w, ")").unwrap();
1135 if var.discriminant.is_some() { unimplemented!(); }
1136 writeln!(w, ",").unwrap();
1138 writeln!(w, "}}\nuse {}::{}::{} as native{};\nimpl {} {{", types.orig_crate, types.module_path, e.ident, e.ident, e.ident).unwrap();
1140 macro_rules! write_conv {
1141 ($fn_sig: expr, $to_c: expr, $ref: expr) => {
1142 writeln!(w, "\t#[allow(unused)]\n\tpub(crate) fn {} {{\n\t\tmatch {} {{", $fn_sig, if $to_c { "native" } else { "self" }).unwrap();
1143 for var in e.variants.iter() {
1144 write!(w, "\t\t\t{}{}::{} ", if $to_c { "native" } else { "" }, e.ident, var.ident).unwrap();
1145 if let syn::Fields::Named(fields) = &var.fields {
1146 write!(w, "{{").unwrap();
1147 for field in fields.named.iter() {
1148 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1149 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, field.ident.as_ref().unwrap()).unwrap();
1151 write!(w, "}} ").unwrap();
1152 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1153 write!(w, "(").unwrap();
1154 for (idx, field) in fields.unnamed.iter().enumerate() {
1155 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1156 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, ('a' as u8 + idx as u8) as char).unwrap();
1158 write!(w, ") ").unwrap();
1160 write!(w, "=>").unwrap();
1162 macro_rules! handle_field_a {
1163 ($field: expr, $field_ident: expr) => { {
1164 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1165 let mut sink = ::std::io::sink();
1166 let mut out: &mut dyn std::io::Write = if $ref { &mut sink } else { w };
1167 let new_var = if $to_c {
1168 types.write_to_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None, false)
1170 types.write_from_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None)
1172 if $ref || new_var {
1174 write!(w, "let mut {}_nonref = (*{}).clone();\n\t\t\t\t", $field_ident, $field_ident).unwrap();
1176 let nonref_ident = syn::Ident::new(&format!("{}_nonref", $field_ident), Span::call_site());
1178 types.write_to_c_conversion_new_var(w, &nonref_ident, &$field.ty, None, false);
1180 types.write_from_c_conversion_new_var(w, &nonref_ident, &$field.ty, None);
1182 write!(w, "\n\t\t\t\t").unwrap();
1185 write!(w, "\n\t\t\t\t").unwrap();
1190 if let syn::Fields::Named(fields) = &var.fields {
1191 write!(w, " {{\n\t\t\t\t").unwrap();
1192 for field in fields.named.iter() {
1193 handle_field_a!(field, field.ident.as_ref().unwrap());
1195 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1196 write!(w, " {{\n\t\t\t\t").unwrap();
1197 for (idx, field) in fields.unnamed.iter().enumerate() {
1198 handle_field_a!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1200 } else { write!(w, " ").unwrap(); }
1202 write!(w, "{}{}::{}", if $to_c { "" } else { "native" }, e.ident, var.ident).unwrap();
1204 macro_rules! handle_field_b {
1205 ($field: expr, $field_ident: expr) => { {
1206 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1208 types.write_to_c_conversion_inline_prefix(w, &$field.ty, None, false);
1210 types.write_from_c_conversion_prefix(w, &$field.ty, None);
1212 write!(w, "{}{}", $field_ident,
1213 if $ref { "_nonref" } else { "" }).unwrap();
1215 types.write_to_c_conversion_inline_suffix(w, &$field.ty, None, false);
1217 types.write_from_c_conversion_suffix(w, &$field.ty, None);
1219 write!(w, ",").unwrap();
1223 if let syn::Fields::Named(fields) = &var.fields {
1224 write!(w, " {{").unwrap();
1225 for field in fields.named.iter() {
1226 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1227 write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1228 handle_field_b!(field, field.ident.as_ref().unwrap());
1230 writeln!(w, "\n\t\t\t\t}}").unwrap();
1231 write!(w, "\t\t\t}}").unwrap();
1232 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1233 write!(w, " (").unwrap();
1234 for (idx, field) in fields.unnamed.iter().enumerate() {
1235 write!(w, "\n\t\t\t\t\t").unwrap();
1236 handle_field_b!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1238 writeln!(w, "\n\t\t\t\t)").unwrap();
1239 write!(w, "\t\t\t}}").unwrap();
1241 writeln!(w, ",").unwrap();
1243 writeln!(w, "\t\t}}\n\t}}").unwrap();
1247 write_conv!(format!("to_native(&self) -> native{}", e.ident), false, true);
1248 write_conv!(format!("into_native(self) -> native{}", e.ident), false, false);
1249 write_conv!(format!("from_native(native: &native{}) -> Self", e.ident), true, true);
1250 write_conv!(format!("native_into(native: native{}) -> Self", e.ident), true, false);
1251 writeln!(w, "}}").unwrap();
1254 writeln!(w, "/// Frees any resources used by the {}", e.ident).unwrap();
1255 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", e.ident, e.ident).unwrap();
1257 writeln!(w, "/// Creates a copy of the {}", e.ident).unwrap();
1258 writeln!(w, "#[no_mangle]").unwrap();
1259 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
1260 writeln!(w, "\torig.clone()").unwrap();
1261 writeln!(w, "}}").unwrap();
1262 write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free);
1265 fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &mut TypeResolver<'b, 'a>) {
1266 match export_status(&f.attrs) {
1267 ExportStatus::Export => {},
1268 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1270 writeln_docs(w, &f.attrs, "");
1272 let mut gen_types = GenericTypes::new();
1273 if !gen_types.learn_generics(&f.sig.generics, types) { return; }
1275 write!(w, "#[no_mangle]\npub extern \"C\" fn {}(", f.sig.ident).unwrap();
1276 write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
1277 write!(w, " {{\n\t").unwrap();
1278 write_method_var_decl_body(w, &f.sig, "", types, Some(&gen_types), false);
1279 write!(w, "{}::{}::{}(", types.orig_crate, types.module_path, f.sig.ident).unwrap();
1280 write_method_call_params(w, &f.sig, "", types, Some(&gen_types), "", false);
1281 writeln!(w, "\n}}\n").unwrap();
1284 // ********************************
1285 // *** File/Crate Walking Logic ***
1286 // ********************************
1289 pub attrs: Vec<syn::Attribute>,
1290 pub items: Vec<syn::Item>,
1291 pub submods: Vec<String>,
1293 /// A struct containing the syn::File AST for each file in the crate.
1294 struct FullLibraryAST {
1295 modules: HashMap<String, ASTModule, NonRandomHash>,
1297 impl FullLibraryAST {
1298 fn load_module(&mut self, module: String, attrs: Vec<syn::Attribute>, mut items: Vec<syn::Item>) {
1299 let mut non_mod_items = Vec::with_capacity(items.len());
1300 let mut submods = Vec::with_capacity(items.len());
1301 for item in items.drain(..) {
1303 syn::Item::Mod(m) if m.content.is_some() => {
1304 if export_status(&m.attrs) == ExportStatus::Export {
1305 if let syn::Visibility::Public(_) = m.vis {
1306 let modident = format!("{}", m.ident);
1307 let modname = if module != "" {
1308 module.clone() + "::" + &modident
1312 self.load_module(modname, m.attrs, m.content.unwrap().1);
1313 submods.push(modident);
1315 non_mod_items.push(syn::Item::Mod(m));
1319 syn::Item::Mod(_) => panic!("--pretty=expanded output should never have non-body modules"),
1320 _ => { non_mod_items.push(item); }
1323 self.modules.insert(module, ASTModule { attrs, items: non_mod_items, submods });
1326 pub fn load_lib(lib: syn::File) -> Self {
1327 assert_eq!(export_status(&lib.attrs), ExportStatus::Export);
1328 let mut res = Self { modules: HashMap::default() };
1329 res.load_module("".to_owned(), lib.attrs, lib.items);
1334 /// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
1335 /// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
1336 /// at `module` from C.
1337 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) {
1338 for (module, astmod) in libast.modules.iter() {
1339 let ASTModule { ref attrs, ref items, ref submods } = astmod;
1340 assert_eq!(export_status(&attrs), ExportStatus::Export);
1342 let new_file_path = if submods.is_empty() {
1343 format!("{}/{}.rs", out_dir, module.replace("::", "/"))
1344 } else if module != "" {
1345 format!("{}/{}/mod.rs", out_dir, module.replace("::", "/"))
1347 format!("{}/lib.rs", out_dir)
1349 let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
1350 let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1351 .open(new_file_path).expect("Unable to open new src file");
1353 writeln!(out, "// This file is Copyright its original authors, visible in version control").unwrap();
1354 writeln!(out, "// history and in the source files from which this was generated.").unwrap();
1355 writeln!(out, "//").unwrap();
1356 writeln!(out, "// This file is licensed under the license available in the LICENSE or LICENSE.md").unwrap();
1357 writeln!(out, "// file in the root of this repository or, if no such file exists, the same").unwrap();
1358 writeln!(out, "// license as that which applies to the original source files from which this").unwrap();
1359 writeln!(out, "// source was automatically generated.").unwrap();
1360 writeln!(out, "").unwrap();
1362 writeln_docs(&mut out, &attrs, "");
1365 // Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
1366 // and bitcoin hand-written modules.
1367 writeln!(out, "#![allow(unknown_lints)]").unwrap();
1368 writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
1369 writeln!(out, "#![allow(non_snake_case)]").unwrap();
1370 writeln!(out, "#![allow(unused_imports)]").unwrap();
1371 writeln!(out, "#![allow(unused_variables)]").unwrap();
1372 writeln!(out, "#![allow(unused_mut)]").unwrap();
1373 writeln!(out, "#![allow(unused_parens)]").unwrap();
1374 writeln!(out, "#![allow(unused_unsafe)]").unwrap();
1375 writeln!(out, "#![allow(unused_braces)]").unwrap();
1376 writeln!(out, "#![deny(missing_docs)]").unwrap();
1377 writeln!(out, "mod c_types;").unwrap();
1378 writeln!(out, "mod bitcoin;").unwrap();
1380 writeln!(out, "\nuse std::ffi::c_void;\nuse bitcoin::hashes::Hash;\nuse crate::c_types::*;\n").unwrap();
1384 writeln!(out, "pub mod {};", m).unwrap();
1387 eprintln!("Converting {} entries...", module);
1389 let import_resolver = ImportResolver::new(module, items);
1390 let mut type_resolver = TypeResolver::new(orig_crate, module, import_resolver, crate_types);
1392 for item in items.iter() {
1394 syn::Item::Use(_) => {}, // Handled above
1395 syn::Item::Static(_) => {},
1396 syn::Item::Enum(e) => {
1397 if let syn::Visibility::Public(_) = e.vis {
1398 writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
1401 syn::Item::Impl(i) => {
1402 writeln_impl(&mut out, &i, &mut type_resolver);
1404 syn::Item::Struct(s) => {
1405 if let syn::Visibility::Public(_) = s.vis {
1406 writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
1409 syn::Item::Trait(t) => {
1410 if let syn::Visibility::Public(_) = t.vis {
1411 writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
1414 syn::Item::Mod(_) => {}, // We don't have to do anything - the top loop handles these.
1415 syn::Item::Const(c) => {
1416 // Re-export any primitive-type constants.
1417 if let syn::Visibility::Public(_) = c.vis {
1418 if let syn::Type::Path(p) = &*c.ty {
1419 let resolved_path = type_resolver.resolve_path(&p.path, None);
1420 if type_resolver.is_primitive(&resolved_path) {
1421 writeln_docs(&mut out, &c.attrs, "");
1422 writeln!(out, "\n#[no_mangle]").unwrap();
1423 writeln!(out, "pub static {}: {} = {}::{}::{};", c.ident, resolved_path, orig_crate, module, c.ident).unwrap();
1428 syn::Item::Type(t) => {
1429 if let syn::Visibility::Public(_) = t.vis {
1430 match export_status(&t.attrs) {
1431 ExportStatus::Export => {},
1432 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1435 let mut process_alias = true;
1436 for tok in t.generics.params.iter() {
1437 if let syn::GenericParam::Lifetime(_) = tok {}
1438 else { process_alias = false; }
1442 syn::Type::Path(_) =>
1443 writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &t.generics, &t.attrs, &type_resolver, header_file, cpp_header_file),
1449 syn::Item::Fn(f) => {
1450 if let syn::Visibility::Public(_) = f.vis {
1451 writeln_fn(&mut out, &f, &mut type_resolver);
1454 syn::Item::Macro(m) => {
1455 if m.ident.is_none() { // If its not a macro definition
1456 convert_macro(&mut out, &m.mac.path, &m.mac.tokens, &type_resolver);
1459 syn::Item::Verbatim(_) => {},
1460 syn::Item::ExternCrate(_) => {},
1461 _ => unimplemented!(),
1465 out.flush().unwrap();
1469 fn walk_private_mod<'a>(module: String, items: &'a syn::ItemMod, crate_types: &mut CrateTypes<'a>) {
1470 let import_resolver = ImportResolver::new(&module, &items.content.as_ref().unwrap().1);
1471 for item in items.content.as_ref().unwrap().1.iter() {
1473 syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types),
1474 syn::Item::Impl(i) => {
1475 if let &syn::Type::Path(ref p) = &*i.self_ty {
1476 if let Some(trait_path) = i.trait_.as_ref() {
1477 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1478 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1479 match crate_types.trait_impls.entry(sp) {
1480 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1481 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1493 /// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
1494 fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
1495 for (module, astmod) in ast_storage.modules.iter() {
1496 let ASTModule { ref attrs, ref items, submods: _ } = astmod;
1497 assert_eq!(export_status(&attrs), ExportStatus::Export);
1498 let import_resolver = ImportResolver::new(module, items);
1500 for item in items.iter() {
1502 syn::Item::Struct(s) => {
1503 if let syn::Visibility::Public(_) = s.vis {
1504 match export_status(&s.attrs) {
1505 ExportStatus::Export => {},
1506 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1508 let struct_path = format!("{}::{}", module, s.ident);
1509 crate_types.opaques.insert(struct_path, &s.ident);
1512 syn::Item::Trait(t) => {
1513 if let syn::Visibility::Public(_) = t.vis {
1514 match export_status(&t.attrs) {
1515 ExportStatus::Export => {},
1516 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1518 let trait_path = format!("{}::{}", module, t.ident);
1519 walk_supertraits!(t, None, (
1521 crate_types.clonable_types.insert("crate::".to_owned() + &trait_path);
1525 crate_types.traits.insert(trait_path, &t);
1528 syn::Item::Type(t) => {
1529 if let syn::Visibility::Public(_) = t.vis {
1530 match export_status(&t.attrs) {
1531 ExportStatus::Export => {},
1532 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1534 let type_path = format!("{}::{}", module, t.ident);
1535 let mut process_alias = true;
1536 for tok in t.generics.params.iter() {
1537 if let syn::GenericParam::Lifetime(_) = tok {}
1538 else { process_alias = false; }
1542 syn::Type::Path(p) => {
1543 // If its a path with no generics, assume we don't map the aliased type and map it opaque
1544 let mut segments = syn::punctuated::Punctuated::new();
1545 segments.push(syn::PathSegment {
1546 ident: t.ident.clone(),
1547 arguments: syn::PathArguments::None,
1549 let path_obj = syn::Path { leading_colon: None, segments };
1550 let args_obj = p.path.segments.last().unwrap().arguments.clone();
1551 match crate_types.reverse_alias_map.entry(import_resolver.maybe_resolve_path(&p.path, None).unwrap()) {
1552 hash_map::Entry::Occupied(mut e) => { e.get_mut().push((path_obj, args_obj)); },
1553 hash_map::Entry::Vacant(e) => { e.insert(vec![(path_obj, args_obj)]); },
1556 crate_types.opaques.insert(type_path.clone(), &t.ident);
1559 crate_types.type_aliases.insert(type_path, import_resolver.resolve_imported_refs((*t.ty).clone()));
1565 syn::Item::Enum(e) if is_enum_opaque(e) => {
1566 if let syn::Visibility::Public(_) = e.vis {
1567 match export_status(&e.attrs) {
1568 ExportStatus::Export => {},
1569 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1571 let enum_path = format!("{}::{}", module, e.ident);
1572 crate_types.opaques.insert(enum_path, &e.ident);
1575 syn::Item::Enum(e) => {
1576 if let syn::Visibility::Public(_) = e.vis {
1577 match export_status(&e.attrs) {
1578 ExportStatus::Export => {},
1579 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1581 let enum_path = format!("{}::{}", module, e.ident);
1582 crate_types.mirrored_enums.insert(enum_path, &e);
1585 syn::Item::Impl(i) => {
1586 if let &syn::Type::Path(ref p) = &*i.self_ty {
1587 if let Some(trait_path) = i.trait_.as_ref() {
1588 if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) {
1589 if let Some(full_path) = import_resolver.maybe_resolve_path(&p.path, None) {
1590 crate_types.clonable_types.insert("crate::".to_owned() + &full_path);
1593 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1594 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1595 match crate_types.trait_impls.entry(sp) {
1596 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1597 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1604 syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types),
1612 let args: Vec<String> = env::args().collect();
1613 if args.len() != 6 {
1614 eprintln!("Usage: target/dir source_crate_name derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
1618 let mut derived_templates = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1619 .open(&args[3]).expect("Unable to open new header file");
1620 let mut header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1621 .open(&args[4]).expect("Unable to open new header file");
1622 let mut cpp_header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1623 .open(&args[5]).expect("Unable to open new header file");
1625 writeln!(header_file, "#if defined(__GNUC__)").unwrap();
1626 writeln!(header_file, "#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
1627 writeln!(header_file, "#define MUST_USE_RES __attribute__((warn_unused_result))").unwrap();
1628 writeln!(header_file, "#else").unwrap();
1629 writeln!(header_file, "#define MUST_USE_STRUCT").unwrap();
1630 writeln!(header_file, "#define MUST_USE_RES").unwrap();
1631 writeln!(header_file, "#endif").unwrap();
1632 writeln!(header_file, "#if defined(__clang__)").unwrap();
1633 writeln!(header_file, "#define NONNULL_PTR _Nonnull").unwrap();
1634 writeln!(header_file, "#else").unwrap();
1635 writeln!(header_file, "#define NONNULL_PTR").unwrap();
1636 writeln!(header_file, "#endif").unwrap();
1637 writeln!(cpp_header_file, "#include <string.h>\nnamespace LDK {{").unwrap();
1639 // First parse the full crate's ASTs, caching them so that we can hold references to the AST
1640 // objects in other datastructures:
1641 let mut lib_src = String::new();
1642 std::io::stdin().lock().read_to_string(&mut lib_src).unwrap();
1643 let lib_syntax = syn::parse_file(&lib_src).expect("Unable to parse file");
1644 let libast = FullLibraryAST::load_lib(lib_syntax);
1646 // ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
1647 // when parsing other file ASTs...
1648 let mut libtypes = CrateTypes { traits: HashMap::new(), opaques: HashMap::new(), mirrored_enums: HashMap::new(),
1649 type_aliases: HashMap::new(), reverse_alias_map: HashMap::new(), templates_defined: HashMap::default(),
1650 template_file: &mut derived_templates,
1651 clonable_types: HashSet::new(), trait_impls: HashMap::new() };
1652 walk_ast(&libast, &mut libtypes);
1654 // ... finally, do the actual file conversion/mapping, writing out types as we go.
1655 convert_file(&libast, &mut libtypes, &args[1], &args[2], &mut header_file, &mut cpp_header_file);
1657 // For container templates which we created while walking the crate, make sure we add C++
1658 // mapped types so that C++ users can utilize the auto-destructors available.
1659 for (ty, has_destructor) in libtypes.templates_defined.iter() {
1660 write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor);
1662 writeln!(cpp_header_file, "}}").unwrap();
1664 header_file.flush().unwrap();
1665 cpp_header_file.flush().unwrap();
1666 derived_templates.flush().unwrap();