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;
34 // *************************************
35 // *** Manually-expanded conversions ***
36 // *************************************
38 /// Convert "impl trait_path for for_ty { .. }" for manually-mapped types (ie (de)serialization)
39 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) {
40 if let Some(t) = types.maybe_resolve_path(&trait_path, Some(generics)) {
43 let mut has_inner = false;
44 if let syn::Type::Path(ref p) = for_ty {
45 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
46 for_obj = format!("{}", ident);
47 full_obj_path = for_obj.clone();
48 has_inner = types.c_type_has_inner_from_path(&types.resolve_path(&p.path, Some(generics)));
51 // We assume that anything that isn't a Path is somehow a generic that ends up in our
52 // derived-types module.
53 let mut for_obj_vec = Vec::new();
54 types.write_c_type(&mut for_obj_vec, for_ty, Some(generics), false);
55 full_obj_path = String::from_utf8(for_obj_vec).unwrap();
56 assert!(full_obj_path.starts_with(TypeResolver::generated_container_path()));
57 for_obj = full_obj_path[TypeResolver::generated_container_path().len() + 2..].into();
61 "lightning::util::ser::Writeable" => {
62 writeln!(w, "#[no_mangle]").unwrap();
63 writeln!(w, "/// Serialize the {} object into a byte array which can be read by {}_read", for_obj, for_obj).unwrap();
64 writeln!(w, "pub extern \"C\" fn {}_write(obj: &{}) -> crate::c_types::derived::CVec_u8Z {{", for_obj, full_obj_path).unwrap();
66 let ref_type = syn::Type::Reference(syn::TypeReference {
67 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
68 elem: Box::new(for_ty.clone()) });
69 assert!(!types.write_from_c_conversion_new_var(w, &syn::Ident::new("obj", Span::call_site()), &ref_type, Some(generics)));
71 write!(w, "\tcrate::c_types::serialize_obj(").unwrap();
72 types.write_from_c_conversion_prefix(w, &ref_type, Some(generics));
73 write!(w, "unsafe {{ &*obj }}").unwrap();
74 types.write_from_c_conversion_suffix(w, &ref_type, Some(generics));
75 writeln!(w, ")").unwrap();
77 writeln!(w, "}}").unwrap();
79 writeln!(w, "#[no_mangle]").unwrap();
80 writeln!(w, "pub(crate) extern \"C\" fn {}_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {{", for_obj).unwrap();
81 writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &*(obj as *const native{}) }})", for_obj).unwrap();
82 writeln!(w, "}}").unwrap();
85 "lightning::util::ser::Readable"|"lightning::util::ser::ReadableArgs" => {
86 // Create the Result<Object, DecodeError> syn::Type
87 let mut err_segs = syn::punctuated::Punctuated::new();
88 err_segs.push(syn::PathSegment { ident: syn::Ident::new("ln", Span::call_site()), arguments: syn::PathArguments::None });
89 err_segs.push(syn::PathSegment { ident: syn::Ident::new("msgs", Span::call_site()), arguments: syn::PathArguments::None });
90 err_segs.push(syn::PathSegment { ident: syn::Ident::new("DecodeError", Span::call_site()), arguments: syn::PathArguments::None });
91 let mut args = syn::punctuated::Punctuated::new();
92 args.push(syn::GenericArgument::Type(for_ty.clone()));
93 args.push(syn::GenericArgument::Type(syn::Type::Path(syn::TypePath {
94 qself: None, path: syn::Path {
95 leading_colon: Some(syn::Token![::](Span::call_site())), segments: err_segs,
98 let mut res_segs = syn::punctuated::Punctuated::new();
99 res_segs.push(syn::PathSegment {
100 ident: syn::Ident::new("Result", Span::call_site()),
101 arguments: syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
102 colon2_token: None, lt_token: syn::Token![<](Span::call_site()), args, gt_token: syn::Token![>](Span::call_site()),
105 let res_ty = syn::Type::Path(syn::TypePath { qself: None, path: syn::Path {
106 leading_colon: None, segments: res_segs } });
108 writeln!(w, "#[no_mangle]").unwrap();
109 writeln!(w, "/// Read a {} from a byte array, created by {}_write", for_obj, for_obj).unwrap();
110 write!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice", for_obj).unwrap();
112 let mut arg_conv = Vec::new();
113 if t == "lightning::util::ser::ReadableArgs" {
114 write!(w, ", arg: ").unwrap();
115 assert!(trait_path.leading_colon.is_none());
116 let args_seg = trait_path.segments.iter().last().unwrap();
117 assert_eq!(format!("{}", args_seg.ident), "ReadableArgs");
118 if let syn::PathArguments::AngleBracketed(args) = &args_seg.arguments {
119 assert_eq!(args.args.len(), 1);
120 if let syn::GenericArgument::Type(args_ty) = args.args.iter().next().unwrap() {
121 types.write_c_type(w, args_ty, Some(generics), false);
123 assert!(!types.write_from_c_conversion_new_var(&mut arg_conv, &syn::Ident::new("arg", Span::call_site()), &args_ty, Some(generics)));
125 write!(&mut arg_conv, "\tlet arg_conv = ").unwrap();
126 types.write_from_c_conversion_prefix(&mut arg_conv, &args_ty, Some(generics));
127 write!(&mut arg_conv, "arg").unwrap();
128 types.write_from_c_conversion_suffix(&mut arg_conv, &args_ty, Some(generics));
129 } else { unreachable!(); }
130 } else { unreachable!(); }
132 write!(w, ") -> ").unwrap();
133 types.write_c_type(w, &res_ty, Some(generics), false);
134 writeln!(w, " {{").unwrap();
136 if t == "lightning::util::ser::ReadableArgs" {
137 w.write(&arg_conv).unwrap();
138 write!(w, ";\n\tlet res: ").unwrap();
139 // At least in one case we need type annotations here, so provide them.
140 types.write_rust_type(w, Some(generics), &res_ty);
141 writeln!(w, " = crate::c_types::deserialize_obj_arg(ser, arg_conv);").unwrap();
143 writeln!(w, "\tlet res = crate::c_types::deserialize_obj(ser);").unwrap();
145 write!(w, "\t").unwrap();
146 if types.write_to_c_conversion_new_var(w, &syn::Ident::new("res", Span::call_site()), &res_ty, Some(generics), false) {
147 write!(w, "\n\t").unwrap();
149 types.write_to_c_conversion_inline_prefix(w, &res_ty, Some(generics), false);
150 write!(w, "res").unwrap();
151 types.write_to_c_conversion_inline_suffix(w, &res_ty, Some(generics), false);
152 writeln!(w, "\n}}").unwrap();
159 /// Convert "TraitA : TraitB" to a single function name and return type.
161 /// This is (obviously) somewhat over-specialized and only useful for TraitB's that only require a
162 /// single function (eg for serialization).
163 fn convert_trait_impl_field(trait_path: &str) -> (&'static str, String, &'static str) {
165 "lightning::util::ser::Writeable" => ("Serialize the object into a byte array", "write".to_owned(), "crate::c_types::derived::CVec_u8Z"),
166 _ => unimplemented!(),
170 /// Companion to convert_trait_impl_field, write an assignment for the function defined by it for
171 /// `for_obj` which implements the the trait at `trait_path`.
172 fn write_trait_impl_field_assign<W: std::io::Write>(w: &mut W, trait_path: &str, for_obj: &syn::Ident) {
174 "lightning::util::ser::Writeable" => {
175 writeln!(w, "\t\twrite: {}_write_void,", for_obj).unwrap();
177 _ => unimplemented!(),
181 /// Write out the impl block for a defined trait struct which has a supertrait
182 fn do_write_impl_trait<W: std::io::Write>(w: &mut W, trait_path: &str, _trait_name: &syn::Ident, for_obj: &str) {
183 eprintln!("{}", trait_path);
185 "lightning::util::ser::Writeable" => {
186 writeln!(w, "impl {} for {} {{", trait_path, for_obj).unwrap();
187 writeln!(w, "\tfn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {{").unwrap();
188 writeln!(w, "\t\tlet vec = (self.write)(self.this_arg);").unwrap();
189 writeln!(w, "\t\tw.write_all(vec.as_slice())").unwrap();
190 writeln!(w, "\t}}\n}}").unwrap();
196 // *******************************
197 // *** Per-Type Printing Logic ***
198 // *******************************
200 macro_rules! walk_supertraits { ($t: expr, $types: expr, ($( $pat: pat => $e: expr),*) ) => { {
201 if $t.colon_token.is_some() {
202 for st in $t.supertraits.iter() {
204 syn::TypeParamBound::Trait(supertrait) => {
205 if supertrait.paren_token.is_some() || supertrait.lifetimes.is_some() {
208 // First try to resolve path to find in-crate traits, but if that doesn't work
209 // assume its a prelude trait (eg Clone, etc) and just use the single ident.
210 let types_opt: Option<&TypeResolver> = $types;
211 if let Some(types) = types_opt {
212 if let Some(path) = types.maybe_resolve_path(&supertrait.path, None) {
213 match (&path as &str, &supertrait.path.segments.iter().last().unwrap().ident) {
219 if let Some(ident) = supertrait.path.get_ident() {
220 match (&format!("{}", ident) as &str, &ident) {
223 } else if types_opt.is_some() {
224 panic!("Supertrait unresolvable and not single-ident");
227 syn::TypeParamBound::Lifetime(_) => unimplemented!(),
233 /// Prints a C-mapped trait object containing a void pointer and a jump table for each function in
234 /// the original trait.
235 /// Implements the native Rust trait and relevant parent traits for the new C-mapped trait.
237 /// Finally, implements Deref<MappedTrait> for MappedTrait which allows its use in types which need
238 /// a concrete Deref to the Rust trait.
239 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) {
240 let trait_name = format!("{}", t.ident);
241 match export_status(&t.attrs) {
242 ExportStatus::Export => {},
243 ExportStatus::NoExport|ExportStatus::TestOnly => return,
245 writeln_docs(w, &t.attrs, "");
247 let mut gen_types = GenericTypes::new();
248 assert!(gen_types.learn_generics(&t.generics, types));
249 gen_types.learn_associated_types(&t, types);
251 writeln!(w, "#[repr(C)]\npub struct {} {{", trait_name).unwrap();
252 writeln!(w, "\t/// An opaque pointer which is passed to your function implementations as an argument.").unwrap();
253 writeln!(w, "\t/// This has no meaning in the LDK, and can be NULL or any other value.").unwrap();
254 writeln!(w, "\tpub this_arg: *mut c_void,").unwrap();
255 let mut generated_fields = Vec::new(); // Every field's (name, is_clonable) except this_arg, used in Clone generation
256 for item in t.items.iter() {
258 &syn::TraitItem::Method(ref m) => {
259 match export_status(&m.attrs) {
260 ExportStatus::NoExport => {
261 // NoExport in this context means we'll hit an unimplemented!() at runtime,
265 ExportStatus::Export => {},
266 ExportStatus::TestOnly => continue,
268 if m.default.is_some() { unimplemented!(); }
270 let mut meth_gen_types = gen_types.push_ctx();
271 assert!(meth_gen_types.learn_generics(&m.sig.generics, types));
273 writeln_docs(w, &m.attrs, "\t");
275 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
276 if let syn::Type::Reference(r) = &**rtype {
277 // We have to do quite a dance for trait functions which return references
278 // - they ultimately require us to have a native Rust object stored inside
279 // our concrete trait to return a reference to. However, users may wish to
280 // update the value to be returned each time the function is called (or, to
281 // make C copies of Rust impls equivalent, we have to be able to).
283 // Thus, we store a copy of the C-mapped type (which is just a pointer to
284 // the Rust type and a flag to indicate whether deallocation needs to
285 // happen) as well as provide an Option<>al function pointer which is
286 // called when the trait method is called which allows updating on the fly.
287 write!(w, "\tpub {}: ", m.sig.ident).unwrap();
288 generated_fields.push((format!("{}", m.sig.ident), true));
289 types.write_c_type(w, &*r.elem, Some(&meth_gen_types), false);
290 writeln!(w, ",").unwrap();
291 writeln!(w, "\t/// Fill in the {} field as a reference to it will be given to Rust after this returns", m.sig.ident).unwrap();
292 writeln!(w, "\t/// Note that this takes a pointer to this object, not the this_ptr like other methods do").unwrap();
293 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();
294 writeln!(w, "\tpub set_{}: Option<extern \"C\" fn(&{})>,", m.sig.ident, trait_name).unwrap();
295 generated_fields.push((format!("set_{}", m.sig.ident), true));
296 // Note that cbindgen will now generate
297 // typedef struct Thing {..., set_thing: (const Thing*), ...} Thing;
298 // which does not compile since Thing is not defined before it is used.
299 writeln!(extra_headers, "struct LDK{};", trait_name).unwrap();
300 writeln!(extra_headers, "typedef struct LDK{} LDK{};", trait_name, trait_name).unwrap();
303 // Sadly, this currently doesn't do what we want, but it should be easy to get
304 // cbindgen to support it. See https://github.com/eqrion/cbindgen/issues/531
305 writeln!(w, "\t#[must_use]").unwrap();
308 write!(w, "\tpub {}: extern \"C\" fn (", m.sig.ident).unwrap();
309 generated_fields.push((format!("{}", m.sig.ident), true));
310 write_method_params(w, &m.sig, "c_void", types, Some(&meth_gen_types), true, false);
311 writeln!(w, ",").unwrap();
313 &syn::TraitItem::Type(_) => {},
314 _ => unimplemented!(),
317 // Add functions which may be required for supertrait implementations.
318 let mut requires_clone = false;
319 walk_supertraits!(t, Some(&types), (
320 ("Clone", _) => requires_clone = true,
323 walk_supertraits!(t, Some(&types), (
325 writeln!(w, "\t/// Creates a copy of the object pointed to by this_arg, for a copy of this {}.", trait_name).unwrap();
326 writeln!(w, "\t/// Note that the ultimate copy of the {} will have all function pointers the same as the original.", trait_name).unwrap();
327 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();
328 writeln!(w, "\tpub clone: Option<extern \"C\" fn (this_arg: *const c_void) -> *mut c_void>,").unwrap();
329 generated_fields.push(("clone".to_owned(), true));
331 ("std::cmp::Eq", _) => {
332 writeln!(w, "\t/// Checks if two objects are equal given this object's this_arg pointer and another object.").unwrap();
333 writeln!(w, "\tpub eq: extern \"C\" fn (this_arg: *const c_void, other_arg: &{}) -> bool,", trait_name).unwrap();
334 writeln!(extra_headers, "typedef struct LDK{} LDK{};", trait_name, trait_name).unwrap();
335 generated_fields.push(("eq".to_owned(), true));
337 ("std::hash::Hash", _) => {
338 writeln!(w, "\t/// Calculate a succinct non-cryptographic hash for an object given its this_arg pointer.").unwrap();
339 writeln!(w, "\t/// This is used, for example, for inclusion of this object in a hash map.").unwrap();
340 writeln!(w, "\tpub hash: extern \"C\" fn (this_arg: *const c_void) -> u64,").unwrap();
341 generated_fields.push(("hash".to_owned(), true));
343 ("Send", _) => {}, ("Sync", _) => {},
345 generated_fields.push(if types.crate_types.traits.get(s).is_none() {
346 let (docs, name, ret) = convert_trait_impl_field(s);
347 writeln!(w, "\t/// {}", docs).unwrap();
348 writeln!(w, "\tpub {}: extern \"C\" fn (this_arg: *const c_void) -> {},", name, ret).unwrap();
349 (name, true) // Assume clonable
351 // For in-crate supertraits, just store a C-mapped copy of the supertrait as a member.
352 writeln!(w, "\t/// Implementation of {} for this object.", i).unwrap();
353 writeln!(w, "\tpub {}: crate::{},", i, s).unwrap();
354 let is_clonable = types.is_clonable(s);
355 if !is_clonable && requires_clone {
356 writeln!(w, "\t/// Creates a copy of the {}, for a copy of this {}.", i, trait_name).unwrap();
357 writeln!(w, "\t/// Because {} doesn't natively support copying itself, you have to provide a full copy implementation here.", i).unwrap();
358 writeln!(w, "\tpub {}_clone: extern \"C\" fn (orig_{}: &{}) -> {},", i, i, i, i).unwrap();
360 (format!("{}", i), is_clonable)
364 writeln!(w, "\t/// Frees any resources associated with this object given its this_arg pointer.").unwrap();
365 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();
366 writeln!(w, "\tpub free: Option<extern \"C\" fn(this_arg: *mut c_void)>,").unwrap();
367 generated_fields.push(("free".to_owned(), true));
368 writeln!(w, "}}").unwrap();
370 macro_rules! impl_trait_for_c {
371 ($t: expr, $impl_accessor: expr, $type_resolver: expr) => {
372 for item in $t.items.iter() {
374 syn::TraitItem::Method(m) => {
375 if let ExportStatus::TestOnly = export_status(&m.attrs) { continue; }
376 if m.default.is_some() { unimplemented!(); }
377 if m.sig.constness.is_some() || m.sig.asyncness.is_some() || m.sig.unsafety.is_some() ||
378 m.sig.abi.is_some() || m.sig.variadic.is_some() {
381 let mut meth_gen_types = gen_types.push_ctx();
382 assert!(meth_gen_types.learn_generics(&m.sig.generics, $type_resolver));
383 write!(w, "\tfn {}", m.sig.ident).unwrap();
384 $type_resolver.write_rust_generic_param(w, Some(&meth_gen_types), m.sig.generics.params.iter());
385 write!(w, "(").unwrap();
386 for inp in m.sig.inputs.iter() {
388 syn::FnArg::Receiver(recv) => {
389 if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
390 write!(w, "&").unwrap();
391 if let Some(lft) = &recv.reference.as_ref().unwrap().1 {
392 write!(w, "'{} ", lft.ident).unwrap();
394 if recv.mutability.is_some() {
395 write!(w, "mut self").unwrap();
397 write!(w, "self").unwrap();
400 syn::FnArg::Typed(arg) => {
401 if !arg.attrs.is_empty() { unimplemented!(); }
403 syn::Pat::Ident(ident) => {
404 if !ident.attrs.is_empty() || ident.by_ref.is_some() ||
405 ident.mutability.is_some() || ident.subpat.is_some() {
408 write!(w, ", {}{}: ", if $type_resolver.skip_arg(&*arg.ty, Some(&meth_gen_types)) { "_" } else { "" }, ident.ident).unwrap();
410 _ => unimplemented!(),
412 $type_resolver.write_rust_type(w, Some(&meth_gen_types), &*arg.ty);
416 write!(w, ")").unwrap();
417 match &m.sig.output {
418 syn::ReturnType::Type(_, rtype) => {
419 write!(w, " -> ").unwrap();
420 $type_resolver.write_rust_type(w, Some(&meth_gen_types), &*rtype)
424 write!(w, " {{\n\t\t").unwrap();
425 match export_status(&m.attrs) {
426 ExportStatus::NoExport => {
431 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
432 if let syn::Type::Reference(r) = &**rtype {
433 assert_eq!(m.sig.inputs.len(), 1); // Must only take self!
434 writeln!(w, "if let Some(f) = self{}.set_{} {{", $impl_accessor, m.sig.ident).unwrap();
435 writeln!(w, "\t\t\t(f)(&self{});", $impl_accessor).unwrap();
436 write!(w, "\t\t}}\n\t\t").unwrap();
437 $type_resolver.write_from_c_conversion_to_ref_prefix(w, &*r.elem, Some(&meth_gen_types));
438 write!(w, "self{}.{}", $impl_accessor, m.sig.ident).unwrap();
439 $type_resolver.write_from_c_conversion_to_ref_suffix(w, &*r.elem, Some(&meth_gen_types));
440 writeln!(w, "\n\t}}").unwrap();
444 write_method_var_decl_body(w, &m.sig, "\t", $type_resolver, Some(&meth_gen_types), true);
445 write!(w, "(self{}.{})(", $impl_accessor, m.sig.ident).unwrap();
446 write_method_call_params(w, &m.sig, "\t", $type_resolver, Some(&meth_gen_types), "", true);
448 writeln!(w, "\n\t}}").unwrap();
450 &syn::TraitItem::Type(ref t) => {
451 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
452 let mut bounds_iter = t.bounds.iter();
453 match bounds_iter.next().unwrap() {
454 syn::TypeParamBound::Trait(tr) => {
455 writeln!(w, "\ttype {} = crate::{};", t.ident, $type_resolver.resolve_path(&tr.path, Some(&gen_types))).unwrap();
457 _ => unimplemented!(),
459 if bounds_iter.next().is_some() { unimplemented!(); }
461 _ => unimplemented!(),
468 // Implement supertraits for the C-mapped struct.
469 walk_supertraits!(t, Some(&types), (
470 ("Send", _) => writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap(),
471 ("Sync", _) => writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap(),
472 ("std::cmp::Eq", _) => {
473 writeln!(w, "impl std::cmp::Eq for {} {{}}", trait_name).unwrap();
474 writeln!(w, "impl std::cmp::PartialEq for {} {{", trait_name).unwrap();
475 writeln!(w, "\tfn eq(&self, o: &Self) -> bool {{ (self.eq)(self.this_arg, o) }}\n}}").unwrap();
477 ("std::hash::Hash", _) => {
478 writeln!(w, "impl std::hash::Hash for {} {{", trait_name).unwrap();
479 writeln!(w, "\tfn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {{ hasher.write_u64((self.hash)(self.this_arg)) }}\n}}").unwrap();
482 writeln!(w, "#[no_mangle]").unwrap();
483 writeln!(w, "/// Creates a copy of a {}", trait_name).unwrap();
484 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", trait_name, trait_name, trait_name).unwrap();
485 writeln!(w, "\t{} {{", trait_name).unwrap();
486 writeln!(w, "\t\tthis_arg: if let Some(f) = orig.clone {{ (f)(orig.this_arg) }} else {{ orig.this_arg }},").unwrap();
487 for (field, clonable) in generated_fields.iter() {
489 writeln!(w, "\t\t{}: Clone::clone(&orig.{}),", field, field).unwrap();
491 writeln!(w, "\t\t{}: (orig.{}_clone)(&orig.{}),", field, field, field).unwrap();
492 writeln!(w, "\t\t{}_clone: orig.{}_clone,", field, field).unwrap();
495 writeln!(w, "\t}}\n}}").unwrap();
496 writeln!(w, "impl Clone for {} {{", trait_name).unwrap();
497 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
498 writeln!(w, "\t\t{}_clone(self)", trait_name).unwrap();
499 writeln!(w, "\t}}\n}}").unwrap();
502 if let Some(supertrait) = types.crate_types.traits.get(s) {
503 let mut module_iter = s.rsplitn(2, "::");
504 module_iter.next().unwrap();
505 let supertrait_module = module_iter.next().unwrap();
506 let imports = ImportResolver::new(supertrait_module.splitn(2, "::").next().unwrap(), &types.crate_types.lib_ast.dependencies,
507 supertrait_module, &types.crate_types.lib_ast.modules.get(supertrait_module).unwrap().items);
508 let resolver = TypeResolver::new(&supertrait_module, imports, types.crate_types);
509 writeln!(w, "impl {} for {} {{", s, trait_name).unwrap();
510 impl_trait_for_c!(supertrait, format!(".{}", i), &resolver);
511 writeln!(w, "}}").unwrap();
512 walk_supertraits!(supertrait, Some(&types), (
513 ("Send", _) => writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap(),
514 ("Sync", _) => writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap(),
515 _ => unimplemented!()
518 do_write_impl_trait(w, s, i, &trait_name);
523 // Finally, implement the original Rust trait for the newly created mapped trait.
524 writeln!(w, "\nuse {}::{} as rust{};", types.module_path, t.ident, trait_name).unwrap();
525 write!(w, "impl rust{}", t.ident).unwrap();
526 maybe_write_generics(w, &t.generics, types, false);
527 writeln!(w, " for {} {{", trait_name).unwrap();
528 impl_trait_for_c!(t, "", types);
529 writeln!(w, "}}\n").unwrap();
530 writeln!(w, "// We're essentially a pointer already, or at least a set of pointers, so allow us to be used").unwrap();
531 writeln!(w, "// directly as a Deref trait in higher-level structs:").unwrap();
532 writeln!(w, "impl std::ops::Deref for {} {{\n\ttype Target = Self;", trait_name).unwrap();
533 writeln!(w, "\tfn deref(&self) -> &Self {{\n\t\tself\n\t}}\n}}").unwrap();
535 writeln!(w, "/// Calls the free function if one is set").unwrap();
536 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", trait_name, trait_name).unwrap();
537 writeln!(w, "impl Drop for {} {{", trait_name).unwrap();
538 writeln!(w, "\tfn drop(&mut self) {{").unwrap();
539 writeln!(w, "\t\tif let Some(f) = self.free {{").unwrap();
540 writeln!(w, "\t\t\tf(self.this_arg);").unwrap();
541 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
543 write_cpp_wrapper(cpp_headers, &trait_name, true);
546 /// Write out a simple "opaque" type (eg structs) which contain a pointer to the native Rust type
547 /// and a flag to indicate whether Drop'ing the mapped struct drops the underlying Rust type.
549 /// Also writes out a _free function and a C++ wrapper which handles calling _free.
550 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) {
551 // If we directly read the original type by its original name, cbindgen hits
552 // https://github.com/eqrion/cbindgen/issues/286 Thus, instead, we import it as a temporary
553 // name and then reference it by that name, which works around the issue.
554 write!(w, "\nuse {}::{} as native{}Import;\ntype native{} = native{}Import", types.module_path, ident, ident, ident, ident).unwrap();
555 maybe_write_generics(w, &generics, &types, true);
556 writeln!(w, ";\n").unwrap();
557 writeln!(extra_headers, "struct native{}Opaque;\ntypedef struct native{}Opaque LDKnative{};", ident, ident, ident).unwrap();
558 writeln_docs(w, &attrs, "");
559 writeln!(w, "#[must_use]\n#[repr(C)]\npub struct {} {{", struct_name).unwrap();
560 writeln!(w, "\t/// A pointer to the opaque Rust object.\n").unwrap();
561 writeln!(w, "\t/// Nearly everywhere, inner must be non-null, however in places where").unwrap();
562 writeln!(w, "\t/// the Rust equivalent takes an Option, it may be set to null to indicate None.").unwrap();
563 writeln!(w, "\tpub inner: *mut native{},", ident).unwrap();
564 writeln!(w, "\t/// Indicates that this is the only struct which contains the same pointer.\n").unwrap();
565 writeln!(w, "\t/// Rust functions which take ownership of an object provided via an argument require").unwrap();
566 writeln!(w, "\t/// this to be true and invalidate the object pointed to by inner.").unwrap();
567 writeln!(w, "\tpub is_owned: bool,").unwrap();
568 writeln!(w, "}}\n").unwrap();
569 writeln!(w, "impl Drop for {} {{\n\tfn drop(&mut self) {{", struct_name).unwrap();
570 writeln!(w, "\t\tif self.is_owned && !<*mut native{}>::is_null(self.inner) {{", ident).unwrap();
571 writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(self.inner) }};\n\t\t}}\n\t}}\n}}").unwrap();
572 writeln!(w, "/// Frees any resources used by the {}, if is_owned is set and inner is non-NULL.", struct_name).unwrap();
573 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_obj: {}) {{ }}", struct_name, struct_name).unwrap();
574 writeln!(w, "#[allow(unused)]").unwrap();
575 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
576 writeln!(w, "extern \"C\" fn {}_free_void(this_ptr: *mut c_void) {{", struct_name).unwrap();
577 writeln!(w, "\tunsafe {{ let _ = Box::from_raw(this_ptr as *mut native{}); }}\n}}", struct_name).unwrap();
578 writeln!(w, "#[allow(unused)]").unwrap();
579 writeln!(w, "/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy").unwrap();
580 writeln!(w, "impl {} {{", struct_name).unwrap();
581 writeln!(w, "\tpub(crate) fn take_inner(mut self) -> *mut native{} {{", struct_name).unwrap();
582 writeln!(w, "\t\tassert!(self.is_owned);").unwrap();
583 writeln!(w, "\t\tlet ret = self.inner;").unwrap();
584 writeln!(w, "\t\tself.inner = std::ptr::null_mut();").unwrap();
585 writeln!(w, "\t\tret").unwrap();
586 writeln!(w, "\t}}\n}}").unwrap();
588 write_cpp_wrapper(cpp_headers, &format!("{}", ident), true);
591 /// Writes out all the relevant mappings for a Rust struct, deferring to writeln_opaque to generate
592 /// the struct itself, and then writing getters and setters for public, understood-type fields and
593 /// a constructor if every field is public.
594 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) {
595 if export_status(&s.attrs) != ExportStatus::Export { return; }
597 let struct_name = &format!("{}", s.ident);
598 writeln_opaque(w, &s.ident, struct_name, &s.generics, &s.attrs, types, extra_headers, cpp_headers);
600 if let syn::Fields::Named(fields) = &s.fields {
601 let mut gen_types = GenericTypes::new();
602 assert!(gen_types.learn_generics(&s.generics, types));
604 let mut all_fields_settable = true;
605 for field in fields.named.iter() {
606 if let syn::Visibility::Public(_) = field.vis {
607 let export = export_status(&field.attrs);
609 ExportStatus::Export => {},
610 ExportStatus::NoExport|ExportStatus::TestOnly => {
611 all_fields_settable = false;
616 if let Some(ident) = &field.ident {
617 let ref_type = syn::Type::Reference(syn::TypeReference {
618 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
619 elem: Box::new(field.ty.clone()) });
620 if types.understood_c_type(&ref_type, Some(&gen_types)) {
621 writeln_docs(w, &field.attrs, "");
622 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> ", struct_name, ident, struct_name).unwrap();
623 types.write_c_type(w, &ref_type, Some(&gen_types), true);
624 write!(w, " {{\n\tlet mut inner_val = &mut unsafe {{ &mut *this_ptr.inner }}.{};\n\t", ident).unwrap();
625 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);
626 if local_var { write!(w, "\n\t").unwrap(); }
627 types.write_to_c_conversion_inline_prefix(w, &ref_type, Some(&gen_types), true);
629 write!(w, "inner_val").unwrap();
631 write!(w, "(*inner_val)").unwrap();
633 types.write_to_c_conversion_inline_suffix(w, &ref_type, Some(&gen_types), true);
634 writeln!(w, "\n}}").unwrap();
637 if types.understood_c_type(&field.ty, Some(&gen_types)) {
638 writeln_docs(w, &field.attrs, "");
639 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_set_{}(this_ptr: &mut {}, mut val: ", struct_name, ident, struct_name).unwrap();
640 types.write_c_type(w, &field.ty, Some(&gen_types), false);
641 write!(w, ") {{\n\t").unwrap();
642 let local_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("val", Span::call_site()), &field.ty, Some(&gen_types));
643 if local_var { write!(w, "\n\t").unwrap(); }
644 write!(w, "unsafe {{ &mut *this_ptr.inner }}.{} = ", ident).unwrap();
645 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
646 write!(w, "val").unwrap();
647 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
648 writeln!(w, ";\n}}").unwrap();
649 } else { all_fields_settable = false; }
650 } else { all_fields_settable = false; }
651 } else { all_fields_settable = false; }
654 if all_fields_settable {
655 // Build a constructor!
656 writeln!(w, "/// Constructs a new {} given each field", struct_name).unwrap();
657 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_new(", struct_name).unwrap();
658 for (idx, field) in fields.named.iter().enumerate() {
659 if idx != 0 { write!(w, ", ").unwrap(); }
660 write!(w, "mut {}_arg: ", field.ident.as_ref().unwrap()).unwrap();
661 types.write_c_type(w, &field.ty, Some(&gen_types), false);
663 write!(w, ") -> {} {{\n\t", struct_name).unwrap();
664 for field in fields.named.iter() {
665 let field_name = format!("{}_arg", field.ident.as_ref().unwrap());
666 if types.write_from_c_conversion_new_var(w, &syn::Ident::new(&field_name, Span::call_site()), &field.ty, Some(&gen_types)) {
667 write!(w, "\n\t").unwrap();
670 writeln!(w, "{} {{ inner: Box::into_raw(Box::new(native{} {{", struct_name, s.ident).unwrap();
671 for field in fields.named.iter() {
672 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
673 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
674 write!(w, "{}_arg", field.ident.as_ref().unwrap()).unwrap();
675 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
676 writeln!(w, ",").unwrap();
678 writeln!(w, "\t}})), is_owned: true }}\n}}").unwrap();
683 /// Prints a relevant conversion for impl *
685 /// For simple impl Struct {}s, this just outputs the wrapper functions as Struct_fn_name() { .. }.
687 /// For impl Trait for Struct{}s, this non-exported generates wrapper functions as
688 /// Trait_Struct_fn_name and a Struct_as_Trait(&struct) -> Trait function which returns a populated
689 /// Trait struct containing a pointer to the passed struct's inner field and the wrapper functions.
691 /// A few non-crate Traits are hard-coded including Default.
692 fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut TypeResolver) {
693 match export_status(&i.attrs) {
694 ExportStatus::Export => {},
695 ExportStatus::NoExport|ExportStatus::TestOnly => return,
698 if let syn::Type::Tuple(_) = &*i.self_ty {
699 if types.understood_c_type(&*i.self_ty, None) {
700 let mut gen_types = GenericTypes::new();
701 if !gen_types.learn_generics(&i.generics, types) {
702 eprintln!("Not implementing anything for `impl (..)` due to not understood generics");
706 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
707 if let Some(trait_path) = i.trait_.as_ref() {
708 if trait_path.0.is_some() { unimplemented!(); }
709 if types.understood_c_path(&trait_path.1) {
710 eprintln!("Not implementing anything for `impl Trait for (..)` - we only support manual defines");
713 // Just do a manual implementation:
714 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
717 eprintln!("Not implementing anything for plain `impl (..)` block - we only support `impl Trait for (..)` blocks");
723 if let &syn::Type::Path(ref p) = &*i.self_ty {
724 if p.qself.is_some() { unimplemented!(); }
725 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
726 if let Some(resolved_path) = types.maybe_resolve_non_ignored_ident(&ident) {
727 let mut gen_types = GenericTypes::new();
728 if !gen_types.learn_generics(&i.generics, types) {
729 eprintln!("Not implementing anything for impl {} due to not understood generics", ident);
733 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
734 if let Some(trait_path) = i.trait_.as_ref() {
735 if trait_path.0.is_some() { unimplemented!(); }
736 if types.understood_c_path(&trait_path.1) {
737 let full_trait_path = types.resolve_path(&trait_path.1, None);
738 let trait_obj = *types.crate_types.traits.get(&full_trait_path).unwrap();
739 // We learn the associated types maping from the original trait object.
740 // That's great, except that they are unresolved idents, so if we learn
741 // mappings from a trai defined in a different file, we may mis-resolve or
742 // fail to resolve the mapped types.
743 gen_types.learn_associated_types(trait_obj, types);
744 let mut impl_associated_types = HashMap::new();
745 for item in i.items.iter() {
747 syn::ImplItem::Type(t) => {
748 if let syn::Type::Path(p) = &t.ty {
749 if let Some(id) = single_ident_generic_path_to_ident(&p.path) {
750 impl_associated_types.insert(&t.ident, id);
758 let export = export_status(&trait_obj.attrs);
760 ExportStatus::Export => {},
761 ExportStatus::NoExport|ExportStatus::TestOnly => return,
764 // For cases where we have a concrete native object which implements a
765 // trait and need to return the C-mapped version of the trait, provide a
766 // From<> implementation which does all the work to ensure free is handled
767 // properly. This way we can call this method from deep in the
768 // type-conversion logic without actually knowing the concrete native type.
769 writeln!(w, "impl From<native{}> for crate::{} {{", ident, full_trait_path).unwrap();
770 writeln!(w, "\tfn from(obj: native{}) -> Self {{", ident).unwrap();
771 writeln!(w, "\t\tlet mut rust_obj = {} {{ inner: Box::into_raw(Box::new(obj)), is_owned: true }};", ident).unwrap();
772 writeln!(w, "\t\tlet mut ret = {}_as_{}(&rust_obj);", ident, trait_obj.ident).unwrap();
773 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();
774 writeln!(w, "\t\trust_obj.inner = std::ptr::null_mut();").unwrap();
775 writeln!(w, "\t\tret.free = Some({}_free_void);", ident).unwrap();
776 writeln!(w, "\t\tret\n\t}}\n}}").unwrap();
778 writeln!(w, "/// Constructs a new {} which calls the relevant methods on this_arg.", trait_obj.ident).unwrap();
779 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();
780 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_as_{}(this_arg: &{}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
781 writeln!(w, "\tcrate::{} {{", full_trait_path).unwrap();
782 writeln!(w, "\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
783 writeln!(w, "\t\tfree: None,").unwrap();
785 macro_rules! write_meth {
786 ($m: expr, $trait: expr, $indent: expr) => {
787 let trait_method = $trait.items.iter().filter_map(|item| {
788 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
789 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
790 match export_status(&trait_method.attrs) {
791 ExportStatus::Export => {},
792 ExportStatus::NoExport => {
793 write!(w, "{}\t\t//XXX: Need to export {}\n", $indent, $m.sig.ident).unwrap();
796 ExportStatus::TestOnly => continue,
799 let mut printed = false;
800 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
801 if let syn::Type::Reference(r) = &**rtype {
802 write!(w, "\n\t\t{}{}: ", $indent, $m.sig.ident).unwrap();
803 types.write_empty_rust_val(Some(&gen_types), w, &*r.elem);
804 writeln!(w, ",\n{}\t\tset_{}: Some({}_{}_set_{}),", $indent, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
809 write!(w, "{}\t\t{}: {}_{}_{},\n", $indent, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
813 for item in trait_obj.items.iter() {
815 syn::TraitItem::Method(m) => {
816 write_meth!(m, trait_obj, "");
821 let mut requires_clone = false;
822 walk_supertraits!(trait_obj, Some(&types), (
823 ("Clone", _) => requires_clone = true,
826 walk_supertraits!(trait_obj, Some(&types), (
828 writeln!(w, "\t\tclone: Some({}_clone_void),", ident).unwrap();
830 ("Sync", _) => {}, ("Send", _) => {},
831 ("std::marker::Sync", _) => {}, ("std::marker::Send", _) => {},
833 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
834 writeln!(w, "\t\t{}: crate::{} {{", t, s).unwrap();
835 writeln!(w, "\t\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
836 writeln!(w, "\t\t\tfree: None,").unwrap();
837 for item in supertrait_obj.items.iter() {
839 syn::TraitItem::Method(m) => {
840 write_meth!(m, supertrait_obj, "\t");
845 write!(w, "\t\t}},\n").unwrap();
846 if !types.is_clonable(s) && requires_clone {
847 writeln!(w, "\t\t{}_clone: {}_{}_clone,", t, ident, t).unwrap();
850 write_trait_impl_field_assign(w, s, ident);
854 writeln!(w, "\t}}\n}}\n").unwrap();
856 macro_rules! impl_meth {
857 ($m: expr, $trait_path: expr, $trait: expr, $indent: expr) => {
858 let trait_method = $trait.items.iter().filter_map(|item| {
859 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
860 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
861 match export_status(&trait_method.attrs) {
862 ExportStatus::Export => {},
863 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
866 if let syn::ReturnType::Type(_, _) = &$m.sig.output {
867 writeln!(w, "#[must_use]").unwrap();
869 write!(w, "extern \"C\" fn {}_{}_{}(", ident, $trait.ident, $m.sig.ident).unwrap();
870 let mut meth_gen_types = gen_types.push_ctx();
871 assert!(meth_gen_types.learn_generics(&$m.sig.generics, types));
872 write_method_params(w, &$m.sig, "c_void", types, Some(&meth_gen_types), true, true);
873 write!(w, " {{\n\t").unwrap();
874 write_method_var_decl_body(w, &$m.sig, "", types, Some(&meth_gen_types), false);
875 let mut takes_self = false;
876 for inp in $m.sig.inputs.iter() {
877 if let syn::FnArg::Receiver(_) = inp {
882 let mut t_gen_args = String::new();
883 for (idx, _) in $trait.generics.params.iter().enumerate() {
884 if idx != 0 { t_gen_args += ", " };
888 write!(w, "<native{} as {}<{}>>::{}(unsafe {{ &mut *(this_arg as *mut native{}) }}, ", ident, $trait_path, t_gen_args, $m.sig.ident, ident).unwrap();
890 write!(w, "<native{} as {}<{}>>::{}(", ident, $trait_path, t_gen_args, $m.sig.ident).unwrap();
893 let mut real_type = "".to_string();
894 match &$m.sig.output {
895 syn::ReturnType::Type(_, rtype) => {
896 if let Some(mut remaining_path) = first_seg_self(&*rtype) {
897 if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
898 real_type = format!("{}", impl_associated_types.get(associated_seg).unwrap());
904 write_method_call_params(w, &$m.sig, "", types, Some(&meth_gen_types), &real_type, false);
905 write!(w, "\n}}\n").unwrap();
906 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
907 if let syn::Type::Reference(r) = &**rtype {
908 assert_eq!($m.sig.inputs.len(), 1); // Must only take self
909 writeln!(w, "extern \"C\" fn {}_{}_set_{}(trait_self_arg: &{}) {{", ident, $trait.ident, $m.sig.ident, $trait.ident).unwrap();
910 writeln!(w, "\t// This is a bit race-y in the general case, but for our specific use-cases today, we're safe").unwrap();
911 writeln!(w, "\t// Specifically, we must ensure that the first time we're called it can never be in parallel").unwrap();
912 write!(w, "\tif ").unwrap();
913 types.write_empty_rust_val_check(Some(&meth_gen_types), w, &*r.elem, &format!("trait_self_arg.{}", $m.sig.ident));
914 writeln!(w, " {{").unwrap();
915 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();
916 writeln!(w, "\t}}").unwrap();
917 writeln!(w, "}}").unwrap();
923 for item in i.items.iter() {
925 syn::ImplItem::Method(m) => {
926 impl_meth!(m, full_trait_path, trait_obj, "");
928 syn::ImplItem::Type(_) => {},
929 _ => unimplemented!(),
932 walk_supertraits!(trait_obj, Some(&types), (
934 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
935 if !types.is_clonable(s) && requires_clone {
936 writeln!(w, "extern \"C\" fn {}_{}_clone(orig: &crate::{}) -> crate::{} {{", ident, t, s, s).unwrap();
937 writeln!(w, "\tcrate::{} {{", s).unwrap();
938 writeln!(w, "\t\tthis_arg: orig.this_arg,").unwrap();
939 writeln!(w, "\t\tfree: None,").unwrap();
940 for item in supertrait_obj.items.iter() {
942 syn::TraitItem::Method(m) => {
943 write_meth!(m, supertrait_obj, "");
948 write!(w, "\t}}\n}}\n").unwrap();
953 write!(w, "\n").unwrap();
954 } else if path_matches_nongeneric(&trait_path.1, &["From"]) {
955 } else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
956 writeln!(w, "/// Creates a \"default\" {}. See struct and individual field documentaiton for details on which values are used.", ident).unwrap();
957 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
958 write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
959 write!(w, "}}\n").unwrap();
960 } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "PartialEq"]) {
961 } else if (path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) || path_matches_nongeneric(&trait_path.1, &["Clone"])) &&
962 types.c_type_has_inner_from_path(&resolved_path) {
963 writeln!(w, "impl Clone for {} {{", ident).unwrap();
964 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
965 writeln!(w, "\t\tSelf {{").unwrap();
966 writeln!(w, "\t\t\tinner: if <*mut native{}>::is_null(self.inner) {{ std::ptr::null_mut() }} else {{", ident).unwrap();
967 writeln!(w, "\t\t\t\tBox::into_raw(Box::new(unsafe {{ &*self.inner }}.clone())) }},").unwrap();
968 writeln!(w, "\t\t\tis_owned: true,").unwrap();
969 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
970 writeln!(w, "#[allow(unused)]").unwrap();
971 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
972 writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", ident).unwrap();
973 writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", ident).unwrap();
974 writeln!(w, "}}").unwrap();
975 writeln!(w, "#[no_mangle]").unwrap();
976 writeln!(w, "/// Creates a copy of the {}", ident).unwrap();
977 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", ident, ident, ident).unwrap();
978 writeln!(w, "\torig.clone()").unwrap();
979 writeln!(w, "}}").unwrap();
981 //XXX: implement for other things like ToString
982 // If we have no generics, try a manual implementation:
983 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
986 let declared_type = (*types.get_declared_type(&ident).unwrap()).clone();
987 for item in i.items.iter() {
989 syn::ImplItem::Method(m) => {
990 if let syn::Visibility::Public(_) = m.vis {
991 match export_status(&m.attrs) {
992 ExportStatus::Export => {},
993 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
995 if m.defaultness.is_some() { unimplemented!(); }
996 writeln_docs(w, &m.attrs, "");
997 if let syn::ReturnType::Type(_, _) = &m.sig.output {
998 writeln!(w, "#[must_use]").unwrap();
1000 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_{}(", ident, m.sig.ident).unwrap();
1001 let ret_type = match &declared_type {
1002 DeclType::MirroredEnum => format!("{}", ident),
1003 DeclType::StructImported => format!("{}", ident),
1004 _ => unimplemented!(),
1006 let mut meth_gen_types = gen_types.push_ctx();
1007 assert!(meth_gen_types.learn_generics(&m.sig.generics, types));
1008 write_method_params(w, &m.sig, &ret_type, types, Some(&meth_gen_types), false, true);
1009 write!(w, " {{\n\t").unwrap();
1010 write_method_var_decl_body(w, &m.sig, "", types, Some(&meth_gen_types), false);
1011 let mut takes_self = false;
1012 let mut takes_mut_self = false;
1013 for inp in m.sig.inputs.iter() {
1014 if let syn::FnArg::Receiver(r) = inp {
1016 if r.mutability.is_some() { takes_mut_self = true; }
1020 write!(w, "unsafe {{ &mut (*(this_arg.inner as *mut native{})) }}.{}(", ident, m.sig.ident).unwrap();
1021 } else if takes_self {
1022 write!(w, "unsafe {{ &*this_arg.inner }}.{}(", m.sig.ident).unwrap();
1024 write!(w, "{}::{}(", resolved_path, m.sig.ident).unwrap();
1026 write_method_call_params(w, &m.sig, "", types, Some(&meth_gen_types), &ret_type, false);
1027 writeln!(w, "\n}}\n").unwrap();
1034 } else if let Some(resolved_path) = types.maybe_resolve_ident(&ident) {
1035 if let Some(aliases) = types.crate_types.reverse_alias_map.get(&resolved_path).cloned() {
1036 'alias_impls: for (alias, arguments) in aliases {
1037 let alias_resolved = types.resolve_path(&alias, None);
1038 for (idx, gen) in i.generics.params.iter().enumerate() {
1040 syn::GenericParam::Type(type_param) => {
1041 'bounds_check: for bound in type_param.bounds.iter() {
1042 if let syn::TypeParamBound::Trait(trait_bound) = bound {
1043 if let syn::PathArguments::AngleBracketed(ref t) = &arguments {
1044 assert!(idx < t.args.len());
1045 if let syn::GenericArgument::Type(syn::Type::Path(p)) = &t.args[idx] {
1046 let generic_arg = types.resolve_path(&p.path, None);
1047 let generic_bound = types.resolve_path(&trait_bound.path, None);
1048 if let Some(traits_impld) = types.crate_types.trait_impls.get(&generic_arg) {
1049 for trait_impld in traits_impld {
1050 if *trait_impld == generic_bound { continue 'bounds_check; }
1052 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1053 continue 'alias_impls;
1055 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1056 continue 'alias_impls;
1058 } else { unimplemented!(); }
1059 } else { unimplemented!(); }
1060 } else { unimplemented!(); }
1063 syn::GenericParam::Lifetime(_) => {},
1064 syn::GenericParam::Const(_) => unimplemented!(),
1067 let aliased_impl = syn::ItemImpl {
1068 attrs: i.attrs.clone(),
1069 brace_token: syn::token::Brace(Span::call_site()),
1071 generics: syn::Generics {
1073 params: syn::punctuated::Punctuated::new(),
1077 impl_token: syn::Token![impl](Span::call_site()),
1078 items: i.items.clone(),
1079 self_ty: Box::new(syn::Type::Path(syn::TypePath { qself: None, path: alias.clone() })),
1080 trait_: i.trait_.clone(),
1083 writeln_impl(w, &aliased_impl, types);
1086 eprintln!("Not implementing anything for {} due to it being marked not exported", ident);
1089 eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub)", ident);
1096 /// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
1097 /// is unitary), we generate an equivalent enum with all types replaced with their C mapped
1098 /// versions followed by conversion functions which map between the Rust version and the C mapped
1100 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) {
1101 match export_status(&e.attrs) {
1102 ExportStatus::Export => {},
1103 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1106 if is_enum_opaque(e) {
1107 eprintln!("Skipping enum {} as it contains non-unit fields", e.ident);
1108 writeln_opaque(w, &e.ident, &format!("{}", e.ident), &e.generics, &e.attrs, types, extra_headers, cpp_headers);
1111 writeln_docs(w, &e.attrs, "");
1113 if e.generics.lt_token.is_some() {
1117 let mut needs_free = false;
1119 writeln!(w, "#[must_use]\n#[derive(Clone)]\n#[repr(C)]\npub enum {} {{", e.ident).unwrap();
1120 for var in e.variants.iter() {
1121 assert_eq!(export_status(&var.attrs), ExportStatus::Export); // We can't partially-export a mirrored enum
1122 writeln_docs(w, &var.attrs, "\t");
1123 write!(w, "\t{}", var.ident).unwrap();
1124 if let syn::Fields::Named(fields) = &var.fields {
1126 writeln!(w, " {{").unwrap();
1127 for field in fields.named.iter() {
1128 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1129 writeln_docs(w, &field.attrs, "\t\t");
1130 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1131 types.write_c_type(w, &field.ty, None, false);
1132 writeln!(w, ",").unwrap();
1134 write!(w, "\t}}").unwrap();
1135 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1137 write!(w, "(").unwrap();
1138 for (idx, field) in fields.unnamed.iter().enumerate() {
1139 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1140 types.write_c_type(w, &field.ty, None, false);
1141 if idx != fields.unnamed.len() - 1 {
1142 write!(w, ",").unwrap();
1145 write!(w, ")").unwrap();
1147 if var.discriminant.is_some() { unimplemented!(); }
1148 writeln!(w, ",").unwrap();
1150 writeln!(w, "}}\nuse {}::{} as native{};\nimpl {} {{", types.module_path, e.ident, e.ident, e.ident).unwrap();
1152 macro_rules! write_conv {
1153 ($fn_sig: expr, $to_c: expr, $ref: expr) => {
1154 writeln!(w, "\t#[allow(unused)]\n\tpub(crate) fn {} {{\n\t\tmatch {} {{", $fn_sig, if $to_c { "native" } else { "self" }).unwrap();
1155 for var in e.variants.iter() {
1156 write!(w, "\t\t\t{}{}::{} ", if $to_c { "native" } else { "" }, e.ident, var.ident).unwrap();
1157 if let syn::Fields::Named(fields) = &var.fields {
1158 write!(w, "{{").unwrap();
1159 for field in fields.named.iter() {
1160 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1161 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, field.ident.as_ref().unwrap()).unwrap();
1163 write!(w, "}} ").unwrap();
1164 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1165 write!(w, "(").unwrap();
1166 for (idx, field) in fields.unnamed.iter().enumerate() {
1167 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1168 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, ('a' as u8 + idx as u8) as char).unwrap();
1170 write!(w, ") ").unwrap();
1172 write!(w, "=>").unwrap();
1174 macro_rules! handle_field_a {
1175 ($field: expr, $field_ident: expr) => { {
1176 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1177 let mut sink = ::std::io::sink();
1178 let mut out: &mut dyn std::io::Write = if $ref { &mut sink } else { w };
1179 let new_var = if $to_c {
1180 types.write_to_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None, false)
1182 types.write_from_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None)
1184 if $ref || new_var {
1186 write!(w, "let mut {}_nonref = (*{}).clone();\n\t\t\t\t", $field_ident, $field_ident).unwrap();
1188 let nonref_ident = syn::Ident::new(&format!("{}_nonref", $field_ident), Span::call_site());
1190 types.write_to_c_conversion_new_var(w, &nonref_ident, &$field.ty, None, false);
1192 types.write_from_c_conversion_new_var(w, &nonref_ident, &$field.ty, None);
1194 write!(w, "\n\t\t\t\t").unwrap();
1197 write!(w, "\n\t\t\t\t").unwrap();
1202 if let syn::Fields::Named(fields) = &var.fields {
1203 write!(w, " {{\n\t\t\t\t").unwrap();
1204 for field in fields.named.iter() {
1205 handle_field_a!(field, field.ident.as_ref().unwrap());
1207 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1208 write!(w, " {{\n\t\t\t\t").unwrap();
1209 for (idx, field) in fields.unnamed.iter().enumerate() {
1210 handle_field_a!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1212 } else { write!(w, " ").unwrap(); }
1214 write!(w, "{}{}::{}", if $to_c { "" } else { "native" }, e.ident, var.ident).unwrap();
1216 macro_rules! handle_field_b {
1217 ($field: expr, $field_ident: expr) => { {
1218 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1220 types.write_to_c_conversion_inline_prefix(w, &$field.ty, None, false);
1222 types.write_from_c_conversion_prefix(w, &$field.ty, None);
1224 write!(w, "{}{}", $field_ident,
1225 if $ref { "_nonref" } else { "" }).unwrap();
1227 types.write_to_c_conversion_inline_suffix(w, &$field.ty, None, false);
1229 types.write_from_c_conversion_suffix(w, &$field.ty, None);
1231 write!(w, ",").unwrap();
1235 if let syn::Fields::Named(fields) = &var.fields {
1236 write!(w, " {{").unwrap();
1237 for field in fields.named.iter() {
1238 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1239 write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1240 handle_field_b!(field, field.ident.as_ref().unwrap());
1242 writeln!(w, "\n\t\t\t\t}}").unwrap();
1243 write!(w, "\t\t\t}}").unwrap();
1244 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1245 write!(w, " (").unwrap();
1246 for (idx, field) in fields.unnamed.iter().enumerate() {
1247 write!(w, "\n\t\t\t\t\t").unwrap();
1248 handle_field_b!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1250 writeln!(w, "\n\t\t\t\t)").unwrap();
1251 write!(w, "\t\t\t}}").unwrap();
1253 writeln!(w, ",").unwrap();
1255 writeln!(w, "\t\t}}\n\t}}").unwrap();
1259 write_conv!(format!("to_native(&self) -> native{}", e.ident), false, true);
1260 write_conv!(format!("into_native(self) -> native{}", e.ident), false, false);
1261 write_conv!(format!("from_native(native: &native{}) -> Self", e.ident), true, true);
1262 write_conv!(format!("native_into(native: native{}) -> Self", e.ident), true, false);
1263 writeln!(w, "}}").unwrap();
1266 writeln!(w, "/// Frees any resources used by the {}", e.ident).unwrap();
1267 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", e.ident, e.ident).unwrap();
1269 writeln!(w, "/// Creates a copy of the {}", e.ident).unwrap();
1270 writeln!(w, "#[no_mangle]").unwrap();
1271 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
1272 writeln!(w, "\torig.clone()").unwrap();
1273 writeln!(w, "}}").unwrap();
1274 write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free);
1277 fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &mut TypeResolver<'b, 'a>) {
1278 match export_status(&f.attrs) {
1279 ExportStatus::Export => {},
1280 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1282 writeln_docs(w, &f.attrs, "");
1284 let mut gen_types = GenericTypes::new();
1285 if !gen_types.learn_generics(&f.sig.generics, types) { return; }
1287 write!(w, "#[no_mangle]\npub extern \"C\" fn {}(", f.sig.ident).unwrap();
1288 write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
1289 write!(w, " {{\n\t").unwrap();
1290 write_method_var_decl_body(w, &f.sig, "", types, Some(&gen_types), false);
1291 write!(w, "{}::{}(", types.module_path, f.sig.ident).unwrap();
1292 write_method_call_params(w, &f.sig, "", types, Some(&gen_types), "", false);
1293 writeln!(w, "\n}}\n").unwrap();
1296 // ********************************
1297 // *** File/Crate Walking Logic ***
1298 // ********************************
1300 /// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
1301 /// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
1302 /// at `module` from C.
1303 fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &CrateTypes<'a>, out_dir: &str, orig_crate: &str, header_file: &mut File, cpp_header_file: &mut File) {
1304 for (module, astmod) in libast.modules.iter() {
1305 let ASTModule { ref attrs, ref items, ref submods } = astmod;
1306 assert_eq!(export_status(&attrs), ExportStatus::Export);
1308 let new_file_path = if submods.is_empty() {
1309 format!("{}/{}.rs", out_dir, module.replace("::", "/"))
1310 } else if module != "" {
1311 format!("{}/{}/mod.rs", out_dir, module.replace("::", "/"))
1313 format!("{}/lib.rs", out_dir)
1315 let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
1316 let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1317 .open(new_file_path).expect("Unable to open new src file");
1319 writeln!(out, "// This file is Copyright its original authors, visible in version control").unwrap();
1320 writeln!(out, "// history and in the source files from which this was generated.").unwrap();
1321 writeln!(out, "//").unwrap();
1322 writeln!(out, "// This file is licensed under the license available in the LICENSE or LICENSE.md").unwrap();
1323 writeln!(out, "// file in the root of this repository or, if no such file exists, the same").unwrap();
1324 writeln!(out, "// license as that which applies to the original source files from which this").unwrap();
1325 writeln!(out, "// source was automatically generated.").unwrap();
1326 writeln!(out, "").unwrap();
1328 writeln_docs(&mut out, &attrs, "");
1331 // Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
1332 // and bitcoin hand-written modules.
1333 writeln!(out, "//! C Bindings").unwrap();
1334 writeln!(out, "#![allow(unknown_lints)]").unwrap();
1335 writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
1336 writeln!(out, "#![allow(non_snake_case)]").unwrap();
1337 writeln!(out, "#![allow(unused_imports)]").unwrap();
1338 writeln!(out, "#![allow(unused_variables)]").unwrap();
1339 writeln!(out, "#![allow(unused_mut)]").unwrap();
1340 writeln!(out, "#![allow(unused_parens)]").unwrap();
1341 writeln!(out, "#![allow(unused_unsafe)]").unwrap();
1342 writeln!(out, "#![allow(unused_braces)]").unwrap();
1343 writeln!(out, "#![deny(missing_docs)]").unwrap();
1344 writeln!(out, "pub mod c_types;").unwrap();
1345 writeln!(out, "pub mod bitcoin;").unwrap();
1347 writeln!(out, "\nuse std::ffi::c_void;\nuse bitcoin::hashes::Hash;\nuse crate::c_types::*;\n").unwrap();
1351 writeln!(out, "pub mod {};", m).unwrap();
1354 eprintln!("Converting {} entries...", module);
1356 let import_resolver = ImportResolver::new(orig_crate, &libast.dependencies, module, items);
1357 let mut type_resolver = TypeResolver::new(module, import_resolver, crate_types);
1359 for item in items.iter() {
1361 syn::Item::Use(_) => {}, // Handled above
1362 syn::Item::Static(_) => {},
1363 syn::Item::Enum(e) => {
1364 if let syn::Visibility::Public(_) = e.vis {
1365 writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
1368 syn::Item::Impl(i) => {
1369 writeln_impl(&mut out, &i, &mut type_resolver);
1371 syn::Item::Struct(s) => {
1372 if let syn::Visibility::Public(_) = s.vis {
1373 writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
1376 syn::Item::Trait(t) => {
1377 if let syn::Visibility::Public(_) = t.vis {
1378 writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
1381 syn::Item::Mod(_) => {}, // We don't have to do anything - the top loop handles these.
1382 syn::Item::Const(c) => {
1383 // Re-export any primitive-type constants.
1384 if let syn::Visibility::Public(_) = c.vis {
1385 if let syn::Type::Path(p) = &*c.ty {
1386 let resolved_path = type_resolver.resolve_path(&p.path, None);
1387 if type_resolver.is_primitive(&resolved_path) {
1388 writeln_docs(&mut out, &c.attrs, "");
1389 writeln!(out, "\n#[no_mangle]").unwrap();
1390 writeln!(out, "pub static {}: {} = {}::{};", c.ident, resolved_path, module, c.ident).unwrap();
1395 syn::Item::Type(t) => {
1396 if let syn::Visibility::Public(_) = t.vis {
1397 match export_status(&t.attrs) {
1398 ExportStatus::Export => {},
1399 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1402 let mut process_alias = true;
1403 for tok in t.generics.params.iter() {
1404 if let syn::GenericParam::Lifetime(_) = tok {}
1405 else { process_alias = false; }
1409 syn::Type::Path(_) =>
1410 writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &t.generics, &t.attrs, &type_resolver, header_file, cpp_header_file),
1416 syn::Item::Fn(f) => {
1417 if let syn::Visibility::Public(_) = f.vis {
1418 writeln_fn(&mut out, &f, &mut type_resolver);
1421 syn::Item::Macro(_) => {},
1422 syn::Item::Verbatim(_) => {},
1423 syn::Item::ExternCrate(_) => {},
1424 _ => unimplemented!(),
1428 out.flush().unwrap();
1432 fn walk_private_mod<'a>(ast_storage: &'a FullLibraryAST, orig_crate: &str, module: String, items: &'a syn::ItemMod, crate_types: &mut CrateTypes<'a>) {
1433 let import_resolver = ImportResolver::new(orig_crate, &ast_storage.dependencies, &module, &items.content.as_ref().unwrap().1);
1434 for item in items.content.as_ref().unwrap().1.iter() {
1436 syn::Item::Mod(m) => walk_private_mod(ast_storage, orig_crate, format!("{}::{}", module, m.ident), m, crate_types),
1437 syn::Item::Impl(i) => {
1438 if let &syn::Type::Path(ref p) = &*i.self_ty {
1439 if let Some(trait_path) = i.trait_.as_ref() {
1440 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1441 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1442 match crate_types.trait_impls.entry(sp) {
1443 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1444 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1456 /// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
1457 fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, orig_crate: &str, crate_types: &mut CrateTypes<'a>) {
1458 for (module, astmod) in ast_storage.modules.iter() {
1459 let ASTModule { ref attrs, ref items, submods: _ } = astmod;
1460 assert_eq!(export_status(&attrs), ExportStatus::Export);
1461 let import_resolver = ImportResolver::new(orig_crate, &ast_storage.dependencies, module, items);
1463 for item in items.iter() {
1465 syn::Item::Struct(s) => {
1466 if let syn::Visibility::Public(_) = s.vis {
1467 match export_status(&s.attrs) {
1468 ExportStatus::Export => {},
1469 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1471 let struct_path = format!("{}::{}", module, s.ident);
1472 crate_types.opaques.insert(struct_path, &s.ident);
1475 syn::Item::Trait(t) => {
1476 if let syn::Visibility::Public(_) = t.vis {
1477 match export_status(&t.attrs) {
1478 ExportStatus::Export => {},
1479 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1481 let trait_path = format!("{}::{}", module, t.ident);
1482 walk_supertraits!(t, None, (
1484 crate_types.set_clonable("crate::".to_owned() + &trait_path);
1488 crate_types.traits.insert(trait_path, &t);
1491 syn::Item::Type(t) => {
1492 if let syn::Visibility::Public(_) = t.vis {
1493 match export_status(&t.attrs) {
1494 ExportStatus::Export => {},
1495 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1497 let type_path = format!("{}::{}", module, t.ident);
1498 let mut process_alias = true;
1499 for tok in t.generics.params.iter() {
1500 if let syn::GenericParam::Lifetime(_) = tok {}
1501 else { process_alias = false; }
1505 syn::Type::Path(p) => {
1506 // If its a path with no generics, assume we don't map the aliased type and map it opaque
1507 let mut segments = syn::punctuated::Punctuated::new();
1508 segments.push(syn::PathSegment {
1509 ident: t.ident.clone(),
1510 arguments: syn::PathArguments::None,
1512 let path_obj = syn::Path { leading_colon: None, segments };
1513 let args_obj = p.path.segments.last().unwrap().arguments.clone();
1514 match crate_types.reverse_alias_map.entry(import_resolver.maybe_resolve_path(&p.path, None).unwrap()) {
1515 hash_map::Entry::Occupied(mut e) => { e.get_mut().push((path_obj, args_obj)); },
1516 hash_map::Entry::Vacant(e) => { e.insert(vec![(path_obj, args_obj)]); },
1519 crate_types.opaques.insert(type_path.clone(), &t.ident);
1522 crate_types.type_aliases.insert(type_path, import_resolver.resolve_imported_refs((*t.ty).clone()));
1528 syn::Item::Enum(e) if is_enum_opaque(e) => {
1529 if let syn::Visibility::Public(_) = e.vis {
1530 match export_status(&e.attrs) {
1531 ExportStatus::Export => {},
1532 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1534 let enum_path = format!("{}::{}", module, e.ident);
1535 crate_types.opaques.insert(enum_path, &e.ident);
1538 syn::Item::Enum(e) => {
1539 if let syn::Visibility::Public(_) = e.vis {
1540 match export_status(&e.attrs) {
1541 ExportStatus::Export => {},
1542 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1544 let enum_path = format!("{}::{}", module, e.ident);
1545 crate_types.mirrored_enums.insert(enum_path, &e);
1548 syn::Item::Impl(i) => {
1549 if let &syn::Type::Path(ref p) = &*i.self_ty {
1550 if let Some(trait_path) = i.trait_.as_ref() {
1551 if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) {
1552 if let Some(full_path) = import_resolver.maybe_resolve_path(&p.path, None) {
1553 crate_types.set_clonable("crate::".to_owned() + &full_path);
1556 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1557 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1558 match crate_types.trait_impls.entry(sp) {
1559 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1560 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1567 syn::Item::Mod(m) => walk_private_mod(ast_storage, orig_crate, format!("{}::{}", module, m.ident), m, crate_types),
1575 let args: Vec<String> = env::args().collect();
1576 if args.len() != 6 {
1577 eprintln!("Usage: target/dir source_crate_name derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
1581 let mut derived_templates = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1582 .open(&args[3]).expect("Unable to open new header file");
1583 let mut header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1584 .open(&args[4]).expect("Unable to open new header file");
1585 let mut cpp_header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1586 .open(&args[5]).expect("Unable to open new header file");
1588 writeln!(header_file, "#if defined(__GNUC__)").unwrap();
1589 writeln!(header_file, "#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
1590 writeln!(header_file, "#define MUST_USE_RES __attribute__((warn_unused_result))").unwrap();
1591 writeln!(header_file, "#else").unwrap();
1592 writeln!(header_file, "#define MUST_USE_STRUCT").unwrap();
1593 writeln!(header_file, "#define MUST_USE_RES").unwrap();
1594 writeln!(header_file, "#endif").unwrap();
1595 writeln!(header_file, "#if defined(__clang__)").unwrap();
1596 writeln!(header_file, "#define NONNULL_PTR _Nonnull").unwrap();
1597 writeln!(header_file, "#else").unwrap();
1598 writeln!(header_file, "#define NONNULL_PTR").unwrap();
1599 writeln!(header_file, "#endif").unwrap();
1600 writeln!(cpp_header_file, "#include <string.h>\nnamespace LDK {{").unwrap();
1602 // First parse the full crate's ASTs, caching them so that we can hold references to the AST
1603 // objects in other datastructures:
1604 let mut lib_src = String::new();
1605 std::io::stdin().lock().read_to_string(&mut lib_src).unwrap();
1606 let lib_syntax = syn::parse_file(&lib_src).expect("Unable to parse file");
1607 let libast = FullLibraryAST::load_lib(lib_syntax);
1609 // ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
1610 // when parsing other file ASTs...
1611 let mut libtypes = CrateTypes::new(&mut derived_templates, &libast);
1612 walk_ast(&libast, &args[2], &mut libtypes);
1614 // ... finally, do the actual file conversion/mapping, writing out types as we go.
1615 convert_file(&libast, &libtypes, &args[1], &args[2], &mut header_file, &mut cpp_header_file);
1617 // For container templates which we created while walking the crate, make sure we add C++
1618 // mapped types so that C++ users can utilize the auto-destructors available.
1619 for (ty, has_destructor) in libtypes.templates_defined.borrow().iter() {
1620 write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor);
1622 writeln!(cpp_header_file, "}}").unwrap();
1624 header_file.flush().unwrap();
1625 cpp_header_file.flush().unwrap();
1626 derived_templates.flush().unwrap();