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) {
167 "lightning::util::ser::Writeable" => {
168 writeln!(w, "impl {} for {} {{", trait_path, for_obj).unwrap();
169 writeln!(w, "\tfn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {{").unwrap();
170 writeln!(w, "\t\tlet vec = (self.write)(self.this_arg);").unwrap();
171 writeln!(w, "\t\tw.write_all(vec.as_slice())").unwrap();
172 writeln!(w, "\t}}\n}}").unwrap();
178 // *******************************
179 // *** Per-Type Printing Logic ***
180 // *******************************
182 macro_rules! walk_supertraits { ($t: expr, $types: expr, ($( $($pat: pat)|* => $e: expr),*) ) => { {
183 if $t.colon_token.is_some() {
184 for st in $t.supertraits.iter() {
186 syn::TypeParamBound::Trait(supertrait) => {
187 if supertrait.paren_token.is_some() || supertrait.lifetimes.is_some() {
190 // First try to resolve path to find in-crate traits, but if that doesn't work
191 // assume its a prelude trait (eg Clone, etc) and just use the single ident.
192 let types_opt: Option<&TypeResolver> = $types;
193 if let Some(types) = types_opt {
194 if let Some(path) = types.maybe_resolve_path(&supertrait.path, None) {
195 match (&path as &str, &supertrait.path.segments.iter().last().unwrap().ident) {
196 $( $($pat)|* => $e, )*
201 if let Some(ident) = supertrait.path.get_ident() {
202 match (&format!("{}", ident) as &str, &ident) {
203 $( $($pat)|* => $e, )*
205 } else if types_opt.is_some() {
206 panic!("Supertrait unresolvable and not single-ident");
209 syn::TypeParamBound::Lifetime(_) => unimplemented!(),
215 macro_rules! get_module_type_resolver {
216 ($module: expr, $crate_libs: expr, $crate_types: expr) => { {
217 let module: &str = &$module;
218 let mut module_iter = module.rsplitn(2, "::");
219 module_iter.next().unwrap();
220 let module = module_iter.next().unwrap();
221 let imports = ImportResolver::new(module.splitn(2, "::").next().unwrap(), &$crate_types.lib_ast.dependencies,
222 module, &$crate_types.lib_ast.modules.get(module).unwrap().items);
223 TypeResolver::new(module, imports, $crate_types)
227 /// Prints a C-mapped trait object containing a void pointer and a jump table for each function in
228 /// the original trait.
229 /// Implements the native Rust trait and relevant parent traits for the new C-mapped trait.
231 /// Finally, implements Deref<MappedTrait> for MappedTrait which allows its use in types which need
232 /// a concrete Deref to the Rust trait.
233 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) {
234 let trait_name = format!("{}", t.ident);
236 match export_status(&t.attrs) {
237 ExportStatus::Export => { implementable = true; }
238 ExportStatus::NotImplementable => { implementable = false; },
239 ExportStatus::NoExport|ExportStatus::TestOnly => return,
241 writeln_docs(w, &t.attrs, "");
243 let mut gen_types = GenericTypes::new(None);
245 // Add functions which may be required for supertrait implementations.
246 // Due to borrow checker limitations, we only support one in-crate supertrait here.
248 let supertrait_resolver;
249 walk_supertraits!(t, Some(&types), (
251 if let Some(supertrait) = types.crate_types.traits.get(s) {
252 supertrait_name = s.to_string();
253 supertrait_resolver = get_module_type_resolver!(supertrait_name, types.crate_libs, types.crate_types);
254 gen_types.learn_associated_types(&supertrait, &supertrait_resolver);
260 assert!(gen_types.learn_generics(&t.generics, types));
261 gen_types.learn_associated_types(&t, types);
263 writeln!(w, "#[repr(C)]\npub struct {} {{", trait_name).unwrap();
264 writeln!(w, "\t/// An opaque pointer which is passed to your function implementations as an argument.").unwrap();
265 writeln!(w, "\t/// This has no meaning in the LDK, and can be NULL or any other value.").unwrap();
266 writeln!(w, "\tpub this_arg: *mut c_void,").unwrap();
267 // We store every field's (name, Option<clone_fn>, docs) except this_arg, used in Clone generation
268 // docs is only set if its a function which should be callable on the object itself in C++
269 let mut generated_fields = Vec::new();
270 for item in t.items.iter() {
272 &syn::TraitItem::Method(ref m) => {
273 match export_status(&m.attrs) {
274 ExportStatus::NoExport => {
275 // NoExport in this context means we'll hit an unimplemented!() at runtime,
279 ExportStatus::Export => {},
280 ExportStatus::TestOnly => continue,
281 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
283 if m.default.is_some() { unimplemented!(); }
285 let mut meth_gen_types = gen_types.push_ctx();
286 assert!(meth_gen_types.learn_generics(&m.sig.generics, types));
288 writeln_fn_docs(w, &m.attrs, "\t", types, Some(&meth_gen_types), m.sig.inputs.iter(), &m.sig.output);
290 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
291 if let syn::Type::Reference(r) = &**rtype {
292 // We have to do quite a dance for trait functions which return references
293 // - they ultimately require us to have a native Rust object stored inside
294 // our concrete trait to return a reference to. However, users may wish to
295 // update the value to be returned each time the function is called (or, to
296 // make C copies of Rust impls equivalent, we have to be able to).
298 // Thus, we store a copy of the C-mapped type (which is just a pointer to
299 // the Rust type and a flag to indicate whether deallocation needs to
300 // happen) as well as provide an Option<>al function pointer which is
301 // called when the trait method is called which allows updating on the fly.
302 write!(w, "\tpub {}: ", m.sig.ident).unwrap();
303 generated_fields.push((format!("{}", m.sig.ident), None, None));
304 types.write_c_type(w, &*r.elem, Some(&meth_gen_types), false);
305 writeln!(w, ",").unwrap();
306 writeln!(w, "\t/// Fill in the {} field as a reference to it will be given to Rust after this returns", m.sig.ident).unwrap();
307 writeln!(w, "\t/// Note that this takes a pointer to this object, not the this_ptr like other methods do").unwrap();
308 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();
309 writeln!(w, "\tpub set_{}: Option<extern \"C\" fn(&{})>,", m.sig.ident, trait_name).unwrap();
310 generated_fields.push((format!("set_{}", m.sig.ident), None, None));
311 // Note that cbindgen will now generate
312 // typedef struct Thing {..., set_thing: (const struct Thing*), ...} Thing;
313 // which does not compile since Thing is not defined before it is used.
314 writeln!(extra_headers, "struct LDK{};", trait_name).unwrap();
317 // Sadly, this currently doesn't do what we want, but it should be easy to get
318 // cbindgen to support it. See https://github.com/eqrion/cbindgen/issues/531
319 writeln!(w, "\t#[must_use]").unwrap();
322 let mut cpp_docs = Vec::new();
323 writeln_fn_docs(&mut cpp_docs, &m.attrs, "\t * ", types, Some(&meth_gen_types), m.sig.inputs.iter(), &m.sig.output);
324 let docs_string = "\t/**\n".to_owned() + &String::from_utf8(cpp_docs).unwrap().replace("///", "") + "\t */\n";
326 write!(w, "\tpub {}: extern \"C\" fn (", m.sig.ident).unwrap();
327 generated_fields.push((format!("{}", m.sig.ident), None, Some(docs_string)));
328 write_method_params(w, &m.sig, "c_void", types, Some(&meth_gen_types), true, false);
329 writeln!(w, ",").unwrap();
331 &syn::TraitItem::Type(_) => {},
332 _ => unimplemented!(),
335 // Add functions which may be required for supertrait implementations.
336 walk_supertraits!(t, Some(&types), (
338 writeln!(w, "\t/// Called, if set, after this {} has been cloned into a duplicate object.", trait_name).unwrap();
339 writeln!(w, "\t/// The new {} is provided, and should be mutated as needed to perform a", trait_name).unwrap();
340 writeln!(w, "\t/// deep copy of the object pointed to by this_arg or avoid any double-freeing.").unwrap();
341 writeln!(w, "\tpub cloned: Option<extern \"C\" fn (new_{}: &mut {})>,", trait_name, trait_name).unwrap();
342 generated_fields.push(("cloned".to_owned(), None, None));
344 ("std::cmp::Eq", _)|("core::cmp::Eq", _) => {
345 let eq_docs = "Checks if two objects are equal given this object's this_arg pointer and another object.";
346 writeln!(w, "\t/// {}", eq_docs).unwrap();
347 writeln!(w, "\tpub eq: extern \"C\" fn (this_arg: *const c_void, other_arg: &{}) -> bool,", trait_name).unwrap();
348 generated_fields.push(("eq".to_owned(), None, Some(format!("\t/** {} */\n", eq_docs))));
350 ("std::hash::Hash", _)|("core::hash::Hash", _) => {
351 let hash_docs_a = "Calculate a succinct non-cryptographic hash for an object given its this_arg pointer.";
352 let hash_docs_b = "This is used, for example, for inclusion of this object in a hash map.";
353 writeln!(w, "\t/// {}", hash_docs_a).unwrap();
354 writeln!(w, "\t/// {}", hash_docs_b).unwrap();
355 writeln!(w, "\tpub hash: extern \"C\" fn (this_arg: *const c_void) -> u64,").unwrap();
356 generated_fields.push(("hash".to_owned(), None,
357 Some(format!("\t/**\n\t * {}\n\t * {}\n\t */\n", hash_docs_a, hash_docs_b))));
359 ("Send", _) => {}, ("Sync", _) => {},
360 ("std::fmt::Debug", _)|("core::fmt::Debug", _) => {
361 let debug_docs = "Return a human-readable \"debug\" string describing this object";
362 writeln!(w, "\t/// {}", debug_docs).unwrap();
363 writeln!(w, "\tpub debug_str: extern \"C\" fn (this_arg: *const c_void) -> crate::c_types::Str,").unwrap();
364 generated_fields.push(("debug_str".to_owned(), None,
365 Some(format!("\t/**\n\t * {}\n\t */\n", debug_docs))));
368 // TODO: Both of the below should expose supertrait methods in C++, but doing so is
370 generated_fields.push(if types.crate_types.traits.get(s).is_none() {
371 let (docs, name, ret) = convert_trait_impl_field(s);
372 writeln!(w, "\t/// {}", docs).unwrap();
373 writeln!(w, "\tpub {}: extern \"C\" fn (this_arg: *const c_void) -> {},", name, ret).unwrap();
374 (name, None, None) // Assume clonable
376 // For in-crate supertraits, just store a C-mapped copy of the supertrait as a member.
377 writeln!(w, "\t/// Implementation of {} for this object.", i).unwrap();
378 let is_clonable = types.is_clonable(s);
379 writeln!(w, "\tpub {}: crate::{},", i, s).unwrap();
380 (format!("{}", i), if !is_clonable {
381 Some(format!("crate::{}_clone_fields", s))
382 } else { None }, None)
386 writeln!(w, "\t/// Frees any resources associated with this object given its this_arg pointer.").unwrap();
387 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();
388 writeln!(w, "\tpub free: Option<extern \"C\" fn(this_arg: *mut c_void)>,").unwrap();
389 generated_fields.push(("free".to_owned(), None, None));
390 writeln!(w, "}}").unwrap();
392 macro_rules! impl_trait_for_c {
393 ($t: expr, $impl_accessor: expr, $type_resolver: expr) => {
394 for item in $t.items.iter() {
396 syn::TraitItem::Method(m) => {
397 if let ExportStatus::TestOnly = export_status(&m.attrs) { continue; }
398 if m.default.is_some() { unimplemented!(); }
399 if m.sig.constness.is_some() || m.sig.asyncness.is_some() || m.sig.unsafety.is_some() ||
400 m.sig.abi.is_some() || m.sig.variadic.is_some() {
403 let mut meth_gen_types = gen_types.push_ctx();
404 assert!(meth_gen_types.learn_generics(&m.sig.generics, $type_resolver));
405 // Note that we do *not* use the method generics when printing "native"
406 // rust parts - if the method is generic, we need to print a generic
408 write!(w, "\tfn {}", m.sig.ident).unwrap();
409 $type_resolver.write_rust_generic_param(w, Some(&gen_types), m.sig.generics.params.iter());
410 write!(w, "(").unwrap();
411 for inp in m.sig.inputs.iter() {
413 syn::FnArg::Receiver(recv) => {
414 if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
415 write!(w, "&").unwrap();
416 if let Some(lft) = &recv.reference.as_ref().unwrap().1 {
417 write!(w, "'{} ", lft.ident).unwrap();
419 if recv.mutability.is_some() {
420 write!(w, "mut self").unwrap();
422 write!(w, "self").unwrap();
425 syn::FnArg::Typed(arg) => {
426 if !arg.attrs.is_empty() { unimplemented!(); }
428 syn::Pat::Ident(ident) => {
429 if !ident.attrs.is_empty() || ident.by_ref.is_some() ||
430 ident.mutability.is_some() || ident.subpat.is_some() {
433 write!(w, ", mut {}{}: ", if $type_resolver.skip_arg(&*arg.ty, Some(&meth_gen_types)) { "_" } else { "" }, ident.ident).unwrap();
435 _ => unimplemented!(),
437 $type_resolver.write_rust_type(w, Some(&gen_types), &*arg.ty);
441 write!(w, ")").unwrap();
442 match &m.sig.output {
443 syn::ReturnType::Type(_, rtype) => {
444 write!(w, " -> ").unwrap();
445 $type_resolver.write_rust_type(w, Some(&gen_types), &*rtype)
449 write!(w, " {{\n\t\t").unwrap();
450 match export_status(&m.attrs) {
451 ExportStatus::NoExport => {
456 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
457 if let syn::Type::Reference(r) = &**rtype {
458 assert_eq!(m.sig.inputs.len(), 1); // Must only take self!
459 writeln!(w, "if let Some(f) = self{}.set_{} {{", $impl_accessor, m.sig.ident).unwrap();
460 writeln!(w, "\t\t\t(f)(&self{});", $impl_accessor).unwrap();
461 write!(w, "\t\t}}\n\t\t").unwrap();
462 $type_resolver.write_from_c_conversion_to_ref_prefix(w, &*r.elem, Some(&meth_gen_types));
463 write!(w, "self{}.{}", $impl_accessor, m.sig.ident).unwrap();
464 $type_resolver.write_from_c_conversion_to_ref_suffix(w, &*r.elem, Some(&meth_gen_types));
465 writeln!(w, "\n\t}}").unwrap();
469 write_method_var_decl_body(w, &m.sig, "\t", $type_resolver, Some(&meth_gen_types), true);
470 write!(w, "(self{}.{})(", $impl_accessor, m.sig.ident).unwrap();
471 let mut args = Vec::new();
472 write_method_call_params(&mut args, &m.sig, "\t", $type_resolver, Some(&meth_gen_types), "", true);
473 w.write_all(String::from_utf8(args).unwrap().replace("self", &format!("self{}", $impl_accessor)).as_bytes()).unwrap();
475 writeln!(w, "\n\t}}").unwrap();
477 &syn::TraitItem::Type(ref t) => {
478 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
479 let mut bounds_iter = t.bounds.iter();
480 match bounds_iter.next().unwrap() {
481 syn::TypeParamBound::Trait(tr) => {
482 writeln!(w, "\ttype {} = crate::{};", t.ident, $type_resolver.resolve_path(&tr.path, Some(&gen_types))).unwrap();
484 _ => unimplemented!(),
486 if bounds_iter.next().is_some() { unimplemented!(); }
488 _ => unimplemented!(),
494 writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap();
495 writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap();
497 writeln!(w, "#[no_mangle]").unwrap();
498 writeln!(w, "pub(crate) extern \"C\" fn {}_clone_fields(orig: &{}) -> {} {{", trait_name, trait_name, trait_name).unwrap();
499 writeln!(w, "\t{} {{", trait_name).unwrap();
500 writeln!(w, "\t\tthis_arg: orig.this_arg,").unwrap();
501 for (field, clone_fn, _) in generated_fields.iter() {
502 if let Some(f) = clone_fn {
503 // If the field isn't clonable, blindly assume its a trait and hope for the best.
504 writeln!(w, "\t\t{}: {}(&orig.{}),", field, f, field).unwrap();
506 writeln!(w, "\t\t{}: Clone::clone(&orig.{}),", field, field).unwrap();
509 writeln!(w, "\t}}\n}}").unwrap();
511 // Implement supertraits for the C-mapped struct.
512 walk_supertraits!(t, Some(&types), (
513 ("std::cmp::Eq", _)|("core::cmp::Eq", _) => {
514 writeln!(w, "impl std::cmp::Eq for {} {{}}", trait_name).unwrap();
515 writeln!(w, "impl std::cmp::PartialEq for {} {{", trait_name).unwrap();
516 writeln!(w, "\tfn eq(&self, o: &Self) -> bool {{ (self.eq)(self.this_arg, o) }}\n}}").unwrap();
518 ("std::hash::Hash", _)|("core::hash::Hash", _) => {
519 writeln!(w, "impl std::hash::Hash for {} {{", trait_name).unwrap();
520 writeln!(w, "\tfn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {{ hasher.write_u64((self.hash)(self.this_arg)) }}\n}}").unwrap();
522 ("Send", _) => {}, ("Sync", _) => {},
524 writeln!(w, "#[no_mangle]").unwrap();
525 writeln!(w, "/// Creates a copy of a {}", trait_name).unwrap();
526 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", trait_name, trait_name, trait_name).unwrap();
527 writeln!(w, "\tlet mut res = {}_clone_fields(orig);", trait_name).unwrap();
528 writeln!(w, "\tif let Some(f) = orig.cloned {{ (f)(&mut res) }};").unwrap();
529 writeln!(w, "\tres\n}}").unwrap();
530 writeln!(w, "impl Clone for {} {{", trait_name).unwrap();
531 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
532 writeln!(w, "\t\t{}_clone(self)", trait_name).unwrap();
533 writeln!(w, "\t}}\n}}").unwrap();
535 ("std::fmt::Debug", _)|("core::fmt::Debug", _) => {
536 writeln!(w, "impl core::fmt::Debug for {} {{", trait_name).unwrap();
537 writeln!(w, "\tfn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {{").unwrap();
538 writeln!(w, "\t\tf.write_str((self.debug_str)(self.this_arg).into_str())").unwrap();
539 writeln!(w, "\t}}").unwrap();
540 writeln!(w, "}}").unwrap();
543 if let Some(supertrait) = types.crate_types.traits.get(s) {
544 let resolver = get_module_type_resolver!(s, types.crate_libs, types.crate_types);
545 writeln!(w, "impl {} for {} {{", s, trait_name).unwrap();
546 impl_trait_for_c!(supertrait, format!(".{}", i), &resolver);
547 writeln!(w, "}}").unwrap();
549 do_write_impl_trait(w, s, i, &trait_name);
554 // Finally, implement the original Rust trait for the newly created mapped trait.
555 writeln!(w, "\nuse {}::{} as rust{};", types.module_path, t.ident, trait_name).unwrap();
557 write!(w, "impl rust{}", t.ident).unwrap();
558 maybe_write_generics(w, &t.generics, types, false);
559 writeln!(w, " for {} {{", trait_name).unwrap();
560 impl_trait_for_c!(t, "", types);
561 writeln!(w, "}}\n").unwrap();
562 writeln!(w, "// We're essentially a pointer already, or at least a set of pointers, so allow us to be used").unwrap();
563 writeln!(w, "// directly as a Deref trait in higher-level structs:").unwrap();
564 writeln!(w, "impl std::ops::Deref for {} {{\n\ttype Target = Self;", trait_name).unwrap();
565 writeln!(w, "\tfn deref(&self) -> &Self {{\n\t\tself\n\t}}\n}}").unwrap();
568 writeln!(w, "/// Calls the free function if one is set").unwrap();
569 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", trait_name, trait_name).unwrap();
570 writeln!(w, "impl Drop for {} {{", trait_name).unwrap();
571 writeln!(w, "\tfn drop(&mut self) {{").unwrap();
572 writeln!(w, "\t\tif let Some(f) = self.free {{").unwrap();
573 writeln!(w, "\t\t\tf(self.this_arg);").unwrap();
574 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
576 write_cpp_wrapper(cpp_headers, &trait_name, true, Some(generated_fields.drain(..)
577 .filter_map(|(name, _, docs)| if let Some(docs) = docs { Some((name, docs)) } else { None }).collect()));
580 /// Write out a simple "opaque" type (eg structs) which contain a pointer to the native Rust type
581 /// and a flag to indicate whether Drop'ing the mapped struct drops the underlying Rust type.
583 /// Also writes out a _free function and a C++ wrapper which handles calling _free.
584 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) {
585 // If we directly read the original type by its original name, cbindgen hits
586 // https://github.com/eqrion/cbindgen/issues/286 Thus, instead, we import it as a temporary
587 // name and then reference it by that name, which works around the issue.
588 write!(w, "\nuse {}::{} as native{}Import;\ntype native{} = native{}Import", types.module_path, ident, ident, ident, ident).unwrap();
589 maybe_write_generics(w, &generics, &types, true);
590 writeln!(w, ";\n").unwrap();
591 writeln!(extra_headers, "struct native{}Opaque;\ntypedef struct native{}Opaque LDKnative{};", ident, ident, ident).unwrap();
592 writeln_docs(w, &attrs, "");
593 writeln!(w, "#[must_use]\n#[repr(C)]\npub struct {} {{", struct_name).unwrap();
594 writeln!(w, "\t/// A pointer to the opaque Rust object.\n").unwrap();
595 writeln!(w, "\t/// Nearly everywhere, inner must be non-null, however in places where").unwrap();
596 writeln!(w, "\t/// the Rust equivalent takes an Option, it may be set to null to indicate None.").unwrap();
597 writeln!(w, "\tpub inner: *mut native{},", ident).unwrap();
598 writeln!(w, "\t/// Indicates that this is the only struct which contains the same pointer.\n").unwrap();
599 writeln!(w, "\t/// Rust functions which take ownership of an object provided via an argument require").unwrap();
600 writeln!(w, "\t/// this to be true and invalidate the object pointed to by inner.").unwrap();
601 writeln!(w, "\tpub is_owned: bool,").unwrap();
602 writeln!(w, "}}\n").unwrap();
603 writeln!(w, "impl Drop for {} {{\n\tfn drop(&mut self) {{", struct_name).unwrap();
604 writeln!(w, "\t\tif self.is_owned && !<*mut native{}>::is_null(self.inner) {{", ident).unwrap();
605 writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(ObjOps::untweak_ptr(self.inner)) }};\n\t\t}}\n\t}}\n}}").unwrap();
606 writeln!(w, "/// Frees any resources used by the {}, if is_owned is set and inner is non-NULL.", struct_name).unwrap();
607 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_obj: {}) {{ }}", struct_name, struct_name).unwrap();
608 writeln!(w, "#[allow(unused)]").unwrap();
609 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
610 writeln!(w, "extern \"C\" fn {}_free_void(this_ptr: *mut c_void) {{", struct_name).unwrap();
611 writeln!(w, "\tunsafe {{ let _ = Box::from_raw(this_ptr as *mut native{}); }}\n}}", struct_name).unwrap();
612 writeln!(w, "#[allow(unused)]").unwrap();
613 writeln!(w, "impl {} {{", struct_name).unwrap();
614 writeln!(w, "\tpub(crate) fn get_native_ref(&self) -> &'static native{} {{", struct_name).unwrap();
615 writeln!(w, "\t\tunsafe {{ &*ObjOps::untweak_ptr(self.inner) }}").unwrap();
616 writeln!(w, "\t}}").unwrap();
617 writeln!(w, "\tpub(crate) fn get_native_mut_ref(&self) -> &'static mut native{} {{", struct_name).unwrap();
618 writeln!(w, "\t\tunsafe {{ &mut *ObjOps::untweak_ptr(self.inner) }}").unwrap();
619 writeln!(w, "\t}}").unwrap();
620 writeln!(w, "\t/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy").unwrap();
621 writeln!(w, "\tpub(crate) fn take_inner(mut self) -> *mut native{} {{", struct_name).unwrap();
622 writeln!(w, "\t\tassert!(self.is_owned);").unwrap();
623 writeln!(w, "\t\tlet ret = ObjOps::untweak_ptr(self.inner);").unwrap();
624 writeln!(w, "\t\tself.inner = std::ptr::null_mut();").unwrap();
625 writeln!(w, "\t\tret").unwrap();
626 writeln!(w, "\t}}\n}}").unwrap();
628 write_cpp_wrapper(cpp_headers, &format!("{}", ident), true, None);
631 /// Writes out all the relevant mappings for a Rust struct, deferring to writeln_opaque to generate
632 /// the struct itself, and then writing getters and setters for public, understood-type fields and
633 /// a constructor if every field is public.
634 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) {
635 if export_status(&s.attrs) != ExportStatus::Export { return; }
637 let struct_name = &format!("{}", s.ident);
638 writeln_opaque(w, &s.ident, struct_name, &s.generics, &s.attrs, types, extra_headers, cpp_headers);
640 if let syn::Fields::Named(fields) = &s.fields {
641 let mut self_path_segs = syn::punctuated::Punctuated::new();
642 self_path_segs.push(s.ident.clone().into());
643 let self_path = syn::Path { leading_colon: None, segments: self_path_segs};
644 let mut gen_types = GenericTypes::new(Some((types.resolve_path(&self_path, None), &self_path)));
645 assert!(gen_types.learn_generics(&s.generics, types));
647 let mut all_fields_settable = true;
648 for field in fields.named.iter() {
649 if let syn::Visibility::Public(_) = field.vis {
650 let export = export_status(&field.attrs);
652 ExportStatus::Export => {},
653 ExportStatus::NoExport|ExportStatus::TestOnly => {
654 all_fields_settable = false;
657 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
660 if let Some(ident) = &field.ident {
661 if let Some(ref_type) = types.create_ownable_reference(&field.ty, Some(&gen_types)) {
662 if types.understood_c_type(&ref_type, Some(&gen_types)) {
663 writeln_arg_docs(w, &field.attrs, "", types, Some(&gen_types), vec![].drain(..), Some(&ref_type));
664 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> ", struct_name, ident, struct_name).unwrap();
665 types.write_c_type(w, &ref_type, Some(&gen_types), true);
666 write!(w, " {{\n\tlet mut inner_val = &mut this_ptr.get_native_mut_ref().{};\n\t", ident).unwrap();
667 let local_var = types.write_to_c_conversion_new_var(w, &format_ident!("inner_val"), &ref_type, Some(&gen_types), true);
668 if local_var { write!(w, "\n\t").unwrap(); }
669 types.write_to_c_conversion_inline_prefix(w, &ref_type, Some(&gen_types), true);
670 write!(w, "inner_val").unwrap();
671 types.write_to_c_conversion_inline_suffix(w, &ref_type, Some(&gen_types), true);
672 writeln!(w, "\n}}").unwrap();
676 if types.understood_c_type(&field.ty, Some(&gen_types)) {
677 writeln_arg_docs(w, &field.attrs, "", types, Some(&gen_types), vec![("val".to_owned(), &field.ty)].drain(..), None);
678 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_set_{}(this_ptr: &mut {}, mut val: ", struct_name, ident, struct_name).unwrap();
679 types.write_c_type(w, &field.ty, Some(&gen_types), false);
680 write!(w, ") {{\n\t").unwrap();
681 let local_var = types.write_from_c_conversion_new_var(w, &format_ident!("val"), &field.ty, Some(&gen_types));
682 if local_var { write!(w, "\n\t").unwrap(); }
683 write!(w, "unsafe {{ &mut *ObjOps::untweak_ptr(this_ptr.inner) }}.{} = ", ident).unwrap();
684 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
685 write!(w, "val").unwrap();
686 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
687 writeln!(w, ";\n}}").unwrap();
688 } else { all_fields_settable = false; }
689 } else { all_fields_settable = false; }
690 } else { all_fields_settable = false; }
693 if all_fields_settable {
694 // Build a constructor!
695 writeln!(w, "/// Constructs a new {} given each field", struct_name).unwrap();
696 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_new(", struct_name).unwrap();
697 for (idx, field) in fields.named.iter().enumerate() {
698 if idx != 0 { write!(w, ", ").unwrap(); }
699 write!(w, "mut {}_arg: ", field.ident.as_ref().unwrap()).unwrap();
700 types.write_c_type(w, &field.ty, Some(&gen_types), false);
702 write!(w, ") -> {} {{\n\t", struct_name).unwrap();
703 for field in fields.named.iter() {
704 let field_ident = format_ident!("{}_arg", field.ident.as_ref().unwrap());
705 if types.write_from_c_conversion_new_var(w, &field_ident, &field.ty, Some(&gen_types)) {
706 write!(w, "\n\t").unwrap();
709 writeln!(w, "{} {{ inner: ObjOps::heap_alloc(native{} {{", struct_name, s.ident).unwrap();
710 for field in fields.named.iter() {
711 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
712 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
713 write!(w, "{}_arg", field.ident.as_ref().unwrap()).unwrap();
714 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
715 writeln!(w, ",").unwrap();
717 writeln!(w, "\t}}), is_owned: true }}\n}}").unwrap();
722 /// Prints a relevant conversion for impl *
724 /// For simple impl Struct {}s, this just outputs the wrapper functions as Struct_fn_name() { .. }.
726 /// For impl Trait for Struct{}s, this non-exported generates wrapper functions as
727 /// Trait_Struct_fn_name and a Struct_as_Trait(&struct) -> Trait function which returns a populated
728 /// Trait struct containing a pointer to the passed struct's inner field and the wrapper functions.
730 /// A few non-crate Traits are hard-coded including Default.
731 fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut TypeResolver) {
732 match export_status(&i.attrs) {
733 ExportStatus::Export => {},
734 ExportStatus::NoExport|ExportStatus::TestOnly => return,
735 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
738 if let syn::Type::Tuple(_) = &*i.self_ty {
739 if types.understood_c_type(&*i.self_ty, None) {
740 let mut gen_types = GenericTypes::new(None);
741 if !gen_types.learn_generics(&i.generics, types) {
742 eprintln!("Not implementing anything for `impl (..)` due to not understood generics");
746 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
747 if let Some(trait_path) = i.trait_.as_ref() {
748 if trait_path.0.is_some() { unimplemented!(); }
749 if types.understood_c_path(&trait_path.1) {
750 eprintln!("Not implementing anything for `impl Trait for (..)` - we only support manual defines");
753 // Just do a manual implementation:
754 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
757 eprintln!("Not implementing anything for plain `impl (..)` block - we only support `impl Trait for (..)` blocks");
763 if let &syn::Type::Path(ref p) = &*i.self_ty {
764 if p.qself.is_some() { unimplemented!(); }
765 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
766 if let Some(resolved_path) = types.maybe_resolve_non_ignored_ident(&ident) {
767 let mut gen_types = GenericTypes::new(Some((resolved_path.clone(), &p.path)));
768 if !gen_types.learn_generics(&i.generics, types) {
769 eprintln!("Not implementing anything for impl {} due to not understood generics", ident);
773 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
774 if let Some(trait_path) = i.trait_.as_ref() {
775 if trait_path.0.is_some() { unimplemented!(); }
776 if types.understood_c_path(&trait_path.1) {
777 let full_trait_path = types.resolve_path(&trait_path.1, None);
778 let trait_obj = *types.crate_types.traits.get(&full_trait_path).unwrap();
781 let supertrait_resolver;
782 walk_supertraits!(trait_obj, Some(&types), (
784 if let Some(supertrait) = types.crate_types.traits.get(s) {
785 supertrait_name = s.to_string();
786 supertrait_resolver = get_module_type_resolver!(supertrait_name, types.crate_libs, types.crate_types);
787 gen_types.learn_associated_types(&supertrait, &supertrait_resolver);
792 // We learn the associated types maping from the original trait object.
793 // That's great, except that they are unresolved idents, so if we learn
794 // mappings from a trai defined in a different file, we may mis-resolve or
795 // fail to resolve the mapped types. Thus, we have to construct a new
796 // resolver for the module that the trait was defined in here first.
797 let trait_resolver = get_module_type_resolver!(full_trait_path, types.crate_libs, types.crate_types);
798 gen_types.learn_associated_types(trait_obj, &trait_resolver);
799 let mut impl_associated_types = HashMap::new();
800 for item in i.items.iter() {
802 syn::ImplItem::Type(t) => {
803 if let syn::Type::Path(p) = &t.ty {
804 if let Some(id) = single_ident_generic_path_to_ident(&p.path) {
805 impl_associated_types.insert(&t.ident, id);
813 let export = export_status(&trait_obj.attrs);
815 ExportStatus::Export|ExportStatus::NotImplementable => {},
816 ExportStatus::NoExport|ExportStatus::TestOnly => return,
819 // For cases where we have a concrete native object which implements a
820 // trait and need to return the C-mapped version of the trait, provide a
821 // From<> implementation which does all the work to ensure free is handled
822 // properly. This way we can call this method from deep in the
823 // type-conversion logic without actually knowing the concrete native type.
824 writeln!(w, "impl From<native{}> for crate::{} {{", ident, full_trait_path).unwrap();
825 writeln!(w, "\tfn from(obj: native{}) -> Self {{", ident).unwrap();
826 writeln!(w, "\t\tlet mut rust_obj = {} {{ inner: ObjOps::heap_alloc(obj), is_owned: true }};", ident).unwrap();
827 writeln!(w, "\t\tlet mut ret = {}_as_{}(&rust_obj);", ident, trait_obj.ident).unwrap();
828 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();
829 writeln!(w, "\t\trust_obj.inner = std::ptr::null_mut();").unwrap();
830 writeln!(w, "\t\tret.free = Some({}_free_void);", ident).unwrap();
831 writeln!(w, "\t\tret\n\t}}\n}}").unwrap();
833 writeln!(w, "/// Constructs a new {} which calls the relevant methods on this_arg.", trait_obj.ident).unwrap();
834 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();
835 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_as_{}(this_arg: &{}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
836 writeln!(w, "\tcrate::{} {{", full_trait_path).unwrap();
837 writeln!(w, "\t\tthis_arg: unsafe {{ ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }},").unwrap();
838 writeln!(w, "\t\tfree: None,").unwrap();
840 macro_rules! write_meth {
841 ($m: expr, $trait: expr, $indent: expr) => {
842 let trait_method = $trait.items.iter().filter_map(|item| {
843 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
844 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
845 match export_status(&trait_method.attrs) {
846 ExportStatus::Export => {},
847 ExportStatus::NoExport => {
848 write!(w, "{}\t\t//XXX: Need to export {}\n", $indent, $m.sig.ident).unwrap();
851 ExportStatus::TestOnly => continue,
852 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
855 let mut printed = false;
856 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
857 if let syn::Type::Reference(r) = &**rtype {
858 write!(w, "\n\t\t{}{}: ", $indent, $m.sig.ident).unwrap();
859 types.write_empty_rust_val(Some(&gen_types), w, &*r.elem);
860 writeln!(w, ",\n{}\t\tset_{}: Some({}_{}_set_{}),", $indent, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
865 write!(w, "{}\t\t{}: {}_{}_{},\n", $indent, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
869 for item in trait_obj.items.iter() {
871 syn::TraitItem::Method(m) => {
872 write_meth!(m, trait_obj, "");
877 let mut requires_clone = false;
878 walk_supertraits!(trait_obj, Some(&types), (
880 requires_clone = true;
881 writeln!(w, "\t\tcloned: Some({}_{}_cloned),", trait_obj.ident, ident).unwrap();
883 ("Sync", _) => {}, ("Send", _) => {},
884 ("std::marker::Sync", _) => {}, ("std::marker::Send", _) => {},
885 ("core::fmt::Debug", _) => {},
887 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
888 writeln!(w, "\t\t{}: crate::{} {{", t, s).unwrap();
889 writeln!(w, "\t\t\tthis_arg: unsafe {{ ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }},").unwrap();
890 writeln!(w, "\t\t\tfree: None,").unwrap();
891 for item in supertrait_obj.items.iter() {
893 syn::TraitItem::Method(m) => {
894 write_meth!(m, supertrait_obj, "\t");
899 write!(w, "\t\t}},\n").unwrap();
901 write_trait_impl_field_assign(w, s, ident);
905 writeln!(w, "\t}}\n}}\n").unwrap();
907 macro_rules! impl_meth {
908 ($m: expr, $trait_path: expr, $trait: expr, $indent: expr) => {
909 let trait_method = $trait.items.iter().filter_map(|item| {
910 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
911 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
912 match export_status(&trait_method.attrs) {
913 ExportStatus::Export => {},
914 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
915 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
918 if let syn::ReturnType::Type(_, _) = &$m.sig.output {
919 writeln!(w, "#[must_use]").unwrap();
921 write!(w, "extern \"C\" fn {}_{}_{}(", ident, $trait.ident, $m.sig.ident).unwrap();
922 let mut meth_gen_types = gen_types.push_ctx();
923 assert!(meth_gen_types.learn_generics(&$m.sig.generics, types));
924 write_method_params(w, &$m.sig, "c_void", types, Some(&meth_gen_types), true, true);
925 write!(w, " {{\n\t").unwrap();
926 write_method_var_decl_body(w, &$m.sig, "", types, Some(&meth_gen_types), false);
927 let mut takes_self = false;
928 for inp in $m.sig.inputs.iter() {
929 if let syn::FnArg::Receiver(_) = inp {
934 let mut t_gen_args = String::new();
935 for (idx, _) in $trait.generics.params.iter().enumerate() {
936 if idx != 0 { t_gen_args += ", " };
940 write!(w, "<native{} as {}<{}>>::{}(unsafe {{ &mut *(this_arg as *mut native{}) }}, ", ident, $trait_path, t_gen_args, $m.sig.ident, ident).unwrap();
942 write!(w, "<native{} as {}<{}>>::{}(", ident, $trait_path, t_gen_args, $m.sig.ident).unwrap();
945 let mut real_type = "".to_string();
946 match &$m.sig.output {
947 syn::ReturnType::Type(_, rtype) => {
948 if let Some(mut remaining_path) = first_seg_self(&*rtype) {
949 if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
950 real_type = format!("{}", impl_associated_types.get(associated_seg).unwrap());
956 write_method_call_params(w, &$m.sig, "", types, Some(&meth_gen_types), &real_type, false);
957 write!(w, "\n}}\n").unwrap();
958 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
959 if let syn::Type::Reference(r) = &**rtype {
960 assert_eq!($m.sig.inputs.len(), 1); // Must only take self
961 writeln!(w, "extern \"C\" fn {}_{}_set_{}(trait_self_arg: &{}) {{", ident, $trait.ident, $m.sig.ident, $trait.ident).unwrap();
962 writeln!(w, "\t// This is a bit race-y in the general case, but for our specific use-cases today, we're safe").unwrap();
963 writeln!(w, "\t// Specifically, we must ensure that the first time we're called it can never be in parallel").unwrap();
964 write!(w, "\tif ").unwrap();
965 types.write_empty_rust_val_check(Some(&meth_gen_types), w, &*r.elem, &format!("trait_self_arg.{}", $m.sig.ident));
966 writeln!(w, " {{").unwrap();
967 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();
968 writeln!(w, "\t}}").unwrap();
969 writeln!(w, "}}").unwrap();
975 for item in i.items.iter() {
977 syn::ImplItem::Method(m) => {
978 impl_meth!(m, full_trait_path, trait_obj, "");
980 syn::ImplItem::Type(_) => {},
981 _ => unimplemented!(),
985 writeln!(w, "extern \"C\" fn {}_{}_cloned(new_obj: &mut crate::{}) {{", trait_obj.ident, ident, full_trait_path).unwrap();
986 writeln!(w, "\tnew_obj.this_arg = {}_clone_void(new_obj.this_arg);", ident).unwrap();
987 writeln!(w, "\tnew_obj.free = Some({}_free_void);", ident).unwrap();
988 walk_supertraits!(trait_obj, Some(&types), (
990 if types.crate_types.traits.get(s).is_some() {
991 assert!(!types.is_clonable(s)); // We don't currently support cloning with a clonable supertrait
992 writeln!(w, "\tnew_obj.{}.this_arg = new_obj.this_arg;", t).unwrap();
993 writeln!(w, "\tnew_obj.{}.free = None;", t).unwrap();
997 writeln!(w, "}}").unwrap();
999 write!(w, "\n").unwrap();
1000 } else if path_matches_nongeneric(&trait_path.1, &["From"]) {
1001 } else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
1002 writeln!(w, "/// Creates a \"default\" {}. See struct and individual field documentaiton for details on which values are used.", ident).unwrap();
1003 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
1004 write!(w, "\t{} {{ inner: ObjOps::heap_alloc(Default::default()), is_owned: true }}\n", ident).unwrap();
1005 write!(w, "}}\n").unwrap();
1006 } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "PartialEq"]) {
1007 } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "Eq"]) {
1008 writeln!(w, "/// Checks if two {}s contain equal inner contents.", ident).unwrap();
1009 writeln!(w, "/// This ignores pointers and is_owned flags and looks at the values in fields.").unwrap();
1010 if types.c_type_has_inner_from_path(&resolved_path) {
1011 writeln!(w, "/// Two objects with NULL inner values will be considered \"equal\" here.").unwrap();
1013 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_eq(a: &{}, b: &{}) -> bool {{\n", ident, ident, ident).unwrap();
1014 if types.c_type_has_inner_from_path(&resolved_path) {
1015 write!(w, "\tif a.inner == b.inner {{ return true; }}\n").unwrap();
1016 write!(w, "\tif a.inner.is_null() || b.inner.is_null() {{ return false; }}\n").unwrap();
1020 let ref_type: syn::Type = syn::parse_quote!(&#path);
1021 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");
1023 write!(w, "\tif ").unwrap();
1024 types.write_from_c_conversion_prefix(w, &ref_type, Some(&gen_types));
1025 write!(w, "a").unwrap();
1026 types.write_from_c_conversion_suffix(w, &ref_type, Some(&gen_types));
1027 write!(w, " == ").unwrap();
1028 types.write_from_c_conversion_prefix(w, &ref_type, Some(&gen_types));
1029 write!(w, "b").unwrap();
1030 types.write_from_c_conversion_suffix(w, &ref_type, Some(&gen_types));
1032 writeln!(w, " {{ true }} else {{ false }}\n}}").unwrap();
1033 } else if path_matches_nongeneric(&trait_path.1, &["core", "hash", "Hash"]) {
1034 writeln!(w, "/// Checks if two {}s contain equal inner contents.", ident).unwrap();
1035 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_hash(o: &{}) -> u64 {{\n", ident, ident).unwrap();
1036 if types.c_type_has_inner_from_path(&resolved_path) {
1037 write!(w, "\tif o.inner.is_null() {{ return 0; }}\n").unwrap();
1041 let ref_type: syn::Type = syn::parse_quote!(&#path);
1042 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");
1044 writeln!(w, "\t// Note that we'd love to use std::collections::hash_map::DefaultHasher but it's not in core").unwrap();
1045 writeln!(w, "\t#[allow(deprecated)]").unwrap();
1046 writeln!(w, "\tlet mut hasher = core::hash::SipHasher::new();").unwrap();
1047 write!(w, "\tstd::hash::Hash::hash(").unwrap();
1048 types.write_from_c_conversion_prefix(w, &ref_type, Some(&gen_types));
1049 write!(w, "o").unwrap();
1050 types.write_from_c_conversion_suffix(w, &ref_type, Some(&gen_types));
1051 writeln!(w, ", &mut hasher);").unwrap();
1052 writeln!(w, "\tstd::hash::Hasher::finish(&hasher)\n}}").unwrap();
1053 } else if (path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) || path_matches_nongeneric(&trait_path.1, &["Clone"])) &&
1054 types.c_type_has_inner_from_path(&resolved_path) {
1055 writeln!(w, "impl Clone for {} {{", ident).unwrap();
1056 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
1057 writeln!(w, "\t\tSelf {{").unwrap();
1058 writeln!(w, "\t\t\tinner: if <*mut native{}>::is_null(self.inner) {{ std::ptr::null_mut() }} else {{", ident).unwrap();
1059 writeln!(w, "\t\t\t\tObjOps::heap_alloc(unsafe {{ &*ObjOps::untweak_ptr(self.inner) }}.clone()) }},").unwrap();
1060 writeln!(w, "\t\t\tis_owned: true,").unwrap();
1061 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
1062 writeln!(w, "#[allow(unused)]").unwrap();
1063 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
1064 writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", ident).unwrap();
1065 writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", ident).unwrap();
1066 writeln!(w, "}}").unwrap();
1067 writeln!(w, "#[no_mangle]").unwrap();
1068 writeln!(w, "/// Creates a copy of the {}", ident).unwrap();
1069 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", ident, ident, ident).unwrap();
1070 writeln!(w, "\torig.clone()").unwrap();
1071 writeln!(w, "}}").unwrap();
1072 } else if path_matches_nongeneric(&trait_path.1, &["FromStr"]) {
1073 if let Some(container) = types.get_c_mangled_container_type(
1074 vec![&*i.self_ty, &syn::Type::Tuple(syn::TypeTuple { paren_token: Default::default(), elems: syn::punctuated::Punctuated::new() })],
1075 Some(&gen_types), "Result") {
1076 writeln!(w, "#[no_mangle]").unwrap();
1077 writeln!(w, "/// Read a {} object from a string", ident).unwrap();
1078 writeln!(w, "pub extern \"C\" fn {}_from_str(s: crate::c_types::Str) -> {} {{", ident, container).unwrap();
1079 writeln!(w, "\tmatch {}::from_str(s.into_str()) {{", resolved_path).unwrap();
1080 writeln!(w, "\t\tOk(r) => {{").unwrap();
1081 let new_var = types.write_to_c_conversion_new_var(w, &format_ident!("r"), &*i.self_ty, Some(&gen_types), false);
1082 write!(w, "\t\t\tcrate::c_types::CResultTempl::ok(\n\t\t\t\t").unwrap();
1083 types.write_to_c_conversion_inline_prefix(w, &*i.self_ty, Some(&gen_types), false);
1084 write!(w, "{}r", if new_var { "local_" } else { "" }).unwrap();
1085 types.write_to_c_conversion_inline_suffix(w, &*i.self_ty, Some(&gen_types), false);
1086 writeln!(w, "\n\t\t\t)\n\t\t}},").unwrap();
1087 writeln!(w, "\t\tErr(e) => crate::c_types::CResultTempl::err(()),").unwrap();
1088 writeln!(w, "\t}}.into()\n}}").unwrap();
1090 } else if path_matches_nongeneric(&trait_path.1, &["Display"]) {
1091 writeln!(w, "#[no_mangle]").unwrap();
1092 writeln!(w, "/// Get the string representation of a {} object", ident).unwrap();
1093 writeln!(w, "pub extern \"C\" fn {}_to_str(o: &crate::{}) -> Str {{", ident, resolved_path).unwrap();
1095 let self_ty = &i.self_ty;
1096 let ref_type: syn::Type = syn::parse_quote!(&#self_ty);
1097 let new_var = types.write_from_c_conversion_new_var(w, &format_ident!("o"), &ref_type, Some(&gen_types));
1098 write!(w, "\tformat!(\"{{}}\", ").unwrap();
1099 types.write_from_c_conversion_prefix(w, &ref_type, Some(&gen_types));
1100 write!(w, "{}o", if new_var { "local_" } else { "" }).unwrap();
1101 types.write_from_c_conversion_suffix(w, &ref_type, Some(&gen_types));
1102 writeln!(w, ").into()").unwrap();
1104 writeln!(w, "}}").unwrap();
1106 //XXX: implement for other things like ToString
1107 // If we have no generics, try a manual implementation:
1108 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
1111 let declared_type = (*types.get_declared_type(&ident).unwrap()).clone();
1112 for item in i.items.iter() {
1114 syn::ImplItem::Method(m) => {
1115 if let syn::Visibility::Public(_) = m.vis {
1116 match export_status(&m.attrs) {
1117 ExportStatus::Export => {},
1118 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1119 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1121 let mut meth_gen_types = gen_types.push_ctx();
1122 assert!(meth_gen_types.learn_generics(&m.sig.generics, types));
1123 if m.defaultness.is_some() { unimplemented!(); }
1124 writeln_fn_docs(w, &m.attrs, "", types, Some(&meth_gen_types), m.sig.inputs.iter(), &m.sig.output);
1125 if let syn::ReturnType::Type(_, _) = &m.sig.output {
1126 writeln!(w, "#[must_use]").unwrap();
1128 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_{}(", ident, m.sig.ident).unwrap();
1129 let ret_type = match &declared_type {
1130 DeclType::MirroredEnum => format!("{}", ident),
1131 DeclType::StructImported => format!("{}", ident),
1132 _ => unimplemented!(),
1134 write_method_params(w, &m.sig, &ret_type, types, Some(&meth_gen_types), false, true);
1135 write!(w, " {{\n\t").unwrap();
1136 write_method_var_decl_body(w, &m.sig, "", types, Some(&meth_gen_types), false);
1137 let mut takes_self = false;
1138 let mut takes_mut_self = false;
1139 let mut takes_owned_self = false;
1140 for inp in m.sig.inputs.iter() {
1141 if let syn::FnArg::Receiver(r) = inp {
1143 if r.mutability.is_some() { takes_mut_self = true; }
1144 if r.reference.is_none() { takes_owned_self = true; }
1147 if !takes_mut_self && !takes_self {
1148 write!(w, "{}::{}(", resolved_path, m.sig.ident).unwrap();
1150 match &declared_type {
1151 DeclType::MirroredEnum => write!(w, "this_arg.to_native().{}(", m.sig.ident).unwrap(),
1152 DeclType::StructImported => {
1153 if takes_owned_self {
1154 write!(w, "(*unsafe {{ Box::from_raw(this_arg.take_inner()) }}).{}(", m.sig.ident).unwrap();
1155 } else if takes_mut_self {
1156 write!(w, "unsafe {{ &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut native{})) }}.{}(", ident, m.sig.ident).unwrap();
1158 write!(w, "unsafe {{ &*ObjOps::untweak_ptr(this_arg.inner) }}.{}(", m.sig.ident).unwrap();
1161 _ => unimplemented!(),
1164 write_method_call_params(w, &m.sig, "", types, Some(&meth_gen_types), &ret_type, false);
1165 writeln!(w, "\n}}\n").unwrap();
1172 } else if let Some(resolved_path) = types.maybe_resolve_ident(&ident) {
1173 if let Some(aliases) = types.crate_types.reverse_alias_map.get(&resolved_path).cloned() {
1174 'alias_impls: for (alias, arguments) in aliases {
1175 let alias_resolved = types.resolve_path(&alias, None);
1176 for (idx, gen) in i.generics.params.iter().enumerate() {
1178 syn::GenericParam::Type(type_param) => {
1179 'bounds_check: for bound in type_param.bounds.iter() {
1180 if let syn::TypeParamBound::Trait(trait_bound) = bound {
1181 if let syn::PathArguments::AngleBracketed(ref t) = &arguments {
1182 assert!(idx < t.args.len());
1183 if let syn::GenericArgument::Type(syn::Type::Path(p)) = &t.args[idx] {
1184 let generic_arg = types.resolve_path(&p.path, None);
1185 let generic_bound = types.resolve_path(&trait_bound.path, None);
1186 if let Some(traits_impld) = types.crate_types.trait_impls.get(&generic_arg) {
1187 for trait_impld in traits_impld {
1188 if *trait_impld == generic_bound { continue 'bounds_check; }
1190 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1191 continue 'alias_impls;
1193 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1194 continue 'alias_impls;
1196 } else { unimplemented!(); }
1197 } else { unimplemented!(); }
1198 } else { unimplemented!(); }
1201 syn::GenericParam::Lifetime(_) => {},
1202 syn::GenericParam::Const(_) => unimplemented!(),
1205 let aliased_impl = syn::ItemImpl {
1206 attrs: i.attrs.clone(),
1207 brace_token: syn::token::Brace(Span::call_site()),
1209 generics: syn::Generics {
1211 params: syn::punctuated::Punctuated::new(),
1215 impl_token: syn::Token![impl](Span::call_site()),
1216 items: i.items.clone(),
1217 self_ty: Box::new(syn::Type::Path(syn::TypePath { qself: None, path: alias.clone() })),
1218 trait_: i.trait_.clone(),
1221 writeln_impl(w, &aliased_impl, types);
1224 eprintln!("Not implementing anything for {} due to it being marked not exported", ident);
1227 eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub)", ident);
1233 /// Replaces upper case charachters with underscore followed by lower case except the first
1234 /// charachter and repeated upper case characthers (which are only made lower case).
1235 fn camel_to_snake_case(camel: &str) -> String {
1236 let mut res = "".to_string();
1237 let mut last_upper = -1;
1238 for (idx, c) in camel.chars().enumerate() {
1239 if c.is_uppercase() {
1240 if last_upper != idx as isize - 1 { res.push('_'); }
1241 res.push(c.to_lowercase().next().unwrap());
1242 last_upper = idx as isize;
1251 /// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
1252 /// is unitary), we generate an equivalent enum with all types replaced with their C mapped
1253 /// versions followed by conversion functions which map between the Rust version and the C mapped
1255 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) {
1256 match export_status(&e.attrs) {
1257 ExportStatus::Export => {},
1258 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1259 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1262 if is_enum_opaque(e) {
1263 eprintln!("Skipping enum {} as it contains non-unit fields", e.ident);
1264 writeln_opaque(w, &e.ident, &format!("{}", e.ident), &e.generics, &e.attrs, types, extra_headers, cpp_headers);
1267 writeln_docs(w, &e.attrs, "");
1269 let mut gen_types = GenericTypes::new(None);
1270 assert!(gen_types.learn_generics(&e.generics, types));
1272 let mut needs_free = false;
1273 let mut constr = Vec::new();
1275 writeln!(w, "#[must_use]\n#[derive(Clone)]\n#[repr(C)]\npub enum {} {{", e.ident).unwrap();
1276 for var in e.variants.iter() {
1277 assert_eq!(export_status(&var.attrs), ExportStatus::Export); // We can't partially-export a mirrored enum
1278 writeln_docs(w, &var.attrs, "\t");
1279 write!(w, "\t{}", var.ident).unwrap();
1280 writeln!(&mut constr, "#[no_mangle]\n/// Utility method to constructs a new {}-variant {}", var.ident, e.ident).unwrap();
1281 let constr_name = camel_to_snake_case(&format!("{}", var.ident));
1282 write!(&mut constr, "pub extern \"C\" fn {}_{}(", e.ident, constr_name).unwrap();
1283 let mut empty_tuple_variant = false;
1284 if let syn::Fields::Named(fields) = &var.fields {
1286 writeln!(w, " {{").unwrap();
1287 for (idx, field) in fields.named.iter().enumerate() {
1288 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1289 writeln_field_docs(w, &field.attrs, "\t\t", types, Some(&gen_types), &field.ty);
1290 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1291 write!(&mut constr, "{}{}: ", if idx != 0 { ", " } else { "" }, field.ident.as_ref().unwrap()).unwrap();
1292 types.write_c_type(w, &field.ty, Some(&gen_types), false);
1293 types.write_c_type(&mut constr, &field.ty, Some(&gen_types), false);
1294 writeln!(w, ",").unwrap();
1296 write!(w, "\t}}").unwrap();
1297 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1298 if fields.unnamed.len() == 1 {
1299 let mut empty_check = Vec::new();
1300 types.write_c_type(&mut empty_check, &fields.unnamed[0].ty, Some(&gen_types), false);
1301 if empty_check.is_empty() {
1302 empty_tuple_variant = true;
1305 if !empty_tuple_variant {
1307 write!(w, "(").unwrap();
1308 for (idx, field) in fields.unnamed.iter().enumerate() {
1309 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1310 write!(&mut constr, "{}: ", ('a' as u8 + idx as u8) as char).unwrap();
1311 types.write_c_type(w, &field.ty, Some(&gen_types), false);
1312 types.write_c_type(&mut constr, &field.ty, Some(&gen_types), false);
1313 if idx != fields.unnamed.len() - 1 {
1314 write!(w, ",").unwrap();
1315 write!(&mut constr, ",").unwrap();
1318 write!(w, ")").unwrap();
1321 if var.discriminant.is_some() { unimplemented!(); }
1322 write!(&mut constr, ") -> {} {{\n\t{}::{}", e.ident, e.ident, var.ident).unwrap();
1323 if let syn::Fields::Named(fields) = &var.fields {
1324 writeln!(&mut constr, " {{").unwrap();
1325 for field in fields.named.iter() {
1326 writeln!(&mut constr, "\t\t{},", field.ident.as_ref().unwrap()).unwrap();
1328 writeln!(&mut constr, "\t}}").unwrap();
1329 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1330 if !empty_tuple_variant {
1331 write!(&mut constr, "(").unwrap();
1332 for idx in 0..fields.unnamed.len() {
1333 write!(&mut constr, "{}, ", ('a' as u8 + idx as u8) as char).unwrap();
1335 writeln!(&mut constr, ")").unwrap();
1337 writeln!(&mut constr, "").unwrap();
1340 writeln!(&mut constr, "}}").unwrap();
1341 writeln!(w, ",").unwrap();
1343 writeln!(w, "}}\nuse {}::{} as native{};\nimpl {} {{", types.module_path, e.ident, e.ident, e.ident).unwrap();
1345 macro_rules! write_conv {
1346 ($fn_sig: expr, $to_c: expr, $ref: expr) => {
1347 writeln!(w, "\t#[allow(unused)]\n\tpub(crate) fn {} {{\n\t\tmatch {} {{", $fn_sig, if $to_c { "native" } else { "self" }).unwrap();
1348 for var in e.variants.iter() {
1349 write!(w, "\t\t\t{}{}::{} ", if $to_c { "native" } else { "" }, e.ident, var.ident).unwrap();
1350 let mut empty_tuple_variant = false;
1351 if let syn::Fields::Named(fields) = &var.fields {
1352 write!(w, "{{").unwrap();
1353 for field in fields.named.iter() {
1354 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1355 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, field.ident.as_ref().unwrap()).unwrap();
1357 write!(w, "}} ").unwrap();
1358 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1359 if fields.unnamed.len() == 1 {
1360 let mut empty_check = Vec::new();
1361 types.write_c_type(&mut empty_check, &fields.unnamed[0].ty, Some(&gen_types), false);
1362 if empty_check.is_empty() {
1363 empty_tuple_variant = true;
1366 if !empty_tuple_variant || $to_c {
1367 write!(w, "(").unwrap();
1368 for (idx, field) in fields.unnamed.iter().enumerate() {
1369 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1370 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, ('a' as u8 + idx as u8) as char).unwrap();
1372 write!(w, ") ").unwrap();
1375 write!(w, "=>").unwrap();
1377 macro_rules! handle_field_a {
1378 ($field: expr, $field_ident: expr) => { {
1379 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1380 let mut sink = ::std::io::sink();
1381 let mut out: &mut dyn std::io::Write = if $ref { &mut sink } else { w };
1382 let new_var = if $to_c {
1383 types.write_to_c_conversion_new_var(&mut out, $field_ident, &$field.ty, Some(&gen_types), false)
1385 types.write_from_c_conversion_new_var(&mut out, $field_ident, &$field.ty, Some(&gen_types))
1387 if $ref || new_var {
1389 write!(w, "let mut {}_nonref = (*{}).clone();\n\t\t\t\t", $field_ident, $field_ident).unwrap();
1391 let nonref_ident = format_ident!("{}_nonref", $field_ident);
1393 types.write_to_c_conversion_new_var(w, &nonref_ident, &$field.ty, Some(&gen_types), false);
1395 types.write_from_c_conversion_new_var(w, &nonref_ident, &$field.ty, Some(&gen_types));
1397 write!(w, "\n\t\t\t\t").unwrap();
1400 write!(w, "\n\t\t\t\t").unwrap();
1405 if let syn::Fields::Named(fields) = &var.fields {
1406 write!(w, " {{\n\t\t\t\t").unwrap();
1407 for field in fields.named.iter() {
1408 handle_field_a!(field, field.ident.as_ref().unwrap());
1410 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1411 write!(w, " {{\n\t\t\t\t").unwrap();
1412 for (idx, field) in fields.unnamed.iter().enumerate() {
1413 if !empty_tuple_variant {
1414 handle_field_a!(field, &format_ident!("{}", ('a' as u8 + idx as u8) as char));
1417 } else { write!(w, " ").unwrap(); }
1419 write!(w, "{}{}::{}", if $to_c { "" } else { "native" }, e.ident, var.ident).unwrap();
1421 macro_rules! handle_field_b {
1422 ($field: expr, $field_ident: expr) => { {
1423 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1425 types.write_to_c_conversion_inline_prefix(w, &$field.ty, Some(&gen_types), false);
1427 types.write_from_c_conversion_prefix(w, &$field.ty, Some(&gen_types));
1429 write!(w, "{}{}", $field_ident,
1430 if $ref { "_nonref" } else { "" }).unwrap();
1432 types.write_to_c_conversion_inline_suffix(w, &$field.ty, Some(&gen_types), false);
1434 types.write_from_c_conversion_suffix(w, &$field.ty, Some(&gen_types));
1436 write!(w, ",").unwrap();
1440 if let syn::Fields::Named(fields) = &var.fields {
1441 write!(w, " {{").unwrap();
1442 for field in fields.named.iter() {
1443 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1444 write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1445 handle_field_b!(field, field.ident.as_ref().unwrap());
1447 writeln!(w, "\n\t\t\t\t}}").unwrap();
1448 write!(w, "\t\t\t}}").unwrap();
1449 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1450 if !empty_tuple_variant || !$to_c {
1451 write!(w, " (").unwrap();
1452 for (idx, field) in fields.unnamed.iter().enumerate() {
1453 write!(w, "\n\t\t\t\t\t").unwrap();
1454 handle_field_b!(field, &format_ident!("{}", ('a' as u8 + idx as u8) as char));
1456 writeln!(w, "\n\t\t\t\t)").unwrap();
1458 write!(w, "\t\t\t}}").unwrap();
1460 writeln!(w, ",").unwrap();
1462 writeln!(w, "\t\t}}\n\t}}").unwrap();
1466 write_conv!(format!("to_native(&self) -> native{}", e.ident), false, true);
1467 write_conv!(format!("into_native(self) -> native{}", e.ident), false, false);
1468 write_conv!(format!("from_native(native: &native{}) -> Self", e.ident), true, true);
1469 write_conv!(format!("native_into(native: native{}) -> Self", e.ident), true, false);
1470 writeln!(w, "}}").unwrap();
1473 writeln!(w, "/// Frees any resources used by the {}", e.ident).unwrap();
1474 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", e.ident, e.ident).unwrap();
1476 writeln!(w, "/// Creates a copy of the {}", e.ident).unwrap();
1477 writeln!(w, "#[no_mangle]").unwrap();
1478 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
1479 writeln!(w, "\torig.clone()").unwrap();
1480 writeln!(w, "}}").unwrap();
1481 w.write_all(&constr).unwrap();
1482 write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free, None);
1485 fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &mut TypeResolver<'b, 'a>) {
1486 match export_status(&f.attrs) {
1487 ExportStatus::Export => {},
1488 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1489 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1491 let mut gen_types = GenericTypes::new(None);
1492 if !gen_types.learn_generics(&f.sig.generics, types) { return; }
1494 writeln_fn_docs(w, &f.attrs, "", types, Some(&gen_types), f.sig.inputs.iter(), &f.sig.output);
1496 write!(w, "#[no_mangle]\npub extern \"C\" fn {}(", f.sig.ident).unwrap();
1497 write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
1498 write!(w, " {{\n\t").unwrap();
1499 write_method_var_decl_body(w, &f.sig, "", types, Some(&gen_types), false);
1500 write!(w, "{}::{}(", types.module_path, f.sig.ident).unwrap();
1501 write_method_call_params(w, &f.sig, "", types, Some(&gen_types), "", false);
1502 writeln!(w, "\n}}\n").unwrap();
1505 // ********************************
1506 // *** File/Crate Walking Logic ***
1507 // ********************************
1509 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) {
1510 // We want to ignore all items declared in this module (as they are not pub), but we still need
1511 // to give the ImportResolver any use statements, so we copy them here.
1512 let mut use_items = Vec::new();
1513 for item in module.content.as_ref().unwrap().1.iter() {
1514 if let syn::Item::Use(_) = item {
1515 use_items.push(item);
1518 let import_resolver = ImportResolver::from_borrowed_items(mod_path.splitn(2, "::").next().unwrap(), &libast.dependencies, mod_path, &use_items);
1519 let mut types = TypeResolver::new(mod_path, import_resolver, crate_types);
1521 writeln!(w, "mod {} {{\n{}", module.ident, DEFAULT_IMPORTS).unwrap();
1522 for item in module.content.as_ref().unwrap().1.iter() {
1524 syn::Item::Mod(m) => convert_priv_mod(w, libast, crate_types, out_dir, &format!("{}::{}", mod_path, module.ident), m),
1525 syn::Item::Impl(i) => {
1526 if let &syn::Type::Path(ref p) = &*i.self_ty {
1527 if p.path.get_ident().is_some() {
1528 writeln_impl(w, i, &mut types);
1535 writeln!(w, "}}").unwrap();
1538 /// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
1539 /// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
1540 /// at `module` from C.
1541 fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &CrateTypes<'a>, out_dir: &str, header_file: &mut File, cpp_header_file: &mut File) {
1542 for (module, astmod) in libast.modules.iter() {
1543 let orig_crate = module.splitn(2, "::").next().unwrap();
1544 let ASTModule { ref attrs, ref items, ref submods } = astmod;
1545 assert_eq!(export_status(&attrs), ExportStatus::Export);
1547 let new_file_path = if submods.is_empty() {
1548 format!("{}/{}.rs", out_dir, module.replace("::", "/"))
1549 } else if module != "" {
1550 format!("{}/{}/mod.rs", out_dir, module.replace("::", "/"))
1552 format!("{}/lib.rs", out_dir)
1554 let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
1555 let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1556 .open(new_file_path).expect("Unable to open new src file");
1558 writeln!(out, "// This file is Copyright its original authors, visible in version control").unwrap();
1559 writeln!(out, "// history and in the source files from which this was generated.").unwrap();
1560 writeln!(out, "//").unwrap();
1561 writeln!(out, "// This file is licensed under the license available in the LICENSE or LICENSE.md").unwrap();
1562 writeln!(out, "// file in the root of this repository or, if no such file exists, the same").unwrap();
1563 writeln!(out, "// license as that which applies to the original source files from which this").unwrap();
1564 writeln!(out, "// source was automatically generated.").unwrap();
1565 writeln!(out, "").unwrap();
1567 writeln_docs(&mut out, &attrs, "");
1570 // Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
1571 // and bitcoin hand-written modules.
1572 writeln!(out, "//! C Bindings").unwrap();
1573 writeln!(out, "#![allow(unknown_lints)]").unwrap();
1574 writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
1575 writeln!(out, "#![allow(non_snake_case)]").unwrap();
1576 writeln!(out, "#![allow(unused_imports)]").unwrap();
1577 writeln!(out, "#![allow(unused_variables)]").unwrap();
1578 writeln!(out, "#![allow(unused_mut)]").unwrap();
1579 writeln!(out, "#![allow(unused_parens)]").unwrap();
1580 writeln!(out, "#![allow(unused_unsafe)]").unwrap();
1581 writeln!(out, "#![allow(unused_braces)]").unwrap();
1582 // TODO: We need to map deny(missing_docs) in the source crate(s)
1583 //writeln!(out, "#![deny(missing_docs)]").unwrap();
1584 writeln!(out, "pub mod version;").unwrap();
1585 writeln!(out, "pub mod c_types;").unwrap();
1586 writeln!(out, "pub mod bitcoin;").unwrap();
1588 writeln!(out, "{}", DEFAULT_IMPORTS).unwrap();
1592 writeln!(out, "pub mod {};", m).unwrap();
1595 eprintln!("Converting {} entries...", module);
1597 let import_resolver = ImportResolver::new(orig_crate, &libast.dependencies, module, items);
1598 let mut type_resolver = TypeResolver::new(module, import_resolver, crate_types);
1600 for item in items.iter() {
1602 syn::Item::Use(_) => {}, // Handled above
1603 syn::Item::Static(_) => {},
1604 syn::Item::Enum(e) => {
1605 if let syn::Visibility::Public(_) = e.vis {
1606 writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
1609 syn::Item::Impl(i) => {
1610 writeln_impl(&mut out, &i, &mut type_resolver);
1612 syn::Item::Struct(s) => {
1613 if let syn::Visibility::Public(_) = s.vis {
1614 writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
1617 syn::Item::Trait(t) => {
1618 if let syn::Visibility::Public(_) = t.vis {
1619 writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
1622 syn::Item::Mod(m) => {
1623 convert_priv_mod(&mut out, libast, crate_types, out_dir, &format!("{}::{}", module, m.ident), m);
1625 syn::Item::Const(c) => {
1626 // Re-export any primitive-type constants.
1627 if let syn::Visibility::Public(_) = c.vis {
1628 if let syn::Type::Path(p) = &*c.ty {
1629 let resolved_path = type_resolver.resolve_path(&p.path, None);
1630 if type_resolver.is_primitive(&resolved_path) {
1631 writeln_field_docs(&mut out, &c.attrs, "", &mut type_resolver, None, &*c.ty);
1632 writeln!(out, "\n#[no_mangle]").unwrap();
1633 writeln!(out, "pub static {}: {} = {}::{};", c.ident, resolved_path, module, c.ident).unwrap();
1638 syn::Item::Type(t) => {
1639 if let syn::Visibility::Public(_) = t.vis {
1640 match export_status(&t.attrs) {
1641 ExportStatus::Export => {},
1642 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1643 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1646 let mut process_alias = true;
1647 for tok in t.generics.params.iter() {
1648 if let syn::GenericParam::Lifetime(_) = tok {}
1649 else { process_alias = false; }
1653 syn::Type::Path(_) =>
1654 writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &t.generics, &t.attrs, &type_resolver, header_file, cpp_header_file),
1660 syn::Item::Fn(f) => {
1661 if let syn::Visibility::Public(_) = f.vis {
1662 writeln_fn(&mut out, &f, &mut type_resolver);
1665 syn::Item::Macro(_) => {},
1666 syn::Item::Verbatim(_) => {},
1667 syn::Item::ExternCrate(_) => {},
1668 _ => unimplemented!(),
1672 out.flush().unwrap();
1676 fn walk_private_mod<'a>(ast_storage: &'a FullLibraryAST, orig_crate: &str, module: String, items: &'a syn::ItemMod, crate_types: &mut CrateTypes<'a>) {
1677 let import_resolver = ImportResolver::new(orig_crate, &ast_storage.dependencies, &module, &items.content.as_ref().unwrap().1);
1678 for item in items.content.as_ref().unwrap().1.iter() {
1680 syn::Item::Mod(m) => walk_private_mod(ast_storage, orig_crate, format!("{}::{}", module, m.ident), m, crate_types),
1681 syn::Item::Impl(i) => {
1682 if let &syn::Type::Path(ref p) = &*i.self_ty {
1683 if let Some(trait_path) = i.trait_.as_ref() {
1684 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1685 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1686 match crate_types.trait_impls.entry(sp) {
1687 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1688 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1700 /// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
1701 fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
1702 for (module, astmod) in ast_storage.modules.iter() {
1703 let ASTModule { ref attrs, ref items, submods: _ } = astmod;
1704 assert_eq!(export_status(&attrs), ExportStatus::Export);
1705 let orig_crate = module.splitn(2, "::").next().unwrap();
1706 let import_resolver = ImportResolver::new(orig_crate, &ast_storage.dependencies, module, items);
1708 for item in items.iter() {
1710 syn::Item::Struct(s) => {
1711 if let syn::Visibility::Public(_) = s.vis {
1712 match export_status(&s.attrs) {
1713 ExportStatus::Export => {},
1714 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1715 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1717 let struct_path = format!("{}::{}", module, s.ident);
1718 crate_types.opaques.insert(struct_path, &s.ident);
1721 syn::Item::Trait(t) => {
1722 if let syn::Visibility::Public(_) = t.vis {
1723 match export_status(&t.attrs) {
1724 ExportStatus::Export|ExportStatus::NotImplementable => {},
1725 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1727 let trait_path = format!("{}::{}", module, t.ident);
1728 walk_supertraits!(t, None, (
1730 crate_types.set_clonable("crate::".to_owned() + &trait_path);
1734 crate_types.traits.insert(trait_path, &t);
1737 syn::Item::Type(t) => {
1738 if let syn::Visibility::Public(_) = t.vis {
1739 match export_status(&t.attrs) {
1740 ExportStatus::Export => {},
1741 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1742 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1744 let type_path = format!("{}::{}", module, t.ident);
1745 let mut process_alias = true;
1746 for tok in t.generics.params.iter() {
1747 if let syn::GenericParam::Lifetime(_) = tok {}
1748 else { process_alias = false; }
1752 syn::Type::Path(p) => {
1753 let t_ident = &t.ident;
1755 // If its a path with no generics, assume we don't map the aliased type and map it opaque
1756 let path_obj = parse_quote!(#t_ident);
1757 let args_obj = p.path.segments.last().unwrap().arguments.clone();
1758 match crate_types.reverse_alias_map.entry(import_resolver.maybe_resolve_path(&p.path, None).unwrap()) {
1759 hash_map::Entry::Occupied(mut e) => { e.get_mut().push((path_obj, args_obj)); },
1760 hash_map::Entry::Vacant(e) => { e.insert(vec![(path_obj, args_obj)]); },
1763 crate_types.opaques.insert(type_path, t_ident);
1766 crate_types.type_aliases.insert(type_path, import_resolver.resolve_imported_refs((*t.ty).clone()));
1772 syn::Item::Enum(e) if is_enum_opaque(e) => {
1773 if let syn::Visibility::Public(_) = e.vis {
1774 match export_status(&e.attrs) {
1775 ExportStatus::Export => {},
1776 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1777 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1779 let enum_path = format!("{}::{}", module, e.ident);
1780 crate_types.opaques.insert(enum_path, &e.ident);
1783 syn::Item::Enum(e) => {
1784 if let syn::Visibility::Public(_) = e.vis {
1785 match export_status(&e.attrs) {
1786 ExportStatus::Export => {},
1787 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1788 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1790 let enum_path = format!("{}::{}", module, e.ident);
1791 crate_types.mirrored_enums.insert(enum_path, &e);
1794 syn::Item::Impl(i) => {
1795 if let &syn::Type::Path(ref p) = &*i.self_ty {
1796 if let Some(trait_path) = i.trait_.as_ref() {
1797 if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) {
1798 if let Some(full_path) = import_resolver.maybe_resolve_path(&p.path, None) {
1799 crate_types.set_clonable("crate::".to_owned() + &full_path);
1802 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1803 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1804 match crate_types.trait_impls.entry(sp) {
1805 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1806 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1813 syn::Item::Mod(m) => walk_private_mod(ast_storage, orig_crate, format!("{}::{}", module, m.ident), m, crate_types),
1821 let args: Vec<String> = env::args().collect();
1822 if args.len() != 5 {
1823 eprintln!("Usage: target/dir derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
1827 let mut derived_templates = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1828 .open(&args[2]).expect("Unable to open new header file");
1829 let mut header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1830 .open(&args[3]).expect("Unable to open new header file");
1831 let mut cpp_header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1832 .open(&args[4]).expect("Unable to open new header file");
1834 writeln!(header_file, "#if defined(__GNUC__)").unwrap();
1835 writeln!(header_file, "#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
1836 writeln!(header_file, "#define MUST_USE_RES __attribute__((warn_unused_result))").unwrap();
1837 writeln!(header_file, "#else").unwrap();
1838 writeln!(header_file, "#define MUST_USE_STRUCT").unwrap();
1839 writeln!(header_file, "#define MUST_USE_RES").unwrap();
1840 writeln!(header_file, "#endif").unwrap();
1841 writeln!(header_file, "#if defined(__clang__)").unwrap();
1842 writeln!(header_file, "#define NONNULL_PTR _Nonnull").unwrap();
1843 writeln!(header_file, "#else").unwrap();
1844 writeln!(header_file, "#define NONNULL_PTR").unwrap();
1845 writeln!(header_file, "#endif").unwrap();
1846 writeln!(cpp_header_file, "#include <string.h>\nnamespace LDK {{").unwrap();
1848 // First parse the full crate's ASTs, caching them so that we can hold references to the AST
1849 // objects in other datastructures:
1850 let mut lib_src = String::new();
1851 std::io::stdin().lock().read_to_string(&mut lib_src).unwrap();
1852 let lib_syntax = syn::parse_file(&lib_src).expect("Unable to parse file");
1853 let libast = FullLibraryAST::load_lib(lib_syntax);
1855 // ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
1856 // when parsing other file ASTs...
1857 let mut libtypes = CrateTypes::new(&mut derived_templates, &libast);
1858 walk_ast(&libast, &mut libtypes);
1860 // ... finally, do the actual file conversion/mapping, writing out types as we go.
1861 convert_file(&libast, &libtypes, &args[1], &mut header_file, &mut cpp_header_file);
1863 // For container templates which we created while walking the crate, make sure we add C++
1864 // mapped types so that C++ users can utilize the auto-destructors available.
1865 for (ty, has_destructor) in libtypes.templates_defined.borrow().iter() {
1866 write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor, None);
1868 writeln!(cpp_header_file, "}}").unwrap();
1870 header_file.flush().unwrap();
1871 cpp_header_file.flush().unwrap();
1872 derived_templates.flush().unwrap();