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, HashSet};
24 use std::io::{Read, Write};
25 use std::iter::FromIterator;
28 use proc_macro2::Span;
29 use quote::format_ident;
37 const DEFAULT_IMPORTS: &'static str = "
38 use alloc::str::FromStr;
39 use alloc::string::String;
40 use core::ffi::c_void;
41 use core::convert::Infallible;
42 use bitcoin::hashes::Hash;
43 use crate::c_types::*;
44 #[cfg(feature=\"no-std\")]
45 use alloc::{vec::Vec, boxed::Box};
49 /// str.rsplit_once but with an older MSRV
50 fn rsplit_once<'a>(inp: &'a str, pattern: &str) -> Option<(&'a str, &'a str)> {
51 let mut iter = inp.rsplitn(2, pattern);
52 let second_entry = iter.next().unwrap();
53 Some((iter.next().unwrap(), second_entry))
56 // *************************************
57 // *** Manually-expanded conversions ***
58 // *************************************
60 /// Convert "impl trait_path for for_ty { .. }" for manually-mapped types (ie (de)serialization)
61 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) {
62 if let Some(t) = types.maybe_resolve_path(&trait_path, Some(generics)) {
65 let mut has_inner = false;
66 if let syn::Type::Path(ref p) = for_ty {
67 let resolved_path = types.resolve_path(&p.path, Some(generics));
68 for_obj = format!("{}", p.path.segments.last().unwrap().ident);
69 full_obj_path = format!("crate::{}", resolved_path);
70 has_inner = types.c_type_has_inner_from_path(&resolved_path);
72 // We assume that anything that isn't a Path is somehow a generic that ends up in our
73 // derived-types module.
74 let mut for_obj_vec = Vec::new();
75 types.write_c_type(&mut for_obj_vec, for_ty, Some(generics), false);
76 full_obj_path = String::from_utf8(for_obj_vec).unwrap();
77 if !full_obj_path.starts_with(TypeResolver::generated_container_path()) { return; }
78 for_obj = full_obj_path[TypeResolver::generated_container_path().len() + 2..].into();
82 "lightning::util::ser::Writeable" => {
83 writeln!(w, "#[no_mangle]").unwrap();
84 writeln!(w, "/// Serialize the {} object into a byte array which can be read by {}_read", for_obj, for_obj).unwrap();
85 writeln!(w, "pub extern \"C\" fn {}_write(obj: &{}) -> crate::c_types::derived::CVec_u8Z {{", for_obj, full_obj_path).unwrap();
87 let ref_type: syn::Type = syn::parse_quote!(&#for_ty);
88 assert!(!types.write_from_c_conversion_new_var(w, &format_ident!("obj"), &ref_type, Some(generics)));
90 write!(w, "\tcrate::c_types::serialize_obj(").unwrap();
91 types.write_from_c_conversion_prefix(w, &ref_type, Some(generics));
92 write!(w, "unsafe {{ &*obj }}").unwrap();
93 types.write_from_c_conversion_suffix(w, &ref_type, Some(generics));
94 writeln!(w, ")").unwrap();
96 writeln!(w, "}}").unwrap();
98 writeln!(w, "#[allow(unused)]").unwrap();
99 writeln!(w, "pub(crate) extern \"C\" fn {}_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {{", for_obj).unwrap();
101 writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &*(obj as *const native{}) }})", for_obj).unwrap();
103 writeln!(w, "\t{}_write(unsafe {{ &*(obj as *const {}) }})", for_obj, for_obj).unwrap();
105 writeln!(w, "}}").unwrap();
107 "lightning::util::ser::Readable"|"lightning::util::ser::ReadableArgs"|"lightning::util::ser::MaybeReadable" => {
108 // Create the Result<Object, DecodeError> syn::Type
109 let mut res_ty: syn::Type = parse_quote!(Result<#for_ty, lightning::ln::msgs::DecodeError>);
111 writeln!(w, "#[no_mangle]").unwrap();
112 writeln!(w, "/// Read a {} from a byte array, created by {}_write", for_obj, for_obj).unwrap();
113 write!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice", for_obj).unwrap();
115 let mut arg_conv = Vec::new();
116 if t == "lightning::util::ser::ReadableArgs" {
117 assert!(trait_path.leading_colon.is_none());
118 let args_seg = trait_path.segments.iter().last().unwrap();
119 assert_eq!(format!("{}", args_seg.ident), "ReadableArgs");
120 if let syn::PathArguments::AngleBracketed(args) = &args_seg.arguments {
121 assert_eq!(args.args.len(), 1);
122 if let syn::GenericArgument::Type(args_ty) = args.args.iter().next().unwrap() {
123 macro_rules! write_arg_conv {
124 ($ty: expr, $arg_name: expr) => {
125 write!(w, ", {}: ", $arg_name).unwrap();
126 types.write_c_type(w, $ty, Some(generics), false);
128 write!(&mut arg_conv, "\t").unwrap();
129 if types.write_from_c_conversion_new_var(&mut arg_conv, &format_ident!("{}", $arg_name), &$ty, Some(generics)) {
130 write!(&mut arg_conv, "\n\t").unwrap();
133 write!(&mut arg_conv, "let {}_conv = ", $arg_name).unwrap();
134 types.write_from_c_conversion_prefix(&mut arg_conv, &$ty, Some(generics));
135 write!(&mut arg_conv, "{}", $arg_name).unwrap();
136 types.write_from_c_conversion_suffix(&mut arg_conv, &$ty, Some(generics));
137 write!(&mut arg_conv, ";\n").unwrap();
141 if let syn::Type::Tuple(tup) = args_ty {
142 // Crack open tuples and make them separate arguments instead of
143 // converting the full tuple. This makes it substantially easier to
144 // reason about things like references in the tuple fields.
145 let mut arg_conv_res = Vec::new();
146 for (idx, elem) in tup.elems.iter().enumerate() {
147 let arg_name = format!("arg_{}", ('a' as u8 + idx as u8) as char);
148 write_arg_conv!(elem, arg_name);
149 write!(&mut arg_conv_res, "{}_conv{}", arg_name, if idx != tup.elems.len() - 1 { ", " } else { "" }).unwrap();
151 writeln!(&mut arg_conv, "\tlet arg_conv = ({});", String::from_utf8(arg_conv_res).unwrap()).unwrap();
153 write_arg_conv!(args_ty, "arg");
155 } else { unreachable!(); }
156 } else { unreachable!(); }
157 } else if t == "lightning::util::ser::MaybeReadable" {
158 res_ty = parse_quote!(Result<Option<#for_ty>, lightning::ln::msgs::DecodeError>);
160 write!(w, ") -> ").unwrap();
161 types.write_c_type(w, &res_ty, Some(generics), false);
162 writeln!(w, " {{").unwrap();
164 if t == "lightning::util::ser::ReadableArgs" {
165 w.write(&arg_conv).unwrap();
168 write!(w, "\tlet res: ").unwrap();
169 // At least in one case we need type annotations here, so provide them.
170 types.write_rust_type(w, Some(generics), &res_ty, false);
172 if t == "lightning::util::ser::ReadableArgs" {
173 writeln!(w, " = crate::c_types::deserialize_obj_arg(ser, arg_conv);").unwrap();
174 } else if t == "lightning::util::ser::MaybeReadable" {
175 writeln!(w, " = crate::c_types::maybe_deserialize_obj(ser);").unwrap();
177 writeln!(w, " = crate::c_types::deserialize_obj(ser);").unwrap();
179 write!(w, "\t").unwrap();
180 if types.write_to_c_conversion_new_var(w, &format_ident!("res"), &res_ty, Some(generics), false) {
181 write!(w, "\n\t").unwrap();
183 types.write_to_c_conversion_inline_prefix(w, &res_ty, Some(generics), false);
184 write!(w, "res").unwrap();
185 types.write_to_c_conversion_inline_suffix(w, &res_ty, Some(generics), false);
186 writeln!(w, "\n}}").unwrap();
193 /// Convert "TraitA : TraitB" to a single function name and return type.
195 /// This is (obviously) somewhat over-specialized and only useful for TraitB's that only require a
196 /// single function (eg for serialization).
197 fn convert_trait_impl_field(trait_path: &str) -> (&'static str, String, &'static str) {
199 "lightning::util::ser::Writeable" => ("Serialize the object into a byte array", "write".to_owned(), "crate::c_types::derived::CVec_u8Z"),
200 _ => unimplemented!(),
204 /// Companion to convert_trait_impl_field, write an assignment for the function defined by it for
205 /// `for_obj` which implements the the trait at `trait_path`.
206 fn write_trait_impl_field_assign<W: std::io::Write>(w: &mut W, trait_path: &str, for_obj: &syn::Ident) {
208 "lightning::util::ser::Writeable" => {
209 writeln!(w, "\t\twrite: {}_write_void,", for_obj).unwrap();
211 _ => unimplemented!(),
215 /// Write out the impl block for a defined trait struct which has a supertrait
216 fn do_write_impl_trait<W: std::io::Write>(w: &mut W, trait_path: &str, _trait_name: &syn::Ident, for_obj: &str) {
218 "lightning::util::ser::Writeable" => {
219 writeln!(w, "impl {} for {} {{", trait_path, for_obj).unwrap();
220 writeln!(w, "\tfn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> {{").unwrap();
221 writeln!(w, "\t\tlet vec = (self.write)(self.this_arg);").unwrap();
222 writeln!(w, "\t\tw.write_all(vec.as_slice())").unwrap();
223 writeln!(w, "\t}}\n}}").unwrap();
229 /// Returns true if an instance of the given type must never exist
230 fn is_type_unconstructable(path: &str) -> bool {
231 path == "core::convert::Infallible" || path == "crate::c_types::NotConstructable"
234 // *******************************
235 // *** Per-Type Printing Logic ***
236 // *******************************
238 macro_rules! walk_supertraits { ($t: expr, $types: expr, ($( $($pat: pat)|* => $e: expr),*) ) => { {
239 if $t.colon_token.is_some() {
240 for st in $t.supertraits.iter() {
242 syn::TypeParamBound::Trait(supertrait) => {
243 if supertrait.paren_token.is_some() || supertrait.lifetimes.is_some() {
246 // First try to resolve path to find in-crate traits, but if that doesn't work
247 // assume its a prelude trait (eg Clone, etc) and just use the single ident.
248 let types_opt: Option<&TypeResolver> = $types;
249 if let Some(types) = types_opt {
250 if let Some(path) = types.maybe_resolve_path(&supertrait.path, None) {
251 let last_seg = supertrait.path.segments.iter().last().unwrap();
252 match (&path as &str, &last_seg.ident, &last_seg.arguments) {
253 $( $($pat)|* => $e, )*
258 if let Some(ident) = supertrait.path.get_ident() {
259 match (&format!("{}", ident) as &str, &ident, &syn::PathArguments::None) {
260 $( $($pat)|* => $e, )*
262 } else if types_opt.is_some() {
263 panic!("Supertrait unresolvable and not single-ident");
266 syn::TypeParamBound::Lifetime(_) => unimplemented!(),
272 macro_rules! get_module_type_resolver {
273 ($type_in_module: expr, $crate_types: expr) => { {
274 let module: &str = &$type_in_module;
275 let mut module_iter = module.rsplitn(2, "::");
276 module_iter.next().unwrap();
277 let module = module_iter.next().unwrap();
278 let imports = ImportResolver::new(module.splitn(2, "::").next().unwrap(), &$crate_types.lib_ast,
279 module, &$crate_types.lib_ast.modules.get(module).unwrap().items);
280 TypeResolver::new(module, imports, $crate_types)
284 /// Prints a C-mapped trait object containing a void pointer and a jump table for each function in
285 /// the original trait.
286 /// Implements the native Rust trait and relevant parent traits for the new C-mapped trait.
288 /// Finally, implements Deref<MappedTrait> for MappedTrait which allows its use in types which need
289 /// a concrete Deref to the Rust trait.
290 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) {
291 let trait_name = format!("{}", t.ident);
293 match export_status(&t.attrs) {
294 ExportStatus::Export => { implementable = true; }
295 ExportStatus::NotImplementable => { implementable = false; },
296 ExportStatus::NoExport|ExportStatus::TestOnly => return,
298 writeln_docs(w, &t.attrs, "");
300 let mut gen_types = GenericTypes::new(Some(format!("{}::{}", types.module_path, trait_name)));
302 // Add functions which may be required for supertrait implementations.
303 // Due to borrow checker limitations, we only support one in-crate supertrait here.
305 let supertrait_resolver;
306 walk_supertraits!(t, Some(&types), (
308 if let Some(supertrait) = types.crate_types.traits.get(s) {
309 supertrait_name = s.to_string();
310 supertrait_resolver = get_module_type_resolver!(supertrait_name, types.crate_types);
311 gen_types.learn_associated_types(&supertrait, &supertrait_resolver);
317 assert!(gen_types.learn_generics(&t.generics, types));
318 gen_types.learn_associated_types(&t, types);
320 writeln!(w, "#[repr(C)]\npub struct {} {{", trait_name).unwrap();
321 writeln!(w, "\t/// An opaque pointer which is passed to your function implementations as an argument.").unwrap();
322 writeln!(w, "\t/// This has no meaning in the LDK, and can be NULL or any other value.").unwrap();
323 writeln!(w, "\tpub this_arg: *mut c_void,").unwrap();
324 // We store every field's (name, Option<clone_fn>, docs) except this_arg, used in Clone generation
325 // docs is only set if its a function which should be callable on the object itself in C++
326 let mut generated_fields = Vec::new();
327 for item in t.items.iter() {
329 &syn::TraitItem::Method(ref m) => {
330 match export_status(&m.attrs) {
331 ExportStatus::NoExport => {
332 // NoExport in this context means we'll hit an unimplemented!() at runtime,
336 ExportStatus::Export => {},
337 ExportStatus::TestOnly => continue,
338 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
341 let mut meth_gen_types = gen_types.push_ctx();
342 assert!(meth_gen_types.learn_generics(&m.sig.generics, types));
344 writeln_fn_docs(w, &m.attrs, "\t", types, Some(&meth_gen_types), m.sig.inputs.iter(), &m.sig.output);
346 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
347 if let syn::Type::Reference(r) = &**rtype {
348 // We have to do quite a dance for trait functions which return references
349 // - they ultimately require us to have a native Rust object stored inside
350 // our concrete trait to return a reference to. However, users may wish to
351 // update the value to be returned each time the function is called (or, to
352 // make C copies of Rust impls equivalent, we have to be able to).
354 // Thus, we store a copy of the C-mapped type (which is just a pointer to
355 // the Rust type and a flag to indicate whether deallocation needs to
356 // happen) as well as provide an Option<>al function pointer which is
357 // called when the trait method is called which allows updating on the fly.
358 write!(w, "\tpub {}: core::cell::UnsafeCell<", m.sig.ident).unwrap();
359 generated_fields.push((format!("{}", m.sig.ident), Some(("Clone::clone(unsafe { &*core::cell::UnsafeCell::get(".to_owned(), ")}).into()")), None));
360 types.write_c_type(w, &*r.elem, Some(&meth_gen_types), false);
361 writeln!(w, ">,").unwrap();
362 writeln!(w, "\t/// Fill in the {} field as a reference to it will be given to Rust after this returns", m.sig.ident).unwrap();
363 writeln!(w, "\t/// Note that this takes a pointer to this object, not the this_ptr like other methods do").unwrap();
364 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();
365 writeln!(w, "\tpub set_{}: Option<extern \"C\" fn(&{})>,", m.sig.ident, trait_name).unwrap();
366 generated_fields.push((format!("set_{}", m.sig.ident), None, None));
367 // Note that cbindgen will now generate
368 // typedef struct Thing {..., set_thing: (const struct Thing*), ...} Thing;
369 // which does not compile since Thing is not defined before it is used.
370 writeln!(extra_headers, "struct LDK{};", trait_name).unwrap();
375 let mut cpp_docs = Vec::new();
376 writeln_fn_docs(&mut cpp_docs, &m.attrs, "\t * ", types, Some(&meth_gen_types), m.sig.inputs.iter(), &m.sig.output);
377 let docs_string = "\t/**\n".to_owned() + &String::from_utf8(cpp_docs).unwrap().replace("///", "") + "\t */\n";
379 write!(w, "\tpub {}: extern \"C\" fn (", m.sig.ident).unwrap();
380 generated_fields.push((format!("{}", m.sig.ident), None, Some(docs_string)));
381 write_method_params(w, &m.sig, "c_void", types, Some(&meth_gen_types), true, false);
382 writeln!(w, ",").unwrap();
384 &syn::TraitItem::Type(_) => {},
385 _ => unimplemented!(),
388 // Add functions which may be required for supertrait implementations.
389 walk_supertraits!(t, Some(&types), (
391 writeln!(w, "\t/// Called, if set, after this {} has been cloned into a duplicate object.", trait_name).unwrap();
392 writeln!(w, "\t/// The new {} is provided, and should be mutated as needed to perform a", trait_name).unwrap();
393 writeln!(w, "\t/// deep copy of the object pointed to by this_arg or avoid any double-freeing.").unwrap();
394 writeln!(w, "\tpub cloned: Option<extern \"C\" fn (new_{}: &mut {})>,", trait_name, trait_name).unwrap();
395 generated_fields.push(("cloned".to_owned(), None, None));
397 ("std::cmp::Eq", _, _)|("core::cmp::Eq", _, _) => {
398 let eq_docs = "Checks if two objects are equal given this object's this_arg pointer and another object.";
399 writeln!(w, "\t/// {}", eq_docs).unwrap();
400 writeln!(w, "\tpub eq: extern \"C\" fn (this_arg: *const c_void, other_arg: &{}) -> bool,", trait_name).unwrap();
401 generated_fields.push(("eq".to_owned(), None, Some(format!("\t/** {} */\n", eq_docs))));
403 ("std::hash::Hash", _, _)|("core::hash::Hash", _, _) => {
404 let hash_docs_a = "Calculate a succinct non-cryptographic hash for an object given its this_arg pointer.";
405 let hash_docs_b = "This is used, for example, for inclusion of this object in a hash map.";
406 writeln!(w, "\t/// {}", hash_docs_a).unwrap();
407 writeln!(w, "\t/// {}", hash_docs_b).unwrap();
408 writeln!(w, "\tpub hash: extern \"C\" fn (this_arg: *const c_void) -> u64,").unwrap();
409 generated_fields.push(("hash".to_owned(), None,
410 Some(format!("\t/**\n\t * {}\n\t * {}\n\t */\n", hash_docs_a, hash_docs_b))));
412 ("Send", _, _) => {}, ("Sync", _, _) => {},
413 ("std::fmt::Debug", _, _)|("core::fmt::Debug", _, _) => {
414 let debug_docs = "Return a human-readable \"debug\" string describing this object";
415 writeln!(w, "\t/// {}", debug_docs).unwrap();
416 writeln!(w, "\tpub debug_str: extern \"C\" fn (this_arg: *const c_void) -> crate::c_types::Str,").unwrap();
417 generated_fields.push(("debug_str".to_owned(), None,
418 Some(format!("\t/**\n\t * {}\n\t */\n", debug_docs))));
421 // TODO: Both of the below should expose supertrait methods in C++, but doing so is
423 generated_fields.push(if types.crate_types.traits.get(s).is_none() {
424 let (docs, name, ret) = convert_trait_impl_field(s);
425 writeln!(w, "\t/// {}", docs).unwrap();
426 writeln!(w, "\tpub {}: extern \"C\" fn (this_arg: *const c_void) -> {},", name, ret).unwrap();
427 (name, None, None) // Assume clonable
429 // For in-crate supertraits, just store a C-mapped copy of the supertrait as a member.
430 writeln!(w, "\t/// Implementation of {} for this object.", i).unwrap();
431 let is_clonable = types.is_clonable(s);
432 writeln!(w, "\tpub {}: crate::{},", i, s).unwrap();
433 (format!("{}", i), if !is_clonable {
434 Some((format!("crate::{}_clone_fields(", s), ")"))
435 } else { None }, None)
439 writeln!(w, "\t/// Frees any resources associated with this object given its this_arg pointer.").unwrap();
440 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();
441 writeln!(w, "\tpub free: Option<extern \"C\" fn(this_arg: *mut c_void)>,").unwrap();
442 generated_fields.push(("free".to_owned(), None, None));
443 writeln!(w, "}}").unwrap();
445 macro_rules! impl_trait_for_c {
446 ($t: expr, $impl_accessor: expr, $type_resolver: expr, $generic_impls: expr) => {
447 let mut trait_gen_types = gen_types.push_ctx();
448 assert!(trait_gen_types.learn_generics_with_impls(&$t.generics, $generic_impls, $type_resolver));
449 for item in $t.items.iter() {
451 syn::TraitItem::Method(m) => {
452 if let ExportStatus::TestOnly = export_status(&m.attrs) { continue; }
453 if m.sig.constness.is_some() || m.sig.asyncness.is_some() || m.sig.unsafety.is_some() ||
454 m.sig.abi.is_some() || m.sig.variadic.is_some() {
457 let mut meth_gen_types = trait_gen_types.push_ctx();
458 assert!(meth_gen_types.learn_generics(&m.sig.generics, $type_resolver));
459 // Note that we do *not* use the method generics when printing "native"
460 // rust parts - if the method is generic, we need to print a generic
462 write!(w, "\tfn {}", m.sig.ident).unwrap();
463 $type_resolver.write_rust_generic_param(w, Some(&gen_types), m.sig.generics.params.iter());
464 write!(w, "(").unwrap();
465 for inp in m.sig.inputs.iter() {
467 syn::FnArg::Receiver(recv) => {
468 if !recv.attrs.is_empty() || recv.reference.is_none() { panic!("2"); }
469 write!(w, "&").unwrap();
470 if let Some(lft) = &recv.reference.as_ref().unwrap().1 {
471 write!(w, "'{} ", lft.ident).unwrap();
473 if recv.mutability.is_some() {
474 write!(w, "mut self").unwrap();
476 write!(w, "self").unwrap();
479 syn::FnArg::Typed(arg) => {
480 if !arg.attrs.is_empty() { panic!("3"); }
482 syn::Pat::Ident(ident) => {
483 if !ident.attrs.is_empty() || ident.by_ref.is_some() ||
484 ident.mutability.is_some() || ident.subpat.is_some() {
487 write!(w, ", mut {}{}: ", if $type_resolver.skip_arg(&*arg.ty, Some(&meth_gen_types)) { "_" } else { "" }, ident.ident).unwrap();
491 $type_resolver.write_rust_type(w, Some(&gen_types), &*arg.ty, false);
495 write!(w, ")").unwrap();
496 match &m.sig.output {
497 syn::ReturnType::Type(_, rtype) => {
498 write!(w, " -> ").unwrap();
499 $type_resolver.write_rust_type(w, Some(&gen_types), &*rtype, false)
503 write!(w, " {{\n\t\t").unwrap();
504 match export_status(&m.attrs) {
505 ExportStatus::NoExport => {
510 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
511 if let syn::Type::Reference(r) = &**rtype {
512 assert_eq!(m.sig.inputs.len(), 1); // Must only take self!
513 writeln!(w, "if let Some(f) = self{}.set_{} {{", $impl_accessor, m.sig.ident).unwrap();
514 writeln!(w, "\t\t\t(f)(&self{});", $impl_accessor).unwrap();
515 write!(w, "\t\t}}\n\t\t").unwrap();
516 $type_resolver.write_from_c_conversion_to_ref_prefix(w, &*r.elem, Some(&meth_gen_types));
517 write!(w, "unsafe {{ &*self{}.{}.get() }}", $impl_accessor, m.sig.ident).unwrap();
518 $type_resolver.write_from_c_conversion_to_ref_suffix(w, &*r.elem, Some(&meth_gen_types));
519 writeln!(w, "\n\t}}").unwrap();
523 write_method_var_decl_body(w, &m.sig, "\t", $type_resolver, Some(&meth_gen_types), true);
524 write!(w, "(self{}.{})(", $impl_accessor, m.sig.ident).unwrap();
525 let mut args = Vec::new();
526 write_method_call_params(&mut args, &m.sig, "\t", $type_resolver, Some(&meth_gen_types), "", true);
527 w.write_all(String::from_utf8(args).unwrap().replace("self", &format!("self{}", $impl_accessor)).as_bytes()).unwrap();
529 writeln!(w, "\n\t}}").unwrap();
531 &syn::TraitItem::Type(ref t) => {
532 if t.default.is_some() || t.generics.lt_token.is_some() { panic!("10"); }
533 let mut bounds_iter = t.bounds.iter();
535 match bounds_iter.next().unwrap() {
536 syn::TypeParamBound::Trait(tr) => {
537 writeln!(w, "\ttype {} = crate::{};", t.ident, $type_resolver.resolve_path(&tr.path, Some(&gen_types))).unwrap();
538 for bound in bounds_iter {
539 if let syn::TypeParamBound::Trait(t) = bound {
540 // We only allow for `Sized` here.
541 assert_eq!(t.path.segments.len(), 1);
542 assert_eq!(format!("{}", t.path.segments[0].ident), "Sized");
547 syn::TypeParamBound::Lifetime(_) => {},
557 writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap();
558 writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap();
560 writeln!(w, "#[allow(unused)]").unwrap();
561 writeln!(w, "pub(crate) fn {}_clone_fields(orig: &{}) -> {} {{", trait_name, trait_name, trait_name).unwrap();
562 writeln!(w, "\t{} {{", trait_name).unwrap();
563 writeln!(w, "\t\tthis_arg: orig.this_arg,").unwrap();
564 for (field, clone_fn, _) in generated_fields.iter() {
565 if let Some((pfx, sfx)) = clone_fn {
566 // If the field isn't clonable, blindly assume its a trait and hope for the best.
567 writeln!(w, "\t\t{}: {}&orig.{}{},", field, pfx, field, sfx).unwrap();
569 writeln!(w, "\t\t{}: Clone::clone(&orig.{}),", field, field).unwrap();
572 writeln!(w, "\t}}\n}}").unwrap();
574 // Implement supertraits for the C-mapped struct.
575 walk_supertraits!(t, Some(&types), (
576 ("std::cmp::Eq", _, _)|("core::cmp::Eq", _, _) => {
577 writeln!(w, "impl core::cmp::Eq for {} {{}}", trait_name).unwrap();
578 writeln!(w, "impl core::cmp::PartialEq for {} {{", trait_name).unwrap();
579 writeln!(w, "\tfn eq(&self, o: &Self) -> bool {{ (self.eq)(self.this_arg, o) }}\n}}").unwrap();
581 ("std::hash::Hash", _, _)|("core::hash::Hash", _, _) => {
582 writeln!(w, "impl core::hash::Hash for {} {{", trait_name).unwrap();
583 writeln!(w, "\tfn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {{ hasher.write_u64((self.hash)(self.this_arg)) }}\n}}").unwrap();
585 ("Send", _, _) => {}, ("Sync", _, _) => {},
587 writeln!(w, "#[no_mangle]").unwrap();
588 writeln!(w, "/// Creates a copy of a {}", trait_name).unwrap();
589 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", trait_name, trait_name, trait_name).unwrap();
590 writeln!(w, "\tlet mut res = {}_clone_fields(orig);", trait_name).unwrap();
591 writeln!(w, "\tif let Some(f) = orig.cloned {{ (f)(&mut res) }};").unwrap();
592 writeln!(w, "\tres\n}}").unwrap();
593 writeln!(w, "impl Clone for {} {{", trait_name).unwrap();
594 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
595 writeln!(w, "\t\t{}_clone(self)", trait_name).unwrap();
596 writeln!(w, "\t}}\n}}").unwrap();
598 ("std::fmt::Debug", _, _)|("core::fmt::Debug", _, _) => {
599 writeln!(w, "impl core::fmt::Debug for {} {{", trait_name).unwrap();
600 writeln!(w, "\tfn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {{").unwrap();
601 writeln!(w, "\t\tf.write_str((self.debug_str)(self.this_arg).into_str())").unwrap();
602 writeln!(w, "\t}}").unwrap();
603 writeln!(w, "}}").unwrap();
605 (s, i, generic_args) => {
606 if let Some(supertrait) = types.crate_types.traits.get(s) {
607 let resolver = get_module_type_resolver!(s, types.crate_types);
608 macro_rules! impl_supertrait {
609 ($s: expr, $supertrait: expr, $i: expr, $generic_args: expr) => {
610 let resolver = get_module_type_resolver!($s, types.crate_types);
612 // Blindly assume that the same imports where `supertrait` is defined are also
613 // imported here. This will almost certainly break at some point, but it should be
614 // a compilation failure when it does so.
615 write!(w, "impl").unwrap();
616 maybe_write_lifetime_generics(w, &$supertrait.generics, types);
617 write!(w, " {}", $s).unwrap();
618 maybe_write_generics(w, &$supertrait.generics, $generic_args, types, false);
619 writeln!(w, " for {} {{", trait_name).unwrap();
621 impl_trait_for_c!($supertrait, format!(".{}", $i), &resolver, $generic_args);
622 writeln!(w, "}}").unwrap();
625 impl_supertrait!(s, supertrait, i, generic_args);
626 walk_supertraits!(supertrait, Some(&resolver), (
627 (s, supertrait_i, generic_args) => {
628 if let Some(supertrait) = types.crate_types.traits.get(s) {
629 impl_supertrait!(s, supertrait, format!("{}.{}", i, supertrait_i), generic_args);
634 do_write_impl_trait(w, s, i, &trait_name);
639 // Finally, implement the original Rust trait for the newly created mapped trait.
640 writeln!(w, "\nuse {}::{} as rust{};", types.module_path, t.ident, trait_name).unwrap();
642 write!(w, "impl").unwrap();
643 maybe_write_lifetime_generics(w, &t.generics, types);
644 write!(w, " rust{}", t.ident).unwrap();
645 maybe_write_generics(w, &t.generics, &syn::PathArguments::None, types, false);
646 writeln!(w, " for {} {{", trait_name).unwrap();
647 impl_trait_for_c!(t, "", types, &syn::PathArguments::None);
648 writeln!(w, "}}\n").unwrap();
649 writeln!(w, "// We're essentially a pointer already, or at least a set of pointers, so allow us to be used").unwrap();
650 writeln!(w, "// directly as a Deref trait in higher-level structs:").unwrap();
651 writeln!(w, "impl core::ops::Deref for {} {{\n\ttype Target = Self;", trait_name).unwrap();
652 writeln!(w, "\tfn deref(&self) -> &Self {{\n\t\tself\n\t}}\n}}").unwrap();
653 writeln!(w, "impl core::ops::DerefMut for {} {{", trait_name).unwrap();
654 writeln!(w, "\tfn deref_mut(&mut self) -> &mut Self {{\n\t\tself\n\t}}\n}}").unwrap();
657 writeln!(w, "/// Calls the free function if one is set").unwrap();
658 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", trait_name, trait_name).unwrap();
659 writeln!(w, "impl Drop for {} {{", trait_name).unwrap();
660 writeln!(w, "\tfn drop(&mut self) {{").unwrap();
661 writeln!(w, "\t\tif let Some(f) = self.free {{").unwrap();
662 writeln!(w, "\t\t\tf(self.this_arg);").unwrap();
663 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
665 write_cpp_wrapper(cpp_headers, &trait_name, true, Some(generated_fields.drain(..)
666 .filter_map(|(name, _, docs)| if let Some(docs) = docs { Some((name, docs)) } else { None }).collect()));
669 /// Write out a simple "opaque" type (eg structs) which contain a pointer to the native Rust type
670 /// and a flag to indicate whether Drop'ing the mapped struct drops the underlying Rust type.
672 /// Also writes out a _free function and a C++ wrapper which handles calling _free.
673 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) {
674 // If we directly read the original type by its original name, cbindgen hits
675 // https://github.com/eqrion/cbindgen/issues/286 Thus, instead, we import it as a temporary
676 // name and then reference it by that name, which works around the issue.
677 write!(w, "\nuse {}::{} as native{}Import;\npub(crate) type native{} = native{}Import", types.module_path, ident, ident, ident, ident).unwrap();
678 maybe_write_generics(w, &generics, &syn::PathArguments::None, &types, true);
679 writeln!(w, ";\n").unwrap();
680 writeln!(extra_headers, "struct native{}Opaque;\ntypedef struct native{}Opaque LDKnative{};", ident, ident, ident).unwrap();
681 writeln_docs(w, &attrs, "");
682 writeln!(w, "#[must_use]\n#[repr(C)]\npub struct {} {{", struct_name).unwrap();
683 writeln!(w, "\t/// A pointer to the opaque Rust object.\n").unwrap();
684 writeln!(w, "\t/// Nearly everywhere, inner must be non-null, however in places where").unwrap();
685 writeln!(w, "\t/// the Rust equivalent takes an Option, it may be set to null to indicate None.").unwrap();
686 writeln!(w, "\tpub inner: *mut native{},", ident).unwrap();
687 writeln!(w, "\t/// Indicates that this is the only struct which contains the same pointer.\n").unwrap();
688 writeln!(w, "\t/// Rust functions which take ownership of an object provided via an argument require").unwrap();
689 writeln!(w, "\t/// this to be true and invalidate the object pointed to by inner.").unwrap();
690 writeln!(w, "\tpub is_owned: bool,").unwrap();
691 writeln!(w, "}}\n").unwrap();
692 writeln!(w, "impl Drop for {} {{\n\tfn drop(&mut self) {{", struct_name).unwrap();
693 writeln!(w, "\t\tif self.is_owned && !<*mut native{}>::is_null(self.inner) {{", ident).unwrap();
694 writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(ObjOps::untweak_ptr(self.inner)) }};\n\t\t}}\n\t}}\n}}").unwrap();
695 writeln!(w, "/// Frees any resources used by the {}, if is_owned is set and inner is non-NULL.", struct_name).unwrap();
696 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_obj: {}) {{ }}", struct_name, struct_name).unwrap();
697 writeln!(w, "#[allow(unused)]").unwrap();
698 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
699 writeln!(w, "pub(crate) extern \"C\" fn {}_free_void(this_ptr: *mut c_void) {{", struct_name).unwrap();
700 writeln!(w, "\tlet _ = unsafe {{ Box::from_raw(this_ptr as *mut native{}) }};\n}}", struct_name).unwrap();
701 writeln!(w, "#[allow(unused)]").unwrap();
702 writeln!(w, "impl {} {{", struct_name).unwrap();
703 writeln!(w, "\tpub(crate) fn get_native_ref(&self) -> &'static native{} {{", struct_name).unwrap();
704 writeln!(w, "\t\tunsafe {{ &*ObjOps::untweak_ptr(self.inner) }}").unwrap();
705 writeln!(w, "\t}}").unwrap();
706 writeln!(w, "\tpub(crate) fn get_native_mut_ref(&self) -> &'static mut native{} {{", struct_name).unwrap();
707 writeln!(w, "\t\tunsafe {{ &mut *ObjOps::untweak_ptr(self.inner) }}").unwrap();
708 writeln!(w, "\t}}").unwrap();
709 writeln!(w, "\t/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy").unwrap();
710 writeln!(w, "\tpub(crate) fn take_inner(mut self) -> *mut native{} {{", struct_name).unwrap();
711 writeln!(w, "\t\tassert!(self.is_owned);").unwrap();
712 writeln!(w, "\t\tlet ret = ObjOps::untweak_ptr(self.inner);").unwrap();
713 writeln!(w, "\t\tself.inner = core::ptr::null_mut();").unwrap();
714 writeln!(w, "\t\tret").unwrap();
715 writeln!(w, "\t}}\n}}").unwrap();
717 write_cpp_wrapper(cpp_headers, &format!("{}", ident), true, None);
720 /// Writes out all the relevant mappings for a Rust struct, deferring to writeln_opaque to generate
721 /// the struct itself, and then writing getters and setters for public, understood-type fields and
722 /// a constructor if every field is public.
723 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) {
724 if export_status(&s.attrs) != ExportStatus::Export { return; }
726 let struct_name = &format!("{}", s.ident);
727 writeln_opaque(w, &s.ident, struct_name, &s.generics, &s.attrs, types, extra_headers, cpp_headers);
729 let mut self_path_segs = syn::punctuated::Punctuated::new();
730 self_path_segs.push(s.ident.clone().into());
731 let self_path = syn::Path { leading_colon: None, segments: self_path_segs};
732 let mut gen_types = GenericTypes::new(Some(types.resolve_path(&self_path, None)));
733 assert!(gen_types.learn_generics(&s.generics, types));
735 let mut all_fields_settable = true;
736 macro_rules! define_field {
737 ($new_name: expr, $real_name: expr, $field: expr) => {
738 if let syn::Visibility::Public(_) = $field.vis {
739 let export = export_status(&$field.attrs);
741 ExportStatus::Export => {},
742 ExportStatus::NoExport|ExportStatus::TestOnly => {
743 all_fields_settable = false;
746 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
749 if let Some(ref_type) = types.create_ownable_reference(&$field.ty, Some(&gen_types)) {
750 if types.understood_c_type(&ref_type, Some(&gen_types)) {
751 writeln_arg_docs(w, &$field.attrs, "", types, Some(&gen_types), vec![].drain(..), Some(&ref_type));
752 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> ", struct_name, $new_name, struct_name).unwrap();
753 types.write_c_type(w, &ref_type, Some(&gen_types), true);
754 write!(w, " {{\n\tlet mut inner_val = &mut this_ptr.get_native_mut_ref().{};\n\t", $real_name).unwrap();
755 let local_var = types.write_to_c_conversion_from_ownable_ref_new_var(w, &format_ident!("inner_val"), &ref_type, Some(&gen_types));
756 if local_var { write!(w, "\n\t").unwrap(); }
757 types.write_to_c_conversion_inline_prefix(w, &ref_type, Some(&gen_types), true);
758 write!(w, "inner_val").unwrap();
759 types.write_to_c_conversion_inline_suffix(w, &ref_type, Some(&gen_types), true);
760 writeln!(w, "\n}}").unwrap();
762 // If the type isn't reference-able, but is clonable, export a getter that just clones
763 if types.understood_c_type(&$field.ty, Some(&gen_types)) {
764 let mut v = Vec::new();
765 types.write_c_type(&mut v, &$field.ty, Some(&gen_types), true);
766 let s = String::from_utf8(v).unwrap();
767 if types.is_clonable(&s) {
768 writeln_arg_docs(w, &$field.attrs, "", types, Some(&gen_types), vec![].drain(..), Some(&$field.ty));
769 writeln!(w, "///\n/// Returns a copy of the field.").unwrap();
770 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> {}", struct_name, $new_name, struct_name, s).unwrap();
771 write!(w, " {{\n\tlet mut inner_val = this_ptr.get_native_mut_ref().{}.clone();\n\t", $real_name).unwrap();
772 let local_var = types.write_to_c_conversion_new_var(w, &format_ident!("inner_val"), &$field.ty, Some(&gen_types), true);
773 if local_var { write!(w, "\n\t").unwrap(); }
774 types.write_to_c_conversion_inline_prefix(w, &$field.ty, Some(&gen_types), true);
775 write!(w, "inner_val").unwrap();
776 types.write_to_c_conversion_inline_suffix(w, &$field.ty, Some(&gen_types), true);
777 writeln!(w, "\n}}").unwrap();
783 if types.understood_c_type(&$field.ty, Some(&gen_types)) {
784 writeln_arg_docs(w, &$field.attrs, "", types, Some(&gen_types), vec![("val".to_owned(), &$field.ty)].drain(..), None);
785 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_set_{}(this_ptr: &mut {}, mut val: ", struct_name, $new_name, struct_name).unwrap();
786 types.write_c_type(w, &$field.ty, Some(&gen_types), false);
787 write!(w, ") {{\n\t").unwrap();
788 let local_var = types.write_from_c_conversion_new_var(w, &format_ident!("val"), &$field.ty, Some(&gen_types));
789 if local_var { write!(w, "\n\t").unwrap(); }
790 write!(w, "unsafe {{ &mut *ObjOps::untweak_ptr(this_ptr.inner) }}.{} = ", $real_name).unwrap();
791 types.write_from_c_conversion_prefix(w, &$field.ty, Some(&gen_types));
792 write!(w, "val").unwrap();
793 types.write_from_c_conversion_suffix(w, &$field.ty, Some(&gen_types));
794 writeln!(w, ";\n}}").unwrap();
795 } else { all_fields_settable = false; }
796 } else { all_fields_settable = false; }
801 syn::Fields::Named(fields) => {
802 for field in fields.named.iter() {
803 if let Some(ident) = &field.ident {
804 define_field!(ident, ident, field);
805 } else { all_fields_settable = false; }
808 syn::Fields::Unnamed(fields) => {
809 for (idx, field) in fields.unnamed.iter().enumerate() {
810 define_field!(('a' as u8 + idx as u8) as char, ('0' as u8 + idx as u8) as char, field);
813 syn::Fields::Unit => {},
816 if all_fields_settable {
817 // Build a constructor!
818 writeln!(w, "/// Constructs a new {} given each field", struct_name).unwrap();
820 syn::Fields::Named(fields) => {
821 writeln_arg_docs(w, &[], "", types, Some(&gen_types),
822 fields.named.iter().map(|field| (format!("{}_arg", field.ident.as_ref().unwrap()), &field.ty)),
825 syn::Fields::Unnamed(fields) => {
826 writeln_arg_docs(w, &[], "", types, Some(&gen_types),
827 fields.unnamed.iter().enumerate().map(|(idx, field)| (format!("{}_arg", ('a' as u8 + idx as u8)), &field.ty)),
830 syn::Fields::Unit => {},
832 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_new(", struct_name).unwrap();
835 syn::Fields::Named(fields) => {
836 for (idx, field) in fields.named.iter().enumerate() {
837 if idx != 0 { write!(w, ", ").unwrap(); }
838 write!(w, "mut {}_arg: ", field.ident.as_ref().unwrap()).unwrap();
839 types.write_c_type(w, &field.ty, Some(&gen_types), false);
842 syn::Fields::Unnamed(fields) => {
843 for (idx, field) in fields.unnamed.iter().enumerate() {
844 if idx != 0 { write!(w, ", ").unwrap(); }
845 write!(w, "mut {}_arg: ", ('a' as u8 + idx as u8) as char).unwrap();
846 types.write_c_type(w, &field.ty, Some(&gen_types), false);
849 syn::Fields::Unit => {},
851 write!(w, ") -> {} {{\n\t", struct_name).unwrap();
853 syn::Fields::Named(fields) => {
854 for field in fields.named.iter() {
855 let field_ident = format_ident!("{}_arg", field.ident.as_ref().unwrap());
856 if types.write_from_c_conversion_new_var(w, &field_ident, &field.ty, Some(&gen_types)) {
857 write!(w, "\n\t").unwrap();
861 syn::Fields::Unnamed(fields) => {
862 for (idx, field) in fields.unnamed.iter().enumerate() {
863 let field_ident = format_ident!("{}_arg", ('a' as u8 + idx as u8) as char);
864 if types.write_from_c_conversion_new_var(w, &field_ident, &field.ty, Some(&gen_types)) {
865 write!(w, "\n\t").unwrap();
869 syn::Fields::Unit => {},
871 write!(w, "{} {{ inner: ObjOps::heap_alloc(", struct_name).unwrap();
873 syn::Fields::Named(fields) => {
874 writeln!(w, "native{} {{", s.ident).unwrap();
875 for field in fields.named.iter() {
876 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
877 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
878 write!(w, "{}_arg", field.ident.as_ref().unwrap()).unwrap();
879 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
880 writeln!(w, ",").unwrap();
882 write!(w, "\t}}").unwrap();
884 syn::Fields::Unnamed(fields) => {
885 assert!(!s.generics.params.iter()
886 .any(|gen| if let syn::GenericParam::Lifetime(_) = gen { false } else { true }));
887 writeln!(w, "{} (", types.maybe_resolve_ident(&s.ident).unwrap()).unwrap();
888 for (idx, field) in fields.unnamed.iter().enumerate() {
889 write!(w, "\t\t").unwrap();
890 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
891 write!(w, "{}_arg", ('a' as u8 + idx as u8) as char).unwrap();
892 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
893 writeln!(w, ",").unwrap();
895 write!(w, "\t)").unwrap();
897 syn::Fields::Unit => write!(w, "{}::{} {{}}", types.module_path, struct_name).unwrap(),
899 writeln!(w, "), is_owned: true }}\n}}").unwrap();
903 /// Prints a relevant conversion for impl *
905 /// For simple impl Struct {}s, this just outputs the wrapper functions as Struct_fn_name() { .. }.
907 /// For impl Trait for Struct{}s, this non-exported generates wrapper functions as
908 /// Trait_Struct_fn_name and a Struct_as_Trait(&struct) -> Trait function which returns a populated
909 /// Trait struct containing a pointer to the passed struct's inner field and the wrapper functions.
911 /// A few non-crate Traits are hard-coded including Default.
912 fn writeln_impl<W: std::io::Write>(w: &mut W, w_uses: &mut HashSet<String, NonRandomHash>, i: &syn::ItemImpl, types: &mut TypeResolver) {
913 match export_status(&i.attrs) {
914 ExportStatus::Export => {},
915 ExportStatus::NoExport|ExportStatus::TestOnly => return,
916 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
919 if let syn::Type::Tuple(_) = &*i.self_ty {
920 if types.understood_c_type(&*i.self_ty, None) {
921 let mut gen_types = GenericTypes::new(None);
922 if !gen_types.learn_generics(&i.generics, types) {
923 eprintln!("Not implementing anything for `impl (..)` due to not understood generics");
927 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
928 if let Some(trait_path) = i.trait_.as_ref() {
929 if trait_path.0.is_some() { unimplemented!(); }
930 if types.understood_c_path(&trait_path.1) {
931 eprintln!("Not implementing anything for `impl Trait for (..)` - we only support manual defines");
934 // Just do a manual implementation:
935 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
938 eprintln!("Not implementing anything for plain `impl (..)` block - we only support `impl Trait for (..)` blocks");
944 if let &syn::Type::Path(ref p) = &*i.self_ty {
945 if p.qself.is_some() { unimplemented!(); }
946 let ident = &p.path.segments.last().unwrap().ident;
947 if let Some(resolved_path) = types.maybe_resolve_path(&p.path, None) {
948 if types.crate_types.opaques.contains_key(&resolved_path) || types.crate_types.mirrored_enums.contains_key(&resolved_path) ||
949 // At least for core::infallible::Infallible we need to support mapping an
950 // out-of-crate trait implementation.
951 (types.understood_c_path(&p.path) && first_seg_is_stdlib(resolved_path.split("::").next().unwrap())) {
952 if !types.understood_c_path(&p.path) {
953 eprintln!("Not implementing anything for impl {} as the type is not understood (probably C-not exported)", ident);
957 let mut gen_types = GenericTypes::new(Some(resolved_path.clone()));
958 if !gen_types.learn_generics(&i.generics, types) {
959 eprintln!("Not implementing anything for impl {} due to not understood generics", ident);
963 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
964 if let Some(trait_path) = i.trait_.as_ref() {
965 if trait_path.0.is_some() { unimplemented!(); }
966 let full_trait_path_opt = types.maybe_resolve_path(&trait_path.1, None);
967 let trait_obj_opt = full_trait_path_opt.as_ref().and_then(|path| types.crate_types.traits.get(path));
968 if types.understood_c_path(&trait_path.1) && trait_obj_opt.is_some() {
969 let full_trait_path = full_trait_path_opt.unwrap();
970 let trait_obj = *trait_obj_opt.unwrap();
973 let supertrait_resolver;
974 walk_supertraits!(trait_obj, Some(&types), (
976 if let Some(supertrait) = types.crate_types.traits.get(s) {
977 supertrait_name = s.to_string();
978 supertrait_resolver = get_module_type_resolver!(supertrait_name, types.crate_types);
979 gen_types.learn_associated_types(&supertrait, &supertrait_resolver);
984 // We learn the associated types maping from the original trait object.
985 // That's great, except that they are unresolved idents, so if we learn
986 // mappings from a trai defined in a different file, we may mis-resolve or
987 // fail to resolve the mapped types. Thus, we have to construct a new
988 // resolver for the module that the trait was defined in here first.
989 let mut trait_resolver = get_module_type_resolver!(full_trait_path, types.crate_types);
990 gen_types.learn_associated_types(trait_obj, &trait_resolver);
991 let mut impl_associated_types = HashMap::new();
992 for item in i.items.iter() {
994 syn::ImplItem::Type(t) => {
995 if let syn::Type::Path(p) = &t.ty {
996 if let Some(id) = single_ident_generic_path_to_ident(&p.path) {
997 impl_associated_types.insert(&t.ident, id);
1005 let export = export_status(&trait_obj.attrs);
1007 ExportStatus::Export|ExportStatus::NotImplementable => {},
1008 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1011 // For cases where we have a concrete native object which implements a
1012 // trait and need to return the C-mapped version of the trait, provide a
1013 // From<> implementation which does all the work to ensure free is handled
1014 // properly. This way we can call this method from deep in the
1015 // type-conversion logic without actually knowing the concrete native type.
1016 if !resolved_path.starts_with(types.module_path) {
1017 if !first_seg_is_stdlib(resolved_path.split("::").next().unwrap()) {
1018 w_uses.insert(format!("use crate::{}::native{} as native{};", resolved_path.rsplitn(2, "::").skip(1).next().unwrap(), ident, ident));
1019 w_uses.insert(format!("use crate::{};", resolved_path));
1020 w_uses.insert(format!("use crate::{}_free_void;", resolved_path));
1022 w_uses.insert(format!("use {} as native{};", resolved_path, ident));
1025 writeln!(w, "impl From<native{}> for crate::{} {{", ident, full_trait_path).unwrap();
1026 writeln!(w, "\tfn from(obj: native{}) -> Self {{", ident).unwrap();
1027 if is_type_unconstructable(&resolved_path) {
1028 writeln!(w, "\t\tunreachable!();").unwrap();
1030 types.write_to_c_conversion_new_var(w, &format_ident!("obj"), &*i.self_ty, Some(&gen_types), false);
1031 write!(w, "\t\tlet rust_obj = ").unwrap();
1032 types.write_to_c_conversion_inline_prefix(w, &*i.self_ty, Some(&gen_types), false);
1033 write!(w, "obj").unwrap();
1034 types.write_to_c_conversion_inline_suffix(w, &*i.self_ty, Some(&gen_types), false);
1035 writeln!(w, ";\n\t\tlet mut ret = {}_as_{}(&rust_obj);", ident, trait_obj.ident).unwrap();
1036 writeln!(w, "\t\t// We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn").unwrap();
1037 writeln!(w, "\t\tcore::mem::forget(rust_obj);").unwrap();
1038 writeln!(w, "\t\tret.free = Some({}_free_void);", ident).unwrap();
1039 writeln!(w, "\t\tret").unwrap();
1041 writeln!(w, "\t}}\n}}").unwrap();
1042 if is_type_unconstructable(&resolved_path) {
1043 // We don't bother with Struct_as_Trait conversion for types which must
1044 // never be instantiated, so just return early.
1048 writeln!(w, "/// Constructs a new {} which calls the relevant methods on this_arg.", trait_obj.ident).unwrap();
1049 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();
1050 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_as_{}(this_arg: &{}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
1051 writeln!(w, "\tcrate::{} {{", full_trait_path).unwrap();
1052 if types.c_type_has_inner_from_path(&resolved_path) {
1053 writeln!(w, "\t\tthis_arg: unsafe {{ ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }},").unwrap();
1055 writeln!(w, "\t\tthis_arg: unsafe {{ ObjOps::untweak_ptr(this_arg as *const {} as *mut {}) as *mut c_void }},", ident, ident).unwrap();
1057 writeln!(w, "\t\tfree: None,").unwrap();
1059 macro_rules! write_meth {
1060 ($m: expr, $trait: expr, $indent: expr) => {
1061 let trait_method = $trait.items.iter().filter_map(|item| {
1062 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
1063 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
1064 match export_status(&trait_method.attrs) {
1065 ExportStatus::Export => {},
1066 ExportStatus::NoExport => {
1067 write!(w, "{}\t\t//XXX: Need to export {}\n", $indent, $m.sig.ident).unwrap();
1070 ExportStatus::TestOnly => continue,
1071 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1074 let mut printed = false;
1075 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
1076 if let syn::Type::Reference(r) = &**rtype {
1077 write!(w, "\n\t\t{}{}: ", $indent, $m.sig.ident).unwrap();
1078 types.write_empty_rust_val(Some(&gen_types), w, &*r.elem);
1079 writeln!(w, ".into(),\n{}\t\tset_{}: Some({}_{}_set_{}),", $indent, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
1084 write!(w, "{}\t\t{}: {}_{}_{},\n", $indent, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
1088 for item in trait_obj.items.iter() {
1090 syn::TraitItem::Method(m) => {
1091 write_meth!(m, trait_obj, "");
1096 let mut requires_clone = false;
1097 walk_supertraits!(trait_obj, Some(&types), (
1098 ("Clone", _, _) => {
1099 requires_clone = true;
1100 writeln!(w, "\t\tcloned: Some({}_{}_cloned),", trait_obj.ident, ident).unwrap();
1102 ("Sync", _, _) => {}, ("Send", _, _) => {},
1103 ("std::marker::Sync", _, _) => {}, ("std::marker::Send", _, _) => {},
1104 ("core::fmt::Debug", _, _) => {
1105 writeln!(w, "\t\tdebug_str: {}_debug_str_void,", ident).unwrap();
1108 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
1109 macro_rules! write_impl_fields {
1110 ($s: expr, $supertrait_obj: expr, $t: expr, $pfx: expr, $resolver: expr) => {
1111 writeln!(w, "{}\t{}: crate::{} {{", $pfx, $t, $s).unwrap();
1112 writeln!(w, "{}\t\tthis_arg: unsafe {{ ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }},", $pfx).unwrap();
1113 writeln!(w, "{}\t\tfree: None,", $pfx).unwrap();
1114 for item in $supertrait_obj.items.iter() {
1116 syn::TraitItem::Method(m) => {
1117 write_meth!(m, $supertrait_obj, $pfx);
1122 walk_supertraits!($supertrait_obj, Some(&$resolver), (
1123 ("Clone", _, _) => {
1124 writeln!(w, "{}\tcloned: Some({}_{}_cloned),", $pfx, $supertrait_obj.ident, ident).unwrap();
1130 write_impl_fields!(s, supertrait_obj, t, "\t", types);
1132 let resolver = get_module_type_resolver!(s, types.crate_types);
1133 walk_supertraits!(supertrait_obj, Some(&resolver), (
1135 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
1136 write_impl_fields!(s, supertrait_obj, t, "\t\t", resolver);
1137 write!(w, "\t\t\t}},\n").unwrap();
1141 write!(w, "\t\t}},\n").unwrap();
1143 write_trait_impl_field_assign(w, s, ident);
1147 writeln!(w, "\t}}\n}}\n").unwrap();
1149 macro_rules! impl_meth {
1150 ($m: expr, $trait_meth: expr, $trait_path: expr, $trait: expr, $indent: expr, $types: expr) => {
1151 let trait_method = $trait.items.iter().filter_map(|item| {
1152 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
1153 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
1154 match export_status(&trait_method.attrs) {
1155 ExportStatus::Export => {},
1156 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1157 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1160 if let syn::ReturnType::Type(_, _) = &$m.sig.output {
1161 writeln!(w, "#[must_use]").unwrap();
1163 write!(w, "extern \"C\" fn {}_{}_{}(", ident, $trait.ident, $m.sig.ident).unwrap();
1164 let mut meth_gen_types = gen_types.push_ctx();
1165 assert!(meth_gen_types.learn_generics(&$m.sig.generics, $types));
1166 let mut uncallable_function = false;
1167 for inp in $m.sig.inputs.iter() {
1169 syn::FnArg::Typed(arg) => {
1170 if $types.skip_arg(&*arg.ty, Some(&meth_gen_types)) { continue; }
1171 let mut c_type = Vec::new();
1172 $types.write_c_type(&mut c_type, &*arg.ty, Some(&meth_gen_types), false);
1173 if is_type_unconstructable(&String::from_utf8(c_type).unwrap()) {
1174 uncallable_function = true;
1180 write_method_params(w, &$trait_meth.sig, "c_void", &mut trait_resolver, Some(&meth_gen_types), true, true);
1181 write!(w, " {{\n\t").unwrap();
1182 if uncallable_function {
1183 write!(w, "unreachable!();").unwrap();
1185 write_method_var_decl_body(w, &$trait_meth.sig, "", &mut trait_resolver, Some(&meth_gen_types), false);
1186 let mut takes_self = false;
1187 for inp in $m.sig.inputs.iter() {
1188 if let syn::FnArg::Receiver(_) = inp {
1193 let mut t_gen_args = String::new();
1194 for (idx, _) in $trait.generics.params.iter().enumerate() {
1195 if idx != 0 { t_gen_args += ", " };
1198 // rustc doesn't like <_> if the _ is actually a lifetime, so
1199 // if all the parameters are lifetimes just skip it.
1200 let mut nonlifetime_param = false;
1201 for param in $trait.generics.params.iter() {
1202 if let syn::GenericParam::Lifetime(_) = param {}
1203 else { nonlifetime_param = true; }
1205 if !nonlifetime_param { t_gen_args = String::new(); }
1207 write!(w, "<native{} as {}<{}>>::{}(unsafe {{ &mut *(this_arg as *mut native{}) }}, ", ident, $trait_path, t_gen_args, $m.sig.ident, ident).unwrap();
1209 write!(w, "<native{} as {}<{}>>::{}(", ident, $trait_path, t_gen_args, $m.sig.ident).unwrap();
1212 let mut real_type = "".to_string();
1213 match &$m.sig.output {
1214 syn::ReturnType::Type(_, rtype) => {
1215 if let Some(mut remaining_path) = first_seg_self(&*rtype) {
1216 if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
1217 real_type = format!("{}", impl_associated_types.get(associated_seg).unwrap());
1223 write_method_call_params(w, &$trait_meth.sig, "", &mut trait_resolver, Some(&meth_gen_types), &real_type, false);
1225 write!(w, "\n}}\n").unwrap();
1226 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
1227 if let syn::Type::Reference(r) = &**rtype {
1228 assert_eq!($m.sig.inputs.len(), 1); // Must only take self
1229 writeln!(w, "extern \"C\" fn {}_{}_set_{}(trait_self_arg: &{}) {{", ident, $trait.ident, $m.sig.ident, $trait.ident).unwrap();
1230 writeln!(w, "\t// This is a bit race-y in the general case, but for our specific use-cases today, we're safe").unwrap();
1231 writeln!(w, "\t// Specifically, we must ensure that the first time we're called it can never be in parallel").unwrap();
1232 write!(w, "\tif ").unwrap();
1233 $types.write_empty_rust_val_check(Some(&meth_gen_types), w, &*r.elem, &format!("unsafe {{ &*trait_self_arg.{}.get() }}", $m.sig.ident));
1234 writeln!(w, " {{").unwrap();
1235 writeln!(w, "\t\t*unsafe {{ &mut *(&*(trait_self_arg as *const {})).{}.get() }} = {}_{}_{}(trait_self_arg.this_arg).into();", $trait.ident, $m.sig.ident, ident, $trait.ident, $m.sig.ident).unwrap();
1236 writeln!(w, "\t}}").unwrap();
1237 writeln!(w, "}}").unwrap();
1243 'impl_item_loop: for trait_item in trait_obj.items.iter() {
1245 syn::TraitItem::Method(meth) => {
1246 for item in i.items.iter() {
1248 syn::ImplItem::Method(m) => {
1249 if meth.sig.ident == m.sig.ident {
1250 impl_meth!(m, meth, full_trait_path, trait_obj, "", types);
1251 continue 'impl_item_loop;
1254 syn::ImplItem::Type(_) => {},
1255 _ => unimplemented!(),
1258 assert!(meth.default.is_some());
1259 let old_gen_types = gen_types;
1260 gen_types = GenericTypes::new(Some(resolved_path.clone()));
1261 impl_meth!(meth, meth, full_trait_path, trait_obj, "", &mut trait_resolver);
1262 gen_types = old_gen_types;
1268 writeln!(w, "extern \"C\" fn {}_{}_cloned(new_obj: &mut crate::{}) {{", trait_obj.ident, ident, full_trait_path).unwrap();
1269 writeln!(w, "\tnew_obj.this_arg = {}_clone_void(new_obj.this_arg);", ident).unwrap();
1270 writeln!(w, "\tnew_obj.free = Some({}_free_void);", ident).unwrap();
1272 fn seek_supertraits<W: std::io::Write>(w: &mut W, pfx: &str, tr: &syn::ItemTrait, types: &TypeResolver) {
1273 walk_supertraits!(tr, Some(types), (
1275 if types.crate_types.traits.get(s).is_some() {
1276 assert!(!types.is_clonable(s)); // We don't currently support cloning with a clonable supertrait
1277 writeln!(w, "\tnew_obj.{}{}.this_arg = new_obj.this_arg;", pfx, t).unwrap();
1278 writeln!(w, "\tnew_obj.{}{}.free = None;", pfx, t).unwrap();
1279 let tr = types.crate_types.traits.get(s).unwrap();
1280 let resolver = get_module_type_resolver!(s, types.crate_types);
1281 seek_supertraits(w, &format!("{}.", t), tr, &resolver);
1286 seek_supertraits(w, "", trait_obj, types);
1287 writeln!(w, "}}").unwrap();
1289 write!(w, "\n").unwrap();
1292 if is_type_unconstructable(&resolved_path) {
1293 // Don't bother exposing trait implementations for objects which cannot be
1297 if path_matches_nongeneric(&trait_path.1, &["From"]) {
1298 } else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
1299 writeln!(w, "/// Creates a \"default\" {}. See struct and individual field documentaiton for details on which values are used.", ident).unwrap();
1300 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
1301 write!(w, "\t{} {{ inner: ObjOps::heap_alloc(Default::default()), is_owned: true }}\n", ident).unwrap();
1302 write!(w, "}}\n").unwrap();
1303 } else if full_trait_path_opt.as_ref().map(|s| s.as_str()) == Some("core::cmp::PartialEq") {
1304 } else if full_trait_path_opt.as_ref().map(|s| s.as_str()) == Some("core::cmp::Eq") {
1305 writeln!(w, "/// Checks if two {}s contain equal inner contents.", ident).unwrap();
1306 writeln!(w, "/// This ignores pointers and is_owned flags and looks at the values in fields.").unwrap();
1307 if types.c_type_has_inner_from_path(&resolved_path) {
1308 writeln!(w, "/// Two objects with NULL inner values will be considered \"equal\" here.").unwrap();
1310 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_eq(a: &{}, b: &{}) -> bool {{\n", ident, ident, ident).unwrap();
1311 if types.c_type_has_inner_from_path(&resolved_path) {
1312 write!(w, "\tif a.inner == b.inner {{ return true; }}\n").unwrap();
1313 write!(w, "\tif a.inner.is_null() || b.inner.is_null() {{ return false; }}\n").unwrap();
1317 let ref_type: syn::Type = syn::parse_quote!(&#path);
1318 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");
1320 write!(w, "\tif ").unwrap();
1321 types.write_from_c_conversion_prefix(w, &ref_type, Some(&gen_types));
1322 write!(w, "a").unwrap();
1323 types.write_from_c_conversion_suffix(w, &ref_type, Some(&gen_types));
1324 write!(w, " == ").unwrap();
1325 types.write_from_c_conversion_prefix(w, &ref_type, Some(&gen_types));
1326 write!(w, "b").unwrap();
1327 types.write_from_c_conversion_suffix(w, &ref_type, Some(&gen_types));
1329 writeln!(w, " {{ true }} else {{ false }}\n}}").unwrap();
1330 } else if full_trait_path_opt.as_ref().map(|s| s.as_str()) == Some("core::hash::Hash") {
1331 writeln!(w, "/// Generates a non-cryptographic 64-bit hash of the {}.", ident).unwrap();
1332 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_hash(o: &{}) -> u64 {{\n", ident, ident).unwrap();
1333 if types.c_type_has_inner_from_path(&resolved_path) {
1334 write!(w, "\tif o.inner.is_null() {{ return 0; }}\n").unwrap();
1338 let ref_type: syn::Type = syn::parse_quote!(&#path);
1339 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");
1341 writeln!(w, "\t// Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core").unwrap();
1342 writeln!(w, "\t#[allow(deprecated)]").unwrap();
1343 writeln!(w, "\tlet mut hasher = core::hash::SipHasher::new();").unwrap();
1344 write!(w, "\tcore::hash::Hash::hash(").unwrap();
1345 types.write_from_c_conversion_prefix(w, &ref_type, Some(&gen_types));
1346 write!(w, "o").unwrap();
1347 types.write_from_c_conversion_suffix(w, &ref_type, Some(&gen_types));
1348 writeln!(w, ", &mut hasher);").unwrap();
1349 writeln!(w, "\tcore::hash::Hasher::finish(&hasher)\n}}").unwrap();
1350 } else if (full_trait_path_opt.as_ref().map(|s| s.as_str()) == Some("core::clone::Clone") || path_matches_nongeneric(&trait_path.1, &["Clone"])) &&
1351 types.c_type_has_inner_from_path(&resolved_path) {
1352 writeln!(w, "impl Clone for {} {{", ident).unwrap();
1353 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
1354 writeln!(w, "\t\tSelf {{").unwrap();
1355 writeln!(w, "\t\t\tinner: if <*mut native{}>::is_null(self.inner) {{ core::ptr::null_mut() }} else {{", ident).unwrap();
1356 writeln!(w, "\t\t\t\tObjOps::heap_alloc(unsafe {{ &*ObjOps::untweak_ptr(self.inner) }}.clone()) }},").unwrap();
1357 writeln!(w, "\t\t\tis_owned: true,").unwrap();
1358 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
1359 writeln!(w, "#[allow(unused)]").unwrap();
1360 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
1361 writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", ident).unwrap();
1362 writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *const native{})).clone() }})) as *mut c_void", ident).unwrap();
1363 writeln!(w, "}}").unwrap();
1364 writeln!(w, "#[no_mangle]").unwrap();
1365 writeln!(w, "/// Creates a copy of the {}", ident).unwrap();
1366 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", ident, ident, ident).unwrap();
1367 writeln!(w, "\torig.clone()").unwrap();
1368 writeln!(w, "}}").unwrap();
1369 } else if path_matches_nongeneric(&trait_path.1, &["FromStr"]) {
1370 let mut err_opt = None;
1371 for item in i.items.iter() {
1373 syn::ImplItem::Type(ty) if format!("{}", ty.ident) == "Err" => {
1374 err_opt = Some(&ty.ty);
1379 let err_ty = err_opt.unwrap();
1380 if let Some(container) = types.get_c_mangled_container_type(vec![&*i.self_ty, &err_ty], Some(&gen_types), "Result") {
1381 writeln!(w, "#[no_mangle]").unwrap();
1382 writeln!(w, "/// Read a {} object from a string", ident).unwrap();
1383 writeln!(w, "pub extern \"C\" fn {}_from_str(s: crate::c_types::Str) -> {} {{", ident, container).unwrap();
1384 writeln!(w, "\tmatch {}::from_str(s.into_str()) {{", resolved_path).unwrap();
1386 writeln!(w, "\t\tOk(r) => {{").unwrap();
1387 let new_var = types.write_to_c_conversion_new_var(w, &format_ident!("r"), &*i.self_ty, Some(&gen_types), false);
1388 write!(w, "\t\t\tcrate::c_types::CResultTempl::ok(\n\t\t\t\t").unwrap();
1389 types.write_to_c_conversion_inline_prefix(w, &*i.self_ty, Some(&gen_types), false);
1390 write!(w, "{}r", if new_var { "local_" } else { "" }).unwrap();
1391 types.write_to_c_conversion_inline_suffix(w, &*i.self_ty, Some(&gen_types), false);
1392 writeln!(w, "\n\t\t\t)\n\t\t}},").unwrap();
1394 writeln!(w, "\t\tErr(e) => {{").unwrap();
1395 let new_var = types.write_to_c_conversion_new_var(w, &format_ident!("e"), &err_ty, Some(&gen_types), false);
1396 write!(w, "\t\t\tcrate::c_types::CResultTempl::err(\n\t\t\t\t").unwrap();
1397 types.write_to_c_conversion_inline_prefix(w, &err_ty, Some(&gen_types), false);
1398 write!(w, "{}e", if new_var { "local_" } else { "" }).unwrap();
1399 types.write_to_c_conversion_inline_suffix(w, &err_ty, Some(&gen_types), false);
1400 writeln!(w, "\n\t\t\t)\n\t\t}},").unwrap();
1402 writeln!(w, "\t}}.into()\n}}").unwrap();
1404 } else if full_trait_path_opt.as_ref().map(|s| s.as_str()) == Some("core::fmt::Debug") {
1405 writeln!(w, "/// Get a string which allows debug introspection of a {} object", ident).unwrap();
1406 writeln!(w, "pub extern \"C\" fn {}_debug_str_void(o: *const c_void) -> Str {{", ident).unwrap();
1408 write!(w, "\talloc::format!(\"{{:?}}\", unsafe {{ o as *const crate::{} }}).into()", resolved_path).unwrap();
1409 writeln!(w, "}}").unwrap();
1410 } else if path_matches_nongeneric(&trait_path.1, &["Display"]) {
1411 writeln!(w, "#[no_mangle]").unwrap();
1412 writeln!(w, "/// Get the string representation of a {} object", ident).unwrap();
1413 writeln!(w, "pub extern \"C\" fn {}_to_str(o: &crate::{}) -> Str {{", ident, resolved_path).unwrap();
1415 let self_ty = &i.self_ty;
1416 let ref_type: syn::Type = syn::parse_quote!(&#self_ty);
1417 let new_var = types.write_from_c_conversion_new_var(w, &format_ident!("o"), &ref_type, Some(&gen_types));
1418 write!(w, "\talloc::format!(\"{{}}\", ").unwrap();
1419 types.write_from_c_conversion_prefix(w, &ref_type, Some(&gen_types));
1420 write!(w, "{}o", if new_var { "local_" } else { "" }).unwrap();
1421 types.write_from_c_conversion_suffix(w, &ref_type, Some(&gen_types));
1422 writeln!(w, ").into()").unwrap();
1424 writeln!(w, "}}").unwrap();
1426 //XXX: implement for other things like ToString
1427 // If we have no generics, try a manual implementation:
1428 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
1431 let is_opaque = types.crate_types.opaques.contains_key(&resolved_path);
1432 let is_mirrored_enum = types.crate_types.mirrored_enums.contains_key(&resolved_path);
1433 for item in i.items.iter() {
1435 syn::ImplItem::Method(m) => {
1436 if let syn::Visibility::Public(_) = m.vis {
1437 match export_status(&m.attrs) {
1438 ExportStatus::Export => {},
1439 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1440 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1442 if m.sig.asyncness.is_some() { continue; }
1443 let mut meth_gen_types = gen_types.push_ctx();
1444 assert!(meth_gen_types.learn_generics(&m.sig.generics, types));
1445 if m.defaultness.is_some() { unimplemented!(); }
1446 writeln_fn_docs(w, &m.attrs, "", types, Some(&meth_gen_types), m.sig.inputs.iter(), &m.sig.output);
1447 if let syn::ReturnType::Type(_, _) = &m.sig.output {
1448 writeln!(w, "#[must_use]").unwrap();
1450 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_{}(", ident, m.sig.ident).unwrap();
1451 let ret_type = format!("crate::{}", resolved_path);
1452 write_method_params(w, &m.sig, &ret_type, types, Some(&meth_gen_types), false, true);
1453 write!(w, " {{\n\t").unwrap();
1454 write_method_var_decl_body(w, &m.sig, "", types, Some(&meth_gen_types), false);
1455 let mut takes_self = false;
1456 let mut takes_mut_self = false;
1457 let mut takes_owned_self = false;
1458 for inp in m.sig.inputs.iter() {
1459 if let syn::FnArg::Receiver(r) = inp {
1461 if r.mutability.is_some() { takes_mut_self = true; }
1462 if r.reference.is_none() { takes_owned_self = true; }
1465 if !takes_mut_self && !takes_self {
1466 write!(w, "{}::{}(", resolved_path, m.sig.ident).unwrap();
1468 if is_mirrored_enum {
1469 write!(w, "this_arg.to_native().{}(", m.sig.ident).unwrap();
1470 } else if is_opaque {
1471 if takes_owned_self {
1472 write!(w, "(*unsafe {{ Box::from_raw(this_arg.take_inner()) }}).{}(", m.sig.ident).unwrap();
1473 } else if takes_mut_self {
1474 write!(w, "unsafe {{ &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::{}::native{})) }}.{}(", rsplit_once(&resolved_path, "::").unwrap().0, ident, m.sig.ident).unwrap();
1476 write!(w, "unsafe {{ &*ObjOps::untweak_ptr(this_arg.inner) }}.{}(", m.sig.ident).unwrap();
1482 write_method_call_params(w, &m.sig, "", types, Some(&meth_gen_types), &ret_type, false);
1483 writeln!(w, "\n}}\n").unwrap();
1490 } else if let Some(resolved_path) = types.maybe_resolve_ident(&ident) {
1491 create_alias_for_impl(resolved_path, i, types, move |aliased_impl, types| writeln_impl(w, w_uses, &aliased_impl, types));
1493 eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub)", ident);
1499 fn create_alias_for_impl<F: FnMut(syn::ItemImpl, &mut TypeResolver)>(resolved_path: String, i: &syn::ItemImpl, types: &mut TypeResolver, mut callback: F) {
1500 if let Some(aliases) = types.crate_types.reverse_alias_map.get(&resolved_path).cloned() {
1501 let mut gen_types = Some(GenericTypes::new(Some(resolved_path.clone())));
1502 if !gen_types.as_mut().unwrap().learn_generics(&i.generics, types) {
1505 let alias_module = rsplit_once(&resolved_path, "::").unwrap().0;
1507 'alias_impls: for (alias_resolved, arguments) in aliases {
1508 let mut new_ty_generics = Vec::new();
1509 let mut new_ty_bounds = Vec::new();
1510 let mut need_generics = false;
1512 let alias_resolver_override;
1513 let alias_resolver = if alias_module != types.module_path {
1514 alias_resolver_override = ImportResolver::new(types.types.crate_name, &types.crate_types.lib_ast,
1515 alias_module, &types.crate_types.lib_ast.modules.get(alias_module).unwrap().items);
1516 &alias_resolver_override
1517 } else { &types.types };
1518 let mut where_clause = syn::WhereClause { where_token: syn::Token![where](Span::call_site()),
1519 predicates: syn::punctuated::Punctuated::new()
1521 for (idx, gen) in i.generics.params.iter().enumerate() {
1523 syn::GenericParam::Type(type_param) => {
1524 'bounds_check: for bound in type_param.bounds.iter() {
1525 if let syn::TypeParamBound::Trait(trait_bound) = bound {
1526 if let syn::PathArguments::AngleBracketed(ref t) = &arguments {
1527 assert!(idx < t.args.len());
1528 if let syn::GenericArgument::Type(syn::Type::Path(p)) = &t.args[idx] {
1529 let generic_bound = types.maybe_resolve_path(&trait_bound.path, None)
1530 .unwrap_or_else(|| format!("{}::{}", types.module_path, single_ident_generic_path_to_ident(&trait_bound.path).unwrap()));
1532 if let Some(generic_arg) = alias_resolver.maybe_resolve_path(&p.path, None) {
1533 new_ty_generics.push((type_param.ident.clone(), syn::Type::Path(p.clone())));
1534 if let Some(traits_impld) = types.crate_types.trait_impls.get(&generic_arg) {
1535 for trait_impld in traits_impld {
1536 if *trait_impld == generic_bound { continue 'bounds_check; }
1538 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1539 continue 'alias_impls;
1541 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1542 continue 'alias_impls;
1544 } else if gen_types.is_some() {
1545 let resp = types.maybe_resolve_path(&p.path, gen_types.as_ref());
1546 if generic_bound == "core::ops::Deref" && resp.is_some() {
1547 new_ty_bounds.push((type_param.ident.clone(),
1548 string_path_to_syn_path("core::ops::Deref")));
1549 let mut bounds = syn::punctuated::Punctuated::new();
1550 bounds.push(syn::TypeParamBound::Trait(syn::TraitBound {
1552 modifier: syn::TraitBoundModifier::None,
1554 path: string_path_to_syn_path(&types.resolve_path(&p.path, gen_types.as_ref())),
1556 let mut path = string_path_to_syn_path(&format!("{}::Target", type_param.ident));
1557 path.leading_colon = None;
1558 where_clause.predicates.push(syn::WherePredicate::Type(syn::PredicateType {
1560 bounded_ty: syn::Type::Path(syn::TypePath { qself: None, path }),
1561 colon_token: syn::Token![:](Span::call_site()),
1565 new_ty_generics.push((type_param.ident.clone(),
1566 gen_types.as_ref().resolve_type(&syn::Type::Path(p.clone())).clone()));
1568 need_generics = true;
1572 } else { unimplemented!(); }
1573 } else { unimplemented!(); }
1574 } else { unimplemented!(); }
1577 syn::GenericParam::Lifetime(_) => {},
1578 syn::GenericParam::Const(_) => unimplemented!(),
1581 let mut params = syn::punctuated::Punctuated::new();
1582 let alias = string_path_to_syn_path(&alias_resolved);
1585 let alias_generics = types.crate_types.opaques.get(&alias_resolved).unwrap().1;
1587 // If we need generics on the alias, create impl generic bounds...
1588 assert_eq!(new_ty_generics.len() + new_ty_bounds.len(), i.generics.params.len());
1589 let mut args = syn::punctuated::Punctuated::new();
1590 for (ident, param) in new_ty_generics.drain(..) {
1591 // TODO: We blindly assume that generics in the type alias and
1592 // the aliased type have the same names, which we really shouldn't.
1593 if alias_generics.params.iter().any(|generic|
1594 if let syn::GenericParam::Type(t) = generic { t.ident == ident } else { false })
1596 args.push(parse_quote!(#ident));
1598 params.push(syn::GenericParam::Type(syn::TypeParam {
1602 bounds: syn::punctuated::Punctuated::new(),
1603 eq_token: Some(syn::token::Eq(Span::call_site())),
1604 default: Some(param),
1607 for (ident, param) in new_ty_bounds.drain(..) {
1608 // TODO: We blindly assume that generics in the type alias and
1609 // the aliased type have the same names, which we really shouldn't.
1610 if alias_generics.params.iter().any(|generic|
1611 if let syn::GenericParam::Type(t) = generic { t.ident == ident } else { false })
1613 args.push(parse_quote!(#ident));
1615 params.push(syn::GenericParam::Type(syn::TypeParam {
1618 colon_token: Some(syn::token::Colon(Span::call_site())),
1619 bounds: syn::punctuated::Punctuated::from_iter(
1620 Some(syn::TypeParamBound::Trait(syn::TraitBound {
1621 path: param, paren_token: None, lifetimes: None,
1622 modifier: syn::TraitBoundModifier::None,
1629 // ... and swap the last segment of the impl self_ty to use the generic bounds.
1630 let mut res = alias.clone();
1631 res.segments.last_mut().unwrap().arguments = syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
1633 lt_token: syn::token::Lt(Span::call_site()),
1635 gt_token: syn::token::Gt(Span::call_site()),
1638 } else { alias.clone() };
1639 callback(syn::ItemImpl {
1640 attrs: i.attrs.clone(),
1641 brace_token: syn::token::Brace(Span::call_site()),
1643 generics: syn::Generics {
1647 where_clause: Some(where_clause),
1649 impl_token: syn::Token![impl](Span::call_site()),
1650 items: i.items.clone(),
1651 self_ty: Box::new(syn::Type::Path(syn::TypePath { qself: None, path: real_aliased })),
1652 trait_: i.trait_.clone(),
1657 eprintln!("Not implementing anything for {} due to it being marked not exported", resolved_path);
1661 /// Replaces upper case charachters with underscore followed by lower case except the first
1662 /// charachter and repeated upper case characthers (which are only made lower case).
1663 fn camel_to_snake_case(camel: &str) -> String {
1664 let mut res = "".to_string();
1665 let mut last_upper = -1;
1666 for (idx, c) in camel.chars().enumerate() {
1667 if c.is_uppercase() {
1668 if last_upper != idx as isize - 1 { res.push('_'); }
1669 res.push(c.to_lowercase().next().unwrap());
1670 last_upper = idx as isize;
1679 /// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
1680 /// is unitary), we generate an equivalent enum with all types replaced with their C mapped
1681 /// versions followed by conversion functions which map between the Rust version and the C mapped
1683 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) {
1684 match export_status(&e.attrs) {
1685 ExportStatus::Export => {},
1686 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1687 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1690 if is_enum_opaque(e) {
1691 eprintln!("Skipping enum {} as it contains non-unit fields", e.ident);
1692 writeln_opaque(w, &e.ident, &format!("{}", e.ident), &e.generics, &e.attrs, types, extra_headers, cpp_headers);
1695 writeln_docs(w, &e.attrs, "");
1697 let mut gen_types = GenericTypes::new(None);
1698 assert!(gen_types.learn_generics(&e.generics, types));
1700 let mut needs_free = false;
1701 let mut constr = Vec::new();
1702 let mut is_clonable = true;
1704 for var in e.variants.iter() {
1705 if let syn::Fields::Named(fields) = &var.fields {
1707 for field in fields.named.iter() {
1708 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1710 let mut ty_checks = Vec::new();
1711 types.write_c_type(&mut ty_checks, &field.ty, Some(&gen_types), false);
1712 if !types.is_clonable(&String::from_utf8(ty_checks).unwrap()) {
1713 is_clonable = false;
1716 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1717 for field in fields.unnamed.iter() {
1718 let mut ty_checks = Vec::new();
1719 types.write_c_type(&mut ty_checks, &field.ty, Some(&gen_types), false);
1720 let ty = String::from_utf8(ty_checks).unwrap();
1721 if ty != "" && !types.is_clonable(&ty) {
1722 is_clonable = false;
1729 writeln!(w, "#[derive(Clone)]").unwrap();
1730 types.crate_types.set_clonable(format!("{}::{}", types.module_path, e.ident));
1732 writeln!(w, "#[must_use]\n#[repr(C)]\npub enum {} {{", e.ident).unwrap();
1733 for var in e.variants.iter() {
1734 assert_eq!(export_status(&var.attrs), ExportStatus::Export); // We can't partially-export a mirrored enum
1735 writeln_docs(w, &var.attrs, "\t");
1736 write!(w, "\t{}", var.ident).unwrap();
1737 writeln!(&mut constr, "#[no_mangle]\n/// Utility method to constructs a new {}-variant {}", var.ident, e.ident).unwrap();
1738 let constr_name = camel_to_snake_case(&format!("{}", var.ident));
1739 write!(&mut constr, "pub extern \"C\" fn {}_{}(", e.ident, constr_name).unwrap();
1740 let mut empty_tuple_variant = false;
1741 if let syn::Fields::Named(fields) = &var.fields {
1743 writeln!(w, " {{").unwrap();
1744 for (idx, field) in fields.named.iter().enumerate() {
1745 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1746 writeln_field_docs(w, &field.attrs, "\t\t", types, Some(&gen_types), &field.ty);
1747 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1748 write!(&mut constr, "{}{}: ", if idx != 0 { ", " } else { "" }, field.ident.as_ref().unwrap()).unwrap();
1749 types.write_c_type(w, &field.ty, Some(&gen_types), true);
1750 types.write_c_type(&mut constr, &field.ty, Some(&gen_types), true);
1751 writeln!(w, ",").unwrap();
1753 write!(w, "\t}}").unwrap();
1754 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1755 if fields.unnamed.len() == 1 {
1756 let mut empty_check = Vec::new();
1757 types.write_c_type(&mut empty_check, &fields.unnamed[0].ty, Some(&gen_types), true);
1758 if empty_check.is_empty() {
1759 empty_tuple_variant = true;
1762 if !empty_tuple_variant {
1764 writeln!(w, "(").unwrap();
1765 for (idx, field) in fields.unnamed.iter().enumerate() {
1766 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1767 writeln_field_docs(w, &field.attrs, "\t\t", types, Some(&gen_types), &field.ty);
1768 write!(w, "\t\t").unwrap();
1769 types.write_c_type(w, &field.ty, Some(&gen_types), true);
1771 write!(&mut constr, "{}: ", ('a' as u8 + idx as u8) as char).unwrap();
1772 types.write_c_type(&mut constr, &field.ty, Some(&gen_types), false);
1773 if idx != fields.unnamed.len() - 1 {
1774 writeln!(w, ",").unwrap();
1775 write!(&mut constr, ",").unwrap();
1778 write!(w, ")").unwrap();
1781 write!(&mut constr, ") -> {} {{\n\t{}::{}", e.ident, e.ident, var.ident).unwrap();
1782 if let syn::Fields::Named(fields) = &var.fields {
1783 writeln!(&mut constr, " {{").unwrap();
1784 for field in fields.named.iter() {
1785 writeln!(&mut constr, "\t\t{},", field.ident.as_ref().unwrap()).unwrap();
1787 writeln!(&mut constr, "\t}}").unwrap();
1788 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1789 if !empty_tuple_variant {
1790 write!(&mut constr, "(").unwrap();
1791 for (idx, field) in fields.unnamed.iter().enumerate() {
1792 let mut ref_c_ty = Vec::new();
1793 let mut nonref_c_ty = Vec::new();
1794 types.write_c_type(&mut ref_c_ty, &field.ty, Some(&gen_types), false);
1795 types.write_c_type(&mut nonref_c_ty, &field.ty, Some(&gen_types), true);
1797 if ref_c_ty != nonref_c_ty {
1798 // We blindly assume references in field types are always opaque types, and
1799 // print out an opaque reference -> owned reference conversion here.
1800 write!(&mut constr, "{} {{ inner: {}.inner, is_owned: false }}, ", String::from_utf8(nonref_c_ty).unwrap(), ('a' as u8 + idx as u8) as char).unwrap();
1802 write!(&mut constr, "{}, ", ('a' as u8 + idx as u8) as char).unwrap();
1805 writeln!(&mut constr, ")").unwrap();
1807 writeln!(&mut constr, "").unwrap();
1810 writeln!(&mut constr, "}}").unwrap();
1811 writeln!(w, ",").unwrap();
1813 writeln!(w, "}}\nuse {}::{} as {}Import;", types.module_path, e.ident, e.ident).unwrap();
1814 write!(w, "pub(crate) type native{} = {}Import", e.ident, e.ident).unwrap();
1815 maybe_write_generics(w, &e.generics, &syn::PathArguments::None, &types, true);
1816 writeln!(w, ";\n\nimpl {} {{", e.ident).unwrap();
1818 macro_rules! write_conv {
1819 ($fn_sig: expr, $to_c: expr, $ref: expr) => {
1820 writeln!(w, "\t#[allow(unused)]\n\tpub(crate) fn {} {{", $fn_sig).unwrap();
1822 writeln!(w, "\t\tlet native = unsafe {{ &*(native as *const _ as *const c_void as *const native{}) }};", e.ident).unwrap();
1824 writeln!(w, "\t\tmatch {} {{", if $to_c { "native" } else { "self" }).unwrap();
1825 for var in e.variants.iter() {
1826 write!(w, "\t\t\t{}{}::{} ", if $to_c { "native" } else { "" }, e.ident, var.ident).unwrap();
1827 let mut empty_tuple_variant = false;
1828 if let syn::Fields::Named(fields) = &var.fields {
1829 write!(w, "{{").unwrap();
1830 for field in fields.named.iter() {
1831 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1832 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, field.ident.as_ref().unwrap()).unwrap();
1834 write!(w, "}} ").unwrap();
1835 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1836 if fields.unnamed.len() == 1 {
1837 let mut empty_check = Vec::new();
1838 types.write_c_type(&mut empty_check, &fields.unnamed[0].ty, Some(&gen_types), true);
1839 if empty_check.is_empty() {
1840 empty_tuple_variant = true;
1843 if !empty_tuple_variant || $to_c {
1844 write!(w, "(").unwrap();
1845 for (idx, field) in fields.unnamed.iter().enumerate() {
1846 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1847 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, ('a' as u8 + idx as u8) as char).unwrap();
1849 write!(w, ") ").unwrap();
1852 write!(w, "=>").unwrap();
1854 macro_rules! handle_field_a {
1855 ($field: expr, $field_ident: expr) => { {
1856 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1857 let mut sink = ::std::io::sink();
1858 let mut out: &mut dyn std::io::Write = if $ref { &mut sink } else { w };
1859 let new_var = if $to_c {
1860 types.write_to_c_conversion_new_var(&mut out, $field_ident, &$field.ty, Some(&gen_types), true)
1862 types.write_from_c_conversion_new_var(&mut out, $field_ident, &$field.ty, Some(&gen_types))
1864 if $ref || new_var {
1866 write!(w, "let mut {}_nonref = Clone::clone({});\n\t\t\t\t", $field_ident, $field_ident).unwrap();
1868 let nonref_ident = format_ident!("{}_nonref", $field_ident);
1870 types.write_to_c_conversion_new_var(w, &nonref_ident, &$field.ty, Some(&gen_types), true);
1872 types.write_from_c_conversion_new_var(w, &nonref_ident, &$field.ty, Some(&gen_types));
1874 write!(w, "\n\t\t\t\t").unwrap();
1877 write!(w, "\n\t\t\t\t").unwrap();
1882 if let syn::Fields::Named(fields) = &var.fields {
1883 write!(w, " {{\n\t\t\t\t").unwrap();
1884 for field in fields.named.iter() {
1885 handle_field_a!(field, field.ident.as_ref().unwrap());
1887 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1888 write!(w, " {{\n\t\t\t\t").unwrap();
1889 for (idx, field) in fields.unnamed.iter().enumerate() {
1890 if !empty_tuple_variant {
1891 handle_field_a!(field, &format_ident!("{}", ('a' as u8 + idx as u8) as char));
1894 } else { write!(w, " ").unwrap(); }
1896 write!(w, "{}{}::{}", if $to_c { "" } else { "native" }, e.ident, var.ident).unwrap();
1898 macro_rules! handle_field_b {
1899 ($field: expr, $field_ident: expr) => { {
1900 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1902 types.write_to_c_conversion_inline_prefix(w, &$field.ty, Some(&gen_types), true);
1904 types.write_from_c_conversion_prefix(w, &$field.ty, Some(&gen_types));
1906 write!(w, "{}{}", $field_ident,
1907 if $ref { "_nonref" } else { "" }).unwrap();
1909 types.write_to_c_conversion_inline_suffix(w, &$field.ty, Some(&gen_types), true);
1911 types.write_from_c_conversion_suffix(w, &$field.ty, Some(&gen_types));
1913 write!(w, ",").unwrap();
1917 if let syn::Fields::Named(fields) = &var.fields {
1918 write!(w, " {{").unwrap();
1919 for field in fields.named.iter() {
1920 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1921 write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1922 handle_field_b!(field, field.ident.as_ref().unwrap());
1924 writeln!(w, "\n\t\t\t\t}}").unwrap();
1925 write!(w, "\t\t\t}}").unwrap();
1926 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1927 if !empty_tuple_variant || !$to_c {
1928 write!(w, " (").unwrap();
1929 for (idx, field) in fields.unnamed.iter().enumerate() {
1930 write!(w, "\n\t\t\t\t\t").unwrap();
1931 handle_field_b!(field, &format_ident!("{}", ('a' as u8 + idx as u8) as char));
1933 writeln!(w, "\n\t\t\t\t)").unwrap();
1935 write!(w, "\t\t\t}}").unwrap();
1937 writeln!(w, ",").unwrap();
1939 writeln!(w, "\t\t}}\n\t}}").unwrap();
1944 write_conv!(format!("to_native(&self) -> native{}", e.ident), false, true);
1946 write_conv!(format!("into_native(self) -> native{}", e.ident), false, false);
1948 let mut args = Vec::new();
1949 maybe_write_non_lifetime_generics(&mut args, &e.generics, &syn::PathArguments::None, &types);
1950 let fn_line = format!("from_native(native: &{}Import{}) -> Self", e.ident, String::from_utf8(args).unwrap());
1951 write_conv!(fn_line, true, true);
1953 write_conv!(format!("native_into(native: native{}) -> Self", e.ident), true, false);
1954 writeln!(w, "}}").unwrap();
1957 writeln!(w, "/// Frees any resources used by the {}", e.ident).unwrap();
1958 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", e.ident, e.ident).unwrap();
1961 writeln!(w, "/// Creates a copy of the {}", e.ident).unwrap();
1962 writeln!(w, "#[no_mangle]").unwrap();
1963 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
1964 writeln!(w, "\torig.clone()").unwrap();
1965 writeln!(w, "}}").unwrap();
1966 writeln!(w, "#[allow(unused)]").unwrap();
1967 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
1968 writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", e.ident).unwrap();
1969 writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *const {})).clone() }})) as *mut c_void", e.ident).unwrap();
1970 writeln!(w, "}}").unwrap();
1973 writeln!(w, "#[allow(unused)]").unwrap();
1974 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
1975 writeln!(w, "pub(crate) extern \"C\" fn {}_free_void(this_ptr: *mut c_void) {{", e.ident).unwrap();
1976 writeln!(w, "\tlet _ = unsafe {{ Box::from_raw(this_ptr as *mut {}) }};\n}}", e.ident).unwrap();
1978 w.write_all(&constr).unwrap();
1979 write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free, None);
1982 fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &mut TypeResolver<'b, 'a>) {
1983 match export_status(&f.attrs) {
1984 ExportStatus::Export => {},
1985 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1986 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
1988 let mut gen_types = GenericTypes::new(None);
1989 if !gen_types.learn_generics(&f.sig.generics, types) { return; }
1991 writeln_fn_docs(w, &f.attrs, "", types, Some(&gen_types), f.sig.inputs.iter(), &f.sig.output);
1993 write!(w, "#[no_mangle]\npub extern \"C\" fn {}(", f.sig.ident).unwrap();
1996 write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
1997 write!(w, " {{\n\t").unwrap();
1998 write_method_var_decl_body(w, &f.sig, "", types, Some(&gen_types), false);
1999 write!(w, "{}::{}", types.module_path, f.sig.ident).unwrap();
2001 let mut function_generic_args = Vec::new();
2002 maybe_write_generics(&mut function_generic_args, &f.sig.generics, &syn::PathArguments::None, types, true);
2003 if !function_generic_args.is_empty() {
2004 write!(w, "::{}", String::from_utf8(function_generic_args).unwrap()).unwrap();
2006 write!(w, "(").unwrap();
2008 write_method_call_params(w, &f.sig, "", types, Some(&gen_types), "", false);
2009 writeln!(w, "\n}}\n").unwrap();
2012 // ********************************
2013 // *** File/Crate Walking Logic ***
2014 // ********************************
2016 fn convert_priv_mod<'a, 'b: 'a, W: std::io::Write>(w: &mut W, w_uses: &mut HashSet<String, NonRandomHash>, libast: &'b FullLibraryAST, crate_types: &CrateTypes<'b>, out_dir: &str, mod_path: &str, module: &'b syn::ItemMod) {
2017 // We want to ignore all items declared in this module (as they are not pub), but we still need
2018 // to give the ImportResolver any use statements, so we copy them here.
2019 let mut use_items = Vec::new();
2020 for item in module.content.as_ref().unwrap().1.iter() {
2021 if let syn::Item::Use(_) = item {
2022 use_items.push(item);
2025 let import_resolver = ImportResolver::from_borrowed_items(mod_path.splitn(2, "::").next().unwrap(), libast, mod_path, &use_items);
2026 let mut types = TypeResolver::new(mod_path, import_resolver, crate_types);
2028 writeln!(w, "mod {} {{\n{}", module.ident, DEFAULT_IMPORTS).unwrap();
2029 for item in module.content.as_ref().unwrap().1.iter() {
2031 syn::Item::Mod(m) => convert_priv_mod(w, w_uses, libast, crate_types, out_dir, &format!("{}::{}", mod_path, module.ident), m),
2032 syn::Item::Impl(i) => {
2033 writeln_impl(w, w_uses, i, &mut types);
2038 writeln!(w, "}}").unwrap();
2041 /// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
2042 /// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
2043 /// at `module` from C.
2044 fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &CrateTypes<'a>, out_dir: &str, header_file: &mut File, cpp_header_file: &mut File) {
2045 for (module, astmod) in libast.modules.iter() {
2046 let orig_crate = module.splitn(2, "::").next().unwrap();
2047 let ASTModule { ref attrs, ref items, ref submods } = astmod;
2048 assert_eq!(export_status(&attrs), ExportStatus::Export);
2050 let new_file_path = if submods.is_empty() {
2051 format!("{}/{}.rs", out_dir, module.replace("::", "/"))
2052 } else if module != "" {
2053 format!("{}/{}/mod.rs", out_dir, module.replace("::", "/"))
2055 format!("{}/lib.rs", out_dir)
2057 let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
2058 let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
2059 .open(new_file_path).expect("Unable to open new src file");
2060 let mut out_uses = HashSet::default();
2062 writeln!(out, "// This file is Copyright its original authors, visible in version control").unwrap();
2063 writeln!(out, "// history and in the source files from which this was generated.").unwrap();
2064 writeln!(out, "//").unwrap();
2065 writeln!(out, "// This file is licensed under the license available in the LICENSE or LICENSE.md").unwrap();
2066 writeln!(out, "// file in the root of this repository or, if no such file exists, the same").unwrap();
2067 writeln!(out, "// license as that which applies to the original source files from which this").unwrap();
2068 writeln!(out, "// source was automatically generated.").unwrap();
2069 writeln!(out, "").unwrap();
2071 writeln_docs(&mut out, &attrs, "");
2074 // Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
2075 // and bitcoin hand-written modules.
2076 writeln!(out, "//! C Bindings").unwrap();
2077 writeln!(out, "#![allow(unknown_lints)]").unwrap();
2078 writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
2079 writeln!(out, "#![allow(non_snake_case)]").unwrap();
2080 writeln!(out, "#![allow(unused_imports)]").unwrap();
2081 writeln!(out, "#![allow(unused_variables)]").unwrap();
2082 writeln!(out, "#![allow(unused_mut)]").unwrap();
2083 writeln!(out, "#![allow(unused_parens)]").unwrap();
2084 writeln!(out, "#![allow(unused_unsafe)]").unwrap();
2085 writeln!(out, "#![allow(unused_braces)]").unwrap();
2086 // TODO: We need to map deny(missing_docs) in the source crate(s)
2087 //writeln!(out, "#![deny(missing_docs)]").unwrap();
2089 writeln!(out, "#![cfg_attr(not(feature = \"std\"), no_std)]").unwrap();
2090 writeln!(out, "#[cfg(not(any(feature = \"std\", feature = \"no-std\")))]").unwrap();
2091 writeln!(out, "compile_error!(\"at least one of the `std` or `no-std` features must be enabled\");").unwrap();
2092 writeln!(out, "extern crate alloc;").unwrap();
2094 writeln!(out, "pub mod version;").unwrap();
2095 writeln!(out, "pub mod c_types;").unwrap();
2096 writeln!(out, "pub mod bitcoin;").unwrap();
2098 writeln!(out, "{}", DEFAULT_IMPORTS).unwrap();
2102 writeln!(out, "pub mod {};", m).unwrap();
2105 eprintln!("Converting {} entries...", module);
2107 let import_resolver = ImportResolver::new(orig_crate, libast, module, items);
2108 let mut type_resolver = TypeResolver::new(module, import_resolver, crate_types);
2110 for item in items.iter() {
2112 syn::Item::Use(_) => {}, // Handled above
2113 syn::Item::Static(_) => {},
2114 syn::Item::Enum(e) => {
2115 if let syn::Visibility::Public(_) = e.vis {
2116 writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
2119 syn::Item::Impl(i) => {
2120 writeln_impl(&mut out, &mut out_uses, &i, &mut type_resolver);
2122 syn::Item::Struct(s) => {
2123 if let syn::Visibility::Public(_) = s.vis {
2124 writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
2127 syn::Item::Trait(t) => {
2128 if let syn::Visibility::Public(_) = t.vis {
2129 writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
2132 syn::Item::Mod(m) => {
2133 convert_priv_mod(&mut out, &mut out_uses, libast, crate_types, out_dir, &format!("{}::{}", module, m.ident), m);
2135 syn::Item::Const(c) => {
2136 // Re-export any primitive-type constants.
2137 if let syn::Visibility::Public(_) = c.vis {
2138 if let syn::Type::Path(p) = &*c.ty {
2139 let resolved_path = type_resolver.resolve_path(&p.path, None);
2140 if type_resolver.is_primitive(&resolved_path) {
2141 writeln_field_docs(&mut out, &c.attrs, "", &mut type_resolver, None, &*c.ty);
2142 writeln!(out, "\n#[no_mangle]").unwrap();
2143 writeln!(out, "pub static {}: {} = {}::{};", c.ident, resolved_path, module, c.ident).unwrap();
2148 syn::Item::Type(t) => {
2149 if let syn::Visibility::Public(_) = t.vis {
2150 match export_status(&t.attrs) {
2151 ExportStatus::Export => {},
2152 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
2153 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
2157 syn::Type::Path(p) => {
2158 let real_ty = type_resolver.resolve_path(&p.path, None);
2159 let real_generic_bounds = type_resolver.crate_types.opaques.get(&real_ty).map(|t| t.1).or(
2160 type_resolver.crate_types.priv_structs.get(&real_ty).map(|r| *r)).unwrap();
2161 let mut resolved_generics = t.generics.clone();
2163 // Assume blindly that the bounds in the struct definition where
2164 // clause matches any equivalent bounds on the type alias.
2165 assert!(resolved_generics.where_clause.is_none());
2166 resolved_generics.where_clause = real_generic_bounds.where_clause.clone();
2168 if let syn::PathArguments::AngleBracketed(real_generics) = &p.path.segments.last().unwrap().arguments {
2169 for (real_idx, real_param) in real_generics.args.iter().enumerate() {
2170 if let syn::GenericArgument::Type(syn::Type::Path(real_param_path)) = real_param {
2171 for param in resolved_generics.params.iter_mut() {
2172 if let syn::GenericParam::Type(type_param) = param {
2173 if Some(&type_param.ident) == real_param_path.path.get_ident() {
2174 if let syn::GenericParam::Type(real_type_param) = &real_generic_bounds.params[real_idx] {
2175 type_param.bounds = real_type_param.bounds.clone();
2176 type_param.default = real_type_param.default.clone();
2186 writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &resolved_generics, &t.attrs, &type_resolver, header_file, cpp_header_file)},
2191 syn::Item::Fn(f) => {
2192 if let syn::Visibility::Public(_) = f.vis {
2193 writeln_fn(&mut out, &f, &mut type_resolver);
2196 syn::Item::Macro(_) => {},
2197 syn::Item::Verbatim(_) => {},
2198 syn::Item::ExternCrate(_) => {},
2199 _ => unimplemented!(),
2203 for use_stmt in out_uses {
2204 writeln!(out, "{}", use_stmt).unwrap();
2207 out.flush().unwrap();
2212 /// Walk the FullLibraryAST, determining if impl aliases need to be marked cloneable.
2213 fn walk_ast_second_pass<'a>(ast_storage: &'a FullLibraryAST, crate_types: &CrateTypes<'a>) {
2214 for (module, astmod) in ast_storage.modules.iter() {
2215 let orig_crate = module.splitn(2, "::").next().unwrap();
2216 let ASTModule { ref attrs, ref items, .. } = astmod;
2217 assert_eq!(export_status(&attrs), ExportStatus::Export);
2219 let import_resolver = ImportResolver::new(orig_crate, ast_storage, module, items);
2220 let mut types = TypeResolver::new(module, import_resolver, crate_types);
2222 for item in items.iter() {
2224 syn::Item::Impl(i) => {
2225 match export_status(&i.attrs) {
2226 ExportStatus::Export => {},
2227 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
2228 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
2230 if let Some(trait_path) = i.trait_.as_ref() {
2231 if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) ||
2232 path_matches_nongeneric(&trait_path.1, &["Clone"])
2234 if let &syn::Type::Path(ref p) = &*i.self_ty {
2235 if let Some(resolved_path) = types.maybe_resolve_path(&p.path, None) {
2236 create_alias_for_impl(resolved_path, i, &mut types, |aliased_impl, types| {
2237 if let &syn::Type::Path(ref p) = &*aliased_impl.self_ty {
2238 if let Some(resolved_aliased_path) = types.maybe_resolve_path(&p.path, None) {
2239 crate_types.set_clonable("crate::".to_owned() + &resolved_aliased_path);
2254 fn walk_private_mod<'a>(ast_storage: &'a FullLibraryAST, orig_crate: &str, module: String, items: &'a syn::ItemMod, crate_types: &mut CrateTypes<'a>) {
2255 let import_resolver = ImportResolver::new(orig_crate, ast_storage, &module, &items.content.as_ref().unwrap().1);
2256 for item in items.content.as_ref().unwrap().1.iter() {
2258 syn::Item::Mod(m) => walk_private_mod(ast_storage, orig_crate, format!("{}::{}", module, m.ident), m, crate_types),
2259 syn::Item::Impl(i) => {
2260 if let &syn::Type::Path(ref p) = &*i.self_ty {
2261 if let Some(trait_path) = i.trait_.as_ref() {
2262 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
2263 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
2264 match crate_types.trait_impls.entry(sp.clone()) {
2265 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp.clone()); },
2266 hash_map::Entry::Vacant(e) => { e.insert(vec![tp.clone()]); },
2268 match crate_types.traits_impld.entry(tp) {
2269 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(sp); },
2270 hash_map::Entry::Vacant(e) => { e.insert(vec![sp]); },
2282 /// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
2283 fn walk_ast_first_pass<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
2284 for (module, astmod) in ast_storage.modules.iter() {
2285 let ASTModule { ref attrs, ref items, submods: _ } = astmod;
2286 assert_eq!(export_status(&attrs), ExportStatus::Export);
2287 let orig_crate = module.splitn(2, "::").next().unwrap();
2288 let import_resolver = ImportResolver::new(orig_crate, ast_storage, module, items);
2290 for item in items.iter() {
2292 syn::Item::Struct(s) => {
2293 if let syn::Visibility::Public(_) = s.vis {
2294 let struct_path = format!("{}::{}", module, s.ident);
2295 match export_status(&s.attrs) {
2296 ExportStatus::Export => {},
2297 ExportStatus::NoExport|ExportStatus::TestOnly => {
2298 crate_types.priv_structs.insert(struct_path, &s.generics);
2301 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
2303 crate_types.opaques.insert(struct_path, (&s.ident, &s.generics));
2306 syn::Item::Trait(t) => {
2307 if let syn::Visibility::Public(_) = t.vis {
2308 match export_status(&t.attrs) {
2309 ExportStatus::Export|ExportStatus::NotImplementable => {},
2310 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
2312 let trait_path = format!("{}::{}", module, t.ident);
2313 walk_supertraits!(t, None, (
2314 ("Clone", _, _) => {
2315 crate_types.set_clonable("crate::".to_owned() + &trait_path);
2319 crate_types.traits.insert(trait_path, &t);
2322 syn::Item::Type(t) => {
2323 if let syn::Visibility::Public(_) = t.vis {
2324 match export_status(&t.attrs) {
2325 ExportStatus::Export => {},
2326 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
2327 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
2329 let type_path = format!("{}::{}", module, t.ident);
2331 syn::Type::Path(p) => {
2332 // If its a path with no generics, assume we don't map the aliased type and map it opaque
2333 let args_obj = p.path.segments.last().unwrap().arguments.clone();
2334 match crate_types.reverse_alias_map.entry(import_resolver.maybe_resolve_path(&p.path, None).unwrap()) {
2335 hash_map::Entry::Occupied(mut e) => { e.get_mut().push((type_path.clone(), args_obj)); },
2336 hash_map::Entry::Vacant(e) => { e.insert(vec![(type_path.clone(), args_obj)]); },
2339 crate_types.opaques.insert(type_path, (&t.ident, &t.generics));
2342 crate_types.type_aliases.insert(type_path, import_resolver.resolve_imported_refs((*t.ty).clone()));
2347 syn::Item::Enum(e) if is_enum_opaque(e) => {
2348 if let syn::Visibility::Public(_) = e.vis {
2349 match export_status(&e.attrs) {
2350 ExportStatus::Export => {},
2351 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
2352 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
2354 let enum_path = format!("{}::{}", module, e.ident);
2355 crate_types.opaques.insert(enum_path, (&e.ident, &e.generics));
2358 syn::Item::Enum(e) => {
2359 if let syn::Visibility::Public(_) = e.vis {
2360 match export_status(&e.attrs) {
2361 ExportStatus::Export => {},
2362 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
2363 ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
2365 let enum_path = format!("{}::{}", module, e.ident);
2366 crate_types.mirrored_enums.insert(enum_path, &e);
2369 syn::Item::Impl(i) => {
2370 if let &syn::Type::Path(ref p) = &*i.self_ty {
2371 if let Some(trait_path) = i.trait_.as_ref() {
2372 if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) ||
2373 path_matches_nongeneric(&trait_path.1, &["Clone"]) {
2374 if let Some(full_path) = import_resolver.maybe_resolve_path(&p.path, None) {
2375 crate_types.set_clonable("crate::".to_owned() + &full_path);
2378 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
2379 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
2380 match crate_types.trait_impls.entry(sp.clone()) {
2381 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp.clone()); },
2382 hash_map::Entry::Vacant(e) => { e.insert(vec![tp.clone()]); },
2384 match crate_types.traits_impld.entry(tp) {
2385 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(sp); },
2386 hash_map::Entry::Vacant(e) => { e.insert(vec![sp]); },
2393 syn::Item::Mod(m) => walk_private_mod(ast_storage, orig_crate, format!("{}::{}", module, m.ident), m, crate_types),
2401 let args: Vec<String> = env::args().collect();
2402 if args.len() != 5 {
2403 eprintln!("Usage: target/dir derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
2407 let mut derived_templates = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
2408 .open(&args[2]).expect("Unable to open new header file");
2409 writeln!(&mut derived_templates, "{}", DEFAULT_IMPORTS).unwrap();
2410 let mut header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
2411 .open(&args[3]).expect("Unable to open new header file");
2412 let mut cpp_header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
2413 .open(&args[4]).expect("Unable to open new header file");
2415 writeln!(header_file, "#if defined(__GNUC__)").unwrap();
2416 writeln!(header_file, "#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
2417 writeln!(header_file, "#define MUST_USE_RES __attribute__((warn_unused_result))").unwrap();
2418 writeln!(header_file, "#else").unwrap();
2419 writeln!(header_file, "#define MUST_USE_STRUCT").unwrap();
2420 writeln!(header_file, "#define MUST_USE_RES").unwrap();
2421 writeln!(header_file, "#endif").unwrap();
2422 writeln!(header_file, "#if defined(__clang__)").unwrap();
2423 writeln!(header_file, "#define NONNULL_PTR _Nonnull").unwrap();
2424 writeln!(header_file, "#else").unwrap();
2425 writeln!(header_file, "#define NONNULL_PTR").unwrap();
2426 writeln!(header_file, "#endif").unwrap();
2427 writeln!(cpp_header_file, "#include <string.h>\nnamespace LDK {{").unwrap();
2429 // Write a few manually-defined types into the C++ header file
2430 write_cpp_wrapper(&mut cpp_header_file, "Str", true, None);
2432 // First parse the full crate's ASTs, caching them so that we can hold references to the AST
2433 // objects in other datastructures:
2434 let mut lib_src = String::new();
2435 std::io::stdin().lock().read_to_string(&mut lib_src).unwrap();
2436 let lib_syntax = syn::parse_file(&lib_src).expect("Unable to parse file");
2437 let libast = FullLibraryAST::load_lib(lib_syntax);
2439 // ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
2440 // when parsing other file ASTs...
2441 let mut libtypes = CrateTypes::new(&mut derived_templates, &libast);
2442 walk_ast_first_pass(&libast, &mut libtypes);
2444 // ... using the generated data, determine a few additional fields, specifically which type
2445 // aliases are to be clone-able...
2446 walk_ast_second_pass(&libast, &libtypes);
2448 // ... finally, do the actual file conversion/mapping, writing out types as we go.
2449 convert_file(&libast, &libtypes, &args[1], &mut header_file, &mut cpp_header_file);
2451 // For container templates which we created while walking the crate, make sure we add C++
2452 // mapped types so that C++ users can utilize the auto-destructors available.
2453 for (ty, has_destructor) in libtypes.templates_defined.borrow().iter() {
2454 write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor, None);
2456 writeln!(cpp_header_file, "}}").unwrap();
2458 header_file.flush().unwrap();
2459 cpp_header_file.flush().unwrap();
2460 derived_templates.flush().unwrap();