1 //! Converts a rust crate into a rust crate containing a number of C-exported wrapper functions and
2 //! classes (which is exportable using cbindgen).
3 //! In general, supports convering:
4 //! * structs as a pointer to the underlying type (either owned or not owned),
5 //! * traits as a void-ptr plus a jump table,
6 //! * enums as an equivalent enum with all the inner fields mapped to the mapped types,
7 //! * certain containers (tuples, slices, Vecs, Options, and Results currently) to a concrete
8 //! version of a defined container template.
10 //! It also generates relevant memory-management functions and free-standing functions with
11 //! parameters mapped.
13 use std::collections::{HashMap, hash_map, HashSet};
16 use std::io::{Read, Write};
19 use proc_macro2::{TokenTree, TokenStream, Span};
26 // *************************************
27 // *** Manually-expanded conversions ***
28 // *************************************
30 /// Because we don't expand macros, any code that we need to generated based on their contents has
31 /// to be completely manual. In this case its all just serialization, so its not too hard.
32 fn convert_macro<W: std::io::Write>(w: &mut W, macro_path: &syn::Path, stream: &TokenStream, types: &TypeResolver) {
33 assert_eq!(macro_path.segments.len(), 1);
34 match &format!("{}", macro_path.segments.iter().next().unwrap().ident) as &str {
35 "impl_writeable" | "impl_writeable_len_match" => {
36 let struct_for = if let TokenTree::Ident(i) = stream.clone().into_iter().next().unwrap() { i } else { unimplemented!(); };
37 if let Some(s) = types.maybe_resolve_ident(&struct_for) {
38 if !types.crate_types.opaques.get(&s).is_some() { return; }
39 writeln!(w, "#[no_mangle]").unwrap();
40 writeln!(w, "pub extern \"C\" fn {}_write(obj: &{}) -> crate::c_types::derived::CVec_u8Z {{", struct_for, struct_for).unwrap();
41 writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &(*(*obj).inner) }})").unwrap();
42 writeln!(w, "}}").unwrap();
43 writeln!(w, "#[no_mangle]").unwrap();
44 writeln!(w, "pub(crate) extern \"C\" fn {}_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {{", struct_for).unwrap();
45 writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &*(obj as *const native{}) }})", struct_for).unwrap();
46 writeln!(w, "}}").unwrap();
47 writeln!(w, "#[no_mangle]").unwrap();
48 writeln!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice) -> {} {{", struct_for, struct_for).unwrap();
49 writeln!(w, "\tif let Ok(res) = crate::c_types::deserialize_obj(ser) {{").unwrap();
50 writeln!(w, "\t\t{} {{ inner: Box::into_raw(Box::new(res)), is_owned: true }}", struct_for).unwrap();
51 writeln!(w, "\t}} else {{").unwrap();
52 writeln!(w, "\t\t{} {{ inner: std::ptr::null_mut(), is_owned: true }}", struct_for).unwrap();
53 writeln!(w, "\t}}\n}}").unwrap();
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 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
68 for_obj = format!("{}", ident);
69 full_obj_path = for_obj.clone();
70 has_inner = types.c_type_has_inner_from_path(&types.resolve_path(&p.path, Some(generics)));
73 // We assume that anything that isn't a Path is somehow a generic that ends up in our
74 // derived-types module.
75 let mut for_obj_vec = Vec::new();
76 types.write_c_type(&mut for_obj_vec, for_ty, Some(generics), false);
77 full_obj_path = String::from_utf8(for_obj_vec).unwrap();
78 assert!(full_obj_path.starts_with(TypeResolver::generated_container_path()));
79 for_obj = full_obj_path[TypeResolver::generated_container_path().len() + 2..].into();
83 "util::ser::Writeable" => {
84 writeln!(w, "#[no_mangle]").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::Reference(syn::TypeReference {
88 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
89 elem: Box::new(for_ty.clone()) });
90 assert!(!types.write_from_c_conversion_new_var(w, &syn::Ident::new("obj", Span::call_site()), &ref_type, Some(generics)));
92 write!(w, "\tcrate::c_types::serialize_obj(").unwrap();
93 types.write_from_c_conversion_prefix(w, &ref_type, Some(generics));
94 write!(w, "unsafe {{ &*obj }}").unwrap();
95 types.write_from_c_conversion_suffix(w, &ref_type, Some(generics));
96 writeln!(w, ")").unwrap();
98 writeln!(w, "}}").unwrap();
100 writeln!(w, "#[no_mangle]").unwrap();
101 writeln!(w, "pub(crate) extern \"C\" fn {}_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {{", for_obj).unwrap();
102 writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &*(obj as *const native{}) }})", for_obj).unwrap();
103 writeln!(w, "}}").unwrap();
106 "util::ser::Readable"|"util::ser::ReadableArgs" => {
107 // Create the Result<Object, DecodeError> syn::Type
108 let mut err_segs = syn::punctuated::Punctuated::new();
109 err_segs.push(syn::PathSegment { ident: syn::Ident::new("ln", Span::call_site()), arguments: syn::PathArguments::None });
110 err_segs.push(syn::PathSegment { ident: syn::Ident::new("msgs", Span::call_site()), arguments: syn::PathArguments::None });
111 err_segs.push(syn::PathSegment { ident: syn::Ident::new("DecodeError", Span::call_site()), arguments: syn::PathArguments::None });
112 let mut args = syn::punctuated::Punctuated::new();
113 args.push(syn::GenericArgument::Type(for_ty.clone()));
114 args.push(syn::GenericArgument::Type(syn::Type::Path(syn::TypePath {
115 qself: None, path: syn::Path {
116 leading_colon: Some(syn::Token![::](Span::call_site())), segments: err_segs,
119 let mut res_segs = syn::punctuated::Punctuated::new();
120 res_segs.push(syn::PathSegment {
121 ident: syn::Ident::new("Result", Span::call_site()),
122 arguments: syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
123 colon2_token: None, lt_token: syn::Token![<](Span::call_site()), args, gt_token: syn::Token![>](Span::call_site()),
126 let res_ty = syn::Type::Path(syn::TypePath { qself: None, path: syn::Path {
127 leading_colon: None, segments: res_segs } });
129 writeln!(w, "#[no_mangle]").unwrap();
130 write!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice", for_obj).unwrap();
132 let mut arg_conv = Vec::new();
133 if t == "util::ser::ReadableArgs" {
134 write!(w, ", arg: ").unwrap();
135 assert!(trait_path.leading_colon.is_none());
136 let args_seg = trait_path.segments.iter().last().unwrap();
137 assert_eq!(format!("{}", args_seg.ident), "ReadableArgs");
138 if let syn::PathArguments::AngleBracketed(args) = &args_seg.arguments {
139 assert_eq!(args.args.len(), 1);
140 if let syn::GenericArgument::Type(args_ty) = args.args.iter().next().unwrap() {
141 types.write_c_type(w, args_ty, Some(generics), false);
143 assert!(!types.write_from_c_conversion_new_var(&mut arg_conv, &syn::Ident::new("arg", Span::call_site()), &args_ty, Some(generics)));
145 write!(&mut arg_conv, "\tlet arg_conv = ").unwrap();
146 types.write_from_c_conversion_prefix(&mut arg_conv, &args_ty, Some(generics));
147 write!(&mut arg_conv, "arg").unwrap();
148 types.write_from_c_conversion_suffix(&mut arg_conv, &args_ty, Some(generics));
149 } else { unreachable!(); }
150 } else { unreachable!(); }
152 write!(w, ") -> ").unwrap();
153 types.write_c_type(w, &res_ty, Some(generics), false);
154 writeln!(w, " {{").unwrap();
156 if t == "util::ser::ReadableArgs" {
157 w.write(&arg_conv).unwrap();
158 write!(w, ";\n\tlet res: ").unwrap();
159 // At least in one case we need type annotations here, so provide them.
160 types.write_rust_type(w, Some(generics), &res_ty);
161 writeln!(w, " = crate::c_types::deserialize_obj_arg(ser, arg_conv);").unwrap();
163 writeln!(w, "\tlet res = crate::c_types::deserialize_obj(ser);").unwrap();
165 write!(w, "\t").unwrap();
166 if types.write_to_c_conversion_new_var(w, &syn::Ident::new("res", Span::call_site()), &res_ty, Some(generics), false) {
167 write!(w, "\n\t").unwrap();
169 types.write_to_c_conversion_inline_prefix(w, &res_ty, Some(generics), false);
170 write!(w, "res").unwrap();
171 types.write_to_c_conversion_inline_suffix(w, &res_ty, Some(generics), false);
172 writeln!(w, "\n}}").unwrap();
179 /// Convert "TraitA : TraitB" to a single function name and return type.
181 /// This is (obviously) somewhat over-specialized and only useful for TraitB's that only require a
182 /// single function (eg for serialization).
183 fn convert_trait_impl_field(trait_path: &str) -> (String, &'static str) {
185 "util::ser::Writeable" => ("write".to_owned(), "crate::c_types::derived::CVec_u8Z"),
186 _ => unimplemented!(),
190 /// Companion to convert_trait_impl_field, write an assignment for the function defined by it for
191 /// `for_obj` which implements the the trait at `trait_path`.
192 fn write_trait_impl_field_assign<W: std::io::Write>(w: &mut W, trait_path: &str, for_obj: &syn::Ident) {
194 "util::ser::Writeable" => {
195 writeln!(w, "\t\twrite: {}_write_void,", for_obj).unwrap();
197 _ => unimplemented!(),
201 /// Write out the impl block for a defined trait struct which has a supertrait
202 fn do_write_impl_trait<W: std::io::Write>(w: &mut W, trait_path: &str, trait_name: &syn::Ident, for_obj: &str) {
204 "util::events::MessageSendEventsProvider" => {
205 writeln!(w, "impl lightning::{} for {} {{", trait_path, for_obj).unwrap();
206 writeln!(w, "\tfn get_and_clear_pending_msg_events(&self) -> Vec<lightning::util::events::MessageSendEvent> {{").unwrap();
207 writeln!(w, "\t\t<crate::{} as lightning::{}>::get_and_clear_pending_msg_events(&self.{})", trait_path, trait_path, trait_name).unwrap();
208 writeln!(w, "\t}}\n}}").unwrap();
210 "util::ser::Writeable" => {
211 writeln!(w, "impl lightning::{} for {} {{", trait_path, for_obj).unwrap();
212 writeln!(w, "\tfn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {{").unwrap();
213 writeln!(w, "\t\tlet vec = (self.write)(self.this_arg);").unwrap();
214 writeln!(w, "\t\tw.write_all(vec.as_slice())").unwrap();
215 writeln!(w, "\t}}\n}}").unwrap();
221 // *******************************
222 // *** Per-Type Printing Logic ***
223 // *******************************
225 macro_rules! walk_supertraits { ($t: expr, $types: expr, ($( $pat: pat => $e: expr),*) ) => { {
226 if $t.colon_token.is_some() {
227 for st in $t.supertraits.iter() {
229 syn::TypeParamBound::Trait(supertrait) => {
230 if supertrait.paren_token.is_some() || supertrait.lifetimes.is_some() {
233 // First try to resolve path to find in-crate traits, but if that doesn't work
234 // assume its a prelude trait (eg Clone, etc) and just use the single ident.
235 let types_opt: Option<&TypeResolver> = $types;
236 if let Some(types) = types_opt {
237 if let Some(path) = types.maybe_resolve_path(&supertrait.path, None) {
238 match (&path as &str, &supertrait.path.segments.iter().last().unwrap().ident) {
244 if let Some(ident) = supertrait.path.get_ident() {
245 match (&format!("{}", ident) as &str, &ident) {
248 } else if types_opt.is_some() {
249 panic!("Supertrait unresolvable and not single-ident");
252 syn::TypeParamBound::Lifetime(_) => unimplemented!(),
258 /// Prints a C-mapped trait object containing a void pointer and a jump table for each function in
259 /// the original trait.
260 /// Implements the native Rust trait and relevant parent traits for the new C-mapped trait.
262 /// Finally, implements Deref<MappedTrait> for MappedTrait which allows its use in types which need
263 /// a concrete Deref to the Rust trait.
264 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) {
265 let trait_name = format!("{}", t.ident);
266 match export_status(&t.attrs) {
267 ExportStatus::Export => {},
268 ExportStatus::NoExport|ExportStatus::TestOnly => return,
270 writeln_docs(w, &t.attrs, "");
272 let mut gen_types = GenericTypes::new();
273 assert!(gen_types.learn_generics(&t.generics, types));
274 gen_types.learn_associated_types(&t, types);
276 writeln!(w, "#[repr(C)]\npub struct {} {{", trait_name).unwrap();
277 writeln!(w, "\tpub this_arg: *mut c_void,").unwrap();
278 let mut generated_fields = Vec::new(); // Every field's name except this_arg, used in Clone generation
279 for item in t.items.iter() {
281 &syn::TraitItem::Method(ref m) => {
282 match export_status(&m.attrs) {
283 ExportStatus::NoExport => {
284 // NoExport in this context means we'll hit an unimplemented!() at runtime,
288 ExportStatus::Export => {},
289 ExportStatus::TestOnly => continue,
291 if m.default.is_some() { unimplemented!(); }
293 gen_types.push_ctx();
294 assert!(gen_types.learn_generics(&m.sig.generics, types));
296 writeln_docs(w, &m.attrs, "\t");
298 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
299 if let syn::Type::Reference(r) = &**rtype {
300 // We have to do quite a dance for trait functions which return references
301 // - they ultimately require us to have a native Rust object stored inside
302 // our concrete trait to return a reference to. However, users may wish to
303 // update the value to be returned each time the function is called (or, to
304 // make C copies of Rust impls equivalent, we have to be able to).
306 // Thus, we store a copy of the C-mapped type (which is just a pointer to
307 // the Rust type and a flag to indicate whether deallocation needs to
308 // happen) as well as provide an Option<>al function pointer which is
309 // called when the trait method is called which allows updating on the fly.
310 write!(w, "\tpub {}: ", m.sig.ident).unwrap();
311 generated_fields.push(format!("{}", m.sig.ident));
312 types.write_c_type(w, &*r.elem, Some(&gen_types), false);
313 writeln!(w, ",").unwrap();
314 writeln!(w, "\t/// Fill in the {} field as a reference to it will be given to Rust after this returns", m.sig.ident).unwrap();
315 writeln!(w, "\t/// Note that this takes a pointer to this object, not the this_ptr like other methods do").unwrap();
316 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();
317 writeln!(w, "\tpub set_{}: Option<extern \"C\" fn(&{})>,", m.sig.ident, trait_name).unwrap();
318 generated_fields.push(format!("set_{}", m.sig.ident));
319 // Note that cbindgen will now generate
320 // typedef struct Thing {..., set_thing: (const Thing*), ...} Thing;
321 // which does not compile since Thing is not defined before it is used.
322 writeln!(extra_headers, "struct LDK{};", trait_name).unwrap();
323 writeln!(extra_headers, "typedef struct LDK{} LDK{};", trait_name, trait_name).unwrap();
327 // Sadly, this currently doesn't do what we want, but it should be easy to get
328 // cbindgen to support it. See https://github.com/eqrion/cbindgen/issues/531
329 writeln!(w, "\t#[must_use]").unwrap();
332 write!(w, "\tpub {}: extern \"C\" fn (", m.sig.ident).unwrap();
333 generated_fields.push(format!("{}", m.sig.ident));
334 write_method_params(w, &m.sig, "c_void", types, Some(&gen_types), true, false);
335 writeln!(w, ",").unwrap();
339 &syn::TraitItem::Type(_) => {},
340 _ => unimplemented!(),
343 // Add functions which may be required for supertrait implementations.
344 walk_supertraits!(t, Some(&types), (
346 writeln!(w, "\tpub clone: Option<extern \"C\" fn (this_arg: *const c_void) -> *mut c_void>,").unwrap();
347 generated_fields.push("clone".to_owned());
349 ("std::cmp::Eq", _) => {
350 writeln!(w, "\tpub eq: extern \"C\" fn (this_arg: *const c_void, other_arg: &{}) -> bool,", trait_name).unwrap();
351 writeln!(extra_headers, "typedef struct LDK{} LDK{};", trait_name, trait_name).unwrap();
352 generated_fields.push("eq".to_owned());
354 ("std::hash::Hash", _) => {
355 writeln!(w, "\tpub hash: extern \"C\" fn (this_arg: *const c_void) -> u64,").unwrap();
356 generated_fields.push("hash".to_owned());
358 ("Send", _) => {}, ("Sync", _) => {},
360 generated_fields.push(if types.crate_types.traits.get(s).is_none() {
361 let (name, ret) = convert_trait_impl_field(s);
362 writeln!(w, "\tpub {}: extern \"C\" fn (this_arg: *const c_void) -> {},", name, ret).unwrap();
365 // For in-crate supertraits, just store a C-mapped copy of the supertrait as a member.
366 writeln!(w, "\tpub {}: crate::{},", i, s).unwrap();
371 writeln!(w, "\tpub free: Option<extern \"C\" fn(this_arg: *mut c_void)>,").unwrap();
372 generated_fields.push("free".to_owned());
373 writeln!(w, "}}").unwrap();
374 // Implement supertraits for the C-mapped struct.
375 walk_supertraits!(t, Some(&types), (
376 ("Send", _) => writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap(),
377 ("Sync", _) => writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap(),
378 ("std::cmp::Eq", _) => {
379 writeln!(w, "impl std::cmp::Eq for {} {{}}", trait_name).unwrap();
380 writeln!(w, "impl std::cmp::PartialEq for {} {{", trait_name).unwrap();
381 writeln!(w, "\tfn eq(&self, o: &Self) -> bool {{ (self.eq)(self.this_arg, o) }}\n}}").unwrap();
383 ("std::hash::Hash", _) => {
384 writeln!(w, "impl std::hash::Hash for {} {{", trait_name).unwrap();
385 writeln!(w, "\tfn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {{ hasher.write_u64((self.hash)(self.this_arg)) }}\n}}").unwrap();
388 writeln!(w, "#[no_mangle]").unwrap();
389 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", trait_name, trait_name, trait_name).unwrap();
390 writeln!(w, "\t{} {{", trait_name).unwrap();
391 writeln!(w, "\t\tthis_arg: if let Some(f) = orig.clone {{ (f)(orig.this_arg) }} else {{ orig.this_arg }},").unwrap();
392 for field in generated_fields.iter() {
393 writeln!(w, "\t\t{}: orig.{}.clone(),", field, field).unwrap();
395 writeln!(w, "\t}}\n}}").unwrap();
396 writeln!(w, "impl Clone for {} {{", trait_name).unwrap();
397 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
398 writeln!(w, "\t\t{}_clone(self)", trait_name).unwrap();
399 writeln!(w, "\t}}\n}}").unwrap();
402 do_write_impl_trait(w, s, i, &trait_name);
406 // Finally, implement the original Rust trait for the newly created mapped trait.
407 writeln!(w, "\nuse {}::{}::{} as rust{};", types.orig_crate, types.module_path, t.ident, trait_name).unwrap();
408 write!(w, "impl rust{}", t.ident).unwrap();
409 maybe_write_generics(w, &t.generics, types, false);
410 writeln!(w, " for {} {{", trait_name).unwrap();
411 for item in t.items.iter() {
413 syn::TraitItem::Method(m) => {
414 if let ExportStatus::TestOnly = export_status(&m.attrs) { continue; }
415 if m.default.is_some() { unimplemented!(); }
416 if m.sig.constness.is_some() || m.sig.asyncness.is_some() || m.sig.unsafety.is_some() ||
417 m.sig.abi.is_some() || m.sig.variadic.is_some() {
420 gen_types.push_ctx();
421 assert!(gen_types.learn_generics(&m.sig.generics, types));
422 write!(w, "\tfn {}", m.sig.ident).unwrap();
423 types.write_rust_generic_param(w, Some(&gen_types), m.sig.generics.params.iter());
424 write!(w, "(").unwrap();
425 for inp in m.sig.inputs.iter() {
427 syn::FnArg::Receiver(recv) => {
428 if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
429 write!(w, "&").unwrap();
430 if let Some(lft) = &recv.reference.as_ref().unwrap().1 {
431 write!(w, "'{} ", lft.ident).unwrap();
433 if recv.mutability.is_some() {
434 write!(w, "mut self").unwrap();
436 write!(w, "self").unwrap();
439 syn::FnArg::Typed(arg) => {
440 if !arg.attrs.is_empty() { unimplemented!(); }
442 syn::Pat::Ident(ident) => {
443 if !ident.attrs.is_empty() || ident.by_ref.is_some() ||
444 ident.mutability.is_some() || ident.subpat.is_some() {
447 write!(w, ", {}{}: ", if types.skip_arg(&*arg.ty, Some(&gen_types)) { "_" } else { "" }, ident.ident).unwrap();
449 _ => unimplemented!(),
451 types.write_rust_type(w, Some(&gen_types), &*arg.ty);
455 write!(w, ")").unwrap();
456 match &m.sig.output {
457 syn::ReturnType::Type(_, rtype) => {
458 write!(w, " -> ").unwrap();
459 types.write_rust_type(w, Some(&gen_types), &*rtype)
463 write!(w, " {{\n\t\t").unwrap();
464 match export_status(&m.attrs) {
465 ExportStatus::NoExport => {
470 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
471 if let syn::Type::Reference(r) = &**rtype {
472 assert_eq!(m.sig.inputs.len(), 1); // Must only take self!
473 writeln!(w, "if let Some(f) = self.set_{} {{", m.sig.ident).unwrap();
474 writeln!(w, "\t\t\t(f)(self);").unwrap();
475 write!(w, "\t\t}}\n\t\t").unwrap();
476 types.write_from_c_conversion_to_ref_prefix(w, &*r.elem, Some(&gen_types));
477 write!(w, "self.{}", m.sig.ident).unwrap();
478 types.write_from_c_conversion_to_ref_suffix(w, &*r.elem, Some(&gen_types));
479 writeln!(w, "\n\t}}").unwrap();
484 write_method_var_decl_body(w, &m.sig, "\t", types, Some(&gen_types), true);
485 write!(w, "(self.{})(", m.sig.ident).unwrap();
486 write_method_call_params(w, &m.sig, "\t", types, Some(&gen_types), "", true);
488 writeln!(w, "\n\t}}").unwrap();
491 &syn::TraitItem::Type(ref t) => {
492 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
493 let mut bounds_iter = t.bounds.iter();
494 match bounds_iter.next().unwrap() {
495 syn::TypeParamBound::Trait(tr) => {
496 writeln!(w, "\ttype {} = crate::{};", t.ident, types.resolve_path(&tr.path, Some(&gen_types))).unwrap();
498 _ => unimplemented!(),
500 if bounds_iter.next().is_some() { unimplemented!(); }
502 _ => unimplemented!(),
505 writeln!(w, "}}\n").unwrap();
506 writeln!(w, "// We're essentially a pointer already, or at least a set of pointers, so allow us to be used").unwrap();
507 writeln!(w, "// directly as a Deref trait in higher-level structs:").unwrap();
508 writeln!(w, "impl std::ops::Deref for {} {{\n\ttype Target = Self;", trait_name).unwrap();
509 writeln!(w, "\tfn deref(&self) -> &Self {{\n\t\tself\n\t}}\n}}").unwrap();
511 writeln!(w, "/// Calls the free function if one is set").unwrap();
512 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", trait_name, trait_name).unwrap();
513 writeln!(w, "impl Drop for {} {{", trait_name).unwrap();
514 writeln!(w, "\tfn drop(&mut self) {{").unwrap();
515 writeln!(w, "\t\tif let Some(f) = self.free {{").unwrap();
516 writeln!(w, "\t\t\tf(self.this_arg);").unwrap();
517 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
519 write_cpp_wrapper(cpp_headers, &trait_name, true);
522 /// Write out a simple "opaque" type (eg structs) which contain a pointer to the native Rust type
523 /// and a flag to indicate whether Drop'ing the mapped struct drops the underlying Rust type.
525 /// Also writes out a _free function and a C++ wrapper which handles calling _free.
526 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) {
527 // If we directly read the original type by its original name, cbindgen hits
528 // https://github.com/eqrion/cbindgen/issues/286 Thus, instead, we import it as a temporary
529 // name and then reference it by that name, which works around the issue.
530 write!(w, "\nuse {}::{}::{} as native{}Import;\ntype native{} = native{}Import", types.orig_crate, types.module_path, ident, ident, ident, ident).unwrap();
531 maybe_write_generics(w, &generics, &types, true);
532 writeln!(w, ";\n").unwrap();
533 writeln!(extra_headers, "struct native{}Opaque;\ntypedef struct native{}Opaque LDKnative{};", ident, ident, ident).unwrap();
534 writeln_docs(w, &attrs, "");
535 writeln!(w, "#[must_use]\n#[repr(C)]\npub struct {} {{\n\t/// Nearly everywhere, inner must be non-null, however in places where", struct_name).unwrap();
536 writeln!(w, "\t/// the Rust equivalent takes an Option, it may be set to null to indicate None.").unwrap();
537 writeln!(w, "\tpub inner: *mut native{},\n\tpub is_owned: bool,\n}}\n", ident).unwrap();
538 writeln!(w, "impl Drop for {} {{\n\tfn drop(&mut self) {{", struct_name).unwrap();
539 writeln!(w, "\t\tif self.is_owned && !self.inner.is_null() {{").unwrap();
540 writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(self.inner) }};\n\t\t}}\n\t}}\n}}").unwrap();
541 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", struct_name, struct_name).unwrap();
542 writeln!(w, "#[allow(unused)]").unwrap();
543 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
544 writeln!(w, "extern \"C\" fn {}_free_void(this_ptr: *mut c_void) {{", struct_name).unwrap();
545 writeln!(w, "\tunsafe {{ let _ = Box::from_raw(this_ptr as *mut native{}); }}\n}}", struct_name).unwrap();
546 writeln!(w, "#[allow(unused)]").unwrap();
547 writeln!(w, "/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy").unwrap();
548 writeln!(w, "impl {} {{", struct_name).unwrap();
549 writeln!(w, "\tpub(crate) fn take_inner(mut self) -> *mut native{} {{", struct_name).unwrap();
550 writeln!(w, "\t\tassert!(self.is_owned);").unwrap();
551 writeln!(w, "\t\tlet ret = self.inner;").unwrap();
552 writeln!(w, "\t\tself.inner = std::ptr::null_mut();").unwrap();
553 writeln!(w, "\t\tret").unwrap();
554 writeln!(w, "\t}}\n}}").unwrap();
556 write_cpp_wrapper(cpp_headers, &format!("{}", ident), true);
559 /// Writes out all the relevant mappings for a Rust struct, deferring to writeln_opaque to generate
560 /// the struct itself, and then writing getters and setters for public, understood-type fields and
561 /// a constructor if every field is public.
562 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) {
563 if export_status(&s.attrs) != ExportStatus::Export { return; }
565 let struct_name = &format!("{}", s.ident);
566 writeln_opaque(w, &s.ident, struct_name, &s.generics, &s.attrs, types, extra_headers, cpp_headers);
568 if let syn::Fields::Named(fields) = &s.fields {
569 let mut gen_types = GenericTypes::new();
570 assert!(gen_types.learn_generics(&s.generics, types));
572 let mut all_fields_settable = true;
573 for field in fields.named.iter() {
574 if let syn::Visibility::Public(_) = field.vis {
575 let export = export_status(&field.attrs);
577 ExportStatus::Export => {},
578 ExportStatus::NoExport|ExportStatus::TestOnly => {
579 all_fields_settable = false;
584 if let Some(ident) = &field.ident {
585 let ref_type = syn::Type::Reference(syn::TypeReference {
586 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
587 elem: Box::new(field.ty.clone()) });
588 if types.understood_c_type(&ref_type, Some(&gen_types)) {
589 writeln_docs(w, &field.attrs, "");
590 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> ", struct_name, ident, struct_name).unwrap();
591 types.write_c_type(w, &ref_type, Some(&gen_types), true);
592 write!(w, " {{\n\tlet mut inner_val = &mut unsafe {{ &mut *this_ptr.inner }}.{};\n\t", ident).unwrap();
593 let local_var = types.write_to_c_conversion_new_var(w, &syn::Ident::new("inner_val", Span::call_site()), &ref_type, Some(&gen_types), true);
594 if local_var { write!(w, "\n\t").unwrap(); }
595 types.write_to_c_conversion_inline_prefix(w, &ref_type, Some(&gen_types), true);
597 write!(w, "inner_val").unwrap();
599 write!(w, "(*inner_val)").unwrap();
601 types.write_to_c_conversion_inline_suffix(w, &ref_type, Some(&gen_types), true);
602 writeln!(w, "\n}}").unwrap();
605 if types.understood_c_type(&field.ty, Some(&gen_types)) {
606 writeln_docs(w, &field.attrs, "");
607 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_set_{}(this_ptr: &mut {}, mut val: ", struct_name, ident, struct_name).unwrap();
608 types.write_c_type(w, &field.ty, Some(&gen_types), false);
609 write!(w, ") {{\n\t").unwrap();
610 let local_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("val", Span::call_site()), &field.ty, Some(&gen_types));
611 if local_var { write!(w, "\n\t").unwrap(); }
612 write!(w, "unsafe {{ &mut *this_ptr.inner }}.{} = ", ident).unwrap();
613 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
614 write!(w, "val").unwrap();
615 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
616 writeln!(w, ";\n}}").unwrap();
617 } else { all_fields_settable = false; }
618 } else { all_fields_settable = false; }
619 } else { all_fields_settable = false; }
622 if all_fields_settable {
623 // Build a constructor!
624 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_new(", struct_name).unwrap();
625 for (idx, field) in fields.named.iter().enumerate() {
626 if idx != 0 { write!(w, ", ").unwrap(); }
627 write!(w, "mut {}_arg: ", field.ident.as_ref().unwrap()).unwrap();
628 types.write_c_type(w, &field.ty, Some(&gen_types), false);
630 write!(w, ") -> {} {{\n\t", struct_name).unwrap();
631 for field in fields.named.iter() {
632 let field_name = format!("{}_arg", field.ident.as_ref().unwrap());
633 if types.write_from_c_conversion_new_var(w, &syn::Ident::new(&field_name, Span::call_site()), &field.ty, Some(&gen_types)) {
634 write!(w, "\n\t").unwrap();
637 writeln!(w, "{} {{ inner: Box::into_raw(Box::new(native{} {{", struct_name, s.ident).unwrap();
638 for field in fields.named.iter() {
639 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
640 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
641 write!(w, "{}_arg", field.ident.as_ref().unwrap()).unwrap();
642 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
643 writeln!(w, ",").unwrap();
645 writeln!(w, "\t}})), is_owned: true }}\n}}").unwrap();
650 /// Prints a relevant conversion for impl *
652 /// For simple impl Struct {}s, this just outputs the wrapper functions as Struct_fn_name() { .. }.
654 /// For impl Trait for Struct{}s, this non-exported generates wrapper functions as
655 /// Trait_Struct_fn_name and a Struct_as_Trait(&struct) -> Trait function which returns a populated
656 /// Trait struct containing a pointer to the passed struct's inner field and the wrapper functions.
658 /// A few non-crate Traits are hard-coded including Default.
659 fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut TypeResolver) {
660 match export_status(&i.attrs) {
661 ExportStatus::Export => {},
662 ExportStatus::NoExport|ExportStatus::TestOnly => return,
665 if let syn::Type::Tuple(_) = &*i.self_ty {
666 if types.understood_c_type(&*i.self_ty, None) {
667 let mut gen_types = GenericTypes::new();
668 if !gen_types.learn_generics(&i.generics, types) {
669 eprintln!("Not implementing anything for `impl (..)` due to not understood generics");
673 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
674 if let Some(trait_path) = i.trait_.as_ref() {
675 if trait_path.0.is_some() { unimplemented!(); }
676 if types.understood_c_path(&trait_path.1) {
677 eprintln!("Not implementing anything for `impl Trait for (..)` - we only support manual defines");
680 // Just do a manual implementation:
681 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
684 eprintln!("Not implementing anything for plain `impl (..)` block - we only support `impl Trait for (..)` blocks");
690 if let &syn::Type::Path(ref p) = &*i.self_ty {
691 if p.qself.is_some() { unimplemented!(); }
692 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
693 if let Some(resolved_path) = types.maybe_resolve_non_ignored_ident(&ident) {
694 let mut gen_types = GenericTypes::new();
695 if !gen_types.learn_generics(&i.generics, types) {
696 eprintln!("Not implementing anything for impl {} due to not understood generics", ident);
700 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
701 if let Some(trait_path) = i.trait_.as_ref() {
702 if trait_path.0.is_some() { unimplemented!(); }
703 if types.understood_c_path(&trait_path.1) {
704 let full_trait_path = types.resolve_path(&trait_path.1, None);
705 let trait_obj = *types.crate_types.traits.get(&full_trait_path).unwrap();
706 // We learn the associated types maping from the original trait object.
707 // That's great, except that they are unresolved idents, so if we learn
708 // mappings from a trai defined in a different file, we may mis-resolve or
709 // fail to resolve the mapped types.
710 gen_types.learn_associated_types(trait_obj, types);
711 let mut impl_associated_types = HashMap::new();
712 for item in i.items.iter() {
714 syn::ImplItem::Type(t) => {
715 if let syn::Type::Path(p) = &t.ty {
716 if let Some(id) = single_ident_generic_path_to_ident(&p.path) {
717 impl_associated_types.insert(&t.ident, id);
725 let export = export_status(&trait_obj.attrs);
727 ExportStatus::Export => {},
728 ExportStatus::NoExport|ExportStatus::TestOnly => return,
731 // For cases where we have a concrete native object which implements a
732 // trait and need to return the C-mapped version of the trait, provide a
733 // From<> implementation which does all the work to ensure free is handled
734 // properly. This way we can call this method from deep in the
735 // type-conversion logic without actually knowing the concrete native type.
736 writeln!(w, "impl From<native{}> for crate::{} {{", ident, full_trait_path).unwrap();
737 writeln!(w, "\tfn from(obj: native{}) -> Self {{", ident).unwrap();
738 writeln!(w, "\t\tlet mut rust_obj = {} {{ inner: Box::into_raw(Box::new(obj)), is_owned: true }};", ident).unwrap();
739 writeln!(w, "\t\tlet mut ret = {}_as_{}(&rust_obj);", ident, trait_obj.ident).unwrap();
740 writeln!(w, "\t\t// We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn").unwrap();
741 writeln!(w, "\t\trust_obj.inner = std::ptr::null_mut();").unwrap();
742 writeln!(w, "\t\tret.free = Some({}_free_void);", ident).unwrap();
743 writeln!(w, "\t\tret\n\t}}\n}}").unwrap();
745 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_as_{}(this_arg: &{}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
746 writeln!(w, "\tcrate::{} {{", full_trait_path).unwrap();
747 writeln!(w, "\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
748 writeln!(w, "\t\tfree: None,").unwrap();
750 macro_rules! write_meth {
751 ($m: expr, $trait: expr, $indent: expr) => {
752 let trait_method = $trait.items.iter().filter_map(|item| {
753 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
754 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
755 match export_status(&trait_method.attrs) {
756 ExportStatus::Export => {},
757 ExportStatus::NoExport => {
758 write!(w, "{}\t\t//XXX: Need to export {}\n", $indent, $m.sig.ident).unwrap();
761 ExportStatus::TestOnly => continue,
764 let mut printed = false;
765 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
766 if let syn::Type::Reference(r) = &**rtype {
767 write!(w, "\n\t\t{}{}: ", $indent, $m.sig.ident).unwrap();
768 types.write_empty_rust_val(Some(&gen_types), w, &*r.elem);
769 writeln!(w, ",\n{}\t\tset_{}: Some({}_{}_set_{}),", $indent, $m.sig.ident, ident, trait_obj.ident, $m.sig.ident).unwrap();
774 write!(w, "{}\t\t{}: {}_{}_{},\n", $indent, $m.sig.ident, ident, trait_obj.ident, $m.sig.ident).unwrap();
778 for item in trait_obj.items.iter() {
780 syn::TraitItem::Method(m) => {
781 write_meth!(m, trait_obj, "");
786 walk_supertraits!(trait_obj, Some(&types), (
788 writeln!(w, "\t\tclone: Some({}_clone_void),", ident).unwrap();
790 ("Sync", _) => {}, ("Send", _) => {},
791 ("std::marker::Sync", _) => {}, ("std::marker::Send", _) => {},
793 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
794 writeln!(w, "\t\t{}: crate::{} {{", t, s).unwrap();
795 writeln!(w, "\t\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
796 writeln!(w, "\t\t\tfree: None,").unwrap();
797 for item in supertrait_obj.items.iter() {
799 syn::TraitItem::Method(m) => {
800 write_meth!(m, supertrait_obj, "\t");
805 write!(w, "\t\t}},\n").unwrap();
807 write_trait_impl_field_assign(w, s, ident);
811 write!(w, "\t}}\n}}\nuse {}::{} as {}TraitImport;\n", types.orig_crate, full_trait_path, trait_obj.ident).unwrap();
813 macro_rules! impl_meth {
814 ($m: expr, $trait: expr, $indent: expr) => {
815 let trait_method = $trait.items.iter().filter_map(|item| {
816 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
817 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
818 match export_status(&trait_method.attrs) {
819 ExportStatus::Export => {},
820 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
823 if let syn::ReturnType::Type(_, _) = &$m.sig.output {
824 writeln!(w, "#[must_use]").unwrap();
826 write!(w, "extern \"C\" fn {}_{}_{}(", ident, trait_obj.ident, $m.sig.ident).unwrap();
827 gen_types.push_ctx();
828 assert!(gen_types.learn_generics(&$m.sig.generics, types));
829 write_method_params(w, &$m.sig, "c_void", types, Some(&gen_types), true, true);
830 write!(w, " {{\n\t").unwrap();
831 write_method_var_decl_body(w, &$m.sig, "", types, Some(&gen_types), false);
832 let mut takes_self = false;
833 for inp in $m.sig.inputs.iter() {
834 if let syn::FnArg::Receiver(_) = inp {
839 let mut t_gen_args = String::new();
840 for (idx, _) in $trait.generics.params.iter().enumerate() {
841 if idx != 0 { t_gen_args += ", " };
845 write!(w, "<native{} as {}TraitImport<{}>>::{}(unsafe {{ &mut *(this_arg as *mut native{}) }}, ", ident, $trait.ident, t_gen_args, $m.sig.ident, ident).unwrap();
847 write!(w, "<native{} as {}TraitImport<{}>>::{}(", ident, $trait.ident, t_gen_args, $m.sig.ident).unwrap();
850 let mut real_type = "".to_string();
851 match &$m.sig.output {
852 syn::ReturnType::Type(_, rtype) => {
853 if let Some(mut remaining_path) = first_seg_self(&*rtype) {
854 if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
855 real_type = format!("{}", impl_associated_types.get(associated_seg).unwrap());
861 write_method_call_params(w, &$m.sig, "", types, Some(&gen_types), &real_type, false);
863 write!(w, "\n}}\n").unwrap();
864 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
865 if let syn::Type::Reference(r) = &**rtype {
866 assert_eq!($m.sig.inputs.len(), 1); // Must only take self
867 writeln!(w, "extern \"C\" fn {}_{}_set_{}(trait_self_arg: &{}) {{", ident, trait_obj.ident, $m.sig.ident, trait_obj.ident).unwrap();
868 writeln!(w, "\t// This is a bit race-y in the general case, but for our specific use-cases today, we're safe").unwrap();
869 writeln!(w, "\t// Specifically, we must ensure that the first time we're called it can never be in parallel").unwrap();
870 write!(w, "\tif ").unwrap();
871 types.write_empty_rust_val_check(Some(&gen_types), w, &*r.elem, &format!("trait_self_arg.{}", $m.sig.ident));
872 writeln!(w, " {{").unwrap();
873 writeln!(w, "\t\tunsafe {{ &mut *(trait_self_arg as *const {} as *mut {}) }}.{} = {}_{}_{}(trait_self_arg.this_arg);", trait_obj.ident, trait_obj.ident, $m.sig.ident, ident, trait_obj.ident, $m.sig.ident).unwrap();
874 writeln!(w, "\t}}").unwrap();
875 writeln!(w, "}}").unwrap();
881 for item in i.items.iter() {
883 syn::ImplItem::Method(m) => {
884 impl_meth!(m, trait_obj, "");
886 syn::ImplItem::Type(_) => {},
887 _ => unimplemented!(),
890 walk_supertraits!(trait_obj, Some(&types), (
892 if let Some(supertrait_obj) = types.crate_types.traits.get(s).cloned() {
893 writeln!(w, "use {}::{} as native{}Trait;", types.orig_crate, s, t).unwrap();
894 for item in supertrait_obj.items.iter() {
896 syn::TraitItem::Method(m) => {
897 impl_meth!(m, supertrait_obj, "\t");
905 write!(w, "\n").unwrap();
906 } else if path_matches_nongeneric(&trait_path.1, &["From"]) {
907 } else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
908 write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
909 write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
910 write!(w, "}}\n").unwrap();
911 } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "PartialEq"]) {
912 } else if (path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) || path_matches_nongeneric(&trait_path.1, &["Clone"])) &&
913 types.c_type_has_inner_from_path(&resolved_path) {
914 writeln!(w, "impl Clone for {} {{", ident).unwrap();
915 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
916 writeln!(w, "\t\tSelf {{").unwrap();
917 writeln!(w, "\t\t\tinner: if self.inner.is_null() {{ std::ptr::null_mut() }} else {{").unwrap();
918 writeln!(w, "\t\t\t\tBox::into_raw(Box::new(unsafe {{ &*self.inner }}.clone())) }},").unwrap();
919 writeln!(w, "\t\t\tis_owned: true,").unwrap();
920 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
921 writeln!(w, "#[allow(unused)]").unwrap();
922 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
923 writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", ident).unwrap();
924 writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", ident).unwrap();
925 writeln!(w, "}}").unwrap();
926 writeln!(w, "#[no_mangle]").unwrap();
927 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", ident, ident, ident).unwrap();
928 writeln!(w, "\torig.clone()").unwrap();
929 writeln!(w, "}}").unwrap();
931 //XXX: implement for other things like ToString
932 // If we have no generics, try a manual implementation:
933 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
936 let declared_type = (*types.get_declared_type(&ident).unwrap()).clone();
937 for item in i.items.iter() {
939 syn::ImplItem::Method(m) => {
940 if let syn::Visibility::Public(_) = m.vis {
941 match export_status(&m.attrs) {
942 ExportStatus::Export => {},
943 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
945 if m.defaultness.is_some() { unimplemented!(); }
946 writeln_docs(w, &m.attrs, "");
947 if let syn::ReturnType::Type(_, _) = &m.sig.output {
948 writeln!(w, "#[must_use]").unwrap();
950 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_{}(", ident, m.sig.ident).unwrap();
951 let ret_type = match &declared_type {
952 DeclType::MirroredEnum => format!("{}", ident),
953 DeclType::StructImported => format!("{}", ident),
954 _ => unimplemented!(),
956 gen_types.push_ctx();
957 assert!(gen_types.learn_generics(&m.sig.generics, types));
958 write_method_params(w, &m.sig, &ret_type, types, Some(&gen_types), false, true);
959 write!(w, " {{\n\t").unwrap();
960 write_method_var_decl_body(w, &m.sig, "", types, Some(&gen_types), false);
961 let mut takes_self = false;
962 let mut takes_mut_self = false;
963 for inp in m.sig.inputs.iter() {
964 if let syn::FnArg::Receiver(r) = inp {
966 if r.mutability.is_some() { takes_mut_self = true; }
970 write!(w, "unsafe {{ &mut (*(this_arg.inner as *mut native{})) }}.{}(", ident, m.sig.ident).unwrap();
971 } else if takes_self {
972 write!(w, "unsafe {{ &*this_arg.inner }}.{}(", m.sig.ident).unwrap();
974 write!(w, "{}::{}::{}(", types.orig_crate, resolved_path, m.sig.ident).unwrap();
976 write_method_call_params(w, &m.sig, "", types, Some(&gen_types), &ret_type, false);
978 writeln!(w, "\n}}\n").unwrap();
985 } else if let Some(resolved_path) = types.maybe_resolve_ident(&ident) {
986 if let Some(aliases) = types.crate_types.reverse_alias_map.get(&resolved_path).cloned() {
987 'alias_impls: for (alias, arguments) in aliases {
988 let alias_resolved = types.resolve_path(&alias, None);
989 for (idx, gen) in i.generics.params.iter().enumerate() {
991 syn::GenericParam::Type(type_param) => {
992 'bounds_check: for bound in type_param.bounds.iter() {
993 if let syn::TypeParamBound::Trait(trait_bound) = bound {
994 if let syn::PathArguments::AngleBracketed(ref t) = &arguments {
995 assert!(idx < t.args.len());
996 if let syn::GenericArgument::Type(syn::Type::Path(p)) = &t.args[idx] {
997 let generic_arg = types.resolve_path(&p.path, None);
998 let generic_bound = types.resolve_path(&trait_bound.path, None);
999 if let Some(traits_impld) = types.crate_types.trait_impls.get(&generic_arg) {
1000 for trait_impld in traits_impld {
1001 if *trait_impld == generic_bound { continue 'bounds_check; }
1003 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1004 continue 'alias_impls;
1006 eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
1007 continue 'alias_impls;
1009 } else { unimplemented!(); }
1010 } else { unimplemented!(); }
1011 } else { unimplemented!(); }
1014 syn::GenericParam::Lifetime(_) => {},
1015 syn::GenericParam::Const(_) => unimplemented!(),
1018 let aliased_impl = syn::ItemImpl {
1019 attrs: i.attrs.clone(),
1020 brace_token: syn::token::Brace(Span::call_site()),
1022 generics: syn::Generics {
1024 params: syn::punctuated::Punctuated::new(),
1028 impl_token: syn::Token![impl](Span::call_site()),
1029 items: i.items.clone(),
1030 self_ty: Box::new(syn::Type::Path(syn::TypePath { qself: None, path: alias.clone() })),
1031 trait_: i.trait_.clone(),
1034 writeln_impl(w, &aliased_impl, types);
1037 eprintln!("Not implementing anything for {} due to it being marked not exported", ident);
1040 eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub)", ident);
1047 /// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
1048 /// is unitary), we generate an equivalent enum with all types replaced with their C mapped
1049 /// versions followed by conversion functions which map between the Rust version and the C mapped
1051 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) {
1052 match export_status(&e.attrs) {
1053 ExportStatus::Export => {},
1054 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1057 if is_enum_opaque(e) {
1058 eprintln!("Skipping enum {} as it contains non-unit fields", e.ident);
1059 writeln_opaque(w, &e.ident, &format!("{}", e.ident), &e.generics, &e.attrs, types, extra_headers, cpp_headers);
1062 writeln_docs(w, &e.attrs, "");
1064 if e.generics.lt_token.is_some() {
1068 let mut needs_free = false;
1070 writeln!(w, "#[must_use]\n#[derive(Clone)]\n#[repr(C)]\npub enum {} {{", e.ident).unwrap();
1071 for var in e.variants.iter() {
1072 assert_eq!(export_status(&var.attrs), ExportStatus::Export); // We can't partially-export a mirrored enum
1073 writeln_docs(w, &var.attrs, "\t");
1074 write!(w, "\t{}", var.ident).unwrap();
1075 if let syn::Fields::Named(fields) = &var.fields {
1077 writeln!(w, " {{").unwrap();
1078 for field in fields.named.iter() {
1079 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1080 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1081 types.write_c_type(w, &field.ty, None, false);
1082 writeln!(w, ",").unwrap();
1084 write!(w, "\t}}").unwrap();
1085 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1087 write!(w, "(").unwrap();
1088 for (idx, field) in fields.unnamed.iter().enumerate() {
1089 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1090 types.write_c_type(w, &field.ty, None, false);
1091 if idx != fields.unnamed.len() - 1 {
1092 write!(w, ",").unwrap();
1095 write!(w, ")").unwrap();
1097 if var.discriminant.is_some() { unimplemented!(); }
1098 writeln!(w, ",").unwrap();
1100 writeln!(w, "}}\nuse {}::{}::{} as native{};\nimpl {} {{", types.orig_crate, types.module_path, e.ident, e.ident, e.ident).unwrap();
1102 macro_rules! write_conv {
1103 ($fn_sig: expr, $to_c: expr, $ref: expr) => {
1104 writeln!(w, "\t#[allow(unused)]\n\tpub(crate) fn {} {{\n\t\tmatch {} {{", $fn_sig, if $to_c { "native" } else { "self" }).unwrap();
1105 for var in e.variants.iter() {
1106 write!(w, "\t\t\t{}{}::{} ", if $to_c { "native" } else { "" }, e.ident, var.ident).unwrap();
1107 if let syn::Fields::Named(fields) = &var.fields {
1108 write!(w, "{{").unwrap();
1109 for field in fields.named.iter() {
1110 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1111 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, field.ident.as_ref().unwrap()).unwrap();
1113 write!(w, "}} ").unwrap();
1114 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1115 write!(w, "(").unwrap();
1116 for (idx, field) in fields.unnamed.iter().enumerate() {
1117 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1118 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, ('a' as u8 + idx as u8) as char).unwrap();
1120 write!(w, ") ").unwrap();
1122 write!(w, "=>").unwrap();
1124 macro_rules! handle_field_a {
1125 ($field: expr, $field_ident: expr) => { {
1126 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1127 let mut sink = ::std::io::sink();
1128 let mut out: &mut dyn std::io::Write = if $ref { &mut sink } else { w };
1129 let new_var = if $to_c {
1130 types.write_to_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None, false)
1132 types.write_from_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None)
1134 if $ref || new_var {
1136 write!(w, "let mut {}_nonref = (*{}).clone();\n\t\t\t\t", $field_ident, $field_ident).unwrap();
1138 let nonref_ident = syn::Ident::new(&format!("{}_nonref", $field_ident), Span::call_site());
1140 types.write_to_c_conversion_new_var(w, &nonref_ident, &$field.ty, None, false);
1142 types.write_from_c_conversion_new_var(w, &nonref_ident, &$field.ty, None);
1144 write!(w, "\n\t\t\t\t").unwrap();
1147 write!(w, "\n\t\t\t\t").unwrap();
1152 if let syn::Fields::Named(fields) = &var.fields {
1153 write!(w, " {{\n\t\t\t\t").unwrap();
1154 for field in fields.named.iter() {
1155 handle_field_a!(field, field.ident.as_ref().unwrap());
1157 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1158 write!(w, " {{\n\t\t\t\t").unwrap();
1159 for (idx, field) in fields.unnamed.iter().enumerate() {
1160 handle_field_a!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1162 } else { write!(w, " ").unwrap(); }
1164 write!(w, "{}{}::{}", if $to_c { "" } else { "native" }, e.ident, var.ident).unwrap();
1166 macro_rules! handle_field_b {
1167 ($field: expr, $field_ident: expr) => { {
1168 if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
1170 types.write_to_c_conversion_inline_prefix(w, &$field.ty, None, false);
1172 types.write_from_c_conversion_prefix(w, &$field.ty, None);
1174 write!(w, "{}{}", $field_ident,
1175 if $ref { "_nonref" } else { "" }).unwrap();
1177 types.write_to_c_conversion_inline_suffix(w, &$field.ty, None, false);
1179 types.write_from_c_conversion_suffix(w, &$field.ty, None);
1181 write!(w, ",").unwrap();
1185 if let syn::Fields::Named(fields) = &var.fields {
1186 write!(w, " {{").unwrap();
1187 for field in fields.named.iter() {
1188 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1189 write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1190 handle_field_b!(field, field.ident.as_ref().unwrap());
1192 writeln!(w, "\n\t\t\t\t}}").unwrap();
1193 write!(w, "\t\t\t}}").unwrap();
1194 } else if let syn::Fields::Unnamed(fields) = &var.fields {
1195 write!(w, " (").unwrap();
1196 for (idx, field) in fields.unnamed.iter().enumerate() {
1197 write!(w, "\n\t\t\t\t\t").unwrap();
1198 handle_field_b!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
1200 writeln!(w, "\n\t\t\t\t)").unwrap();
1201 write!(w, "\t\t\t}}").unwrap();
1203 writeln!(w, ",").unwrap();
1205 writeln!(w, "\t\t}}\n\t}}").unwrap();
1209 write_conv!(format!("to_native(&self) -> native{}", e.ident), false, true);
1210 write_conv!(format!("into_native(self) -> native{}", e.ident), false, false);
1211 write_conv!(format!("from_native(native: &native{}) -> Self", e.ident), true, true);
1212 write_conv!(format!("native_into(native: native{}) -> Self", e.ident), true, false);
1213 writeln!(w, "}}").unwrap();
1216 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", e.ident, e.ident).unwrap();
1218 writeln!(w, "#[no_mangle]").unwrap();
1219 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
1220 writeln!(w, "\torig.clone()").unwrap();
1221 writeln!(w, "}}").unwrap();
1222 write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free);
1225 fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &mut TypeResolver<'b, 'a>) {
1226 match export_status(&f.attrs) {
1227 ExportStatus::Export => {},
1228 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1230 writeln_docs(w, &f.attrs, "");
1232 let mut gen_types = GenericTypes::new();
1233 if !gen_types.learn_generics(&f.sig.generics, types) { return; }
1235 write!(w, "#[no_mangle]\npub extern \"C\" fn {}(", f.sig.ident).unwrap();
1236 write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
1237 write!(w, " {{\n\t").unwrap();
1238 write_method_var_decl_body(w, &f.sig, "", types, Some(&gen_types), false);
1239 write!(w, "{}::{}::{}(", types.orig_crate, types.module_path, f.sig.ident).unwrap();
1240 write_method_call_params(w, &f.sig, "", types, Some(&gen_types), "", false);
1241 writeln!(w, "\n}}\n").unwrap();
1244 // ********************************
1245 // *** File/Crate Walking Logic ***
1246 // ********************************
1249 pub attrs: Vec<syn::Attribute>,
1250 pub items: Vec<syn::Item>,
1251 pub submods: Vec<String>,
1253 /// A struct containing the syn::File AST for each file in the crate.
1254 struct FullLibraryAST {
1255 modules: HashMap<String, ASTModule, NonRandomHash>,
1257 impl FullLibraryAST {
1258 fn load_module(&mut self, module: String, attrs: Vec<syn::Attribute>, mut items: Vec<syn::Item>) {
1259 let mut non_mod_items = Vec::with_capacity(items.len());
1260 let mut submods = Vec::with_capacity(items.len());
1261 for item in items.drain(..) {
1263 syn::Item::Mod(m) if m.content.is_some() => {
1264 if export_status(&m.attrs) == ExportStatus::Export {
1265 if let syn::Visibility::Public(_) = m.vis {
1266 let modident = format!("{}", m.ident);
1267 let modname = if module != "" {
1268 module.clone() + "::" + &modident
1272 self.load_module(modname, m.attrs, m.content.unwrap().1);
1273 submods.push(modident);
1275 non_mod_items.push(syn::Item::Mod(m));
1279 syn::Item::Mod(_) => panic!("--pretty=expanded output should never have non-body modules"),
1280 _ => { non_mod_items.push(item); }
1283 self.modules.insert(module, ASTModule { attrs, items: non_mod_items, submods });
1286 pub fn load_lib(lib: syn::File) -> Self {
1287 assert_eq!(export_status(&lib.attrs), ExportStatus::Export);
1288 let mut res = Self { modules: HashMap::default() };
1289 res.load_module("".to_owned(), lib.attrs, lib.items);
1294 /// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
1295 /// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
1296 /// at `module` from C.
1297 fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>, out_dir: &str, orig_crate: &str, header_file: &mut File, cpp_header_file: &mut File) {
1298 for (module, astmod) in libast.modules.iter() {
1299 let ASTModule { ref attrs, ref items, ref submods } = astmod;
1300 assert_eq!(export_status(&attrs), ExportStatus::Export);
1302 let new_file_path = if submods.is_empty() {
1303 format!("{}/{}.rs", out_dir, module.replace("::", "/"))
1304 } else if module != "" {
1305 format!("{}/{}/mod.rs", out_dir, module.replace("::", "/"))
1307 format!("{}/lib.rs", out_dir)
1309 let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
1310 let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1311 .open(new_file_path).expect("Unable to open new src file");
1313 writeln_docs(&mut out, &attrs, "");
1316 // Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
1317 // and bitcoin hand-written modules.
1318 writeln!(out, "#![allow(unknown_lints)]").unwrap();
1319 writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
1320 writeln!(out, "#![allow(non_snake_case)]").unwrap();
1321 writeln!(out, "#![allow(unused_imports)]").unwrap();
1322 writeln!(out, "#![allow(unused_variables)]").unwrap();
1323 writeln!(out, "#![allow(unused_mut)]").unwrap();
1324 writeln!(out, "#![allow(unused_parens)]").unwrap();
1325 writeln!(out, "#![allow(unused_unsafe)]").unwrap();
1326 writeln!(out, "#![allow(unused_braces)]").unwrap();
1327 writeln!(out, "mod c_types;").unwrap();
1328 writeln!(out, "mod bitcoin;").unwrap();
1330 writeln!(out, "\nuse std::ffi::c_void;\nuse bitcoin::hashes::Hash;\nuse crate::c_types::*;\n").unwrap();
1334 writeln!(out, "pub mod {};", m).unwrap();
1337 eprintln!("Converting {} entries...", module);
1339 let import_resolver = ImportResolver::new(module, items);
1340 let mut type_resolver = TypeResolver::new(orig_crate, module, import_resolver, crate_types);
1342 for item in items.iter() {
1344 syn::Item::Use(_) => {}, // Handled above
1345 syn::Item::Static(_) => {},
1346 syn::Item::Enum(e) => {
1347 if let syn::Visibility::Public(_) = e.vis {
1348 writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
1351 syn::Item::Impl(i) => {
1352 writeln_impl(&mut out, &i, &mut type_resolver);
1354 syn::Item::Struct(s) => {
1355 if let syn::Visibility::Public(_) = s.vis {
1356 writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
1359 syn::Item::Trait(t) => {
1360 if let syn::Visibility::Public(_) = t.vis {
1361 writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
1364 syn::Item::Mod(_) => {}, // We don't have to do anything - the top loop handles these.
1365 syn::Item::Const(c) => {
1366 // Re-export any primitive-type constants.
1367 if let syn::Visibility::Public(_) = c.vis {
1368 if let syn::Type::Path(p) = &*c.ty {
1369 let resolved_path = type_resolver.resolve_path(&p.path, None);
1370 if type_resolver.is_primitive(&resolved_path) {
1371 writeln!(out, "\n#[no_mangle]").unwrap();
1372 writeln!(out, "pub static {}: {} = {}::{}::{};", c.ident, resolved_path, orig_crate, module, c.ident).unwrap();
1377 syn::Item::Type(t) => {
1378 if let syn::Visibility::Public(_) = t.vis {
1379 match export_status(&t.attrs) {
1380 ExportStatus::Export => {},
1381 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1384 let mut process_alias = true;
1385 for tok in t.generics.params.iter() {
1386 if let syn::GenericParam::Lifetime(_) = tok {}
1387 else { process_alias = false; }
1391 syn::Type::Path(_) =>
1392 writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &t.generics, &t.attrs, &type_resolver, header_file, cpp_header_file),
1398 syn::Item::Fn(f) => {
1399 if let syn::Visibility::Public(_) = f.vis {
1400 writeln_fn(&mut out, &f, &mut type_resolver);
1403 syn::Item::Macro(m) => {
1404 if m.ident.is_none() { // If its not a macro definition
1405 convert_macro(&mut out, &m.mac.path, &m.mac.tokens, &type_resolver);
1408 syn::Item::Verbatim(_) => {},
1409 syn::Item::ExternCrate(_) => {},
1410 _ => unimplemented!(),
1414 out.flush().unwrap();
1418 fn walk_private_mod<'a>(module: String, items: &'a syn::ItemMod, crate_types: &mut CrateTypes<'a>) {
1419 let import_resolver = ImportResolver::new(&module, &items.content.as_ref().unwrap().1);
1420 for item in items.content.as_ref().unwrap().1.iter() {
1422 syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types),
1423 syn::Item::Impl(i) => {
1424 if let &syn::Type::Path(ref p) = &*i.self_ty {
1425 if let Some(trait_path) = i.trait_.as_ref() {
1426 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1427 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1428 match crate_types.trait_impls.entry(sp) {
1429 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1430 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1442 /// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
1443 fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
1444 for (module, astmod) in ast_storage.modules.iter() {
1445 let ASTModule { ref attrs, ref items, submods: _ } = astmod;
1446 assert_eq!(export_status(&attrs), ExportStatus::Export);
1447 let import_resolver = ImportResolver::new(module, items);
1449 for item in items.iter() {
1451 syn::Item::Struct(s) => {
1452 if let syn::Visibility::Public(_) = s.vis {
1453 match export_status(&s.attrs) {
1454 ExportStatus::Export => {},
1455 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1457 let struct_path = format!("{}::{}", module, s.ident);
1458 crate_types.opaques.insert(struct_path, &s.ident);
1461 syn::Item::Trait(t) => {
1462 if let syn::Visibility::Public(_) = t.vis {
1463 match export_status(&t.attrs) {
1464 ExportStatus::Export => {},
1465 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1467 let trait_path = format!("{}::{}", module, t.ident);
1468 walk_supertraits!(t, None, (
1470 crate_types.clonable_types.insert("crate::".to_owned() + &trait_path);
1474 crate_types.traits.insert(trait_path, &t);
1477 syn::Item::Type(t) => {
1478 if let syn::Visibility::Public(_) = t.vis {
1479 match export_status(&t.attrs) {
1480 ExportStatus::Export => {},
1481 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1483 let type_path = format!("{}::{}", module, t.ident);
1484 let mut process_alias = true;
1485 for tok in t.generics.params.iter() {
1486 if let syn::GenericParam::Lifetime(_) = tok {}
1487 else { process_alias = false; }
1491 syn::Type::Path(p) => {
1492 // If its a path with no generics, assume we don't map the aliased type and map it opaque
1493 let mut segments = syn::punctuated::Punctuated::new();
1494 segments.push(syn::PathSegment {
1495 ident: t.ident.clone(),
1496 arguments: syn::PathArguments::None,
1498 let path_obj = syn::Path { leading_colon: None, segments };
1499 let args_obj = p.path.segments.last().unwrap().arguments.clone();
1500 match crate_types.reverse_alias_map.entry(import_resolver.maybe_resolve_path(&p.path, None).unwrap()) {
1501 hash_map::Entry::Occupied(mut e) => { e.get_mut().push((path_obj, args_obj)); },
1502 hash_map::Entry::Vacant(e) => { e.insert(vec![(path_obj, args_obj)]); },
1505 crate_types.opaques.insert(type_path.clone(), &t.ident);
1508 crate_types.type_aliases.insert(type_path, import_resolver.resolve_imported_refs((*t.ty).clone()));
1514 syn::Item::Enum(e) if is_enum_opaque(e) => {
1515 if let syn::Visibility::Public(_) = e.vis {
1516 match export_status(&e.attrs) {
1517 ExportStatus::Export => {},
1518 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1520 let enum_path = format!("{}::{}", module, e.ident);
1521 crate_types.opaques.insert(enum_path, &e.ident);
1524 syn::Item::Enum(e) => {
1525 if let syn::Visibility::Public(_) = e.vis {
1526 match export_status(&e.attrs) {
1527 ExportStatus::Export => {},
1528 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1530 let enum_path = format!("{}::{}", module, e.ident);
1531 crate_types.mirrored_enums.insert(enum_path, &e);
1534 syn::Item::Impl(i) => {
1535 if let &syn::Type::Path(ref p) = &*i.self_ty {
1536 if let Some(trait_path) = i.trait_.as_ref() {
1537 if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) {
1538 if let Some(full_path) = import_resolver.maybe_resolve_path(&p.path, None) {
1539 crate_types.clonable_types.insert("crate::".to_owned() + &full_path);
1542 if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
1543 if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
1544 match crate_types.trait_impls.entry(sp) {
1545 hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
1546 hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
1553 syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types),
1561 let args: Vec<String> = env::args().collect();
1562 if args.len() != 6 {
1563 eprintln!("Usage: target/dir source_crate_name derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
1567 let mut derived_templates = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1568 .open(&args[3]).expect("Unable to open new header file");
1569 let mut header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1570 .open(&args[4]).expect("Unable to open new header file");
1571 let mut cpp_header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1572 .open(&args[5]).expect("Unable to open new header file");
1574 writeln!(header_file, "#if defined(__GNUC__)").unwrap();
1575 writeln!(header_file, "#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
1576 writeln!(header_file, "#define MUST_USE_RES __attribute__((warn_unused_result))").unwrap();
1577 writeln!(header_file, "#else").unwrap();
1578 writeln!(header_file, "#define MUST_USE_STRUCT").unwrap();
1579 writeln!(header_file, "#define MUST_USE_RES").unwrap();
1580 writeln!(header_file, "#endif").unwrap();
1581 writeln!(header_file, "#if defined(__clang__)").unwrap();
1582 writeln!(header_file, "#define NONNULL_PTR _Nonnull").unwrap();
1583 writeln!(header_file, "#else").unwrap();
1584 writeln!(header_file, "#define NONNULL_PTR").unwrap();
1585 writeln!(header_file, "#endif").unwrap();
1586 writeln!(cpp_header_file, "#include <string.h>\nnamespace LDK {{").unwrap();
1588 // First parse the full crate's ASTs, caching them so that we can hold references to the AST
1589 // objects in other datastructures:
1590 let mut lib_src = String::new();
1591 std::io::stdin().lock().read_to_string(&mut lib_src).unwrap();
1592 let lib_syntax = syn::parse_file(&lib_src).expect("Unable to parse file");
1593 let libast = FullLibraryAST::load_lib(lib_syntax);
1595 // ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
1596 // when parsing other file ASTs...
1597 let mut libtypes = CrateTypes { traits: HashMap::new(), opaques: HashMap::new(), mirrored_enums: HashMap::new(),
1598 type_aliases: HashMap::new(), reverse_alias_map: HashMap::new(), templates_defined: HashMap::default(),
1599 template_file: &mut derived_templates,
1600 clonable_types: HashSet::new(), trait_impls: HashMap::new() };
1601 walk_ast(&libast, &mut libtypes);
1603 // ... finally, do the actual file conversion/mapping, writing out types as we go.
1604 convert_file(&libast, &mut libtypes, &args[1], &args[2], &mut header_file, &mut cpp_header_file);
1606 // For container templates which we created while walking the crate, make sure we add C++
1607 // mapped types so that C++ users can utilize the auto-destructors available.
1608 for (ty, has_destructor) in libtypes.templates_defined.iter() {
1609 write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor);
1611 writeln!(cpp_header_file, "}}").unwrap();
1613 header_file.flush().unwrap();
1614 cpp_header_file.flush().unwrap();
1615 derived_templates.flush().unwrap();