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};
24 use std::io::{Read, Write};
27 use proc_macro2::Span;
35 // *************************************
36 // *** Manually-expanded conversions ***
37 // *************************************
39 /// Convert "impl trait_path for for_ty { .. }" for manually-mapped types (ie (de)serialization)
40 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) {
41 if let Some(t) = types.maybe_resolve_path(&trait_path, Some(generics)) {
44 let mut has_inner = false;
45 if let syn::Type::Path(ref p) = for_ty {
46 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
47 for_obj = format!("{}", ident);
48 full_obj_path = for_obj.clone();
49 has_inner = types.c_type_has_inner_from_path(&types.resolve_path(&p.path, Some(generics)));
52 // We assume that anything that isn't a Path is somehow a generic that ends up in our
53 // derived-types module.
54 let mut for_obj_vec = Vec::new();
55 types.write_c_type(&mut for_obj_vec, for_ty, Some(generics), false);
56 full_obj_path = String::from_utf8(for_obj_vec).unwrap();
57 assert!(full_obj_path.starts_with(TypeResolver::generated_container_path()));
58 for_obj = full_obj_path[TypeResolver::generated_container_path().len() + 2..].into();
62 "lightning::util::ser::Writeable" => {
63 writeln!(w, "#[no_mangle]").unwrap();
64 writeln!(w, "/// Serialize the {} object into a byte array which can be read by {}_read", for_obj, for_obj).unwrap();
65 writeln!(w, "pub extern \"C\" fn {}_write(obj: &{}) -> crate::c_types::derived::CVec_u8Z {{", for_obj, full_obj_path).unwrap();
67 let ref_type: syn::Type = syn::parse_quote!(&#for_ty);
68 assert!(!types.write_from_c_conversion_new_var(w, &syn::Ident::new("obj", Span::call_site()), &ref_type, Some(generics)));
70 write!(w, "\tcrate::c_types::serialize_obj(").unwrap();
71 types.write_from_c_conversion_prefix(w, &ref_type, Some(generics));
72 write!(w, "unsafe {{ &*obj }}").unwrap();
73 types.write_from_c_conversion_suffix(w, &ref_type, Some(generics));
74 writeln!(w, ")").unwrap();
76 writeln!(w, "}}").unwrap();
78 writeln!(w, "#[no_mangle]").unwrap();
79 writeln!(w, "pub(crate) extern \"C\" fn {}_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {{", for_obj).unwrap();
80 writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &*(obj as *const native{}) }})", for_obj).unwrap();
81 writeln!(w, "}}").unwrap();
84 "lightning::util::ser::Readable"|"lightning::util::ser::ReadableArgs" => {
85 // Create the Result<Object, DecodeError> syn::Type
86 let res_ty: syn::Type = parse_quote!(Result<#for_ty, ::ln::msgs::DecodeError>);
88 writeln!(w, "#[no_mangle]").unwrap();
89 writeln!(w, "/// Read a {} from a byte array, created by {}_write", for_obj, for_obj).unwrap();
90 write!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice", for_obj).unwrap();
92 let mut arg_conv = Vec::new();
93 if t == "lightning::util::ser::ReadableArgs" {
94 write!(w, ", arg: ").unwrap();
95 assert!(trait_path.leading_colon.is_none());
96 let args_seg = trait_path.segments.iter().last().unwrap();
97 assert_eq!(format!("{}", args_seg.ident), "ReadableArgs");
98 if let syn::PathArguments::AngleBracketed(args) = &args_seg.arguments {
99 assert_eq!(args.args.len(), 1);
100 if let syn::GenericArgument::Type(args_ty) = args.args.iter().next().unwrap() {
101 types.write_c_type(w, args_ty, Some(generics), false);
103 assert!(!types.write_from_c_conversion_new_var(&mut arg_conv, &syn::Ident::new("arg", Span::call_site()), &args_ty, Some(generics)));
105 write!(&mut arg_conv, "\tlet arg_conv = ").unwrap();
106 types.write_from_c_conversion_prefix(&mut arg_conv, &args_ty, Some(generics));
107 write!(&mut arg_conv, "arg").unwrap();
108 types.write_from_c_conversion_suffix(&mut arg_conv, &args_ty, Some(generics));
109 } else { unreachable!(); }
110 } else { unreachable!(); }
112 write!(w, ") -> ").unwrap();
113 types.write_c_type(w, &res_ty, Some(generics), false);
114 writeln!(w, " {{").unwrap();
116 if t == "lightning::util::ser::ReadableArgs" {
117 w.write(&arg_conv).unwrap();
118 write!(w, ";\n\tlet res: ").unwrap();
119 // At least in one case we need type annotations here, so provide them.
120 types.write_rust_type(w, Some(generics), &res_ty);
121 writeln!(w, " = crate::c_types::deserialize_obj_arg(ser, arg_conv);").unwrap();
123 writeln!(w, "\tlet res = crate::c_types::deserialize_obj(ser);").unwrap();
125 write!(w, "\t").unwrap();
126 if types.write_to_c_conversion_new_var(w, &syn::Ident::new("res", Span::call_site()), &res_ty, Some(generics), false) {
127 write!(w, "\n\t").unwrap();
129 types.write_to_c_conversion_inline_prefix(w, &res_ty, Some(generics), false);
130 write!(w, "res").unwrap();
131 types.write_to_c_conversion_inline_suffix(w, &res_ty, Some(generics), false);
132 writeln!(w, "\n}}").unwrap();
139 /// Convert "TraitA : TraitB" to a single function name and return type.
141 /// This is (obviously) somewhat over-specialized and only useful for TraitB's that only require a
142 /// single function (eg for serialization).
143 fn convert_trait_impl_field(trait_path: &str) -> (&'static str, String, &'static str) {
145 "lightning::util::ser::Writeable" => ("Serialize the object into a byte array", "write".to_owned(), "crate::c_types::derived::CVec_u8Z"),
146 _ => unimplemented!(),
150 /// Companion to convert_trait_impl_field, write an assignment for the function defined by it for
151 /// `for_obj` which implements the the trait at `trait_path`.
152 fn write_trait_impl_field_assign<W: std::io::Write>(w: &mut W, trait_path: &str, for_obj: &syn::Ident) {
154 "lightning::util::ser::Writeable" => {
155 writeln!(w, "\t\twrite: {}_write_void,", for_obj).unwrap();
157 _ => unimplemented!(),
161 /// Write out the impl block for a defined trait struct which has a supertrait
162 fn do_write_impl_trait<W: std::io::Write>(w: &mut W, trait_path: &str, _trait_name: &syn::Ident, for_obj: &str) {
163 eprintln!("{}", trait_path);
165 "lightning::util::ser::Writeable" => {
166 writeln!(w, "impl {} for {} {{", trait_path, for_obj).unwrap();
167 writeln!(w, "\tfn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {{").unwrap();
168 writeln!(w, "\t\tlet vec = (self.write)(self.this_arg);").unwrap();
169 writeln!(w, "\t\tw.write_all(vec.as_slice())").unwrap();
170 writeln!(w, "\t}}\n}}").unwrap();
176 // *******************************
177 // *** Per-Type Printing Logic ***
178 // *******************************
180 macro_rules! walk_supertraits { ($t: expr, $types: expr, ($( $pat: pat => $e: expr),*) ) => { {
181 if $t.colon_token.is_some() {
182 for st in $t.supertraits.iter() {
184 syn::TypeParamBound::Trait(supertrait) => {
185 if supertrait.paren_token.is_some() || supertrait.lifetimes.is_some() {
188 // First try to resolve path to find in-crate traits, but if that doesn't work
189 // assume its a prelude trait (eg Clone, etc) and just use the single ident.
190 let types_opt: Option<&TypeResolver> = $types;
191 if let Some(types) = types_opt {
192 if let Some(path) = types.maybe_resolve_path(&supertrait.path, None) {
193 match (&path as &str, &supertrait.path.segments.iter().last().unwrap().ident) {
199 if let Some(ident) = supertrait.path.get_ident() {
200 match (&format!("{}", ident) as &str, &ident) {
203 } else if types_opt.is_some() {
204 panic!("Supertrait unresolvable and not single-ident");
207 syn::TypeParamBound::Lifetime(_) => unimplemented!(),
213 /// Prints a C-mapped trait object containing a void pointer and a jump table for each function in
214 /// the original trait.
215 /// Implements the native Rust trait and relevant parent traits for the new C-mapped trait.
217 /// Finally, implements Deref<MappedTrait> for MappedTrait which allows its use in types which need
218 /// a concrete Deref to the Rust trait.
219 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) {
220 let trait_name = format!("{}", t.ident);
221 match export_status(&t.attrs) {
222 ExportStatus::Export => {},
223 ExportStatus::NoExport|ExportStatus::TestOnly => return,
225 writeln_docs(w, &t.attrs, "");
227 let mut gen_types = GenericTypes::new();
228 assert!(gen_types.learn_generics(&t.generics, types));
229 gen_types.learn_associated_types(&t, types);
231 writeln!(w, "#[repr(C)]\npub struct {} {{", trait_name).unwrap();
232 writeln!(w, "\t/// An opaque pointer which is passed to your function implementations as an argument.").unwrap();
233 writeln!(w, "\t/// This has no meaning in the LDK, and can be NULL or any other value.").unwrap();
234 writeln!(w, "\tpub this_arg: *mut c_void,").unwrap();
235 let mut generated_fields = Vec::new(); // Every field's (name, is_clonable) except this_arg, used in Clone generation
236 for item in t.items.iter() {
238 &syn::TraitItem::Method(ref m) => {
239 match export_status(&m.attrs) {
240 ExportStatus::NoExport => {
241 // NoExport in this context means we'll hit an unimplemented!() at runtime,
245 ExportStatus::Export => {},
246 ExportStatus::TestOnly => continue,
248 if m.default.is_some() { unimplemented!(); }
250 let mut meth_gen_types = gen_types.push_ctx();
251 assert!(meth_gen_types.learn_generics(&m.sig.generics, types));
253 writeln_docs(w, &m.attrs, "\t");
255 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
256 if let syn::Type::Reference(r) = &**rtype {
257 // We have to do quite a dance for trait functions which return references
258 // - they ultimately require us to have a native Rust object stored inside
259 // our concrete trait to return a reference to. However, users may wish to
260 // update the value to be returned each time the function is called (or, to
261 // make C copies of Rust impls equivalent, we have to be able to).
263 // Thus, we store a copy of the C-mapped type (which is just a pointer to
264 // the Rust type and a flag to indicate whether deallocation needs to
265 // happen) as well as provide an Option<>al function pointer which is
266 // called when the trait method is called which allows updating on the fly.
267 write!(w, "\tpub {}: ", m.sig.ident).unwrap();
268 generated_fields.push((format!("{}", m.sig.ident), true));
269 types.write_c_type(w, &*r.elem, Some(&meth_gen_types), false);
270 writeln!(w, ",").unwrap();
271 writeln!(w, "\t/// Fill in the {} field as a reference to it will be given to Rust after this returns", m.sig.ident).unwrap();
272 writeln!(w, "\t/// Note that this takes a pointer to this object, not the this_ptr like other methods do").unwrap();
273 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();
274 writeln!(w, "\tpub set_{}: Option<extern \"C\" fn(&{})>,", m.sig.ident, trait_name).unwrap();
275 generated_fields.push((format!("set_{}", m.sig.ident), true));
276 // Note that cbindgen will now generate
277 // typedef struct Thing {..., set_thing: (const Thing*), ...} Thing;
278 // which does not compile since Thing is not defined before it is used.
279 writeln!(extra_headers, "struct LDK{};", trait_name).unwrap();
280 writeln!(extra_headers, "typedef struct LDK{} LDK{};", trait_name, trait_name).unwrap();
283 // Sadly, this currently doesn't do what we want, but it should be easy to get
284 // cbindgen to support it. See https://github.com/eqrion/cbindgen/issues/531
285 writeln!(w, "\t#[must_use]").unwrap();
288 write!(w, "\tpub {}: extern \"C\" fn (", m.sig.ident).unwrap();
289 generated_fields.push((format!("{}", m.sig.ident), true));
290 write_method_params(w, &m.sig, "c_void", types, Some(&meth_gen_types), true, false);
291 writeln!(w, ",").unwrap();
293 &syn::TraitItem::Type(_) => {},
294 _ => unimplemented!(),
297 // Add functions which may be required for supertrait implementations.
298 let mut requires_clone = false;
299 walk_supertraits!(t, Some(&types), (
300 ("Clone", _) => requires_clone = true,
303 walk_supertraits!(t, Some(&types), (
305 writeln!(w, "\t/// Creates a copy of the object pointed to by this_arg, for a copy of this {}.", trait_name).unwrap();
306 writeln!(w, "\t/// Note that the ultimate copy of the {} will have all function pointers the same as the original.", trait_name).unwrap();
307 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();
308 writeln!(w, "\tpub clone: Option<extern \"C\" fn (this_arg: *const c_void) -> *mut c_void>,").unwrap();
309 generated_fields.push(("clone".to_owned(), true));
311 ("std::cmp::Eq", _) => {
312 writeln!(w, "\t/// Checks if two objects are equal given this object's this_arg pointer and another object.").unwrap();
313 writeln!(w, "\tpub eq: extern \"C\" fn (this_arg: *const c_void, other_arg: &{}) -> bool,", trait_name).unwrap();
314 writeln!(extra_headers, "typedef struct LDK{} LDK{};", trait_name, trait_name).unwrap();
315 generated_fields.push(("eq".to_owned(), true));
317 ("std::hash::Hash", _) => {
318 writeln!(w, "\t/// Calculate a succinct non-cryptographic hash for an object given its this_arg pointer.").unwrap();
319 writeln!(w, "\t/// This is used, for example, for inclusion of this object in a hash map.").unwrap();
320 writeln!(w, "\tpub hash: extern \"C\" fn (this_arg: *const c_void) -> u64,").unwrap();
321 generated_fields.push(("hash".to_owned(), true));
323 ("Send", _) => {}, ("Sync", _) => {},
325 generated_fields.push(if types.crate_types.traits.get(s).is_none() {
326 let (docs, name, ret) = convert_trait_impl_field(s);
327 writeln!(w, "\t/// {}", docs).unwrap();
328 writeln!(w, "\tpub {}: extern \"C\" fn (this_arg: *const c_void) -> {},", name, ret).unwrap();
329 (name, true) // Assume clonable
331 // For in-crate supertraits, just store a C-mapped copy of the supertrait as a member.
332 writeln!(w, "\t/// Implementation of {} for this object.", i).unwrap();
333 writeln!(w, "\tpub {}: crate::{},", i, s).unwrap();
334 let is_clonable = types.is_clonable(s);
335 if !is_clonable && requires_clone {
336 writeln!(w, "\t/// Creates a copy of the {}, for a copy of this {}.", i, trait_name).unwrap();
337 writeln!(w, "\t/// Because {} doesn't natively support copying itself, you have to provide a full copy implementation here.", i).unwrap();
338 writeln!(w, "\tpub {}_clone: extern \"C\" fn (orig_{}: &{}) -> {},", i, i, i, i).unwrap();
340 (format!("{}", i), is_clonable)
344 writeln!(w, "\t/// Frees any resources associated with this object given its this_arg pointer.").unwrap();
345 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();
346 writeln!(w, "\tpub free: Option<extern \"C\" fn(this_arg: *mut c_void)>,").unwrap();
347 generated_fields.push(("free".to_owned(), true));
348 writeln!(w, "}}").unwrap();
350 macro_rules! impl_trait_for_c {
351 ($t: expr, $impl_accessor: expr, $type_resolver: expr) => {
352 for item in $t.items.iter() {
354 syn::TraitItem::Method(m) => {
355 if let ExportStatus::TestOnly = export_status(&m.attrs) { continue; }
356 if m.default.is_some() { unimplemented!(); }
357 if m.sig.constness.is_some() || m.sig.asyncness.is_some() || m.sig.unsafety.is_some() ||
358 m.sig.abi.is_some() || m.sig.variadic.is_some() {
361 let mut meth_gen_types = gen_types.push_ctx();
362 assert!(meth_gen_types.learn_generics(&m.sig.generics, $type_resolver));
363 write!(w, "\tfn {}", m.sig.ident).unwrap();
364 $type_resolver.write_rust_generic_param(w, Some(&meth_gen_types), m.sig.generics.params.iter());
365 write!(w, "(").unwrap();
366 for inp in m.sig.inputs.iter() {
368 syn::FnArg::Receiver(recv) => {
369 if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
370 write!(w, "&").unwrap();
371 if let Some(lft) = &recv.reference.as_ref().unwrap().1 {
372 write!(w, "'{} ", lft.ident).unwrap();
374 if recv.mutability.is_some() {
375 write!(w, "mut self").unwrap();
377 write!(w, "self").unwrap();
380 syn::FnArg::Typed(arg) => {
381 if !arg.attrs.is_empty() { unimplemented!(); }
383 syn::Pat::Ident(ident) => {
384 if !ident.attrs.is_empty() || ident.by_ref.is_some() ||
385 ident.mutability.is_some() || ident.subpat.is_some() {
388 write!(w, ", {}{}: ", if $type_resolver.skip_arg(&*arg.ty, Some(&meth_gen_types)) { "_" } else { "" }, ident.ident).unwrap();
390 _ => unimplemented!(),
392 $type_resolver.write_rust_type(w, Some(&meth_gen_types), &*arg.ty);
396 write!(w, ")").unwrap();
397 match &m.sig.output {
398 syn::ReturnType::Type(_, rtype) => {
399 write!(w, " -> ").unwrap();
400 $type_resolver.write_rust_type(w, Some(&meth_gen_types), &*rtype)
404 write!(w, " {{\n\t\t").unwrap();
405 match export_status(&m.attrs) {
406 ExportStatus::NoExport => {
411 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
412 if let syn::Type::Reference(r) = &**rtype {
413 assert_eq!(m.sig.inputs.len(), 1); // Must only take self!
414 writeln!(w, "if let Some(f) = self{}.set_{} {{", $impl_accessor, m.sig.ident).unwrap();
415 writeln!(w, "\t\t\t(f)(&self{});", $impl_accessor).unwrap();
416 write!(w, "\t\t}}\n\t\t").unwrap();
417 $type_resolver.write_from_c_conversion_to_ref_prefix(w, &*r.elem, Some(&meth_gen_types));
418 write!(w, "self{}.{}", $impl_accessor, m.sig.ident).unwrap();
419 $type_resolver.write_from_c_conversion_to_ref_suffix(w, &*r.elem, Some(&meth_gen_types));
420 writeln!(w, "\n\t}}").unwrap();
424 write_method_var_decl_body(w, &m.sig, "\t", $type_resolver, Some(&meth_gen_types), true);
425 write!(w, "(self{}.{})(", $impl_accessor, m.sig.ident).unwrap();
426 write_method_call_params(w, &m.sig, "\t", $type_resolver, Some(&meth_gen_types), "", true);
428 writeln!(w, "\n\t}}").unwrap();
430 &syn::TraitItem::Type(ref t) => {
431 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
432 let mut bounds_iter = t.bounds.iter();
433 match bounds_iter.next().unwrap() {
434 syn::TypeParamBound::Trait(tr) => {
435 writeln!(w, "\ttype {} = crate::{};", t.ident, $type_resolver.resolve_path(&tr.path, Some(&gen_types))).unwrap();
437 _ => unimplemented!(),
439 if bounds_iter.next().is_some() { unimplemented!(); }
441 _ => unimplemented!(),
448 // Implement supertraits for the C-mapped struct.
449 walk_supertraits!(t, Some(&types), (
450 ("Send", _) => writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap(),
451 ("Sync", _) => writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap(),
452 ("std::cmp::Eq", _) => {
453 writeln!(w, "impl std::cmp::Eq for {} {{}}", trait_name).unwrap();
454 writeln!(w, "impl std::cmp::PartialEq for {} {{", trait_name).unwrap();
455 writeln!(w, "\tfn eq(&self, o: &Self) -> bool {{ (self.eq)(self.this_arg, o) }}\n}}").unwrap();
457 ("std::hash::Hash", _) => {
458 writeln!(w, "impl std::hash::Hash for {} {{", trait_name).unwrap();
459 writeln!(w, "\tfn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {{ hasher.write_u64((self.hash)(self.this_arg)) }}\n}}").unwrap();
462 writeln!(w, "#[no_mangle]").unwrap();
463 writeln!(w, "/// Creates a copy of a {}", trait_name).unwrap();
464 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", trait_name, trait_name, trait_name).unwrap();
465 writeln!(w, "\t{} {{", trait_name).unwrap();
466 writeln!(w, "\t\tthis_arg: if let Some(f) = orig.clone {{ (f)(orig.this_arg) }} else {{ orig.this_arg }},").unwrap();
467 for (field, clonable) in generated_fields.iter() {
469 writeln!(w, "\t\t{}: Clone::clone(&orig.{}),", field, field).unwrap();
471 writeln!(w, "\t\t{}: (orig.{}_clone)(&orig.{}),", field, field, field).unwrap();
472 writeln!(w, "\t\t{}_clone: orig.{}_clone,", field, field).unwrap();
475 writeln!(w, "\t}}\n}}").unwrap();
476 writeln!(w, "impl Clone for {} {{", trait_name).unwrap();
477 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
478 writeln!(w, "\t\t{}_clone(self)", trait_name).unwrap();
479 writeln!(w, "\t}}\n}}").unwrap();
482 if let Some(supertrait) = types.crate_types.traits.get(s) {
483 let mut module_iter = s.rsplitn(2, "::");
484 module_iter.next().unwrap();
485 let supertrait_module = module_iter.next().unwrap();
486 let imports = ImportResolver::new(supertrait_module.splitn(2, "::").next().unwrap(), &types.crate_types.lib_ast.dependencies,
487 supertrait_module, &types.crate_types.lib_ast.modules.get(supertrait_module).unwrap().items);
488 let resolver = TypeResolver::new(&supertrait_module, imports, types.crate_types);
489 writeln!(w, "impl {} for {} {{", s, trait_name).unwrap();
490 impl_trait_for_c!(supertrait, format!(".{}", i), &resolver);
491 writeln!(w, "}}").unwrap();
492 walk_supertraits!(supertrait, Some(&types), (
493 ("Send", _) => writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap(),
494 ("Sync", _) => writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap(),
495 _ => unimplemented!()
498 do_write_impl_trait(w, s, i, &trait_name);
503 // Finally, implement the original Rust trait for the newly created mapped trait.
504 writeln!(w, "\nuse {}::{} as rust{};", types.module_path, t.ident, trait_name).unwrap();
505 write!(w, "impl rust{}", t.ident).unwrap();
506 maybe_write_generics(w, &t.generics, types, false);
507 writeln!(w, " for {} {{", trait_name).unwrap();
508 impl_trait_for_c!(t, "", types);
509 writeln!(w, "}}\n").unwrap();
510 writeln!(w, "// We're essentially a pointer already, or at least a set of pointers, so allow us to be used").unwrap();
511 writeln!(w, "// directly as a Deref trait in higher-level structs:").unwrap();
512 writeln!(w, "impl std::ops::Deref for {} {{\n\ttype Target = Self;", trait_name).unwrap();
513 writeln!(w, "\tfn deref(&self) -> &Self {{\n\t\tself\n\t}}\n}}").unwrap();
515 writeln!(w, "/// Calls the free function if one is set").unwrap();
516 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", trait_name, trait_name).unwrap();
517 writeln!(w, "impl Drop for {} {{", trait_name).unwrap();
518 writeln!(w, "\tfn drop(&mut self) {{").unwrap();
519 writeln!(w, "\t\tif let Some(f) = self.free {{").unwrap();
520 writeln!(w, "\t\t\tf(self.this_arg);").unwrap();
521 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
523 write_cpp_wrapper(cpp_headers, &trait_name, true);
526 /// Write out a simple "opaque" type (eg structs) which contain a pointer to the native Rust type
527 /// and a flag to indicate whether Drop'ing the mapped struct drops the underlying Rust type.
529 /// Also writes out a _free function and a C++ wrapper which handles calling _free.
530 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) {
531 // If we directly read the original type by its original name, cbindgen hits
532 // https://github.com/eqrion/cbindgen/issues/286 Thus, instead, we import it as a temporary
533 // name and then reference it by that name, which works around the issue.
534 write!(w, "\nuse {}::{} as native{}Import;\ntype native{} = native{}Import", types.module_path, ident, ident, ident, ident).unwrap();
535 maybe_write_generics(w, &generics, &types, true);
536 writeln!(w, ";\n").unwrap();
537 writeln!(extra_headers, "struct native{}Opaque;\ntypedef struct native{}Opaque LDKnative{};", ident, ident, ident).unwrap();
538 writeln_docs(w, &attrs, "");
539 writeln!(w, "#[must_use]\n#[repr(C)]\npub struct {} {{", struct_name).unwrap();
540 writeln!(w, "\t/// A pointer to the opaque Rust object.\n").unwrap();
541 writeln!(w, "\t/// Nearly everywhere, inner must be non-null, however in places where").unwrap();
542 writeln!(w, "\t/// the Rust equivalent takes an Option, it may be set to null to indicate None.").unwrap();
543 writeln!(w, "\tpub inner: *mut native{},", ident).unwrap();
544 writeln!(w, "\t/// Indicates that this is the only struct which contains the same pointer.\n").unwrap();
545 writeln!(w, "\t/// Rust functions which take ownership of an object provided via an argument require").unwrap();
546 writeln!(w, "\t/// this to be true and invalidate the object pointed to by inner.").unwrap();
547 writeln!(w, "\tpub is_owned: bool,").unwrap();
548 writeln!(w, "}}\n").unwrap();
549 writeln!(w, "impl Drop for {} {{\n\tfn drop(&mut self) {{", struct_name).unwrap();
550 writeln!(w, "\t\tif self.is_owned && !<*mut native{}>::is_null(self.inner) {{", ident).unwrap();
551 writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(self.inner) }};\n\t\t}}\n\t}}\n}}").unwrap();
552 writeln!(w, "/// Frees any resources used by the {}, if is_owned is set and inner is non-NULL.", struct_name).unwrap();
553 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_obj: {}) {{ }}", struct_name, struct_name).unwrap();
554 writeln!(w, "#[allow(unused)]").unwrap();
555 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
556 writeln!(w, "extern \"C\" fn {}_free_void(this_ptr: *mut c_void) {{", struct_name).unwrap();
557 writeln!(w, "\tunsafe {{ let _ = Box::from_raw(this_ptr as *mut native{}); }}\n}}", struct_name).unwrap();
558 writeln!(w, "#[allow(unused)]").unwrap();
559 writeln!(w, "/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy").unwrap();
560 writeln!(w, "impl {} {{", struct_name).unwrap();
561 writeln!(w, "\tpub(crate) fn take_inner(mut self) -> *mut native{} {{", struct_name).unwrap();
562 writeln!(w, "\t\tassert!(self.is_owned);").unwrap();
563 writeln!(w, "\t\tlet ret = self.inner;").unwrap();
564 writeln!(w, "\t\tself.inner = std::ptr::null_mut();").unwrap();
565 writeln!(w, "\t\tret").unwrap();
566 writeln!(w, "\t}}\n}}").unwrap();
568 write_cpp_wrapper(cpp_headers, &format!("{}", ident), true);
571 /// Writes out all the relevant mappings for a Rust struct, deferring to writeln_opaque to generate
572 /// the struct itself, and then writing getters and setters for public, understood-type fields and
573 /// a constructor if every field is public.
574 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) {
575 if export_status(&s.attrs) != ExportStatus::Export { return; }
577 let struct_name = &format!("{}", s.ident);
578 writeln_opaque(w, &s.ident, struct_name, &s.generics, &s.attrs, types, extra_headers, cpp_headers);
580 if let syn::Fields::Named(fields) = &s.fields {
581 let mut gen_types = GenericTypes::new();
582 assert!(gen_types.learn_generics(&s.generics, types));
584 let mut all_fields_settable = true;
585 for field in fields.named.iter() {
586 if let syn::Visibility::Public(_) = field.vis {
587 let export = export_status(&field.attrs);
589 ExportStatus::Export => {},
590 ExportStatus::NoExport|ExportStatus::TestOnly => {
591 all_fields_settable = false;
596 if let Some(ident) = &field.ident {
597 let ref_type = syn::Type::Reference(syn::TypeReference {
598 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
599 elem: Box::new(field.ty.clone()) });
600 if types.understood_c_type(&ref_type, Some(&gen_types)) {
601 writeln_docs(w, &field.attrs, "");
602 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> ", struct_name, ident, struct_name).unwrap();
603 types.write_c_type(w, &ref_type, Some(&gen_types), true);
604 write!(w, " {{\n\tlet mut inner_val = &mut unsafe {{ &mut *this_ptr.inner }}.{};\n\t", ident).unwrap();
605 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);
606 if local_var { write!(w, "\n\t").unwrap(); }
607 types.write_to_c_conversion_inline_prefix(w, &ref_type, Some(&gen_types), true);
609 write!(w, "inner_val").unwrap();
611 write!(w, "(*inner_val)").unwrap();
613 types.write_to_c_conversion_inline_suffix(w, &ref_type, Some(&gen_types), true);
614 writeln!(w, "\n}}").unwrap();
617 if types.understood_c_type(&field.ty, Some(&gen_types)) {
618 writeln_docs(w, &field.attrs, "");
619 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_set_{}(this_ptr: &mut {}, mut val: ", struct_name, ident, struct_name).unwrap();
620 types.write_c_type(w, &field.ty, Some(&gen_types), false);
621 write!(w, ") {{\n\t").unwrap();
622 let local_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("val", Span::call_site()), &field.ty, Some(&gen_types));
623 if local_var { write!(w, "\n\t").unwrap(); }
624 write!(w, "unsafe {{ &mut *this_ptr.inner }}.{} = ", ident).unwrap();
625 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
626 write!(w, "val").unwrap();
627 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
628 writeln!(w, ";\n}}").unwrap();
629 } else { all_fields_settable = false; }
630 } else { all_fields_settable = false; }
631 } else { all_fields_settable = false; }
634 if all_fields_settable {
635 // Build a constructor!
636 writeln!(w, "/// Constructs a new {} given each field", struct_name).unwrap();
637 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_new(", struct_name).unwrap();
638 for (idx, field) in fields.named.iter().enumerate() {
639 if idx != 0 { write!(w, ", ").unwrap(); }
640 write!(w, "mut {}_arg: ", field.ident.as_ref().unwrap()).unwrap();
641 types.write_c_type(w, &field.ty, Some(&gen_types), false);
643 write!(w, ") -> {} {{\n\t", struct_name).unwrap();
644 for field in fields.named.iter() {
645 let field_name = format!("{}_arg", field.ident.as_ref().unwrap());
646 if types.write_from_c_conversion_new_var(w, &syn::Ident::new(&field_name, Span::call_site()), &field.ty, Some(&gen_types)) {
647 write!(w, "\n\t").unwrap();
650 writeln!(w, "{} {{ inner: Box::into_raw(Box::new(native{} {{", struct_name, s.ident).unwrap();
651 for field in fields.named.iter() {
652 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
653 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
654 write!(w, "{}_arg", field.ident.as_ref().unwrap()).unwrap();
655 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
656 writeln!(w, ",").unwrap();
658 writeln!(w, "\t}})), is_owned: true }}\n}}").unwrap();
663 /// Prints a relevant conversion for impl *
665 /// For simple impl Struct {}s, this just outputs the wrapper functions as Struct_fn_name() { .. }.
667 /// For impl Trait for Struct{}s, this non-exported generates wrapper functions as
668 /// Trait_Struct_fn_name and a Struct_as_Trait(&struct) -> Trait function which returns a populated
669 /// Trait struct containing a pointer to the passed struct's inner field and the wrapper functions.
671 /// A few non-crate Traits are hard-coded including Default.
672 fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut TypeResolver) {
673 match export_status(&i.attrs) {
674 ExportStatus::Export => {},
675 ExportStatus::NoExport|ExportStatus::TestOnly => return,
678 if let syn::Type::Tuple(_) = &*i.self_ty {
679 if types.understood_c_type(&*i.self_ty, None) {
680 let mut gen_types = GenericTypes::new();
681 if !gen_types.learn_generics(&i.generics, types) {
682 eprintln!("Not implementing anything for `impl (..)` due to not understood generics");
686 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
687 if let Some(trait_path) = i.trait_.as_ref() {
688 if trait_path.0.is_some() { unimplemented!(); }
689 if types.understood_c_path(&trait_path.1) {
690 eprintln!("Not implementing anything for `impl Trait for (..)` - we only support manual defines");
693 // Just do a manual implementation:
694 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
697 eprintln!("Not implementing anything for plain `impl (..)` block - we only support `impl Trait for (..)` blocks");
703 if let &syn::Type::Path(ref p) = &*i.self_ty {
704 if p.qself.is_some() { unimplemented!(); }
705 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
706 if let Some(resolved_path) = types.maybe_resolve_non_ignored_ident(&ident) {
707 let mut gen_types = GenericTypes::new();
708 if !gen_types.learn_generics(&i.generics, types) {
709 eprintln!("Not implementing anything for impl {} due to not understood generics", ident);
713 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
714 if let Some(trait_path) = i.trait_.as_ref() {
715 if trait_path.0.is_some() { unimplemented!(); }
716 if types.understood_c_path(&trait_path.1) {
717 let full_trait_path = types.resolve_path(&trait_path.1, None);
718 let trait_obj = *types.crate_types.traits.get(&full_trait_path).unwrap();
719 // We learn the associated types maping from the original trait object.
720 // That's great, except that they are unresolved idents, so if we learn
721 // mappings from a trai defined in a different file, we may mis-resolve or
722 // fail to resolve the mapped types.
723 gen_types.learn_associated_types(trait_obj, types);
724 let mut impl_associated_types = HashMap::new();
725 for item in i.items.iter() {
727 syn::ImplItem::Type(t) => {
728 if let syn::Type::Path(p) = &t.ty {
729 if let Some(id) = single_ident_generic_path_to_ident(&p.path) {
730 impl_associated_types.insert(&t.ident, id);
738 let export = export_status(&trait_obj.attrs);
740 ExportStatus::Export => {},
741 ExportStatus::NoExport|ExportStatus::TestOnly => return,
744 // For cases where we have a concrete native object which implements a
745 // trait and need to return the C-mapped version of the trait, provide a
746 // From<> implementation which does all the work to ensure free is handled
747 // properly. This way we can call this method from deep in the
748 // type-conversion logic without actually knowing the concrete native type.
749 writeln!(w, "impl From<native{}> for crate::{} {{", ident, full_trait_path).unwrap();
750 writeln!(w, "\tfn from(obj: native{}) -> Self {{", ident).unwrap();
751 writeln!(w, "\t\tlet mut rust_obj = {} {{ inner: Box::into_raw(Box::new(obj)), is_owned: true }};", ident).unwrap();
752 writeln!(w, "\t\tlet mut ret = {}_as_{}(&rust_obj);", ident, trait_obj.ident).unwrap();
753 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();
754 writeln!(w, "\t\trust_obj.inner = std::ptr::null_mut();").unwrap();
755 writeln!(w, "\t\tret.free = Some({}_free_void);", ident).unwrap();
756 writeln!(w, "\t\tret\n\t}}\n}}").unwrap();
758 writeln!(w, "/// Constructs a new {} which calls the relevant methods on this_arg.", trait_obj.ident).unwrap();
759 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();
760 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_as_{}(this_arg: &{}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
761 writeln!(w, "\tcrate::{} {{", full_trait_path).unwrap();
762 writeln!(w, "\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
763 writeln!(w, "\t\tfree: None,").unwrap();
765 macro_rules! write_meth {
766 ($m: expr, $trait: expr, $indent: expr) => {
767 let trait_method = $trait.items.iter().filter_map(|item| {
768 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
769 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
770 match export_status(&trait_method.attrs) {
771 ExportStatus::Export => {},
772 ExportStatus::NoExport => {
773 write!(w, "{}\t\t//XXX: Need to export {}\n", $indent, $m.sig.ident).unwrap();
776 ExportStatus::TestOnly => continue,
779 let mut printed = false;
780 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
781 if let syn::Type::Reference(r) = &**rtype {
782 write!(w, "\n\t\t{}{}: ", $indent, $m.sig.ident).unwrap();
783 types.write_empty_rust_val(Some(&gen_types), w, &*r.elem);
784 writeln!(w, ",\n{}\t\tset_{}: Some({}_{}_set_{}),", $indent, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
789 write!(w, "{}\t\t{}: {}_{}_{},\n", $indent, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
793 for item in trait_obj.items.iter() {
795 syn::TraitItem::Method(m) => {
796 write_meth!(m, trait_obj, "");
801 let mut requires_clone = false;
802 walk_supertraits!(trait_obj, Some(&types), (
803 ("Clone", _) => requires_clone = true,
806 walk_supertraits!(trait_obj, Some(&types), (
808 writeln!(w, "\t\tclone: Some({}_clone_void),", ident).unwrap();
810 ("Sync", _) => {}, ("Send", _) => {},
811 ("std::marker::Sync", _) => {}, ("std::marker::Send", _) => {},
813 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
814 writeln!(w, "\t\t{}: crate::{} {{", t, s).unwrap();
815 writeln!(w, "\t\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
816 writeln!(w, "\t\t\tfree: None,").unwrap();
817 for item in supertrait_obj.items.iter() {
819 syn::TraitItem::Method(m) => {
820 write_meth!(m, supertrait_obj, "\t");
825 write!(w, "\t\t}},\n").unwrap();
826 if !types.is_clonable(s) && requires_clone {
827 writeln!(w, "\t\t{}_clone: {}_{}_clone,", t, ident, t).unwrap();
830 write_trait_impl_field_assign(w, s, ident);
834 writeln!(w, "\t}}\n}}\n").unwrap();
836 macro_rules! impl_meth {
837 ($m: expr, $trait_path: expr, $trait: expr, $indent: expr) => {
838 let trait_method = $trait.items.iter().filter_map(|item| {
839 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
840 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
841 match export_status(&trait_method.attrs) {
842 ExportStatus::Export => {},
843 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
846 if let syn::ReturnType::Type(_, _) = &$m.sig.output {
847 writeln!(w, "#[must_use]").unwrap();
849 write!(w, "extern \"C\" fn {}_{}_{}(", ident, $trait.ident, $m.sig.ident).unwrap();
850 let mut meth_gen_types = gen_types.push_ctx();
851 assert!(meth_gen_types.learn_generics(&$m.sig.generics, types));
852 write_method_params(w, &$m.sig, "c_void", types, Some(&meth_gen_types), true, true);
853 write!(w, " {{\n\t").unwrap();
854 write_method_var_decl_body(w, &$m.sig, "", types, Some(&meth_gen_types), false);
855 let mut takes_self = false;
856 for inp in $m.sig.inputs.iter() {
857 if let syn::FnArg::Receiver(_) = inp {
862 let mut t_gen_args = String::new();
863 for (idx, _) in $trait.generics.params.iter().enumerate() {
864 if idx != 0 { t_gen_args += ", " };
868 write!(w, "<native{} as {}<{}>>::{}(unsafe {{ &mut *(this_arg as *mut native{}) }}, ", ident, $trait_path, t_gen_args, $m.sig.ident, ident).unwrap();
870 write!(w, "<native{} as {}<{}>>::{}(", ident, $trait_path, t_gen_args, $m.sig.ident).unwrap();
873 let mut real_type = "".to_string();
874 match &$m.sig.output {
875 syn::ReturnType::Type(_, rtype) => {
876 if let Some(mut remaining_path) = first_seg_self(&*rtype) {
877 if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
878 real_type = format!("{}", impl_associated_types.get(associated_seg).unwrap());
884 write_method_call_params(w, &$m.sig, "", types, Some(&meth_gen_types), &real_type, false);
885 write!(w, "\n}}\n").unwrap();
886 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
887 if let syn::Type::Reference(r) = &**rtype {
888 assert_eq!($m.sig.inputs.len(), 1); // Must only take self
889 writeln!(w, "extern \"C\" fn {}_{}_set_{}(trait_self_arg: &{}) {{", ident, $trait.ident, $m.sig.ident, $trait.ident).unwrap();
890 writeln!(w, "\t// This is a bit race-y in the general case, but for our specific use-cases today, we're safe").unwrap();
891 writeln!(w, "\t// Specifically, we must ensure that the first time we're called it can never be in parallel").unwrap();
892 write!(w, "\tif ").unwrap();
893 types.write_empty_rust_val_check(Some(&meth_gen_types), w, &*r.elem, &format!("trait_self_arg.{}", $m.sig.ident));
894 writeln!(w, " {{").unwrap();
895 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();
896 writeln!(w, "\t}}").unwrap();
897 writeln!(w, "}}").unwrap();
903 for item in i.items.iter() {
905 syn::ImplItem::Method(m) => {
906 impl_meth!(m, full_trait_path, trait_obj, "");
908 syn::ImplItem::Type(_) => {},
909 _ => unimplemented!(),
912 walk_supertraits!(trait_obj, Some(&types), (
914 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
915 if !types.is_clonable(s) && requires_clone {
916 writeln!(w, "extern \"C\" fn {}_{}_clone(orig: &crate::{}) -> crate::{} {{", ident, t, s, s).unwrap();
917 writeln!(w, "\tcrate::{} {{", s).unwrap();
918 writeln!(w, "\t\tthis_arg: orig.this_arg,").unwrap();
919 writeln!(w, "\t\tfree: None,").unwrap();
920 for item in supertrait_obj.items.iter() {
922 syn::TraitItem::Method(m) => {
923 write_meth!(m, supertrait_obj, "");
928 write!(w, "\t}}\n}}\n").unwrap();
933 write!(w, "\n").unwrap();
934 } else if path_matches_nongeneric(&trait_path.1, &["From"]) {
935 } else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
936 writeln!(w, "/// Creates a \"default\" {}. See struct and individual field documentaiton for details on which values are used.", ident).unwrap();
937 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
938 write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
939 write!(w, "}}\n").unwrap();
940 } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "PartialEq"]) {
941 } else if (path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) || path_matches_nongeneric(&trait_path.1, &["Clone"])) &&
942 types.c_type_has_inner_from_path(&resolved_path) {
943 writeln!(w, "impl Clone for {} {{", ident).unwrap();
944 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
945 writeln!(w, "\t\tSelf {{").unwrap();
946 writeln!(w, "\t\t\tinner: if <*mut native{}>::is_null(self.inner) {{ std::ptr::null_mut() }} else {{", ident).unwrap();
947 writeln!(w, "\t\t\t\tBox::into_raw(Box::new(unsafe {{ &*self.inner }}.clone())) }},").unwrap();
948 writeln!(w, "\t\t\tis_owned: true,").unwrap();
949 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
950 writeln!(w, "#[allow(unused)]").unwrap();
951 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
952 writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", ident).unwrap();
953 writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", ident).unwrap();
954 writeln!(w, "}}").unwrap();
955 writeln!(w, "#[no_mangle]").unwrap();
956 writeln!(w, "/// Creates a copy of the {}", ident).unwrap();
957 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", ident, ident, ident).unwrap();
958 writeln!(w, "\torig.clone()").unwrap();
959 writeln!(w, "}}").unwrap();
961 //XXX: implement for other things like ToString
962 // If we have no generics, try a manual implementation:
963 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
966 let declared_type = (*types.get_declared_type(&ident).unwrap()).clone();
967 for item in i.items.iter() {
969 syn::ImplItem::Method(m) => {
970 if let syn::Visibility::Public(_) = m.vis {
971 match export_status(&m.attrs) {
972 ExportStatus::Export => {},
973 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
975 if m.defaultness.is_some() { unimplemented!(); }
976 writeln_docs(w, &m.attrs, "");
977 if let syn::ReturnType::Type(_, _) = &m.sig.output {
978 writeln!(w, "#[must_use]").unwrap();
980 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_{}(", ident, m.sig.ident).unwrap();
981 let ret_type = match &declared_type {
982 DeclType::MirroredEnum => format!("{}", ident),
983 DeclType::StructImported => format!("{}", ident),
984 _ => unimplemented!(),
986 let mut meth_gen_types = gen_types.push_ctx();
987 assert!(meth_gen_types.learn_generics(&m.sig.generics, types));
988 write_method_params(w, &m.sig, &ret_type, types, Some(&meth_gen_types), false, true);
989 write!(w, " {{\n\t").unwrap();
990 write_method_var_decl_body(w, &m.sig, "", types, Some(&meth_gen_types), false);
991 let mut takes_self = false;
992 let mut takes_mut_self = false;
993 for inp in m.sig.inputs.iter() {
994 if let syn::FnArg::Receiver(r) = inp {
996 if r.mutability.is_some() { takes_mut_self = true; }
1000 write!(w, "unsafe {{ &mut (*(this_arg.inner as *mut native{})) }}.{}(", ident, m.sig.ident).unwrap();
1001 } else if takes_self {
1002 write!(w, "unsafe {{ &*this_arg.inner }}.{}(", m.sig.ident).unwrap();
1004 write!(w, "{}::{}(", resolved_path, m.sig.ident).unwrap();
1006 write_method_call_params(w, &m.sig, "", types, Some(&meth_gen_types), &ret_type, false);
1007 writeln!(w, "\n}}\n").unwrap();
1014 } else if let Some(resolved_path) = types.maybe_resolve_ident(&ident) {
1015 if let Some(aliases) = types.crate_types.reverse_alias_map.get(&resolved_path).cloned() {
1016 'alias_impls: for (alias, arguments) in aliases {
1017 let alias_resolved = types.resolve_path(&alias, None);
1018 for (idx, gen) in i.generics.params.iter().enumerate() {
1020 syn::GenericParam::Type(type_param) => {
1021 'bounds_check: for bound in type_param.bounds.iter() {
1022 if let syn::TypeParamBound::Trait(trait_bound) = bound {
1023 if let syn::PathArguments::AngleBracketed(ref t) = &arguments {
1024 assert!(idx < t.args.len());
1025 if let syn::GenericArgument::Type(syn::Type::Path(p)) = &t.args[idx] {
1026 let generic_arg = types.resolve_path(&p.path, None);
1027 let generic_bound = types.resolve_path(&trait_bound.path, None);
1028 if let Some(traits_impld) = types.crate_types.trait_impls.get(&generic_arg) {
1029 for trait_impld in traits_impld {
1030 if *trait_impld == generic_bound { continue 'bounds_check; }
1032 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1033 continue 'alias_impls;
1035 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1036 continue 'alias_impls;
1038 } else { unimplemented!(); }
1039 } else { unimplemented!(); }
1040 } else { unimplemented!(); }
1043 syn::GenericParam::Lifetime(_) => {},
1044 syn::GenericParam::Const(_) => unimplemented!(),
1047 let aliased_impl = syn::ItemImpl {
1048 attrs: i.attrs.clone(),
1049 brace_token: syn::token::Brace(Span::call_site()),
1051 generics: syn::Generics {
1053 params: syn::punctuated::Punctuated::new(),
1057 impl_token: syn::Token![impl](Span::call_site()),
1058 items: i.items.clone(),
1059 self_ty: Box::new(syn::Type::Path(syn::TypePath { qself: None, path: alias.clone() })),
1060 trait_: i.trait_.clone(),
1063 writeln_impl(w, &aliased_impl, types);
1066 eprintln!("Not implementing anything for {} due to it being marked not exported", ident);
1069 eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub)", ident);
1076 /// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
1077 /// is unitary), we generate an equivalent enum with all types replaced with their C mapped
1078 /// versions followed by conversion functions which map between the Rust version and the C mapped
1080 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) {
1081 match export_status(&e.attrs) {
1082 ExportStatus::Export => {},
1083 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1086 if is_enum_opaque(e) {
1087 eprintln!("Skipping enum {} as it contains non-unit fields", e.ident);
1088 writeln_opaque(w, &e.ident, &format!("{}", e.ident), &e.generics, &e.attrs, types, extra_headers, cpp_headers);
1091 writeln_docs(w, &e.attrs, "");
1093 if e.generics.lt_token.is_some() {
1097 let mut needs_free = false;
1099 writeln!(w, "#[must_use]\n#[derive(Clone)]\n#[repr(C)]\npub enum {} {{", e.ident).unwrap();
1100 for var in e.variants.iter() {
1101 assert_eq!(export_status(&var.attrs), ExportStatus::Export); // We can't partially-export a mirrored enum
1102 writeln_docs(w, &var.attrs, "\t");
1103 write!(w, "\t{}", var.ident).unwrap();
1104 if let syn::Fields::Named(fields) = &var.fields {
1106 writeln!(w, " {{").unwrap();
1107 for field in fields.named.iter() {
1108 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1109 writeln_docs(w, &field.attrs, "\t\t");
1110 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1111 types.write_c_type(w, &field.ty, None, false);
1112 writeln!(w, ",").unwrap();
1114 write!(w, "\t}}").unwrap();
1115 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1117 write!(w, "(").unwrap();
1118 for (idx, field) in fields.unnamed.iter().enumerate() {
1119 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1120 types.write_c_type(w, &field.ty, None, false);
1121 if idx != fields.unnamed.len() - 1 {
1122 write!(w, ",").unwrap();
1125 write!(w, ")").unwrap();
1127 if var.discriminant.is_some() { unimplemented!(); }
1128 writeln!(w, ",").unwrap();
1130 writeln!(w, "}}\nuse {}::{} as native{};\nimpl {} {{", types.module_path, e.ident, e.ident, e.ident).unwrap();
1132 macro_rules! write_conv {
1133 ($fn_sig: expr, $to_c: expr, $ref: expr) => {
1134 writeln!(w, "\t#[allow(unused)]\n\tpub(crate) fn {} {{\n\t\tmatch {} {{", $fn_sig, if $to_c { "native" } else { "self" }).unwrap();
1135 for var in e.variants.iter() {
1136 write!(w, "\t\t\t{}{}::{} ", if $to_c { "native" } else { "" }, e.ident, var.ident).unwrap();
1137 if let syn::Fields::Named(fields) = &var.fields {
1138 write!(w, "{{").unwrap();
1139 for field in fields.named.iter() {
1140 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1141 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, field.ident.as_ref().unwrap()).unwrap();
1143 write!(w, "}} ").unwrap();
1144 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1145 write!(w, "(").unwrap();
1146 for (idx, field) in fields.unnamed.iter().enumerate() {
1147 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1148 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, ('a' as u8 + idx as u8) as char).unwrap();
1150 write!(w, ") ").unwrap();
1152 write!(w, "=>").unwrap();
1154 macro_rules! handle_field_a {
1155 ($field: expr, $field_ident: expr) => { {
1156 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1157 let mut sink = ::std::io::sink();
1158 let mut out: &mut dyn std::io::Write = if $ref { &mut sink } else { w };
1159 let new_var = if $to_c {
1160 types.write_to_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None, false)
1162 types.write_from_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None)
1164 if $ref || new_var {
1166 write!(w, "let mut {}_nonref = (*{}).clone();\n\t\t\t\t", $field_ident, $field_ident).unwrap();
1168 let nonref_ident = syn::Ident::new(&format!("{}_nonref", $field_ident), Span::call_site());
1170 types.write_to_c_conversion_new_var(w, &nonref_ident, &$field.ty, None, false);
1172 types.write_from_c_conversion_new_var(w, &nonref_ident, &$field.ty, None);
1174 write!(w, "\n\t\t\t\t").unwrap();
1177 write!(w, "\n\t\t\t\t").unwrap();
1182 if let syn::Fields::Named(fields) = &var.fields {
1183 write!(w, " {{\n\t\t\t\t").unwrap();
1184 for field in fields.named.iter() {
1185 handle_field_a!(field, field.ident.as_ref().unwrap());
1187 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1188 write!(w, " {{\n\t\t\t\t").unwrap();
1189 for (idx, field) in fields.unnamed.iter().enumerate() {
1190 handle_field_a!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1192 } else { write!(w, " ").unwrap(); }
1194 write!(w, "{}{}::{}", if $to_c { "" } else { "native" }, e.ident, var.ident).unwrap();
1196 macro_rules! handle_field_b {
1197 ($field: expr, $field_ident: expr) => { {
1198 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1200 types.write_to_c_conversion_inline_prefix(w, &$field.ty, None, false);
1202 types.write_from_c_conversion_prefix(w, &$field.ty, None);
1204 write!(w, "{}{}", $field_ident,
1205 if $ref { "_nonref" } else { "" }).unwrap();
1207 types.write_to_c_conversion_inline_suffix(w, &$field.ty, None, false);
1209 types.write_from_c_conversion_suffix(w, &$field.ty, None);
1211 write!(w, ",").unwrap();
1215 if let syn::Fields::Named(fields) = &var.fields {
1216 write!(w, " {{").unwrap();
1217 for field in fields.named.iter() {
1218 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1219 write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1220 handle_field_b!(field, field.ident.as_ref().unwrap());
1222 writeln!(w, "\n\t\t\t\t}}").unwrap();
1223 write!(w, "\t\t\t}}").unwrap();
1224 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1225 write!(w, " (").unwrap();
1226 for (idx, field) in fields.unnamed.iter().enumerate() {
1227 write!(w, "\n\t\t\t\t\t").unwrap();
1228 handle_field_b!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1230 writeln!(w, "\n\t\t\t\t)").unwrap();
1231 write!(w, "\t\t\t}}").unwrap();
1233 writeln!(w, ",").unwrap();
1235 writeln!(w, "\t\t}}\n\t}}").unwrap();
1239 write_conv!(format!("to_native(&self) -> native{}", e.ident), false, true);
1240 write_conv!(format!("into_native(self) -> native{}", e.ident), false, false);
1241 write_conv!(format!("from_native(native: &native{}) -> Self", e.ident), true, true);
1242 write_conv!(format!("native_into(native: native{}) -> Self", e.ident), true, false);
1243 writeln!(w, "}}").unwrap();
1246 writeln!(w, "/// Frees any resources used by the {}", e.ident).unwrap();
1247 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", e.ident, e.ident).unwrap();
1249 writeln!(w, "/// Creates a copy of the {}", e.ident).unwrap();
1250 writeln!(w, "#[no_mangle]").unwrap();
1251 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
1252 writeln!(w, "\torig.clone()").unwrap();
1253 writeln!(w, "}}").unwrap();
1254 write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free);
1257 fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &mut TypeResolver<'b, 'a>) {
1258 match export_status(&f.attrs) {
1259 ExportStatus::Export => {},
1260 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1262 writeln_docs(w, &f.attrs, "");
1264 let mut gen_types = GenericTypes::new();
1265 if !gen_types.learn_generics(&f.sig.generics, types) { return; }
1267 write!(w, "#[no_mangle]\npub extern \"C\" fn {}(", f.sig.ident).unwrap();
1268 write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
1269 write!(w, " {{\n\t").unwrap();
1270 write_method_var_decl_body(w, &f.sig, "", types, Some(&gen_types), false);
1271 write!(w, "{}::{}(", types.module_path, f.sig.ident).unwrap();
1272 write_method_call_params(w, &f.sig, "", types, Some(&gen_types), "", false);
1273 writeln!(w, "\n}}\n").unwrap();
1276 // ********************************
1277 // *** File/Crate Walking Logic ***
1278 // ********************************
1280 /// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
1281 /// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
1282 /// at `module` from C.
1283 fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &CrateTypes<'a>, out_dir: &str, header_file: &mut File, cpp_header_file: &mut File) {
1284 for (module, astmod) in libast.modules.iter() {
1285 let orig_crate = module.splitn(2, "::").next().unwrap();
1286 let ASTModule { ref attrs, ref items, ref submods } = astmod;
1287 assert_eq!(export_status(&attrs), ExportStatus::Export);
1289 let new_file_path = if submods.is_empty() {
1290 format!("{}/{}.rs", out_dir, module.replace("::", "/"))
1291 } else if module != "" {
1292 format!("{}/{}/mod.rs", out_dir, module.replace("::", "/"))
1294 format!("{}/lib.rs", out_dir)
1296 let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
1297 let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1298 .open(new_file_path).expect("Unable to open new src file");
1300 writeln!(out, "// This file is Copyright its original authors, visible in version control").unwrap();
1301 writeln!(out, "// history and in the source files from which this was generated.").unwrap();
1302 writeln!(out, "//").unwrap();
1303 writeln!(out, "// This file is licensed under the license available in the LICENSE or LICENSE.md").unwrap();
1304 writeln!(out, "// file in the root of this repository or, if no such file exists, the same").unwrap();
1305 writeln!(out, "// license as that which applies to the original source files from which this").unwrap();
1306 writeln!(out, "// source was automatically generated.").unwrap();
1307 writeln!(out, "").unwrap();
1309 writeln_docs(&mut out, &attrs, "");
1312 // Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
1313 // and bitcoin hand-written modules.
1314 writeln!(out, "//! C Bindings").unwrap();
1315 writeln!(out, "#![allow(unknown_lints)]").unwrap();
1316 writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
1317 writeln!(out, "#![allow(non_snake_case)]").unwrap();
1318 writeln!(out, "#![allow(unused_imports)]").unwrap();
1319 writeln!(out, "#![allow(unused_variables)]").unwrap();
1320 writeln!(out, "#![allow(unused_mut)]").unwrap();
1321 writeln!(out, "#![allow(unused_parens)]").unwrap();
1322 writeln!(out, "#![allow(unused_unsafe)]").unwrap();
1323 writeln!(out, "#![allow(unused_braces)]").unwrap();
1324 writeln!(out, "#![deny(missing_docs)]").unwrap();
1325 writeln!(out, "pub mod c_types;").unwrap();
1326 writeln!(out, "pub mod bitcoin;").unwrap();
1328 writeln!(out, "\nuse std::ffi::c_void;\nuse bitcoin::hashes::Hash;\nuse crate::c_types::*;\n").unwrap();
1332 writeln!(out, "pub mod {};", m).unwrap();
1335 eprintln!("Converting {} entries...", module);
1337 let import_resolver = ImportResolver::new(orig_crate, &libast.dependencies, module, items);
1338 let mut type_resolver = TypeResolver::new(module, import_resolver, crate_types);
1340 for item in items.iter() {
1342 syn::Item::Use(_) => {}, // Handled above
1343 syn::Item::Static(_) => {},
1344 syn::Item::Enum(e) => {
1345 if let syn::Visibility::Public(_) = e.vis {
1346 writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
1349 syn::Item::Impl(i) => {
1350 writeln_impl(&mut out, &i, &mut type_resolver);
1352 syn::Item::Struct(s) => {
1353 if let syn::Visibility::Public(_) = s.vis {
1354 writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
1357 syn::Item::Trait(t) => {
1358 if let syn::Visibility::Public(_) = t.vis {
1359 writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
1362 syn::Item::Mod(_) => {}, // We don't have to do anything - the top loop handles these.
1363 syn::Item::Const(c) => {
1364 // Re-export any primitive-type constants.
1365 if let syn::Visibility::Public(_) = c.vis {
1366 if let syn::Type::Path(p) = &*c.ty {
1367 let resolved_path = type_resolver.resolve_path(&p.path, None);
1368 if type_resolver.is_primitive(&resolved_path) {
1369 writeln_docs(&mut out, &c.attrs, "");
1370 writeln!(out, "\n#[no_mangle]").unwrap();
1371 writeln!(out, "pub static {}: {} = {}::{};", c.ident, resolved_path, module, c.ident).unwrap();
1376 syn::Item::Type(t) => {
1377 if let syn::Visibility::Public(_) = t.vis {
1378 match export_status(&t.attrs) {
1379 ExportStatus::Export => {},
1380 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1383 let mut process_alias = true;
1384 for tok in t.generics.params.iter() {
1385 if let syn::GenericParam::Lifetime(_) = tok {}
1386 else { process_alias = false; }
1390 syn::Type::Path(_) =>
1391 writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &t.generics, &t.attrs, &type_resolver, header_file, cpp_header_file),
1397 syn::Item::Fn(f) => {
1398 if let syn::Visibility::Public(_) = f.vis {
1399 writeln_fn(&mut out, &f, &mut type_resolver);
1402 syn::Item::Macro(_) => {},
1403 syn::Item::Verbatim(_) => {},
1404 syn::Item::ExternCrate(_) => {},
1405 _ => unimplemented!(),
1409 out.flush().unwrap();
1413 fn walk_private_mod<'a>(ast_storage: &'a FullLibraryAST, orig_crate: &str, module: String, items: &'a syn::ItemMod, crate_types: &mut CrateTypes<'a>) {
1414 let import_resolver = ImportResolver::new(orig_crate, &ast_storage.dependencies, &module, &items.content.as_ref().unwrap().1);
1415 for item in items.content.as_ref().unwrap().1.iter() {
1417 syn::Item::Mod(m) => walk_private_mod(ast_storage, orig_crate, format!("{}::{}", module, m.ident), m, crate_types),
1418 syn::Item::Impl(i) => {
1419 if let &syn::Type::Path(ref p) = &*i.self_ty {
1420 if let Some(trait_path) = i.trait_.as_ref() {
1421 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1422 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1423 match crate_types.trait_impls.entry(sp) {
1424 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1425 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1437 /// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
1438 fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
1439 for (module, astmod) in ast_storage.modules.iter() {
1440 let ASTModule { ref attrs, ref items, submods: _ } = astmod;
1441 assert_eq!(export_status(&attrs), ExportStatus::Export);
1442 let orig_crate = module.splitn(2, "::").next().unwrap();
1443 let import_resolver = ImportResolver::new(orig_crate, &ast_storage.dependencies, module, items);
1445 for item in items.iter() {
1447 syn::Item::Struct(s) => {
1448 if let syn::Visibility::Public(_) = s.vis {
1449 match export_status(&s.attrs) {
1450 ExportStatus::Export => {},
1451 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1453 let struct_path = format!("{}::{}", module, s.ident);
1454 crate_types.opaques.insert(struct_path, &s.ident);
1457 syn::Item::Trait(t) => {
1458 if let syn::Visibility::Public(_) = t.vis {
1459 match export_status(&t.attrs) {
1460 ExportStatus::Export => {},
1461 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1463 let trait_path = format!("{}::{}", module, t.ident);
1464 walk_supertraits!(t, None, (
1466 crate_types.set_clonable("crate::".to_owned() + &trait_path);
1470 crate_types.traits.insert(trait_path, &t);
1473 syn::Item::Type(t) => {
1474 if let syn::Visibility::Public(_) = t.vis {
1475 match export_status(&t.attrs) {
1476 ExportStatus::Export => {},
1477 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1479 let type_path = format!("{}::{}", module, t.ident);
1480 let mut process_alias = true;
1481 for tok in t.generics.params.iter() {
1482 if let syn::GenericParam::Lifetime(_) = tok {}
1483 else { process_alias = false; }
1487 syn::Type::Path(p) => {
1488 // If its a path with no generics, assume we don't map the aliased type and map it opaque
1489 let mut segments = syn::punctuated::Punctuated::new();
1490 segments.push(syn::PathSegment {
1491 ident: t.ident.clone(),
1492 arguments: syn::PathArguments::None,
1494 let path_obj = syn::Path { leading_colon: None, segments };
1495 let args_obj = p.path.segments.last().unwrap().arguments.clone();
1496 match crate_types.reverse_alias_map.entry(import_resolver.maybe_resolve_path(&p.path, None).unwrap()) {
1497 hash_map::Entry::Occupied(mut e) => { e.get_mut().push((path_obj, args_obj)); },
1498 hash_map::Entry::Vacant(e) => { e.insert(vec![(path_obj, args_obj)]); },
1501 crate_types.opaques.insert(type_path.clone(), &t.ident);
1504 crate_types.type_aliases.insert(type_path, import_resolver.resolve_imported_refs((*t.ty).clone()));
1510 syn::Item::Enum(e) if is_enum_opaque(e) => {
1511 if let syn::Visibility::Public(_) = e.vis {
1512 match export_status(&e.attrs) {
1513 ExportStatus::Export => {},
1514 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1516 let enum_path = format!("{}::{}", module, e.ident);
1517 crate_types.opaques.insert(enum_path, &e.ident);
1520 syn::Item::Enum(e) => {
1521 if let syn::Visibility::Public(_) = e.vis {
1522 match export_status(&e.attrs) {
1523 ExportStatus::Export => {},
1524 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1526 let enum_path = format!("{}::{}", module, e.ident);
1527 crate_types.mirrored_enums.insert(enum_path, &e);
1530 syn::Item::Impl(i) => {
1531 if let &syn::Type::Path(ref p) = &*i.self_ty {
1532 if let Some(trait_path) = i.trait_.as_ref() {
1533 if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) {
1534 if let Some(full_path) = import_resolver.maybe_resolve_path(&p.path, None) {
1535 crate_types.set_clonable("crate::".to_owned() + &full_path);
1538 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1539 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1540 match crate_types.trait_impls.entry(sp) {
1541 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1542 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1549 syn::Item::Mod(m) => walk_private_mod(ast_storage, orig_crate, format!("{}::{}", module, m.ident), m, crate_types),
1557 let args: Vec<String> = env::args().collect();
1558 if args.len() != 5 {
1559 eprintln!("Usage: target/dir derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
1563 let mut derived_templates = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1564 .open(&args[2]).expect("Unable to open new header file");
1565 let mut header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1566 .open(&args[3]).expect("Unable to open new header file");
1567 let mut cpp_header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1568 .open(&args[4]).expect("Unable to open new header file");
1570 writeln!(header_file, "#if defined(__GNUC__)").unwrap();
1571 writeln!(header_file, "#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
1572 writeln!(header_file, "#define MUST_USE_RES __attribute__((warn_unused_result))").unwrap();
1573 writeln!(header_file, "#else").unwrap();
1574 writeln!(header_file, "#define MUST_USE_STRUCT").unwrap();
1575 writeln!(header_file, "#define MUST_USE_RES").unwrap();
1576 writeln!(header_file, "#endif").unwrap();
1577 writeln!(header_file, "#if defined(__clang__)").unwrap();
1578 writeln!(header_file, "#define NONNULL_PTR _Nonnull").unwrap();
1579 writeln!(header_file, "#else").unwrap();
1580 writeln!(header_file, "#define NONNULL_PTR").unwrap();
1581 writeln!(header_file, "#endif").unwrap();
1582 writeln!(cpp_header_file, "#include <string.h>\nnamespace LDK {{").unwrap();
1584 // First parse the full crate's ASTs, caching them so that we can hold references to the AST
1585 // objects in other datastructures:
1586 let mut lib_src = String::new();
1587 std::io::stdin().lock().read_to_string(&mut lib_src).unwrap();
1588 let lib_syntax = syn::parse_file(&lib_src).expect("Unable to parse file");
1589 let libast = FullLibraryAST::load_lib(lib_syntax);
1591 // ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
1592 // when parsing other file ASTs...
1593 let mut libtypes = CrateTypes::new(&mut derived_templates, &libast);
1594 walk_ast(&libast, &mut libtypes);
1596 // ... finally, do the actual file conversion/mapping, writing out types as we go.
1597 convert_file(&libast, &libtypes, &args[1], &mut header_file, &mut cpp_header_file);
1599 // For container templates which we created while walking the crate, make sure we add C++
1600 // mapped types so that C++ users can utilize the auto-destructors available.
1601 for (ty, has_destructor) in libtypes.templates_defined.borrow().iter() {
1602 write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor);
1604 writeln!(cpp_header_file, "}}").unwrap();
1606 header_file.flush().unwrap();
1607 cpp_header_file.flush().unwrap();
1608 derived_templates.flush().unwrap();