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;
28 use quote::format_ident;
36 const DEFAULT_IMPORTS: &'static str = "\nuse std::str::FromStr;\nuse std::ffi::c_void;\nuse bitcoin::hashes::Hash;\nuse crate::c_types::*;\n";
38 // *************************************
39 // *** Manually-expanded conversions ***
40 // *************************************
42 /// Convert "impl trait_path for for_ty { .. }" for manually-mapped types (ie (de)serialization)
43 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) {
44 if let Some(t) = types.maybe_resolve_path(&trait_path, Some(generics)) {
47 let mut has_inner = false;
48 if let syn::Type::Path(ref p) = for_ty {
49 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
50 for_obj = format!("{}", ident);
51 full_obj_path = for_obj.clone();
52 has_inner = types.c_type_has_inner_from_path(&types.resolve_path(&p.path, Some(generics)));
55 // We assume that anything that isn't a Path is somehow a generic that ends up in our
56 // derived-types module.
57 let mut for_obj_vec = Vec::new();
58 types.write_c_type(&mut for_obj_vec, for_ty, Some(generics), false);
59 full_obj_path = String::from_utf8(for_obj_vec).unwrap();
60 assert!(full_obj_path.starts_with(TypeResolver::generated_container_path()));
61 for_obj = full_obj_path[TypeResolver::generated_container_path().len() + 2..].into();
65 "lightning::util::ser::Writeable" => {
66 writeln!(w, "#[no_mangle]").unwrap();
67 writeln!(w, "/// Serialize the {} object into a byte array which can be read by {}_read", for_obj, for_obj).unwrap();
68 writeln!(w, "pub extern \"C\" fn {}_write(obj: &{}) -> crate::c_types::derived::CVec_u8Z {{", for_obj, full_obj_path).unwrap();
70 let ref_type: syn::Type = syn::parse_quote!(&#for_ty);
71 assert!(!types.write_from_c_conversion_new_var(w, &format_ident!("obj"), &ref_type, Some(generics)));
73 write!(w, "\tcrate::c_types::serialize_obj(").unwrap();
74 types.write_from_c_conversion_prefix(w, &ref_type, Some(generics));
75 write!(w, "unsafe {{ &*obj }}").unwrap();
76 types.write_from_c_conversion_suffix(w, &ref_type, Some(generics));
77 writeln!(w, ")").unwrap();
79 writeln!(w, "}}").unwrap();
81 writeln!(w, "#[no_mangle]").unwrap();
82 writeln!(w, "pub(crate) extern \"C\" fn {}_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {{", for_obj).unwrap();
83 writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &*(obj as *const native{}) }})", for_obj).unwrap();
84 writeln!(w, "}}").unwrap();
87 "lightning::util::ser::Readable"|"lightning::util::ser::ReadableArgs" => {
88 // Create the Result<Object, DecodeError> syn::Type
89 let res_ty: syn::Type = parse_quote!(Result<#for_ty, ::ln::msgs::DecodeError>);
91 writeln!(w, "#[no_mangle]").unwrap();
92 writeln!(w, "/// Read a {} from a byte array, created by {}_write", for_obj, for_obj).unwrap();
93 write!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice", for_obj).unwrap();
95 let mut arg_conv = Vec::new();
96 if t == "lightning::util::ser::ReadableArgs" {
97 write!(w, ", arg: ").unwrap();
98 assert!(trait_path.leading_colon.is_none());
99 let args_seg = trait_path.segments.iter().last().unwrap();
100 assert_eq!(format!("{}", args_seg.ident), "ReadableArgs");
101 if let syn::PathArguments::AngleBracketed(args) = &args_seg.arguments {
102 assert_eq!(args.args.len(), 1);
103 if let syn::GenericArgument::Type(args_ty) = args.args.iter().next().unwrap() {
104 types.write_c_type(w, args_ty, Some(generics), false);
106 assert!(!types.write_from_c_conversion_new_var(&mut arg_conv, &format_ident!("arg"), &args_ty, Some(generics)));
108 write!(&mut arg_conv, "\tlet arg_conv = ").unwrap();
109 types.write_from_c_conversion_prefix(&mut arg_conv, &args_ty, Some(generics));
110 write!(&mut arg_conv, "arg").unwrap();
111 types.write_from_c_conversion_suffix(&mut arg_conv, &args_ty, Some(generics));
112 } else { unreachable!(); }
113 } else { unreachable!(); }
115 write!(w, ") -> ").unwrap();
116 types.write_c_type(w, &res_ty, Some(generics), false);
117 writeln!(w, " {{").unwrap();
119 if t == "lightning::util::ser::ReadableArgs" {
120 w.write(&arg_conv).unwrap();
121 write!(w, ";\n\tlet res: ").unwrap();
122 // At least in one case we need type annotations here, so provide them.
123 types.write_rust_type(w, Some(generics), &res_ty);
124 writeln!(w, " = crate::c_types::deserialize_obj_arg(ser, arg_conv);").unwrap();
126 writeln!(w, "\tlet res = crate::c_types::deserialize_obj(ser);").unwrap();
128 write!(w, "\t").unwrap();
129 if types.write_to_c_conversion_new_var(w, &format_ident!("res"), &res_ty, Some(generics), false) {
130 write!(w, "\n\t").unwrap();
132 types.write_to_c_conversion_inline_prefix(w, &res_ty, Some(generics), false);
133 write!(w, "res").unwrap();
134 types.write_to_c_conversion_inline_suffix(w, &res_ty, Some(generics), false);
135 writeln!(w, "\n}}").unwrap();
142 /// Convert "TraitA : TraitB" to a single function name and return type.
144 /// This is (obviously) somewhat over-specialized and only useful for TraitB's that only require a
145 /// single function (eg for serialization).
146 fn convert_trait_impl_field(trait_path: &str) -> (&'static str, String, &'static str) {
148 "lightning::util::ser::Writeable" => ("Serialize the object into a byte array", "write".to_owned(), "crate::c_types::derived::CVec_u8Z"),
149 _ => unimplemented!(),
153 /// Companion to convert_trait_impl_field, write an assignment for the function defined by it for
154 /// `for_obj` which implements the the trait at `trait_path`.
155 fn write_trait_impl_field_assign<W: std::io::Write>(w: &mut W, trait_path: &str, for_obj: &syn::Ident) {
157 "lightning::util::ser::Writeable" => {
158 writeln!(w, "\t\twrite: {}_write_void,", for_obj).unwrap();
160 _ => unimplemented!(),
164 /// Write out the impl block for a defined trait struct which has a supertrait
165 fn do_write_impl_trait<W: std::io::Write>(w: &mut W, trait_path: &str, _trait_name: &syn::Ident, for_obj: &str) {
166 eprintln!("{}", trait_path);
168 "lightning::util::ser::Writeable" => {
169 writeln!(w, "impl {} for {} {{", trait_path, for_obj).unwrap();
170 writeln!(w, "\tfn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {{").unwrap();
171 writeln!(w, "\t\tlet vec = (self.write)(self.this_arg);").unwrap();
172 writeln!(w, "\t\tw.write_all(vec.as_slice())").unwrap();
173 writeln!(w, "\t}}\n}}").unwrap();
179 // *******************************
180 // *** Per-Type Printing Logic ***
181 // *******************************
183 macro_rules! walk_supertraits { ($t: expr, $types: expr, ($( $($pat: pat)|* => $e: expr),*) ) => { {
184 if $t.colon_token.is_some() {
185 for st in $t.supertraits.iter() {
187 syn::TypeParamBound::Trait(supertrait) => {
188 if supertrait.paren_token.is_some() || supertrait.lifetimes.is_some() {
191 // First try to resolve path to find in-crate traits, but if that doesn't work
192 // assume its a prelude trait (eg Clone, etc) and just use the single ident.
193 let types_opt: Option<&TypeResolver> = $types;
194 if let Some(types) = types_opt {
195 if let Some(path) = types.maybe_resolve_path(&supertrait.path, None) {
196 match (&path as &str, &supertrait.path.segments.iter().last().unwrap().ident) {
197 $( $($pat)|* => $e, )*
202 if let Some(ident) = supertrait.path.get_ident() {
203 match (&format!("{}", ident) as &str, &ident) {
204 $( $($pat)|* => $e, )*
206 } else if types_opt.is_some() {
207 panic!("Supertrait unresolvable and not single-ident");
210 syn::TypeParamBound::Lifetime(_) => unimplemented!(),
216 /// Prints a C-mapped trait object containing a void pointer and a jump table for each function in
217 /// the original trait.
218 /// Implements the native Rust trait and relevant parent traits for the new C-mapped trait.
220 /// Finally, implements Deref<MappedTrait> for MappedTrait which allows its use in types which need
221 /// a concrete Deref to the Rust trait.
222 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) {
223 let trait_name = format!("{}", t.ident);
225 match export_status(&t.attrs) {
226 ExportStatus::Export => { implementable = true; }
227 ExportStatus::NotImplementable => { implementable = false; },
228 ExportStatus::NoExport|ExportStatus::TestOnly => return,
230 writeln_docs(w, &t.attrs, "");
232 let mut gen_types = GenericTypes::new(None);
233 assert!(gen_types.learn_generics(&t.generics, types));
234 gen_types.learn_associated_types(&t, types);
236 writeln!(w, "#[repr(C)]\npub struct {} {{", trait_name).unwrap();
237 writeln!(w, "\t/// An opaque pointer which is passed to your function implementations as an argument.").unwrap();
238 writeln!(w, "\t/// This has no meaning in the LDK, and can be NULL or any other value.").unwrap();
239 writeln!(w, "\tpub this_arg: *mut c_void,").unwrap();
240 let mut generated_fields = Vec::new(); // Every field's (name, Option<clone_fn>) except this_arg, used in Clone generation
241 for item in t.items.iter() {
243 &syn::TraitItem::Method(ref m) => {
244 match export_status(&m.attrs) {
245 ExportStatus::NoExport => {
246 // NoExport in this context means we'll hit an unimplemented!() at runtime,
250 ExportStatus::Export => {},
251 ExportStatus::TestOnly => continue,
252 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
254 if m.default.is_some() { unimplemented!(); }
256 let mut meth_gen_types = gen_types.push_ctx();
257 assert!(meth_gen_types.learn_generics(&m.sig.generics, types));
259 writeln_docs(w, &m.attrs, "\t");
261 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
262 if let syn::Type::Reference(r) = &**rtype {
263 // We have to do quite a dance for trait functions which return references
264 // - they ultimately require us to have a native Rust object stored inside
265 // our concrete trait to return a reference to. However, users may wish to
266 // update the value to be returned each time the function is called (or, to
267 // make C copies of Rust impls equivalent, we have to be able to).
269 // Thus, we store a copy of the C-mapped type (which is just a pointer to
270 // the Rust type and a flag to indicate whether deallocation needs to
271 // happen) as well as provide an Option<>al function pointer which is
272 // called when the trait method is called which allows updating on the fly.
273 write!(w, "\tpub {}: ", m.sig.ident).unwrap();
274 generated_fields.push((format!("{}", m.sig.ident), None));
275 types.write_c_type(w, &*r.elem, Some(&meth_gen_types), false);
276 writeln!(w, ",").unwrap();
277 writeln!(w, "\t/// Fill in the {} field as a reference to it will be given to Rust after this returns", m.sig.ident).unwrap();
278 writeln!(w, "\t/// Note that this takes a pointer to this object, not the this_ptr like other methods do").unwrap();
279 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();
280 writeln!(w, "\tpub set_{}: Option<extern \"C\" fn(&{})>,", m.sig.ident, trait_name).unwrap();
281 generated_fields.push((format!("set_{}", m.sig.ident), None));
282 // Note that cbindgen will now generate
283 // typedef struct Thing {..., set_thing: (const struct Thing*), ...} Thing;
284 // which does not compile since Thing is not defined before it is used.
285 writeln!(extra_headers, "struct LDK{};", trait_name).unwrap();
288 // Sadly, this currently doesn't do what we want, but it should be easy to get
289 // cbindgen to support it. See https://github.com/eqrion/cbindgen/issues/531
290 writeln!(w, "\t#[must_use]").unwrap();
293 write!(w, "\tpub {}: extern \"C\" fn (", m.sig.ident).unwrap();
294 generated_fields.push((format!("{}", m.sig.ident), None));
295 write_method_params(w, &m.sig, "c_void", types, Some(&meth_gen_types), true, false);
296 writeln!(w, ",").unwrap();
298 &syn::TraitItem::Type(_) => {},
299 _ => unimplemented!(),
302 // Add functions which may be required for supertrait implementations.
303 walk_supertraits!(t, Some(&types), (
305 writeln!(w, "\t/// Called, if set, after this {} has been cloned into a duplicate object.", trait_name).unwrap();
306 writeln!(w, "\t/// The new {} is provided, and should be mutated as needed to perform a", trait_name).unwrap();
307 writeln!(w, "\t/// deep copy of the object pointed to by this_arg or avoid any double-freeing.").unwrap();
308 writeln!(w, "\tpub cloned: Option<extern \"C\" fn (new_{}: &mut {})>,", trait_name, trait_name).unwrap();
309 generated_fields.push(("cloned".to_owned(), None));
311 ("std::cmp::Eq", _)|("core::cmp::Eq", _) => {
312 writeln!(w, "\t/// Checks if two objects are equal given this object's this_arg pointer and another object.").unwrap();
313 writeln!(w, "\tpub eq: extern \"C\" fn (this_arg: *const c_void, other_arg: &{}) -> bool,", trait_name).unwrap();
314 generated_fields.push(("eq".to_owned(), None));
316 ("std::hash::Hash", _)|("core::hash::Hash", _) => {
317 writeln!(w, "\t/// Calculate a succinct non-cryptographic hash for an object given its this_arg pointer.").unwrap();
318 writeln!(w, "\t/// This is used, for example, for inclusion of this object in a hash map.").unwrap();
319 writeln!(w, "\tpub hash: extern \"C\" fn (this_arg: *const c_void) -> u64,").unwrap();
320 generated_fields.push(("hash".to_owned(), None));
322 ("Send", _) => {}, ("Sync", _) => {},
324 generated_fields.push(if types.crate_types.traits.get(s).is_none() {
325 let (docs, name, ret) = convert_trait_impl_field(s);
326 writeln!(w, "\t/// {}", docs).unwrap();
327 writeln!(w, "\tpub {}: extern \"C\" fn (this_arg: *const c_void) -> {},", name, ret).unwrap();
328 (name, None) // Assume clonable
330 // For in-crate supertraits, just store a C-mapped copy of the supertrait as a member.
331 writeln!(w, "\t/// Implementation of {} for this object.", i).unwrap();
332 let is_clonable = types.is_clonable(s);
333 writeln!(w, "\tpub {}: crate::{},", i, s).unwrap();
334 (format!("{}", i), if !is_clonable {
335 Some(format!("crate::{}_clone_fields", s))
340 writeln!(w, "\t/// Frees any resources associated with this object given its this_arg pointer.").unwrap();
341 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();
342 writeln!(w, "\tpub free: Option<extern \"C\" fn(this_arg: *mut c_void)>,").unwrap();
343 generated_fields.push(("free".to_owned(), None));
344 writeln!(w, "}}").unwrap();
346 macro_rules! impl_trait_for_c {
347 ($t: expr, $impl_accessor: expr, $type_resolver: expr) => {
348 for item in $t.items.iter() {
350 syn::TraitItem::Method(m) => {
351 if let ExportStatus::TestOnly = export_status(&m.attrs) { continue; }
352 if m.default.is_some() { unimplemented!(); }
353 if m.sig.constness.is_some() || m.sig.asyncness.is_some() || m.sig.unsafety.is_some() ||
354 m.sig.abi.is_some() || m.sig.variadic.is_some() {
357 let mut meth_gen_types = gen_types.push_ctx();
358 assert!(meth_gen_types.learn_generics(&m.sig.generics, $type_resolver));
359 write!(w, "\tfn {}", m.sig.ident).unwrap();
360 $type_resolver.write_rust_generic_param(w, Some(&meth_gen_types), m.sig.generics.params.iter());
361 write!(w, "(").unwrap();
362 for inp in m.sig.inputs.iter() {
364 syn::FnArg::Receiver(recv) => {
365 if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
366 write!(w, "&").unwrap();
367 if let Some(lft) = &recv.reference.as_ref().unwrap().1 {
368 write!(w, "'{} ", lft.ident).unwrap();
370 if recv.mutability.is_some() {
371 write!(w, "mut self").unwrap();
373 write!(w, "self").unwrap();
376 syn::FnArg::Typed(arg) => {
377 if !arg.attrs.is_empty() { unimplemented!(); }
379 syn::Pat::Ident(ident) => {
380 if !ident.attrs.is_empty() || ident.by_ref.is_some() ||
381 ident.mutability.is_some() || ident.subpat.is_some() {
384 write!(w, ", mut {}{}: ", if $type_resolver.skip_arg(&*arg.ty, Some(&meth_gen_types)) { "_" } else { "" }, ident.ident).unwrap();
386 _ => unimplemented!(),
388 $type_resolver.write_rust_type(w, Some(&meth_gen_types), &*arg.ty);
392 write!(w, ")").unwrap();
393 match &m.sig.output {
394 syn::ReturnType::Type(_, rtype) => {
395 write!(w, " -> ").unwrap();
396 $type_resolver.write_rust_type(w, Some(&meth_gen_types), &*rtype)
400 write!(w, " {{\n\t\t").unwrap();
401 match export_status(&m.attrs) {
402 ExportStatus::NoExport => {
407 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
408 if let syn::Type::Reference(r) = &**rtype {
409 assert_eq!(m.sig.inputs.len(), 1); // Must only take self!
410 writeln!(w, "if let Some(f) = self{}.set_{} {{", $impl_accessor, m.sig.ident).unwrap();
411 writeln!(w, "\t\t\t(f)(&self{});", $impl_accessor).unwrap();
412 write!(w, "\t\t}}\n\t\t").unwrap();
413 $type_resolver.write_from_c_conversion_to_ref_prefix(w, &*r.elem, Some(&meth_gen_types));
414 write!(w, "self{}.{}", $impl_accessor, m.sig.ident).unwrap();
415 $type_resolver.write_from_c_conversion_to_ref_suffix(w, &*r.elem, Some(&meth_gen_types));
416 writeln!(w, "\n\t}}").unwrap();
420 write_method_var_decl_body(w, &m.sig, "\t", $type_resolver, Some(&meth_gen_types), true);
421 write!(w, "(self{}.{})(", $impl_accessor, m.sig.ident).unwrap();
422 let mut args = Vec::new();
423 write_method_call_params(&mut args, &m.sig, "\t", $type_resolver, Some(&meth_gen_types), "", true);
424 w.write_all(String::from_utf8(args).unwrap().replace("self", &format!("self{}", $impl_accessor)).as_bytes()).unwrap();
426 writeln!(w, "\n\t}}").unwrap();
428 &syn::TraitItem::Type(ref t) => {
429 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
430 let mut bounds_iter = t.bounds.iter();
431 match bounds_iter.next().unwrap() {
432 syn::TypeParamBound::Trait(tr) => {
433 writeln!(w, "\ttype {} = crate::{};", t.ident, $type_resolver.resolve_path(&tr.path, Some(&gen_types))).unwrap();
435 _ => unimplemented!(),
437 if bounds_iter.next().is_some() { unimplemented!(); }
439 _ => unimplemented!(),
445 writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap();
446 writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap();
448 writeln!(w, "#[no_mangle]").unwrap();
449 writeln!(w, "pub(crate) extern \"C\" fn {}_clone_fields(orig: &{}) -> {} {{", trait_name, trait_name, trait_name).unwrap();
450 writeln!(w, "\t{} {{", trait_name).unwrap();
451 writeln!(w, "\t\tthis_arg: orig.this_arg,").unwrap();
452 for (field, clone_fn) in generated_fields.iter() {
453 if let Some(f) = clone_fn {
454 // If the field isn't clonable, blindly assume its a trait and hope for the best.
455 writeln!(w, "\t\t{}: {}(&orig.{}),", field, f, field).unwrap();
457 writeln!(w, "\t\t{}: Clone::clone(&orig.{}),", field, field).unwrap();
460 writeln!(w, "\t}}\n}}").unwrap();
462 // Implement supertraits for the C-mapped struct.
463 walk_supertraits!(t, Some(&types), (
464 ("std::cmp::Eq", _)|("core::cmp::Eq", _) => {
465 writeln!(w, "impl std::cmp::Eq for {} {{}}", trait_name).unwrap();
466 writeln!(w, "impl std::cmp::PartialEq for {} {{", trait_name).unwrap();
467 writeln!(w, "\tfn eq(&self, o: &Self) -> bool {{ (self.eq)(self.this_arg, o) }}\n}}").unwrap();
469 ("std::hash::Hash", _)|("core::hash::Hash", _) => {
470 writeln!(w, "impl std::hash::Hash for {} {{", trait_name).unwrap();
471 writeln!(w, "\tfn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {{ hasher.write_u64((self.hash)(self.this_arg)) }}\n}}").unwrap();
473 ("Send", _) => {}, ("Sync", _) => {},
475 writeln!(w, "#[no_mangle]").unwrap();
476 writeln!(w, "/// Creates a copy of a {}", trait_name).unwrap();
477 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", trait_name, trait_name, trait_name).unwrap();
478 writeln!(w, "\tlet mut res = {}_clone_fields(orig);", trait_name).unwrap();
479 writeln!(w, "\tif let Some(f) = orig.cloned {{ (f)(&mut res) }};").unwrap();
480 writeln!(w, "\tres\n}}").unwrap();
481 writeln!(w, "impl Clone for {} {{", trait_name).unwrap();
482 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
483 writeln!(w, "\t\t{}_clone(self)", trait_name).unwrap();
484 writeln!(w, "\t}}\n}}").unwrap();
487 if let Some(supertrait) = types.crate_types.traits.get(s) {
488 let mut module_iter = s.rsplitn(2, "::");
489 module_iter.next().unwrap();
490 let supertrait_module = module_iter.next().unwrap();
491 let imports = ImportResolver::new(supertrait_module.splitn(2, "::").next().unwrap(), &types.crate_types.lib_ast.dependencies,
492 supertrait_module, &types.crate_types.lib_ast.modules.get(supertrait_module).unwrap().items);
493 let resolver = TypeResolver::new(&supertrait_module, imports, types.crate_types);
494 writeln!(w, "impl {} for {} {{", s, trait_name).unwrap();
495 impl_trait_for_c!(supertrait, format!(".{}", i), &resolver);
496 writeln!(w, "}}").unwrap();
498 do_write_impl_trait(w, s, i, &trait_name);
503 // Finally, implement the original Rust trait for the newly created mapped trait.
504 writeln!(w, "\nuse {}::{} as rust{};", types.module_path, t.ident, trait_name).unwrap();
506 write!(w, "impl rust{}", t.ident).unwrap();
507 maybe_write_generics(w, &t.generics, types, false);
508 writeln!(w, " for {} {{", trait_name).unwrap();
509 impl_trait_for_c!(t, "", types);
510 writeln!(w, "}}\n").unwrap();
511 writeln!(w, "// We're essentially a pointer already, or at least a set of pointers, so allow us to be used").unwrap();
512 writeln!(w, "// directly as a Deref trait in higher-level structs:").unwrap();
513 writeln!(w, "impl std::ops::Deref for {} {{\n\ttype Target = Self;", trait_name).unwrap();
514 writeln!(w, "\tfn deref(&self) -> &Self {{\n\t\tself\n\t}}\n}}").unwrap();
517 writeln!(w, "/// Calls the free function if one is set").unwrap();
518 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", trait_name, trait_name).unwrap();
519 writeln!(w, "impl Drop for {} {{", trait_name).unwrap();
520 writeln!(w, "\tfn drop(&mut self) {{").unwrap();
521 writeln!(w, "\t\tif let Some(f) = self.free {{").unwrap();
522 writeln!(w, "\t\t\tf(self.this_arg);").unwrap();
523 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
525 write_cpp_wrapper(cpp_headers, &trait_name, true);
528 /// Write out a simple "opaque" type (eg structs) which contain a pointer to the native Rust type
529 /// and a flag to indicate whether Drop'ing the mapped struct drops the underlying Rust type.
531 /// Also writes out a _free function and a C++ wrapper which handles calling _free.
532 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) {
533 // If we directly read the original type by its original name, cbindgen hits
534 // https://github.com/eqrion/cbindgen/issues/286 Thus, instead, we import it as a temporary
535 // name and then reference it by that name, which works around the issue.
536 write!(w, "\nuse {}::{} as native{}Import;\ntype native{} = native{}Import", types.module_path, ident, ident, ident, ident).unwrap();
537 maybe_write_generics(w, &generics, &types, true);
538 writeln!(w, ";\n").unwrap();
539 writeln!(extra_headers, "struct native{}Opaque;\ntypedef struct native{}Opaque LDKnative{};", ident, ident, ident).unwrap();
540 writeln_docs(w, &attrs, "");
541 writeln!(w, "#[must_use]\n#[repr(C)]\npub struct {} {{", struct_name).unwrap();
542 writeln!(w, "\t/// A pointer to the opaque Rust object.\n").unwrap();
543 writeln!(w, "\t/// Nearly everywhere, inner must be non-null, however in places where").unwrap();
544 writeln!(w, "\t/// the Rust equivalent takes an Option, it may be set to null to indicate None.").unwrap();
545 writeln!(w, "\tpub inner: *mut native{},", ident).unwrap();
546 writeln!(w, "\t/// Indicates that this is the only struct which contains the same pointer.\n").unwrap();
547 writeln!(w, "\t/// Rust functions which take ownership of an object provided via an argument require").unwrap();
548 writeln!(w, "\t/// this to be true and invalidate the object pointed to by inner.").unwrap();
549 writeln!(w, "\tpub is_owned: bool,").unwrap();
550 writeln!(w, "}}\n").unwrap();
551 writeln!(w, "impl Drop for {} {{\n\tfn drop(&mut self) {{", struct_name).unwrap();
552 writeln!(w, "\t\tif self.is_owned && !<*mut native{}>::is_null(self.inner) {{", ident).unwrap();
553 writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(self.inner) }};\n\t\t}}\n\t}}\n}}").unwrap();
554 writeln!(w, "/// Frees any resources used by the {}, if is_owned is set and inner is non-NULL.", struct_name).unwrap();
555 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_obj: {}) {{ }}", struct_name, struct_name).unwrap();
556 writeln!(w, "#[allow(unused)]").unwrap();
557 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
558 writeln!(w, "extern \"C\" fn {}_free_void(this_ptr: *mut c_void) {{", struct_name).unwrap();
559 writeln!(w, "\tunsafe {{ let _ = Box::from_raw(this_ptr as *mut native{}); }}\n}}", struct_name).unwrap();
560 writeln!(w, "#[allow(unused)]").unwrap();
561 writeln!(w, "/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy").unwrap();
562 writeln!(w, "impl {} {{", struct_name).unwrap();
563 writeln!(w, "\tpub(crate) fn take_inner(mut self) -> *mut native{} {{", struct_name).unwrap();
564 writeln!(w, "\t\tassert!(self.is_owned);").unwrap();
565 writeln!(w, "\t\tlet ret = self.inner;").unwrap();
566 writeln!(w, "\t\tself.inner = std::ptr::null_mut();").unwrap();
567 writeln!(w, "\t\tret").unwrap();
568 writeln!(w, "\t}}\n}}").unwrap();
570 write_cpp_wrapper(cpp_headers, &format!("{}", ident), true);
573 /// Writes out all the relevant mappings for a Rust struct, deferring to writeln_opaque to generate
574 /// the struct itself, and then writing getters and setters for public, understood-type fields and
575 /// a constructor if every field is public.
576 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) {
577 if export_status(&s.attrs) != ExportStatus::Export { return; }
579 let struct_name = &format!("{}", s.ident);
580 writeln_opaque(w, &s.ident, struct_name, &s.generics, &s.attrs, types, extra_headers, cpp_headers);
582 if let syn::Fields::Named(fields) = &s.fields {
583 let mut self_path_segs = syn::punctuated::Punctuated::new();
584 self_path_segs.push(s.ident.clone().into());
585 let self_path = syn::Path { leading_colon: None, segments: self_path_segs};
586 let mut gen_types = GenericTypes::new(Some((types.resolve_path(&self_path, None), &self_path)));
587 assert!(gen_types.learn_generics(&s.generics, types));
589 let mut all_fields_settable = true;
590 for field in fields.named.iter() {
591 if let syn::Visibility::Public(_) = field.vis {
592 let export = export_status(&field.attrs);
594 ExportStatus::Export => {},
595 ExportStatus::NoExport|ExportStatus::TestOnly => {
596 all_fields_settable = false;
599 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
602 if let Some(ident) = &field.ident {
603 let ref_type = syn::Type::Reference(syn::TypeReference {
604 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
605 elem: Box::new(field.ty.clone()) });
606 if types.understood_c_type(&ref_type, Some(&gen_types)) {
607 writeln_docs(w, &field.attrs, "");
608 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> ", struct_name, ident, struct_name).unwrap();
609 types.write_c_type(w, &ref_type, Some(&gen_types), true);
610 write!(w, " {{\n\tlet mut inner_val = &mut unsafe {{ &mut *this_ptr.inner }}.{};\n\t", ident).unwrap();
611 let local_var = types.write_to_c_conversion_new_var(w, &format_ident!("inner_val"), &ref_type, Some(&gen_types), true);
612 if local_var { write!(w, "\n\t").unwrap(); }
613 types.write_to_c_conversion_inline_prefix(w, &ref_type, Some(&gen_types), true);
614 write!(w, "inner_val").unwrap();
615 types.write_to_c_conversion_inline_suffix(w, &ref_type, Some(&gen_types), true);
616 writeln!(w, "\n}}").unwrap();
619 if types.understood_c_type(&field.ty, Some(&gen_types)) {
620 writeln_docs(w, &field.attrs, "");
621 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_set_{}(this_ptr: &mut {}, mut val: ", struct_name, ident, struct_name).unwrap();
622 types.write_c_type(w, &field.ty, Some(&gen_types), false);
623 write!(w, ") {{\n\t").unwrap();
624 let local_var = types.write_from_c_conversion_new_var(w, &format_ident!("val"), &field.ty, Some(&gen_types));
625 if local_var { write!(w, "\n\t").unwrap(); }
626 write!(w, "unsafe {{ &mut *this_ptr.inner }}.{} = ", ident).unwrap();
627 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
628 write!(w, "val").unwrap();
629 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
630 writeln!(w, ";\n}}").unwrap();
631 } else { all_fields_settable = false; }
632 } else { all_fields_settable = false; }
633 } else { all_fields_settable = false; }
636 if all_fields_settable {
637 // Build a constructor!
638 writeln!(w, "/// Constructs a new {} given each field", struct_name).unwrap();
639 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_new(", struct_name).unwrap();
640 for (idx, field) in fields.named.iter().enumerate() {
641 if idx != 0 { write!(w, ", ").unwrap(); }
642 write!(w, "mut {}_arg: ", field.ident.as_ref().unwrap()).unwrap();
643 types.write_c_type(w, &field.ty, Some(&gen_types), false);
645 write!(w, ") -> {} {{\n\t", struct_name).unwrap();
646 for field in fields.named.iter() {
647 let field_ident = format_ident!("{}_arg", field.ident.as_ref().unwrap());
648 if types.write_from_c_conversion_new_var(w, &field_ident, &field.ty, Some(&gen_types)) {
649 write!(w, "\n\t").unwrap();
652 writeln!(w, "{} {{ inner: Box::into_raw(Box::new(native{} {{", struct_name, s.ident).unwrap();
653 for field in fields.named.iter() {
654 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
655 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
656 write!(w, "{}_arg", field.ident.as_ref().unwrap()).unwrap();
657 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
658 writeln!(w, ",").unwrap();
660 writeln!(w, "\t}})), is_owned: true }}\n}}").unwrap();
665 /// Prints a relevant conversion for impl *
667 /// For simple impl Struct {}s, this just outputs the wrapper functions as Struct_fn_name() { .. }.
669 /// For impl Trait for Struct{}s, this non-exported generates wrapper functions as
670 /// Trait_Struct_fn_name and a Struct_as_Trait(&struct) -> Trait function which returns a populated
671 /// Trait struct containing a pointer to the passed struct's inner field and the wrapper functions.
673 /// A few non-crate Traits are hard-coded including Default.
674 fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut TypeResolver) {
675 match export_status(&i.attrs) {
676 ExportStatus::Export => {},
677 ExportStatus::NoExport|ExportStatus::TestOnly => return,
678 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
681 if let syn::Type::Tuple(_) = &*i.self_ty {
682 if types.understood_c_type(&*i.self_ty, None) {
683 let mut gen_types = GenericTypes::new(None);
684 if !gen_types.learn_generics(&i.generics, types) {
685 eprintln!("Not implementing anything for `impl (..)` due to not understood generics");
689 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
690 if let Some(trait_path) = i.trait_.as_ref() {
691 if trait_path.0.is_some() { unimplemented!(); }
692 if types.understood_c_path(&trait_path.1) {
693 eprintln!("Not implementing anything for `impl Trait for (..)` - we only support manual defines");
696 // Just do a manual implementation:
697 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
700 eprintln!("Not implementing anything for plain `impl (..)` block - we only support `impl Trait for (..)` blocks");
706 if let &syn::Type::Path(ref p) = &*i.self_ty {
707 if p.qself.is_some() { unimplemented!(); }
708 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
709 if let Some(resolved_path) = types.maybe_resolve_non_ignored_ident(&ident) {
710 let mut gen_types = GenericTypes::new(Some((resolved_path.clone(), &p.path)));
711 if !gen_types.learn_generics(&i.generics, types) {
712 eprintln!("Not implementing anything for impl {} due to not understood generics", ident);
716 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
717 if let Some(trait_path) = i.trait_.as_ref() {
718 if trait_path.0.is_some() { unimplemented!(); }
719 if types.understood_c_path(&trait_path.1) {
720 let full_trait_path = types.resolve_path(&trait_path.1, None);
721 let trait_obj = *types.crate_types.traits.get(&full_trait_path).unwrap();
722 // We learn the associated types maping from the original trait object.
723 // That's great, except that they are unresolved idents, so if we learn
724 // mappings from a trai defined in a different file, we may mis-resolve or
725 // fail to resolve the mapped types.
726 gen_types.learn_associated_types(trait_obj, types);
727 let mut impl_associated_types = HashMap::new();
728 for item in i.items.iter() {
730 syn::ImplItem::Type(t) => {
731 if let syn::Type::Path(p) = &t.ty {
732 if let Some(id) = single_ident_generic_path_to_ident(&p.path) {
733 impl_associated_types.insert(&t.ident, id);
741 let export = export_status(&trait_obj.attrs);
743 ExportStatus::Export|ExportStatus::NotImplementable => {},
744 ExportStatus::NoExport|ExportStatus::TestOnly => return,
747 // For cases where we have a concrete native object which implements a
748 // trait and need to return the C-mapped version of the trait, provide a
749 // From<> implementation which does all the work to ensure free is handled
750 // properly. This way we can call this method from deep in the
751 // type-conversion logic without actually knowing the concrete native type.
752 writeln!(w, "impl From<native{}> for crate::{} {{", ident, full_trait_path).unwrap();
753 writeln!(w, "\tfn from(obj: native{}) -> Self {{", ident).unwrap();
754 writeln!(w, "\t\tlet mut rust_obj = {} {{ inner: Box::into_raw(Box::new(obj)), is_owned: true }};", ident).unwrap();
755 writeln!(w, "\t\tlet mut ret = {}_as_{}(&rust_obj);", ident, trait_obj.ident).unwrap();
756 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();
757 writeln!(w, "\t\trust_obj.inner = std::ptr::null_mut();").unwrap();
758 writeln!(w, "\t\tret.free = Some({}_free_void);", ident).unwrap();
759 writeln!(w, "\t\tret\n\t}}\n}}").unwrap();
761 writeln!(w, "/// Constructs a new {} which calls the relevant methods on this_arg.", trait_obj.ident).unwrap();
762 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();
763 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_as_{}(this_arg: &{}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
764 writeln!(w, "\tcrate::{} {{", full_trait_path).unwrap();
765 writeln!(w, "\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
766 writeln!(w, "\t\tfree: None,").unwrap();
768 macro_rules! write_meth {
769 ($m: expr, $trait: expr, $indent: expr) => {
770 let trait_method = $trait.items.iter().filter_map(|item| {
771 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
772 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
773 match export_status(&trait_method.attrs) {
774 ExportStatus::Export => {},
775 ExportStatus::NoExport => {
776 write!(w, "{}\t\t//XXX: Need to export {}\n", $indent, $m.sig.ident).unwrap();
779 ExportStatus::TestOnly => continue,
780 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
783 let mut printed = false;
784 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
785 if let syn::Type::Reference(r) = &**rtype {
786 write!(w, "\n\t\t{}{}: ", $indent, $m.sig.ident).unwrap();
787 types.write_empty_rust_val(Some(&gen_types), w, &*r.elem);
788 writeln!(w, ",\n{}\t\tset_{}: Some({}_{}_set_{}),", $indent, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
793 write!(w, "{}\t\t{}: {}_{}_{},\n", $indent, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
797 for item in trait_obj.items.iter() {
799 syn::TraitItem::Method(m) => {
800 write_meth!(m, trait_obj, "");
805 let mut requires_clone = false;
806 walk_supertraits!(trait_obj, Some(&types), (
808 requires_clone = true;
809 writeln!(w, "\t\tcloned: Some({}_{}_cloned),", trait_obj.ident, ident).unwrap();
811 ("Sync", _) => {}, ("Send", _) => {},
812 ("std::marker::Sync", _) => {}, ("std::marker::Send", _) => {},
814 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
815 writeln!(w, "\t\t{}: crate::{} {{", t, s).unwrap();
816 writeln!(w, "\t\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
817 writeln!(w, "\t\t\tfree: None,").unwrap();
818 for item in supertrait_obj.items.iter() {
820 syn::TraitItem::Method(m) => {
821 write_meth!(m, supertrait_obj, "\t");
826 write!(w, "\t\t}},\n").unwrap();
828 write_trait_impl_field_assign(w, s, ident);
832 writeln!(w, "\t}}\n}}\n").unwrap();
834 macro_rules! impl_meth {
835 ($m: expr, $trait_path: expr, $trait: expr, $indent: expr) => {
836 let trait_method = $trait.items.iter().filter_map(|item| {
837 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
838 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
839 match export_status(&trait_method.attrs) {
840 ExportStatus::Export => {},
841 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
842 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
845 if let syn::ReturnType::Type(_, _) = &$m.sig.output {
846 writeln!(w, "#[must_use]").unwrap();
848 write!(w, "extern \"C\" fn {}_{}_{}(", ident, $trait.ident, $m.sig.ident).unwrap();
849 let mut meth_gen_types = gen_types.push_ctx();
850 assert!(meth_gen_types.learn_generics(&$m.sig.generics, types));
851 write_method_params(w, &$m.sig, "c_void", types, Some(&meth_gen_types), true, true);
852 write!(w, " {{\n\t").unwrap();
853 write_method_var_decl_body(w, &$m.sig, "", types, Some(&meth_gen_types), false);
854 let mut takes_self = false;
855 for inp in $m.sig.inputs.iter() {
856 if let syn::FnArg::Receiver(_) = inp {
861 let mut t_gen_args = String::new();
862 for (idx, _) in $trait.generics.params.iter().enumerate() {
863 if idx != 0 { t_gen_args += ", " };
867 write!(w, "<native{} as {}<{}>>::{}(unsafe {{ &mut *(this_arg as *mut native{}) }}, ", ident, $trait_path, t_gen_args, $m.sig.ident, ident).unwrap();
869 write!(w, "<native{} as {}<{}>>::{}(", ident, $trait_path, t_gen_args, $m.sig.ident).unwrap();
872 let mut real_type = "".to_string();
873 match &$m.sig.output {
874 syn::ReturnType::Type(_, rtype) => {
875 if let Some(mut remaining_path) = first_seg_self(&*rtype) {
876 if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
877 real_type = format!("{}", impl_associated_types.get(associated_seg).unwrap());
883 write_method_call_params(w, &$m.sig, "", types, Some(&meth_gen_types), &real_type, false);
884 write!(w, "\n}}\n").unwrap();
885 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
886 if let syn::Type::Reference(r) = &**rtype {
887 assert_eq!($m.sig.inputs.len(), 1); // Must only take self
888 writeln!(w, "extern \"C\" fn {}_{}_set_{}(trait_self_arg: &{}) {{", ident, $trait.ident, $m.sig.ident, $trait.ident).unwrap();
889 writeln!(w, "\t// This is a bit race-y in the general case, but for our specific use-cases today, we're safe").unwrap();
890 writeln!(w, "\t// Specifically, we must ensure that the first time we're called it can never be in parallel").unwrap();
891 write!(w, "\tif ").unwrap();
892 types.write_empty_rust_val_check(Some(&meth_gen_types), w, &*r.elem, &format!("trait_self_arg.{}", $m.sig.ident));
893 writeln!(w, " {{").unwrap();
894 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();
895 writeln!(w, "\t}}").unwrap();
896 writeln!(w, "}}").unwrap();
902 for item in i.items.iter() {
904 syn::ImplItem::Method(m) => {
905 impl_meth!(m, full_trait_path, trait_obj, "");
907 syn::ImplItem::Type(_) => {},
908 _ => unimplemented!(),
912 writeln!(w, "extern \"C\" fn {}_{}_cloned(new_obj: &mut crate::{}) {{", trait_obj.ident, ident, full_trait_path).unwrap();
913 writeln!(w, "\tnew_obj.this_arg = {}_clone_void(new_obj.this_arg);", ident).unwrap();
914 writeln!(w, "\tnew_obj.free = Some({}_free_void);", ident).unwrap();
915 walk_supertraits!(trait_obj, Some(&types), (
917 if types.crate_types.traits.get(s).is_some() {
918 assert!(!types.is_clonable(s)); // We don't currently support cloning with a clonable supertrait
919 writeln!(w, "\tnew_obj.{}.this_arg = new_obj.this_arg;", t).unwrap();
920 writeln!(w, "\tnew_obj.{}.free = None;", t).unwrap();
924 writeln!(w, "}}").unwrap();
926 write!(w, "\n").unwrap();
927 } else if path_matches_nongeneric(&trait_path.1, &["From"]) {
928 } else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
929 writeln!(w, "/// Creates a \"default\" {}. See struct and individual field documentaiton for details on which values are used.", ident).unwrap();
930 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
931 write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
932 write!(w, "}}\n").unwrap();
933 } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "PartialEq"]) {
934 } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "Eq"]) {
935 writeln!(w, "/// Checks if two {}s contain equal inner contents.", ident).unwrap();
936 writeln!(w, "/// This ignores pointers and is_owned flags and looks at the values in fields.").unwrap();
937 if types.c_type_has_inner_from_path(&resolved_path) {
938 writeln!(w, "/// Two objects with NULL inner values will be considered \"equal\" here.").unwrap();
940 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_eq(a: &{}, b: &{}) -> bool {{\n", ident, ident, ident).unwrap();
941 if types.c_type_has_inner_from_path(&resolved_path) {
942 write!(w, "\tif a.inner == b.inner {{ return true; }}\n").unwrap();
943 write!(w, "\tif a.inner.is_null() || b.inner.is_null() {{ return false; }}\n").unwrap();
947 let ref_type: syn::Type = syn::parse_quote!(&#path);
948 assert!(!types.write_to_c_conversion_new_var(w, &format_ident!("a"), &*i.self_ty, Some(&gen_types), false), "We don't support new var conversions when comparing equality");
950 write!(w, "\tif ").unwrap();
951 types.write_from_c_conversion_prefix(w, &ref_type, Some(&gen_types));
952 write!(w, "a").unwrap();
953 types.write_from_c_conversion_suffix(w, &ref_type, Some(&gen_types));
954 write!(w, " == ").unwrap();
955 types.write_from_c_conversion_prefix(w, &ref_type, Some(&gen_types));
956 write!(w, "b").unwrap();
957 types.write_from_c_conversion_suffix(w, &ref_type, Some(&gen_types));
959 writeln!(w, " {{ true }} else {{ false }}\n}}").unwrap();
960 } else if path_matches_nongeneric(&trait_path.1, &["core", "hash", "Hash"]) {
961 writeln!(w, "/// Checks if two {}s contain equal inner contents.", ident).unwrap();
962 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_hash(o: &{}) -> u64 {{\n", ident, ident).unwrap();
963 if types.c_type_has_inner_from_path(&resolved_path) {
964 write!(w, "\tif o.inner.is_null() {{ return 0; }}\n").unwrap();
968 let ref_type: syn::Type = syn::parse_quote!(&#path);
969 assert!(!types.write_to_c_conversion_new_var(w, &format_ident!("a"), &*i.self_ty, Some(&gen_types), false), "We don't support new var conversions when comparing equality");
971 writeln!(w, "\t// Note that we'd love to use std::collections::hash_map::DefaultHasher but it's not in core").unwrap();
972 writeln!(w, "\t#[allow(deprecated)]").unwrap();
973 writeln!(w, "\tlet mut hasher = core::hash::SipHasher::new();").unwrap();
974 write!(w, "\tstd::hash::Hash::hash(").unwrap();
975 types.write_from_c_conversion_prefix(w, &ref_type, Some(&gen_types));
976 write!(w, "o").unwrap();
977 types.write_from_c_conversion_suffix(w, &ref_type, Some(&gen_types));
978 writeln!(w, ", &mut hasher);").unwrap();
979 writeln!(w, "\tstd::hash::Hasher::finish(&hasher)\n}}").unwrap();
980 } else if (path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) || path_matches_nongeneric(&trait_path.1, &["Clone"])) &&
981 types.c_type_has_inner_from_path(&resolved_path) {
982 writeln!(w, "impl Clone for {} {{", ident).unwrap();
983 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
984 writeln!(w, "\t\tSelf {{").unwrap();
985 writeln!(w, "\t\t\tinner: if <*mut native{}>::is_null(self.inner) {{ std::ptr::null_mut() }} else {{", ident).unwrap();
986 writeln!(w, "\t\t\t\tBox::into_raw(Box::new(unsafe {{ &*self.inner }}.clone())) }},").unwrap();
987 writeln!(w, "\t\t\tis_owned: true,").unwrap();
988 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
989 writeln!(w, "#[allow(unused)]").unwrap();
990 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
991 writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", ident).unwrap();
992 writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", ident).unwrap();
993 writeln!(w, "}}").unwrap();
994 writeln!(w, "#[no_mangle]").unwrap();
995 writeln!(w, "/// Creates a copy of the {}", ident).unwrap();
996 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", ident, ident, ident).unwrap();
997 writeln!(w, "\torig.clone()").unwrap();
998 writeln!(w, "}}").unwrap();
999 } else if path_matches_nongeneric(&trait_path.1, &["FromStr"]) {
1000 if let Some(container) = types.get_c_mangled_container_type(
1001 vec![&*i.self_ty, &syn::Type::Tuple(syn::TypeTuple { paren_token: Default::default(), elems: syn::punctuated::Punctuated::new() })],
1002 Some(&gen_types), "Result") {
1003 writeln!(w, "#[no_mangle]").unwrap();
1004 writeln!(w, "/// Read a {} object from a string", ident).unwrap();
1005 writeln!(w, "pub extern \"C\" fn {}_from_str(s: crate::c_types::Str) -> {} {{", ident, container).unwrap();
1006 writeln!(w, "\tmatch {}::from_str(s.into_str()) {{", resolved_path).unwrap();
1007 writeln!(w, "\t\tOk(r) => {{").unwrap();
1008 let new_var = types.write_to_c_conversion_new_var(w, &format_ident!("r"), &*i.self_ty, Some(&gen_types), false);
1009 write!(w, "\t\t\tcrate::c_types::CResultTempl::ok(\n\t\t\t\t").unwrap();
1010 types.write_to_c_conversion_inline_prefix(w, &*i.self_ty, Some(&gen_types), false);
1011 write!(w, "{}r", if new_var { "local_" } else { "" }).unwrap();
1012 types.write_to_c_conversion_inline_suffix(w, &*i.self_ty, Some(&gen_types), false);
1013 writeln!(w, "\n\t\t\t)\n\t\t}},").unwrap();
1014 writeln!(w, "\t\tErr(e) => crate::c_types::CResultTempl::err(()),").unwrap();
1015 writeln!(w, "\t}}.into()\n}}").unwrap();
1017 } else if path_matches_nongeneric(&trait_path.1, &["Display"]) {
1018 writeln!(w, "#[no_mangle]").unwrap();
1019 writeln!(w, "/// Get the string representation of a {} object", ident).unwrap();
1020 writeln!(w, "pub extern \"C\" fn {}_to_str(o: &crate::{}) -> Str {{", ident, resolved_path).unwrap();
1022 let self_ty = &i.self_ty;
1023 let ref_type: syn::Type = syn::parse_quote!(&#self_ty);
1024 let new_var = types.write_from_c_conversion_new_var(w, &format_ident!("o"), &ref_type, Some(&gen_types));
1025 write!(w, "\tformat!(\"{{}}\", ").unwrap();
1026 types.write_from_c_conversion_prefix(w, &ref_type, Some(&gen_types));
1027 write!(w, "{}o", if new_var { "local_" } else { "" }).unwrap();
1028 types.write_from_c_conversion_suffix(w, &ref_type, Some(&gen_types));
1029 writeln!(w, ").into()").unwrap();
1031 writeln!(w, "}}").unwrap();
1033 //XXX: implement for other things like ToString
1034 // If we have no generics, try a manual implementation:
1035 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
1038 let declared_type = (*types.get_declared_type(&ident).unwrap()).clone();
1039 for item in i.items.iter() {
1041 syn::ImplItem::Method(m) => {
1042 if let syn::Visibility::Public(_) = m.vis {
1043 match export_status(&m.attrs) {
1044 ExportStatus::Export => {},
1045 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1046 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1048 if m.defaultness.is_some() { unimplemented!(); }
1049 writeln_docs(w, &m.attrs, "");
1050 if let syn::ReturnType::Type(_, _) = &m.sig.output {
1051 writeln!(w, "#[must_use]").unwrap();
1053 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_{}(", ident, m.sig.ident).unwrap();
1054 let ret_type = match &declared_type {
1055 DeclType::MirroredEnum => format!("{}", ident),
1056 DeclType::StructImported => format!("{}", ident),
1057 _ => unimplemented!(),
1059 let mut meth_gen_types = gen_types.push_ctx();
1060 assert!(meth_gen_types.learn_generics(&m.sig.generics, types));
1061 write_method_params(w, &m.sig, &ret_type, types, Some(&meth_gen_types), false, true);
1062 write!(w, " {{\n\t").unwrap();
1063 write_method_var_decl_body(w, &m.sig, "", types, Some(&meth_gen_types), false);
1064 let mut takes_self = false;
1065 let mut takes_mut_self = false;
1066 let mut takes_owned_self = false;
1067 for inp in m.sig.inputs.iter() {
1068 if let syn::FnArg::Receiver(r) = inp {
1070 if r.mutability.is_some() { takes_mut_self = true; }
1071 if r.reference.is_none() { takes_owned_self = true; }
1074 if !takes_mut_self && !takes_self {
1075 write!(w, "{}::{}(", resolved_path, m.sig.ident).unwrap();
1077 match &declared_type {
1078 DeclType::MirroredEnum => write!(w, "this_arg.to_native().{}(", m.sig.ident).unwrap(),
1079 DeclType::StructImported => {
1080 if takes_owned_self {
1081 write!(w, "(*unsafe {{ Box::from_raw(this_arg.take_inner()) }}).{}(", m.sig.ident).unwrap();
1082 } else if takes_mut_self {
1083 write!(w, "unsafe {{ &mut (*(this_arg.inner as *mut native{})) }}.{}(", ident, m.sig.ident).unwrap();
1085 write!(w, "unsafe {{ &*this_arg.inner }}.{}(", m.sig.ident).unwrap();
1088 _ => unimplemented!(),
1091 write_method_call_params(w, &m.sig, "", types, Some(&meth_gen_types), &ret_type, false);
1092 writeln!(w, "\n}}\n").unwrap();
1099 } else if let Some(resolved_path) = types.maybe_resolve_ident(&ident) {
1100 if let Some(aliases) = types.crate_types.reverse_alias_map.get(&resolved_path).cloned() {
1101 'alias_impls: for (alias, arguments) in aliases {
1102 let alias_resolved = types.resolve_path(&alias, None);
1103 for (idx, gen) in i.generics.params.iter().enumerate() {
1105 syn::GenericParam::Type(type_param) => {
1106 'bounds_check: for bound in type_param.bounds.iter() {
1107 if let syn::TypeParamBound::Trait(trait_bound) = bound {
1108 if let syn::PathArguments::AngleBracketed(ref t) = &arguments {
1109 assert!(idx < t.args.len());
1110 if let syn::GenericArgument::Type(syn::Type::Path(p)) = &t.args[idx] {
1111 let generic_arg = types.resolve_path(&p.path, None);
1112 let generic_bound = types.resolve_path(&trait_bound.path, None);
1113 if let Some(traits_impld) = types.crate_types.trait_impls.get(&generic_arg) {
1114 for trait_impld in traits_impld {
1115 if *trait_impld == generic_bound { continue 'bounds_check; }
1117 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1118 continue 'alias_impls;
1120 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1121 continue 'alias_impls;
1123 } else { unimplemented!(); }
1124 } else { unimplemented!(); }
1125 } else { unimplemented!(); }
1128 syn::GenericParam::Lifetime(_) => {},
1129 syn::GenericParam::Const(_) => unimplemented!(),
1132 let aliased_impl = syn::ItemImpl {
1133 attrs: i.attrs.clone(),
1134 brace_token: syn::token::Brace(Span::call_site()),
1136 generics: syn::Generics {
1138 params: syn::punctuated::Punctuated::new(),
1142 impl_token: syn::Token![impl](Span::call_site()),
1143 items: i.items.clone(),
1144 self_ty: Box::new(syn::Type::Path(syn::TypePath { qself: None, path: alias.clone() })),
1145 trait_: i.trait_.clone(),
1148 writeln_impl(w, &aliased_impl, types);
1151 eprintln!("Not implementing anything for {} due to it being marked not exported", ident);
1154 eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub)", ident);
1161 /// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
1162 /// is unitary), we generate an equivalent enum with all types replaced with their C mapped
1163 /// versions followed by conversion functions which map between the Rust version and the C mapped
1165 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) {
1166 match export_status(&e.attrs) {
1167 ExportStatus::Export => {},
1168 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1169 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1172 if is_enum_opaque(e) {
1173 eprintln!("Skipping enum {} as it contains non-unit fields", e.ident);
1174 writeln_opaque(w, &e.ident, &format!("{}", e.ident), &e.generics, &e.attrs, types, extra_headers, cpp_headers);
1177 writeln_docs(w, &e.attrs, "");
1179 let mut gen_types = GenericTypes::new(None);
1180 assert!(gen_types.learn_generics(&e.generics, types));
1182 let mut needs_free = false;
1184 writeln!(w, "#[must_use]\n#[derive(Clone)]\n#[repr(C)]\npub enum {} {{", e.ident).unwrap();
1185 for var in e.variants.iter() {
1186 assert_eq!(export_status(&var.attrs), ExportStatus::Export); // We can't partially-export a mirrored enum
1187 writeln_docs(w, &var.attrs, "\t");
1188 write!(w, "\t{}", var.ident).unwrap();
1189 if let syn::Fields::Named(fields) = &var.fields {
1191 writeln!(w, " {{").unwrap();
1192 for field in fields.named.iter() {
1193 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1194 writeln_docs(w, &field.attrs, "\t\t");
1195 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1196 types.write_c_type(w, &field.ty, Some(&gen_types), false);
1197 writeln!(w, ",").unwrap();
1199 write!(w, "\t}}").unwrap();
1200 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1201 let mut empty_tuple_variant = false;
1202 if fields.unnamed.len() == 1 {
1203 let mut empty_check = Vec::new();
1204 types.write_c_type(&mut empty_check, &fields.unnamed[0].ty, Some(&gen_types), false);
1205 if empty_check.is_empty() {
1206 empty_tuple_variant = true;
1209 if !empty_tuple_variant {
1211 write!(w, "(").unwrap();
1212 for (idx, field) in fields.unnamed.iter().enumerate() {
1213 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1214 types.write_c_type(w, &field.ty, Some(&gen_types), false);
1215 if idx != fields.unnamed.len() - 1 {
1216 write!(w, ",").unwrap();
1219 write!(w, ")").unwrap();
1222 if var.discriminant.is_some() { unimplemented!(); }
1223 writeln!(w, ",").unwrap();
1225 writeln!(w, "}}\nuse {}::{} as native{};\nimpl {} {{", types.module_path, e.ident, e.ident, e.ident).unwrap();
1227 macro_rules! write_conv {
1228 ($fn_sig: expr, $to_c: expr, $ref: expr) => {
1229 writeln!(w, "\t#[allow(unused)]\n\tpub(crate) fn {} {{\n\t\tmatch {} {{", $fn_sig, if $to_c { "native" } else { "self" }).unwrap();
1230 for var in e.variants.iter() {
1231 write!(w, "\t\t\t{}{}::{} ", if $to_c { "native" } else { "" }, e.ident, var.ident).unwrap();
1232 let mut empty_tuple_variant = false;
1233 if let syn::Fields::Named(fields) = &var.fields {
1234 write!(w, "{{").unwrap();
1235 for field in fields.named.iter() {
1236 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1237 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, field.ident.as_ref().unwrap()).unwrap();
1239 write!(w, "}} ").unwrap();
1240 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1241 if fields.unnamed.len() == 1 {
1242 let mut empty_check = Vec::new();
1243 types.write_c_type(&mut empty_check, &fields.unnamed[0].ty, Some(&gen_types), false);
1244 if empty_check.is_empty() {
1245 empty_tuple_variant = true;
1248 if !empty_tuple_variant || $to_c {
1249 write!(w, "(").unwrap();
1250 for (idx, field) in fields.unnamed.iter().enumerate() {
1251 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1252 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, ('a' as u8 + idx as u8) as char).unwrap();
1254 write!(w, ") ").unwrap();
1257 write!(w, "=>").unwrap();
1259 macro_rules! handle_field_a {
1260 ($field: expr, $field_ident: expr) => { {
1261 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1262 let mut sink = ::std::io::sink();
1263 let mut out: &mut dyn std::io::Write = if $ref { &mut sink } else { w };
1264 let new_var = if $to_c {
1265 types.write_to_c_conversion_new_var(&mut out, $field_ident, &$field.ty, Some(&gen_types), false)
1267 types.write_from_c_conversion_new_var(&mut out, $field_ident, &$field.ty, Some(&gen_types))
1269 if $ref || new_var {
1271 write!(w, "let mut {}_nonref = (*{}).clone();\n\t\t\t\t", $field_ident, $field_ident).unwrap();
1273 let nonref_ident = format_ident!("{}_nonref", $field_ident);
1275 types.write_to_c_conversion_new_var(w, &nonref_ident, &$field.ty, Some(&gen_types), false);
1277 types.write_from_c_conversion_new_var(w, &nonref_ident, &$field.ty, Some(&gen_types));
1279 write!(w, "\n\t\t\t\t").unwrap();
1282 write!(w, "\n\t\t\t\t").unwrap();
1287 if let syn::Fields::Named(fields) = &var.fields {
1288 write!(w, " {{\n\t\t\t\t").unwrap();
1289 for field in fields.named.iter() {
1290 handle_field_a!(field, field.ident.as_ref().unwrap());
1292 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1293 write!(w, " {{\n\t\t\t\t").unwrap();
1294 for (idx, field) in fields.unnamed.iter().enumerate() {
1295 if !empty_tuple_variant {
1296 handle_field_a!(field, &format_ident!("{}", ('a' as u8 + idx as u8) as char));
1299 } else { write!(w, " ").unwrap(); }
1301 write!(w, "{}{}::{}", if $to_c { "" } else { "native" }, e.ident, var.ident).unwrap();
1303 macro_rules! handle_field_b {
1304 ($field: expr, $field_ident: expr) => { {
1305 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1307 types.write_to_c_conversion_inline_prefix(w, &$field.ty, Some(&gen_types), false);
1309 types.write_from_c_conversion_prefix(w, &$field.ty, Some(&gen_types));
1311 write!(w, "{}{}", $field_ident,
1312 if $ref { "_nonref" } else { "" }).unwrap();
1314 types.write_to_c_conversion_inline_suffix(w, &$field.ty, Some(&gen_types), false);
1316 types.write_from_c_conversion_suffix(w, &$field.ty, Some(&gen_types));
1318 write!(w, ",").unwrap();
1322 if let syn::Fields::Named(fields) = &var.fields {
1323 write!(w, " {{").unwrap();
1324 for field in fields.named.iter() {
1325 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1326 write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1327 handle_field_b!(field, field.ident.as_ref().unwrap());
1329 writeln!(w, "\n\t\t\t\t}}").unwrap();
1330 write!(w, "\t\t\t}}").unwrap();
1331 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1332 if !empty_tuple_variant || !$to_c {
1333 write!(w, " (").unwrap();
1334 for (idx, field) in fields.unnamed.iter().enumerate() {
1335 write!(w, "\n\t\t\t\t\t").unwrap();
1336 handle_field_b!(field, &format_ident!("{}", ('a' as u8 + idx as u8) as char));
1338 writeln!(w, "\n\t\t\t\t)").unwrap();
1340 write!(w, "\t\t\t}}").unwrap();
1342 writeln!(w, ",").unwrap();
1344 writeln!(w, "\t\t}}\n\t}}").unwrap();
1348 write_conv!(format!("to_native(&self) -> native{}", e.ident), false, true);
1349 write_conv!(format!("into_native(self) -> native{}", e.ident), false, false);
1350 write_conv!(format!("from_native(native: &native{}) -> Self", e.ident), true, true);
1351 write_conv!(format!("native_into(native: native{}) -> Self", e.ident), true, false);
1352 writeln!(w, "}}").unwrap();
1355 writeln!(w, "/// Frees any resources used by the {}", e.ident).unwrap();
1356 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", e.ident, e.ident).unwrap();
1358 writeln!(w, "/// Creates a copy of the {}", e.ident).unwrap();
1359 writeln!(w, "#[no_mangle]").unwrap();
1360 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
1361 writeln!(w, "\torig.clone()").unwrap();
1362 writeln!(w, "}}").unwrap();
1363 write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free);
1366 fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &mut TypeResolver<'b, 'a>) {
1367 match export_status(&f.attrs) {
1368 ExportStatus::Export => {},
1369 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1370 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1372 writeln_docs(w, &f.attrs, "");
1374 let mut gen_types = GenericTypes::new(None);
1375 if !gen_types.learn_generics(&f.sig.generics, types) { return; }
1377 write!(w, "#[no_mangle]\npub extern \"C\" fn {}(", f.sig.ident).unwrap();
1378 write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
1379 write!(w, " {{\n\t").unwrap();
1380 write_method_var_decl_body(w, &f.sig, "", types, Some(&gen_types), false);
1381 write!(w, "{}::{}(", types.module_path, f.sig.ident).unwrap();
1382 write_method_call_params(w, &f.sig, "", types, Some(&gen_types), "", false);
1383 writeln!(w, "\n}}\n").unwrap();
1386 // ********************************
1387 // *** File/Crate Walking Logic ***
1388 // ********************************
1390 fn convert_priv_mod<'a, 'b: 'a, W: std::io::Write>(w: &mut W, libast: &'b FullLibraryAST, crate_types: &CrateTypes<'b>, out_dir: &str, mod_path: &str, module: &'b syn::ItemMod) {
1391 // We want to ignore all items declared in this module (as they are not pub), but we still need
1392 // to give the ImportResolver any use statements, so we copy them here.
1393 let mut use_items = Vec::new();
1394 for item in module.content.as_ref().unwrap().1.iter() {
1395 if let syn::Item::Use(_) = item {
1396 use_items.push(item);
1399 let import_resolver = ImportResolver::from_borrowed_items(mod_path.splitn(2, "::").next().unwrap(), &libast.dependencies, mod_path, &use_items);
1400 let mut types = TypeResolver::new(mod_path, import_resolver, crate_types);
1402 writeln!(w, "mod {} {{\n{}", module.ident, DEFAULT_IMPORTS).unwrap();
1403 for item in module.content.as_ref().unwrap().1.iter() {
1405 syn::Item::Mod(m) => convert_priv_mod(w, libast, crate_types, out_dir, &format!("{}::{}", mod_path, module.ident), m),
1406 syn::Item::Impl(i) => {
1407 if let &syn::Type::Path(ref p) = &*i.self_ty {
1408 if p.path.get_ident().is_some() {
1409 writeln_impl(w, i, &mut types);
1416 writeln!(w, "}}").unwrap();
1419 /// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
1420 /// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
1421 /// at `module` from C.
1422 fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &CrateTypes<'a>, out_dir: &str, header_file: &mut File, cpp_header_file: &mut File) {
1423 for (module, astmod) in libast.modules.iter() {
1424 let orig_crate = module.splitn(2, "::").next().unwrap();
1425 let ASTModule { ref attrs, ref items, ref submods } = astmod;
1426 assert_eq!(export_status(&attrs), ExportStatus::Export);
1428 let new_file_path = if submods.is_empty() {
1429 format!("{}/{}.rs", out_dir, module.replace("::", "/"))
1430 } else if module != "" {
1431 format!("{}/{}/mod.rs", out_dir, module.replace("::", "/"))
1433 format!("{}/lib.rs", out_dir)
1435 let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
1436 let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1437 .open(new_file_path).expect("Unable to open new src file");
1439 writeln!(out, "// This file is Copyright its original authors, visible in version control").unwrap();
1440 writeln!(out, "// history and in the source files from which this was generated.").unwrap();
1441 writeln!(out, "//").unwrap();
1442 writeln!(out, "// This file is licensed under the license available in the LICENSE or LICENSE.md").unwrap();
1443 writeln!(out, "// file in the root of this repository or, if no such file exists, the same").unwrap();
1444 writeln!(out, "// license as that which applies to the original source files from which this").unwrap();
1445 writeln!(out, "// source was automatically generated.").unwrap();
1446 writeln!(out, "").unwrap();
1448 writeln_docs(&mut out, &attrs, "");
1451 // Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
1452 // and bitcoin hand-written modules.
1453 writeln!(out, "//! C Bindings").unwrap();
1454 writeln!(out, "#![allow(unknown_lints)]").unwrap();
1455 writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
1456 writeln!(out, "#![allow(non_snake_case)]").unwrap();
1457 writeln!(out, "#![allow(unused_imports)]").unwrap();
1458 writeln!(out, "#![allow(unused_variables)]").unwrap();
1459 writeln!(out, "#![allow(unused_mut)]").unwrap();
1460 writeln!(out, "#![allow(unused_parens)]").unwrap();
1461 writeln!(out, "#![allow(unused_unsafe)]").unwrap();
1462 writeln!(out, "#![allow(unused_braces)]").unwrap();
1463 // TODO: We need to map deny(missing_docs) in the source crate(s)
1464 //writeln!(out, "#![deny(missing_docs)]").unwrap();
1465 writeln!(out, "pub mod version;").unwrap();
1466 writeln!(out, "pub mod c_types;").unwrap();
1467 writeln!(out, "pub mod bitcoin;").unwrap();
1469 writeln!(out, "{}", DEFAULT_IMPORTS).unwrap();
1473 writeln!(out, "pub mod {};", m).unwrap();
1476 eprintln!("Converting {} entries...", module);
1478 let import_resolver = ImportResolver::new(orig_crate, &libast.dependencies, module, items);
1479 let mut type_resolver = TypeResolver::new(module, import_resolver, crate_types);
1481 for item in items.iter() {
1483 syn::Item::Use(_) => {}, // Handled above
1484 syn::Item::Static(_) => {},
1485 syn::Item::Enum(e) => {
1486 if let syn::Visibility::Public(_) = e.vis {
1487 writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
1490 syn::Item::Impl(i) => {
1491 writeln_impl(&mut out, &i, &mut type_resolver);
1493 syn::Item::Struct(s) => {
1494 if let syn::Visibility::Public(_) = s.vis {
1495 writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
1498 syn::Item::Trait(t) => {
1499 if let syn::Visibility::Public(_) = t.vis {
1500 writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
1503 syn::Item::Mod(m) => {
1504 convert_priv_mod(&mut out, libast, crate_types, out_dir, &format!("{}::{}", module, m.ident), m);
1506 syn::Item::Const(c) => {
1507 // Re-export any primitive-type constants.
1508 if let syn::Visibility::Public(_) = c.vis {
1509 if let syn::Type::Path(p) = &*c.ty {
1510 let resolved_path = type_resolver.resolve_path(&p.path, None);
1511 if type_resolver.is_primitive(&resolved_path) {
1512 writeln_docs(&mut out, &c.attrs, "");
1513 writeln!(out, "\n#[no_mangle]").unwrap();
1514 writeln!(out, "pub static {}: {} = {}::{};", c.ident, resolved_path, module, c.ident).unwrap();
1519 syn::Item::Type(t) => {
1520 if let syn::Visibility::Public(_) = t.vis {
1521 match export_status(&t.attrs) {
1522 ExportStatus::Export => {},
1523 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1524 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1527 let mut process_alias = true;
1528 for tok in t.generics.params.iter() {
1529 if let syn::GenericParam::Lifetime(_) = tok {}
1530 else { process_alias = false; }
1534 syn::Type::Path(_) =>
1535 writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &t.generics, &t.attrs, &type_resolver, header_file, cpp_header_file),
1541 syn::Item::Fn(f) => {
1542 if let syn::Visibility::Public(_) = f.vis {
1543 writeln_fn(&mut out, &f, &mut type_resolver);
1546 syn::Item::Macro(_) => {},
1547 syn::Item::Verbatim(_) => {},
1548 syn::Item::ExternCrate(_) => {},
1549 _ => unimplemented!(),
1553 out.flush().unwrap();
1557 fn walk_private_mod<'a>(ast_storage: &'a FullLibraryAST, orig_crate: &str, module: String, items: &'a syn::ItemMod, crate_types: &mut CrateTypes<'a>) {
1558 let import_resolver = ImportResolver::new(orig_crate, &ast_storage.dependencies, &module, &items.content.as_ref().unwrap().1);
1559 for item in items.content.as_ref().unwrap().1.iter() {
1561 syn::Item::Mod(m) => walk_private_mod(ast_storage, orig_crate, format!("{}::{}", module, m.ident), m, crate_types),
1562 syn::Item::Impl(i) => {
1563 if let &syn::Type::Path(ref p) = &*i.self_ty {
1564 if let Some(trait_path) = i.trait_.as_ref() {
1565 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1566 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1567 match crate_types.trait_impls.entry(sp) {
1568 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1569 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1581 /// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
1582 fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
1583 for (module, astmod) in ast_storage.modules.iter() {
1584 let ASTModule { ref attrs, ref items, submods: _ } = astmod;
1585 assert_eq!(export_status(&attrs), ExportStatus::Export);
1586 let orig_crate = module.splitn(2, "::").next().unwrap();
1587 let import_resolver = ImportResolver::new(orig_crate, &ast_storage.dependencies, module, items);
1589 for item in items.iter() {
1591 syn::Item::Struct(s) => {
1592 if let syn::Visibility::Public(_) = s.vis {
1593 match export_status(&s.attrs) {
1594 ExportStatus::Export => {},
1595 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1596 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1598 let struct_path = format!("{}::{}", module, s.ident);
1599 crate_types.opaques.insert(struct_path, &s.ident);
1602 syn::Item::Trait(t) => {
1603 if let syn::Visibility::Public(_) = t.vis {
1604 match export_status(&t.attrs) {
1605 ExportStatus::Export|ExportStatus::NotImplementable => {},
1606 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1608 let trait_path = format!("{}::{}", module, t.ident);
1609 walk_supertraits!(t, None, (
1611 crate_types.set_clonable("crate::".to_owned() + &trait_path);
1615 crate_types.traits.insert(trait_path, &t);
1618 syn::Item::Type(t) => {
1619 if let syn::Visibility::Public(_) = t.vis {
1620 match export_status(&t.attrs) {
1621 ExportStatus::Export => {},
1622 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1623 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1625 let type_path = format!("{}::{}", module, t.ident);
1626 let mut process_alias = true;
1627 for tok in t.generics.params.iter() {
1628 if let syn::GenericParam::Lifetime(_) = tok {}
1629 else { process_alias = false; }
1633 syn::Type::Path(p) => {
1634 let t_ident = &t.ident;
1636 // If its a path with no generics, assume we don't map the aliased type and map it opaque
1637 let path_obj = parse_quote!(#t_ident);
1638 let args_obj = p.path.segments.last().unwrap().arguments.clone();
1639 match crate_types.reverse_alias_map.entry(import_resolver.maybe_resolve_path(&p.path, None).unwrap()) {
1640 hash_map::Entry::Occupied(mut e) => { e.get_mut().push((path_obj, args_obj)); },
1641 hash_map::Entry::Vacant(e) => { e.insert(vec![(path_obj, args_obj)]); },
1644 crate_types.opaques.insert(type_path, t_ident);
1647 crate_types.type_aliases.insert(type_path, import_resolver.resolve_imported_refs((*t.ty).clone()));
1653 syn::Item::Enum(e) if is_enum_opaque(e) => {
1654 if let syn::Visibility::Public(_) = e.vis {
1655 match export_status(&e.attrs) {
1656 ExportStatus::Export => {},
1657 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1658 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1660 let enum_path = format!("{}::{}", module, e.ident);
1661 crate_types.opaques.insert(enum_path, &e.ident);
1664 syn::Item::Enum(e) => {
1665 if let syn::Visibility::Public(_) = e.vis {
1666 match export_status(&e.attrs) {
1667 ExportStatus::Export => {},
1668 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1669 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1671 let enum_path = format!("{}::{}", module, e.ident);
1672 crate_types.mirrored_enums.insert(enum_path, &e);
1675 syn::Item::Impl(i) => {
1676 if let &syn::Type::Path(ref p) = &*i.self_ty {
1677 if let Some(trait_path) = i.trait_.as_ref() {
1678 if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) {
1679 if let Some(full_path) = import_resolver.maybe_resolve_path(&p.path, None) {
1680 crate_types.set_clonable("crate::".to_owned() + &full_path);
1683 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1684 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1685 match crate_types.trait_impls.entry(sp) {
1686 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1687 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1694 syn::Item::Mod(m) => walk_private_mod(ast_storage, orig_crate, format!("{}::{}", module, m.ident), m, crate_types),
1702 let args: Vec<String> = env::args().collect();
1703 if args.len() != 5 {
1704 eprintln!("Usage: target/dir derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
1708 let mut derived_templates = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1709 .open(&args[2]).expect("Unable to open new header file");
1710 let mut header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1711 .open(&args[3]).expect("Unable to open new header file");
1712 let mut cpp_header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1713 .open(&args[4]).expect("Unable to open new header file");
1715 writeln!(header_file, "#if defined(__GNUC__)").unwrap();
1716 writeln!(header_file, "#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
1717 writeln!(header_file, "#define MUST_USE_RES __attribute__((warn_unused_result))").unwrap();
1718 writeln!(header_file, "#else").unwrap();
1719 writeln!(header_file, "#define MUST_USE_STRUCT").unwrap();
1720 writeln!(header_file, "#define MUST_USE_RES").unwrap();
1721 writeln!(header_file, "#endif").unwrap();
1722 writeln!(header_file, "#if defined(__clang__)").unwrap();
1723 writeln!(header_file, "#define NONNULL_PTR _Nonnull").unwrap();
1724 writeln!(header_file, "#else").unwrap();
1725 writeln!(header_file, "#define NONNULL_PTR").unwrap();
1726 writeln!(header_file, "#endif").unwrap();
1727 writeln!(cpp_header_file, "#include <string.h>\nnamespace LDK {{").unwrap();
1729 // First parse the full crate's ASTs, caching them so that we can hold references to the AST
1730 // objects in other datastructures:
1731 let mut lib_src = String::new();
1732 std::io::stdin().lock().read_to_string(&mut lib_src).unwrap();
1733 let lib_syntax = syn::parse_file(&lib_src).expect("Unable to parse file");
1734 let libast = FullLibraryAST::load_lib(lib_syntax);
1736 // ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
1737 // when parsing other file ASTs...
1738 let mut libtypes = CrateTypes::new(&mut derived_templates, &libast);
1739 walk_ast(&libast, &mut libtypes);
1741 // ... finally, do the actual file conversion/mapping, writing out types as we go.
1742 convert_file(&libast, &libtypes, &args[1], &mut header_file, &mut cpp_header_file);
1744 // For container templates which we created while walking the crate, make sure we add C++
1745 // mapped types so that C++ users can utilize the auto-destructors available.
1746 for (ty, has_destructor) in libtypes.templates_defined.borrow().iter() {
1747 write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor);
1749 writeln!(cpp_header_file, "}}").unwrap();
1751 header_file.flush().unwrap();
1752 cpp_header_file.flush().unwrap();
1753 derived_templates.flush().unwrap();