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 "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 "util::ser::Readable"|"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 == "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 == "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 "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 "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 "util::ser::Writeable" => {
186 writeln!(w, "impl lightning::{} 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) => {
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, types));
383 write!(w, "\tfn {}", m.sig.ident).unwrap();
384 types.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 types.skip_arg(&*arg.ty, Some(&meth_gen_types)) { "_" } else { "" }, ident.ident).unwrap();
410 _ => unimplemented!(),
412 types.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 types.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 types.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 types.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", types, Some(&meth_gen_types), true);
445 write!(w, "(self{}.{})(", $impl_accessor, m.sig.ident).unwrap();
446 write_method_call_params(w, &m.sig, "\t", types, 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, types.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 writeln!(w, "impl lightning::{} for {} {{", s, trait_name).unwrap(); // TODO: Drop hard-coded crate name here
504 impl_trait_for_c!(supertrait, format!(".{}", i));
505 writeln!(w, "}}").unwrap();
506 walk_supertraits!(supertrait, Some(&types), (
507 ("Send", _) => writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap(),
508 ("Sync", _) => writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap(),
509 _ => unimplemented!()
512 do_write_impl_trait(w, s, i, &trait_name);
517 // Finally, implement the original Rust trait for the newly created mapped trait.
518 writeln!(w, "\nuse {}::{}::{} as rust{};", types.orig_crate, types.module_path, t.ident, trait_name).unwrap();
519 write!(w, "impl rust{}", t.ident).unwrap();
520 maybe_write_generics(w, &t.generics, types, false);
521 writeln!(w, " for {} {{", trait_name).unwrap();
522 impl_trait_for_c!(t, "");
523 writeln!(w, "}}\n").unwrap();
524 writeln!(w, "// We're essentially a pointer already, or at least a set of pointers, so allow us to be used").unwrap();
525 writeln!(w, "// directly as a Deref trait in higher-level structs:").unwrap();
526 writeln!(w, "impl std::ops::Deref for {} {{\n\ttype Target = Self;", trait_name).unwrap();
527 writeln!(w, "\tfn deref(&self) -> &Self {{\n\t\tself\n\t}}\n}}").unwrap();
529 writeln!(w, "/// Calls the free function if one is set").unwrap();
530 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", trait_name, trait_name).unwrap();
531 writeln!(w, "impl Drop for {} {{", trait_name).unwrap();
532 writeln!(w, "\tfn drop(&mut self) {{").unwrap();
533 writeln!(w, "\t\tif let Some(f) = self.free {{").unwrap();
534 writeln!(w, "\t\t\tf(self.this_arg);").unwrap();
535 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
537 write_cpp_wrapper(cpp_headers, &trait_name, true);
540 /// Write out a simple "opaque" type (eg structs) which contain a pointer to the native Rust type
541 /// and a flag to indicate whether Drop'ing the mapped struct drops the underlying Rust type.
543 /// Also writes out a _free function and a C++ wrapper which handles calling _free.
544 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) {
545 // If we directly read the original type by its original name, cbindgen hits
546 // https://github.com/eqrion/cbindgen/issues/286 Thus, instead, we import it as a temporary
547 // name and then reference it by that name, which works around the issue.
548 write!(w, "\nuse {}::{}::{} as native{}Import;\ntype native{} = native{}Import", types.orig_crate, types.module_path, ident, ident, ident, ident).unwrap();
549 maybe_write_generics(w, &generics, &types, true);
550 writeln!(w, ";\n").unwrap();
551 writeln!(extra_headers, "struct native{}Opaque;\ntypedef struct native{}Opaque LDKnative{};", ident, ident, ident).unwrap();
552 writeln_docs(w, &attrs, "");
553 writeln!(w, "#[must_use]\n#[repr(C)]\npub struct {} {{", struct_name).unwrap();
554 writeln!(w, "\t/// A pointer to the opaque Rust object.\n").unwrap();
555 writeln!(w, "\t/// Nearly everywhere, inner must be non-null, however in places where").unwrap();
556 writeln!(w, "\t/// the Rust equivalent takes an Option, it may be set to null to indicate None.").unwrap();
557 writeln!(w, "\tpub inner: *mut native{},", ident).unwrap();
558 writeln!(w, "\t/// Indicates that this is the only struct which contains the same pointer.\n").unwrap();
559 writeln!(w, "\t/// Rust functions which take ownership of an object provided via an argument require").unwrap();
560 writeln!(w, "\t/// this to be true and invalidate the object pointed to by inner.").unwrap();
561 writeln!(w, "\tpub is_owned: bool,").unwrap();
562 writeln!(w, "}}\n").unwrap();
563 writeln!(w, "impl Drop for {} {{\n\tfn drop(&mut self) {{", struct_name).unwrap();
564 writeln!(w, "\t\tif self.is_owned && !<*mut native{}>::is_null(self.inner) {{", ident).unwrap();
565 writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(self.inner) }};\n\t\t}}\n\t}}\n}}").unwrap();
566 writeln!(w, "/// Frees any resources used by the {}, if is_owned is set and inner is non-NULL.", struct_name).unwrap();
567 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_obj: {}) {{ }}", struct_name, struct_name).unwrap();
568 writeln!(w, "#[allow(unused)]").unwrap();
569 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
570 writeln!(w, "extern \"C\" fn {}_free_void(this_ptr: *mut c_void) {{", struct_name).unwrap();
571 writeln!(w, "\tunsafe {{ let _ = Box::from_raw(this_ptr as *mut native{}); }}\n}}", struct_name).unwrap();
572 writeln!(w, "#[allow(unused)]").unwrap();
573 writeln!(w, "/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy").unwrap();
574 writeln!(w, "impl {} {{", struct_name).unwrap();
575 writeln!(w, "\tpub(crate) fn take_inner(mut self) -> *mut native{} {{", struct_name).unwrap();
576 writeln!(w, "\t\tassert!(self.is_owned);").unwrap();
577 writeln!(w, "\t\tlet ret = self.inner;").unwrap();
578 writeln!(w, "\t\tself.inner = std::ptr::null_mut();").unwrap();
579 writeln!(w, "\t\tret").unwrap();
580 writeln!(w, "\t}}\n}}").unwrap();
582 write_cpp_wrapper(cpp_headers, &format!("{}", ident), true);
585 /// Writes out all the relevant mappings for a Rust struct, deferring to writeln_opaque to generate
586 /// the struct itself, and then writing getters and setters for public, understood-type fields and
587 /// a constructor if every field is public.
588 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) {
589 if export_status(&s.attrs) != ExportStatus::Export { return; }
591 let struct_name = &format!("{}", s.ident);
592 writeln_opaque(w, &s.ident, struct_name, &s.generics, &s.attrs, types, extra_headers, cpp_headers);
594 if let syn::Fields::Named(fields) = &s.fields {
595 let mut gen_types = GenericTypes::new();
596 assert!(gen_types.learn_generics(&s.generics, types));
598 let mut all_fields_settable = true;
599 for field in fields.named.iter() {
600 if let syn::Visibility::Public(_) = field.vis {
601 let export = export_status(&field.attrs);
603 ExportStatus::Export => {},
604 ExportStatus::NoExport|ExportStatus::TestOnly => {
605 all_fields_settable = false;
610 if let Some(ident) = &field.ident {
611 let ref_type = syn::Type::Reference(syn::TypeReference {
612 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
613 elem: Box::new(field.ty.clone()) });
614 if types.understood_c_type(&ref_type, Some(&gen_types)) {
615 writeln_docs(w, &field.attrs, "");
616 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> ", struct_name, ident, struct_name).unwrap();
617 types.write_c_type(w, &ref_type, Some(&gen_types), true);
618 write!(w, " {{\n\tlet mut inner_val = &mut unsafe {{ &mut *this_ptr.inner }}.{};\n\t", ident).unwrap();
619 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);
620 if local_var { write!(w, "\n\t").unwrap(); }
621 types.write_to_c_conversion_inline_prefix(w, &ref_type, Some(&gen_types), true);
623 write!(w, "inner_val").unwrap();
625 write!(w, "(*inner_val)").unwrap();
627 types.write_to_c_conversion_inline_suffix(w, &ref_type, Some(&gen_types), true);
628 writeln!(w, "\n}}").unwrap();
631 if types.understood_c_type(&field.ty, Some(&gen_types)) {
632 writeln_docs(w, &field.attrs, "");
633 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_set_{}(this_ptr: &mut {}, mut val: ", struct_name, ident, struct_name).unwrap();
634 types.write_c_type(w, &field.ty, Some(&gen_types), false);
635 write!(w, ") {{\n\t").unwrap();
636 let local_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("val", Span::call_site()), &field.ty, Some(&gen_types));
637 if local_var { write!(w, "\n\t").unwrap(); }
638 write!(w, "unsafe {{ &mut *this_ptr.inner }}.{} = ", ident).unwrap();
639 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
640 write!(w, "val").unwrap();
641 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
642 writeln!(w, ";\n}}").unwrap();
643 } else { all_fields_settable = false; }
644 } else { all_fields_settable = false; }
645 } else { all_fields_settable = false; }
648 if all_fields_settable {
649 // Build a constructor!
650 writeln!(w, "/// Constructs a new {} given each field", struct_name).unwrap();
651 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_new(", struct_name).unwrap();
652 for (idx, field) in fields.named.iter().enumerate() {
653 if idx != 0 { write!(w, ", ").unwrap(); }
654 write!(w, "mut {}_arg: ", field.ident.as_ref().unwrap()).unwrap();
655 types.write_c_type(w, &field.ty, Some(&gen_types), false);
657 write!(w, ") -> {} {{\n\t", struct_name).unwrap();
658 for field in fields.named.iter() {
659 let field_name = format!("{}_arg", field.ident.as_ref().unwrap());
660 if types.write_from_c_conversion_new_var(w, &syn::Ident::new(&field_name, Span::call_site()), &field.ty, Some(&gen_types)) {
661 write!(w, "\n\t").unwrap();
664 writeln!(w, "{} {{ inner: Box::into_raw(Box::new(native{} {{", struct_name, s.ident).unwrap();
665 for field in fields.named.iter() {
666 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
667 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
668 write!(w, "{}_arg", field.ident.as_ref().unwrap()).unwrap();
669 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
670 writeln!(w, ",").unwrap();
672 writeln!(w, "\t}})), is_owned: true }}\n}}").unwrap();
677 /// Prints a relevant conversion for impl *
679 /// For simple impl Struct {}s, this just outputs the wrapper functions as Struct_fn_name() { .. }.
681 /// For impl Trait for Struct{}s, this non-exported generates wrapper functions as
682 /// Trait_Struct_fn_name and a Struct_as_Trait(&struct) -> Trait function which returns a populated
683 /// Trait struct containing a pointer to the passed struct's inner field and the wrapper functions.
685 /// A few non-crate Traits are hard-coded including Default.
686 fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut TypeResolver) {
687 match export_status(&i.attrs) {
688 ExportStatus::Export => {},
689 ExportStatus::NoExport|ExportStatus::TestOnly => return,
692 if let syn::Type::Tuple(_) = &*i.self_ty {
693 if types.understood_c_type(&*i.self_ty, None) {
694 let mut gen_types = GenericTypes::new();
695 if !gen_types.learn_generics(&i.generics, types) {
696 eprintln!("Not implementing anything for `impl (..)` due to not understood generics");
700 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
701 if let Some(trait_path) = i.trait_.as_ref() {
702 if trait_path.0.is_some() { unimplemented!(); }
703 if types.understood_c_path(&trait_path.1) {
704 eprintln!("Not implementing anything for `impl Trait for (..)` - we only support manual defines");
707 // Just do a manual implementation:
708 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
711 eprintln!("Not implementing anything for plain `impl (..)` block - we only support `impl Trait for (..)` blocks");
717 if let &syn::Type::Path(ref p) = &*i.self_ty {
718 if p.qself.is_some() { unimplemented!(); }
719 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
720 if let Some(resolved_path) = types.maybe_resolve_non_ignored_ident(&ident) {
721 let mut gen_types = GenericTypes::new();
722 if !gen_types.learn_generics(&i.generics, types) {
723 eprintln!("Not implementing anything for impl {} due to not understood generics", ident);
727 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
728 if let Some(trait_path) = i.trait_.as_ref() {
729 if trait_path.0.is_some() { unimplemented!(); }
730 if types.understood_c_path(&trait_path.1) {
731 let full_trait_path = types.resolve_path(&trait_path.1, None);
732 let trait_obj = *types.crate_types.traits.get(&full_trait_path).unwrap();
733 // We learn the associated types maping from the original trait object.
734 // That's great, except that they are unresolved idents, so if we learn
735 // mappings from a trai defined in a different file, we may mis-resolve or
736 // fail to resolve the mapped types.
737 gen_types.learn_associated_types(trait_obj, types);
738 let mut impl_associated_types = HashMap::new();
739 for item in i.items.iter() {
741 syn::ImplItem::Type(t) => {
742 if let syn::Type::Path(p) = &t.ty {
743 if let Some(id) = single_ident_generic_path_to_ident(&p.path) {
744 impl_associated_types.insert(&t.ident, id);
752 let export = export_status(&trait_obj.attrs);
754 ExportStatus::Export => {},
755 ExportStatus::NoExport|ExportStatus::TestOnly => return,
758 // For cases where we have a concrete native object which implements a
759 // trait and need to return the C-mapped version of the trait, provide a
760 // From<> implementation which does all the work to ensure free is handled
761 // properly. This way we can call this method from deep in the
762 // type-conversion logic without actually knowing the concrete native type.
763 writeln!(w, "impl From<native{}> for crate::{} {{", ident, full_trait_path).unwrap();
764 writeln!(w, "\tfn from(obj: native{}) -> Self {{", ident).unwrap();
765 writeln!(w, "\t\tlet mut rust_obj = {} {{ inner: Box::into_raw(Box::new(obj)), is_owned: true }};", ident).unwrap();
766 writeln!(w, "\t\tlet mut ret = {}_as_{}(&rust_obj);", ident, trait_obj.ident).unwrap();
767 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();
768 writeln!(w, "\t\trust_obj.inner = std::ptr::null_mut();").unwrap();
769 writeln!(w, "\t\tret.free = Some({}_free_void);", ident).unwrap();
770 writeln!(w, "\t\tret\n\t}}\n}}").unwrap();
772 writeln!(w, "/// Constructs a new {} which calls the relevant methods on this_arg.", trait_obj.ident).unwrap();
773 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();
774 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_as_{}(this_arg: &{}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
775 writeln!(w, "\tcrate::{} {{", full_trait_path).unwrap();
776 writeln!(w, "\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
777 writeln!(w, "\t\tfree: None,").unwrap();
779 macro_rules! write_meth {
780 ($m: expr, $trait: expr, $indent: expr) => {
781 let trait_method = $trait.items.iter().filter_map(|item| {
782 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
783 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
784 match export_status(&trait_method.attrs) {
785 ExportStatus::Export => {},
786 ExportStatus::NoExport => {
787 write!(w, "{}\t\t//XXX: Need to export {}\n", $indent, $m.sig.ident).unwrap();
790 ExportStatus::TestOnly => continue,
793 let mut printed = false;
794 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
795 if let syn::Type::Reference(r) = &**rtype {
796 write!(w, "\n\t\t{}{}: ", $indent, $m.sig.ident).unwrap();
797 types.write_empty_rust_val(Some(&gen_types), w, &*r.elem);
798 writeln!(w, ",\n{}\t\tset_{}: Some({}_{}_set_{}),", $indent, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
803 write!(w, "{}\t\t{}: {}_{}_{},\n", $indent, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
807 for item in trait_obj.items.iter() {
809 syn::TraitItem::Method(m) => {
810 write_meth!(m, trait_obj, "");
815 let mut requires_clone = false;
816 walk_supertraits!(trait_obj, Some(&types), (
817 ("Clone", _) => requires_clone = true,
820 walk_supertraits!(trait_obj, Some(&types), (
822 writeln!(w, "\t\tclone: Some({}_clone_void),", ident).unwrap();
824 ("Sync", _) => {}, ("Send", _) => {},
825 ("std::marker::Sync", _) => {}, ("std::marker::Send", _) => {},
827 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
828 writeln!(w, "\t\t{}: crate::{} {{", t, s).unwrap();
829 writeln!(w, "\t\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
830 writeln!(w, "\t\t\tfree: None,").unwrap();
831 for item in supertrait_obj.items.iter() {
833 syn::TraitItem::Method(m) => {
834 write_meth!(m, supertrait_obj, "\t");
839 write!(w, "\t\t}},\n").unwrap();
840 if !types.is_clonable(s) && requires_clone {
841 writeln!(w, "\t\t{}_clone: {}_{}_clone,", t, ident, t).unwrap();
844 write_trait_impl_field_assign(w, s, ident);
848 writeln!(w, "\t}}\n}}\n").unwrap();
850 macro_rules! impl_meth {
851 ($m: expr, $trait_path: expr, $trait: expr, $indent: expr) => {
852 let trait_method = $trait.items.iter().filter_map(|item| {
853 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
854 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
855 match export_status(&trait_method.attrs) {
856 ExportStatus::Export => {},
857 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
860 if let syn::ReturnType::Type(_, _) = &$m.sig.output {
861 writeln!(w, "#[must_use]").unwrap();
863 write!(w, "extern \"C\" fn {}_{}_{}(", ident, $trait.ident, $m.sig.ident).unwrap();
864 let mut meth_gen_types = gen_types.push_ctx();
865 assert!(meth_gen_types.learn_generics(&$m.sig.generics, types));
866 write_method_params(w, &$m.sig, "c_void", types, Some(&meth_gen_types), true, true);
867 write!(w, " {{\n\t").unwrap();
868 write_method_var_decl_body(w, &$m.sig, "", types, Some(&meth_gen_types), false);
869 let mut takes_self = false;
870 for inp in $m.sig.inputs.iter() {
871 if let syn::FnArg::Receiver(_) = inp {
876 let mut t_gen_args = String::new();
877 for (idx, _) in $trait.generics.params.iter().enumerate() {
878 if idx != 0 { t_gen_args += ", " };
882 write!(w, "<native{} as {}::{}<{}>>::{}(unsafe {{ &mut *(this_arg as *mut native{}) }}, ", ident, types.orig_crate, $trait_path, t_gen_args, $m.sig.ident, ident).unwrap();
884 write!(w, "<native{} as {}::{}<{}>>::{}(", ident, types.orig_crate, $trait_path, t_gen_args, $m.sig.ident).unwrap();
887 let mut real_type = "".to_string();
888 match &$m.sig.output {
889 syn::ReturnType::Type(_, rtype) => {
890 if let Some(mut remaining_path) = first_seg_self(&*rtype) {
891 if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
892 real_type = format!("{}", impl_associated_types.get(associated_seg).unwrap());
898 write_method_call_params(w, &$m.sig, "", types, Some(&meth_gen_types), &real_type, false);
899 write!(w, "\n}}\n").unwrap();
900 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
901 if let syn::Type::Reference(r) = &**rtype {
902 assert_eq!($m.sig.inputs.len(), 1); // Must only take self
903 writeln!(w, "extern \"C\" fn {}_{}_set_{}(trait_self_arg: &{}) {{", ident, $trait.ident, $m.sig.ident, $trait.ident).unwrap();
904 writeln!(w, "\t// This is a bit race-y in the general case, but for our specific use-cases today, we're safe").unwrap();
905 writeln!(w, "\t// Specifically, we must ensure that the first time we're called it can never be in parallel").unwrap();
906 write!(w, "\tif ").unwrap();
907 types.write_empty_rust_val_check(Some(&meth_gen_types), w, &*r.elem, &format!("trait_self_arg.{}", $m.sig.ident));
908 writeln!(w, " {{").unwrap();
909 writeln!(w, "\t\tunsafe {{ &mut *(trait_self_arg as *const {} as *mut {}) }}.{} = {}_{}_{}(trait_self_arg.this_arg);", $trait.ident, $trait.ident, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
910 writeln!(w, "\t}}").unwrap();
911 writeln!(w, "}}").unwrap();
917 for item in i.items.iter() {
919 syn::ImplItem::Method(m) => {
920 impl_meth!(m, full_trait_path, trait_obj, "");
922 syn::ImplItem::Type(_) => {},
923 _ => unimplemented!(),
926 walk_supertraits!(trait_obj, Some(&types), (
928 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
929 if !types.is_clonable(s) && requires_clone {
930 writeln!(w, "extern \"C\" fn {}_{}_clone(orig: &crate::{}) -> crate::{} {{", ident, t, s, s).unwrap();
931 writeln!(w, "\tcrate::{} {{", s).unwrap();
932 writeln!(w, "\t\tthis_arg: orig.this_arg,").unwrap();
933 writeln!(w, "\t\tfree: None,").unwrap();
934 for item in supertrait_obj.items.iter() {
936 syn::TraitItem::Method(m) => {
937 write_meth!(m, supertrait_obj, "");
942 write!(w, "\t}}\n}}\n").unwrap();
947 write!(w, "\n").unwrap();
948 } else if path_matches_nongeneric(&trait_path.1, &["From"]) {
949 } else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
950 writeln!(w, "/// Creates a \"default\" {}. See struct and individual field documentaiton for details on which values are used.", ident).unwrap();
951 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
952 write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
953 write!(w, "}}\n").unwrap();
954 } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "PartialEq"]) {
955 } else if (path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) || path_matches_nongeneric(&trait_path.1, &["Clone"])) &&
956 types.c_type_has_inner_from_path(&resolved_path) {
957 writeln!(w, "impl Clone for {} {{", ident).unwrap();
958 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
959 writeln!(w, "\t\tSelf {{").unwrap();
960 writeln!(w, "\t\t\tinner: if <*mut native{}>::is_null(self.inner) {{ std::ptr::null_mut() }} else {{", ident).unwrap();
961 writeln!(w, "\t\t\t\tBox::into_raw(Box::new(unsafe {{ &*self.inner }}.clone())) }},").unwrap();
962 writeln!(w, "\t\t\tis_owned: true,").unwrap();
963 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
964 writeln!(w, "#[allow(unused)]").unwrap();
965 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
966 writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", ident).unwrap();
967 writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", ident).unwrap();
968 writeln!(w, "}}").unwrap();
969 writeln!(w, "#[no_mangle]").unwrap();
970 writeln!(w, "/// Creates a copy of the {}", ident).unwrap();
971 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", ident, ident, ident).unwrap();
972 writeln!(w, "\torig.clone()").unwrap();
973 writeln!(w, "}}").unwrap();
975 //XXX: implement for other things like ToString
976 // If we have no generics, try a manual implementation:
977 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
980 let declared_type = (*types.get_declared_type(&ident).unwrap()).clone();
981 for item in i.items.iter() {
983 syn::ImplItem::Method(m) => {
984 if let syn::Visibility::Public(_) = m.vis {
985 match export_status(&m.attrs) {
986 ExportStatus::Export => {},
987 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
989 if m.defaultness.is_some() { unimplemented!(); }
990 writeln_docs(w, &m.attrs, "");
991 if let syn::ReturnType::Type(_, _) = &m.sig.output {
992 writeln!(w, "#[must_use]").unwrap();
994 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_{}(", ident, m.sig.ident).unwrap();
995 let ret_type = match &declared_type {
996 DeclType::MirroredEnum => format!("{}", ident),
997 DeclType::StructImported => format!("{}", ident),
998 _ => unimplemented!(),
1000 let mut meth_gen_types = gen_types.push_ctx();
1001 assert!(meth_gen_types.learn_generics(&m.sig.generics, types));
1002 write_method_params(w, &m.sig, &ret_type, types, Some(&meth_gen_types), false, true);
1003 write!(w, " {{\n\t").unwrap();
1004 write_method_var_decl_body(w, &m.sig, "", types, Some(&meth_gen_types), false);
1005 let mut takes_self = false;
1006 let mut takes_mut_self = false;
1007 for inp in m.sig.inputs.iter() {
1008 if let syn::FnArg::Receiver(r) = inp {
1010 if r.mutability.is_some() { takes_mut_self = true; }
1014 write!(w, "unsafe {{ &mut (*(this_arg.inner as *mut native{})) }}.{}(", ident, m.sig.ident).unwrap();
1015 } else if takes_self {
1016 write!(w, "unsafe {{ &*this_arg.inner }}.{}(", m.sig.ident).unwrap();
1018 write!(w, "{}::{}::{}(", types.orig_crate, resolved_path, m.sig.ident).unwrap();
1020 write_method_call_params(w, &m.sig, "", types, Some(&meth_gen_types), &ret_type, false);
1021 writeln!(w, "\n}}\n").unwrap();
1028 } else if let Some(resolved_path) = types.maybe_resolve_ident(&ident) {
1029 if let Some(aliases) = types.crate_types.reverse_alias_map.get(&resolved_path).cloned() {
1030 'alias_impls: for (alias, arguments) in aliases {
1031 let alias_resolved = types.resolve_path(&alias, None);
1032 for (idx, gen) in i.generics.params.iter().enumerate() {
1034 syn::GenericParam::Type(type_param) => {
1035 'bounds_check: for bound in type_param.bounds.iter() {
1036 if let syn::TypeParamBound::Trait(trait_bound) = bound {
1037 if let syn::PathArguments::AngleBracketed(ref t) = &arguments {
1038 assert!(idx < t.args.len());
1039 if let syn::GenericArgument::Type(syn::Type::Path(p)) = &t.args[idx] {
1040 let generic_arg = types.resolve_path(&p.path, None);
1041 let generic_bound = types.resolve_path(&trait_bound.path, None);
1042 if let Some(traits_impld) = types.crate_types.trait_impls.get(&generic_arg) {
1043 for trait_impld in traits_impld {
1044 if *trait_impld == generic_bound { continue 'bounds_check; }
1046 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1047 continue 'alias_impls;
1049 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1050 continue 'alias_impls;
1052 } else { unimplemented!(); }
1053 } else { unimplemented!(); }
1054 } else { unimplemented!(); }
1057 syn::GenericParam::Lifetime(_) => {},
1058 syn::GenericParam::Const(_) => unimplemented!(),
1061 let aliased_impl = syn::ItemImpl {
1062 attrs: i.attrs.clone(),
1063 brace_token: syn::token::Brace(Span::call_site()),
1065 generics: syn::Generics {
1067 params: syn::punctuated::Punctuated::new(),
1071 impl_token: syn::Token![impl](Span::call_site()),
1072 items: i.items.clone(),
1073 self_ty: Box::new(syn::Type::Path(syn::TypePath { qself: None, path: alias.clone() })),
1074 trait_: i.trait_.clone(),
1077 writeln_impl(w, &aliased_impl, types);
1080 eprintln!("Not implementing anything for {} due to it being marked not exported", ident);
1083 eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub)", ident);
1090 /// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
1091 /// is unitary), we generate an equivalent enum with all types replaced with their C mapped
1092 /// versions followed by conversion functions which map between the Rust version and the C mapped
1094 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) {
1095 match export_status(&e.attrs) {
1096 ExportStatus::Export => {},
1097 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1100 if is_enum_opaque(e) {
1101 eprintln!("Skipping enum {} as it contains non-unit fields", e.ident);
1102 writeln_opaque(w, &e.ident, &format!("{}", e.ident), &e.generics, &e.attrs, types, extra_headers, cpp_headers);
1105 writeln_docs(w, &e.attrs, "");
1107 if e.generics.lt_token.is_some() {
1111 let mut needs_free = false;
1113 writeln!(w, "#[must_use]\n#[derive(Clone)]\n#[repr(C)]\npub enum {} {{", e.ident).unwrap();
1114 for var in e.variants.iter() {
1115 assert_eq!(export_status(&var.attrs), ExportStatus::Export); // We can't partially-export a mirrored enum
1116 writeln_docs(w, &var.attrs, "\t");
1117 write!(w, "\t{}", var.ident).unwrap();
1118 if let syn::Fields::Named(fields) = &var.fields {
1120 writeln!(w, " {{").unwrap();
1121 for field in fields.named.iter() {
1122 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1123 writeln_docs(w, &field.attrs, "\t\t");
1124 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1125 types.write_c_type(w, &field.ty, None, false);
1126 writeln!(w, ",").unwrap();
1128 write!(w, "\t}}").unwrap();
1129 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1131 write!(w, "(").unwrap();
1132 for (idx, field) in fields.unnamed.iter().enumerate() {
1133 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1134 types.write_c_type(w, &field.ty, None, false);
1135 if idx != fields.unnamed.len() - 1 {
1136 write!(w, ",").unwrap();
1139 write!(w, ")").unwrap();
1141 if var.discriminant.is_some() { unimplemented!(); }
1142 writeln!(w, ",").unwrap();
1144 writeln!(w, "}}\nuse {}::{}::{} as native{};\nimpl {} {{", types.orig_crate, types.module_path, e.ident, e.ident, e.ident).unwrap();
1146 macro_rules! write_conv {
1147 ($fn_sig: expr, $to_c: expr, $ref: expr) => {
1148 writeln!(w, "\t#[allow(unused)]\n\tpub(crate) fn {} {{\n\t\tmatch {} {{", $fn_sig, if $to_c { "native" } else { "self" }).unwrap();
1149 for var in e.variants.iter() {
1150 write!(w, "\t\t\t{}{}::{} ", if $to_c { "native" } else { "" }, e.ident, var.ident).unwrap();
1151 if let syn::Fields::Named(fields) = &var.fields {
1152 write!(w, "{{").unwrap();
1153 for field in fields.named.iter() {
1154 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1155 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, field.ident.as_ref().unwrap()).unwrap();
1157 write!(w, "}} ").unwrap();
1158 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1159 write!(w, "(").unwrap();
1160 for (idx, field) in fields.unnamed.iter().enumerate() {
1161 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1162 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, ('a' as u8 + idx as u8) as char).unwrap();
1164 write!(w, ") ").unwrap();
1166 write!(w, "=>").unwrap();
1168 macro_rules! handle_field_a {
1169 ($field: expr, $field_ident: expr) => { {
1170 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1171 let mut sink = ::std::io::sink();
1172 let mut out: &mut dyn std::io::Write = if $ref { &mut sink } else { w };
1173 let new_var = if $to_c {
1174 types.write_to_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None, false)
1176 types.write_from_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None)
1178 if $ref || new_var {
1180 write!(w, "let mut {}_nonref = (*{}).clone();\n\t\t\t\t", $field_ident, $field_ident).unwrap();
1182 let nonref_ident = syn::Ident::new(&format!("{}_nonref", $field_ident), Span::call_site());
1184 types.write_to_c_conversion_new_var(w, &nonref_ident, &$field.ty, None, false);
1186 types.write_from_c_conversion_new_var(w, &nonref_ident, &$field.ty, None);
1188 write!(w, "\n\t\t\t\t").unwrap();
1191 write!(w, "\n\t\t\t\t").unwrap();
1196 if let syn::Fields::Named(fields) = &var.fields {
1197 write!(w, " {{\n\t\t\t\t").unwrap();
1198 for field in fields.named.iter() {
1199 handle_field_a!(field, field.ident.as_ref().unwrap());
1201 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1202 write!(w, " {{\n\t\t\t\t").unwrap();
1203 for (idx, field) in fields.unnamed.iter().enumerate() {
1204 handle_field_a!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1206 } else { write!(w, " ").unwrap(); }
1208 write!(w, "{}{}::{}", if $to_c { "" } else { "native" }, e.ident, var.ident).unwrap();
1210 macro_rules! handle_field_b {
1211 ($field: expr, $field_ident: expr) => { {
1212 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1214 types.write_to_c_conversion_inline_prefix(w, &$field.ty, None, false);
1216 types.write_from_c_conversion_prefix(w, &$field.ty, None);
1218 write!(w, "{}{}", $field_ident,
1219 if $ref { "_nonref" } else { "" }).unwrap();
1221 types.write_to_c_conversion_inline_suffix(w, &$field.ty, None, false);
1223 types.write_from_c_conversion_suffix(w, &$field.ty, None);
1225 write!(w, ",").unwrap();
1229 if let syn::Fields::Named(fields) = &var.fields {
1230 write!(w, " {{").unwrap();
1231 for field in fields.named.iter() {
1232 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1233 write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1234 handle_field_b!(field, field.ident.as_ref().unwrap());
1236 writeln!(w, "\n\t\t\t\t}}").unwrap();
1237 write!(w, "\t\t\t}}").unwrap();
1238 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1239 write!(w, " (").unwrap();
1240 for (idx, field) in fields.unnamed.iter().enumerate() {
1241 write!(w, "\n\t\t\t\t\t").unwrap();
1242 handle_field_b!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1244 writeln!(w, "\n\t\t\t\t)").unwrap();
1245 write!(w, "\t\t\t}}").unwrap();
1247 writeln!(w, ",").unwrap();
1249 writeln!(w, "\t\t}}\n\t}}").unwrap();
1253 write_conv!(format!("to_native(&self) -> native{}", e.ident), false, true);
1254 write_conv!(format!("into_native(self) -> native{}", e.ident), false, false);
1255 write_conv!(format!("from_native(native: &native{}) -> Self", e.ident), true, true);
1256 write_conv!(format!("native_into(native: native{}) -> Self", e.ident), true, false);
1257 writeln!(w, "}}").unwrap();
1260 writeln!(w, "/// Frees any resources used by the {}", e.ident).unwrap();
1261 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", e.ident, e.ident).unwrap();
1263 writeln!(w, "/// Creates a copy of the {}", e.ident).unwrap();
1264 writeln!(w, "#[no_mangle]").unwrap();
1265 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
1266 writeln!(w, "\torig.clone()").unwrap();
1267 writeln!(w, "}}").unwrap();
1268 write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free);
1271 fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &mut TypeResolver<'b, 'a>) {
1272 match export_status(&f.attrs) {
1273 ExportStatus::Export => {},
1274 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1276 writeln_docs(w, &f.attrs, "");
1278 let mut gen_types = GenericTypes::new();
1279 if !gen_types.learn_generics(&f.sig.generics, types) { return; }
1281 write!(w, "#[no_mangle]\npub extern \"C\" fn {}(", f.sig.ident).unwrap();
1282 write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
1283 write!(w, " {{\n\t").unwrap();
1284 write_method_var_decl_body(w, &f.sig, "", types, Some(&gen_types), false);
1285 write!(w, "{}::{}::{}(", types.orig_crate, types.module_path, f.sig.ident).unwrap();
1286 write_method_call_params(w, &f.sig, "", types, Some(&gen_types), "", false);
1287 writeln!(w, "\n}}\n").unwrap();
1290 // ********************************
1291 // *** File/Crate Walking Logic ***
1292 // ********************************
1294 /// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
1295 /// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
1296 /// at `module` from C.
1297 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) {
1298 for (module, astmod) in libast.modules.iter() {
1299 let ASTModule { ref attrs, ref items, ref submods } = astmod;
1300 assert_eq!(export_status(&attrs), ExportStatus::Export);
1302 let new_file_path = if submods.is_empty() {
1303 format!("{}/{}.rs", out_dir, module.replace("::", "/"))
1304 } else if module != "" {
1305 format!("{}/{}/mod.rs", out_dir, module.replace("::", "/"))
1307 format!("{}/lib.rs", out_dir)
1309 let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
1310 let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1311 .open(new_file_path).expect("Unable to open new src file");
1313 writeln!(out, "// This file is Copyright its original authors, visible in version control").unwrap();
1314 writeln!(out, "// history and in the source files from which this was generated.").unwrap();
1315 writeln!(out, "//").unwrap();
1316 writeln!(out, "// This file is licensed under the license available in the LICENSE or LICENSE.md").unwrap();
1317 writeln!(out, "// file in the root of this repository or, if no such file exists, the same").unwrap();
1318 writeln!(out, "// license as that which applies to the original source files from which this").unwrap();
1319 writeln!(out, "// source was automatically generated.").unwrap();
1320 writeln!(out, "").unwrap();
1322 writeln_docs(&mut out, &attrs, "");
1325 // Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
1326 // and bitcoin hand-written modules.
1327 writeln!(out, "#![allow(unknown_lints)]").unwrap();
1328 writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
1329 writeln!(out, "#![allow(non_snake_case)]").unwrap();
1330 writeln!(out, "#![allow(unused_imports)]").unwrap();
1331 writeln!(out, "#![allow(unused_variables)]").unwrap();
1332 writeln!(out, "#![allow(unused_mut)]").unwrap();
1333 writeln!(out, "#![allow(unused_parens)]").unwrap();
1334 writeln!(out, "#![allow(unused_unsafe)]").unwrap();
1335 writeln!(out, "#![allow(unused_braces)]").unwrap();
1336 writeln!(out, "#![deny(missing_docs)]").unwrap();
1337 writeln!(out, "pub mod c_types;").unwrap();
1338 writeln!(out, "pub mod bitcoin;").unwrap();
1340 writeln!(out, "\nuse std::ffi::c_void;\nuse bitcoin::hashes::Hash;\nuse crate::c_types::*;\n").unwrap();
1344 writeln!(out, "pub mod {};", m).unwrap();
1347 eprintln!("Converting {} entries...", module);
1349 let import_resolver = ImportResolver::new(module, items);
1350 let mut type_resolver = TypeResolver::new(orig_crate, module, import_resolver, crate_types);
1352 for item in items.iter() {
1354 syn::Item::Use(_) => {}, // Handled above
1355 syn::Item::Static(_) => {},
1356 syn::Item::Enum(e) => {
1357 if let syn::Visibility::Public(_) = e.vis {
1358 writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
1361 syn::Item::Impl(i) => {
1362 writeln_impl(&mut out, &i, &mut type_resolver);
1364 syn::Item::Struct(s) => {
1365 if let syn::Visibility::Public(_) = s.vis {
1366 writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
1369 syn::Item::Trait(t) => {
1370 if let syn::Visibility::Public(_) = t.vis {
1371 writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
1374 syn::Item::Mod(_) => {}, // We don't have to do anything - the top loop handles these.
1375 syn::Item::Const(c) => {
1376 // Re-export any primitive-type constants.
1377 if let syn::Visibility::Public(_) = c.vis {
1378 if let syn::Type::Path(p) = &*c.ty {
1379 let resolved_path = type_resolver.resolve_path(&p.path, None);
1380 if type_resolver.is_primitive(&resolved_path) {
1381 writeln_docs(&mut out, &c.attrs, "");
1382 writeln!(out, "\n#[no_mangle]").unwrap();
1383 writeln!(out, "pub static {}: {} = {}::{}::{};", c.ident, resolved_path, orig_crate, module, c.ident).unwrap();
1388 syn::Item::Type(t) => {
1389 if let syn::Visibility::Public(_) = t.vis {
1390 match export_status(&t.attrs) {
1391 ExportStatus::Export => {},
1392 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1395 let mut process_alias = true;
1396 for tok in t.generics.params.iter() {
1397 if let syn::GenericParam::Lifetime(_) = tok {}
1398 else { process_alias = false; }
1402 syn::Type::Path(_) =>
1403 writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &t.generics, &t.attrs, &type_resolver, header_file, cpp_header_file),
1409 syn::Item::Fn(f) => {
1410 if let syn::Visibility::Public(_) = f.vis {
1411 writeln_fn(&mut out, &f, &mut type_resolver);
1414 syn::Item::Macro(_) => {},
1415 syn::Item::Verbatim(_) => {},
1416 syn::Item::ExternCrate(_) => {},
1417 _ => unimplemented!(),
1421 out.flush().unwrap();
1425 fn walk_private_mod<'a>(module: String, items: &'a syn::ItemMod, crate_types: &mut CrateTypes<'a>) {
1426 let import_resolver = ImportResolver::new(&module, &items.content.as_ref().unwrap().1);
1427 for item in items.content.as_ref().unwrap().1.iter() {
1429 syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types),
1430 syn::Item::Impl(i) => {
1431 if let &syn::Type::Path(ref p) = &*i.self_ty {
1432 if let Some(trait_path) = i.trait_.as_ref() {
1433 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1434 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1435 match crate_types.trait_impls.entry(sp) {
1436 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1437 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1449 /// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
1450 fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
1451 for (module, astmod) in ast_storage.modules.iter() {
1452 let ASTModule { ref attrs, ref items, submods: _ } = astmod;
1453 assert_eq!(export_status(&attrs), ExportStatus::Export);
1454 let import_resolver = ImportResolver::new(module, items);
1456 for item in items.iter() {
1458 syn::Item::Struct(s) => {
1459 if let syn::Visibility::Public(_) = s.vis {
1460 match export_status(&s.attrs) {
1461 ExportStatus::Export => {},
1462 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1464 let struct_path = format!("{}::{}", module, s.ident);
1465 crate_types.opaques.insert(struct_path, &s.ident);
1468 syn::Item::Trait(t) => {
1469 if let syn::Visibility::Public(_) = t.vis {
1470 match export_status(&t.attrs) {
1471 ExportStatus::Export => {},
1472 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1474 let trait_path = format!("{}::{}", module, t.ident);
1475 walk_supertraits!(t, None, (
1477 crate_types.set_clonable("crate::".to_owned() + &trait_path);
1481 crate_types.traits.insert(trait_path, &t);
1484 syn::Item::Type(t) => {
1485 if let syn::Visibility::Public(_) = t.vis {
1486 match export_status(&t.attrs) {
1487 ExportStatus::Export => {},
1488 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1490 let type_path = format!("{}::{}", module, t.ident);
1491 let mut process_alias = true;
1492 for tok in t.generics.params.iter() {
1493 if let syn::GenericParam::Lifetime(_) = tok {}
1494 else { process_alias = false; }
1498 syn::Type::Path(p) => {
1499 // If its a path with no generics, assume we don't map the aliased type and map it opaque
1500 let mut segments = syn::punctuated::Punctuated::new();
1501 segments.push(syn::PathSegment {
1502 ident: t.ident.clone(),
1503 arguments: syn::PathArguments::None,
1505 let path_obj = syn::Path { leading_colon: None, segments };
1506 let args_obj = p.path.segments.last().unwrap().arguments.clone();
1507 match crate_types.reverse_alias_map.entry(import_resolver.maybe_resolve_path(&p.path, None).unwrap()) {
1508 hash_map::Entry::Occupied(mut e) => { e.get_mut().push((path_obj, args_obj)); },
1509 hash_map::Entry::Vacant(e) => { e.insert(vec![(path_obj, args_obj)]); },
1512 crate_types.opaques.insert(type_path.clone(), &t.ident);
1515 crate_types.type_aliases.insert(type_path, import_resolver.resolve_imported_refs((*t.ty).clone()));
1521 syn::Item::Enum(e) if is_enum_opaque(e) => {
1522 if let syn::Visibility::Public(_) = e.vis {
1523 match export_status(&e.attrs) {
1524 ExportStatus::Export => {},
1525 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1527 let enum_path = format!("{}::{}", module, e.ident);
1528 crate_types.opaques.insert(enum_path, &e.ident);
1531 syn::Item::Enum(e) => {
1532 if let syn::Visibility::Public(_) = e.vis {
1533 match export_status(&e.attrs) {
1534 ExportStatus::Export => {},
1535 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1537 let enum_path = format!("{}::{}", module, e.ident);
1538 crate_types.mirrored_enums.insert(enum_path, &e);
1541 syn::Item::Impl(i) => {
1542 if let &syn::Type::Path(ref p) = &*i.self_ty {
1543 if let Some(trait_path) = i.trait_.as_ref() {
1544 if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) {
1545 if let Some(full_path) = import_resolver.maybe_resolve_path(&p.path, None) {
1546 crate_types.set_clonable("crate::".to_owned() + &full_path);
1549 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1550 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1551 match crate_types.trait_impls.entry(sp) {
1552 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1553 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1560 syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types),
1568 let args: Vec<String> = env::args().collect();
1569 if args.len() != 6 {
1570 eprintln!("Usage: target/dir source_crate_name derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
1574 let mut derived_templates = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1575 .open(&args[3]).expect("Unable to open new header file");
1576 let mut header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1577 .open(&args[4]).expect("Unable to open new header file");
1578 let mut cpp_header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1579 .open(&args[5]).expect("Unable to open new header file");
1581 writeln!(header_file, "#if defined(__GNUC__)").unwrap();
1582 writeln!(header_file, "#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
1583 writeln!(header_file, "#define MUST_USE_RES __attribute__((warn_unused_result))").unwrap();
1584 writeln!(header_file, "#else").unwrap();
1585 writeln!(header_file, "#define MUST_USE_STRUCT").unwrap();
1586 writeln!(header_file, "#define MUST_USE_RES").unwrap();
1587 writeln!(header_file, "#endif").unwrap();
1588 writeln!(header_file, "#if defined(__clang__)").unwrap();
1589 writeln!(header_file, "#define NONNULL_PTR _Nonnull").unwrap();
1590 writeln!(header_file, "#else").unwrap();
1591 writeln!(header_file, "#define NONNULL_PTR").unwrap();
1592 writeln!(header_file, "#endif").unwrap();
1593 writeln!(cpp_header_file, "#include <string.h>\nnamespace LDK {{").unwrap();
1595 // First parse the full crate's ASTs, caching them so that we can hold references to the AST
1596 // objects in other datastructures:
1597 let mut lib_src = String::new();
1598 std::io::stdin().lock().read_to_string(&mut lib_src).unwrap();
1599 let lib_syntax = syn::parse_file(&lib_src).expect("Unable to parse file");
1600 let libast = FullLibraryAST::load_lib(lib_syntax);
1602 // ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
1603 // when parsing other file ASTs...
1604 let mut libtypes = CrateTypes::new(&mut derived_templates, &libast);
1605 walk_ast(&libast, &mut libtypes);
1607 // ... finally, do the actual file conversion/mapping, writing out types as we go.
1608 convert_file(&libast, &libtypes, &args[1], &args[2], &mut header_file, &mut cpp_header_file);
1610 // For container templates which we created while walking the crate, make sure we add C++
1611 // mapped types so that C++ users can utilize the auto-destructors available.
1612 for (ty, has_destructor) in libtypes.templates_defined.borrow().iter() {
1613 write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor);
1615 writeln!(cpp_header_file, "}}").unwrap();
1617 header_file.flush().unwrap();
1618 cpp_header_file.flush().unwrap();
1619 derived_templates.flush().unwrap();