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;
16 use std::io::{Read, Write};
20 use proc_macro2::{TokenTree, TokenStream, Span};
27 // *************************************
28 // *** Manually-expanded conversions ***
29 // *************************************
31 /// Because we don't expand macros, any code that we need to generated based on their contents has
32 /// to be completely manual. In this case its all just serialization, so its not too hard.
33 fn convert_macro<W: std::io::Write>(w: &mut W, macro_path: &syn::Path, stream: &TokenStream, types: &TypeResolver) {
34 assert_eq!(macro_path.segments.len(), 1);
35 match &format!("{}", macro_path.segments.iter().next().unwrap().ident) as &str {
36 "impl_writeable" | "impl_writeable_len_match" => {
37 let struct_for = if let TokenTree::Ident(i) = stream.clone().into_iter().next().unwrap() { i } else { unimplemented!(); };
38 if let Some(s) = types.maybe_resolve_ident(&struct_for) {
39 if !types.crate_types.opaques.get(&s).is_some() { return; }
40 writeln!(w, "{}", types.opts.fn_attributes).unwrap();
41 writeln!(w, "pub extern \"C\" fn {}_write(obj: &{}) -> crate::c_types::derived::CVec_u8Z {{", struct_for, struct_for).unwrap();
42 writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &(*(*obj).inner) }})").unwrap();
43 writeln!(w, "}}").unwrap();
44 writeln!(w, "#[allow(unused)]").unwrap();
45 writeln!(w, "pub(crate) extern \"C\" fn {}_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {{", struct_for).unwrap();
46 writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &*(obj as *const native{}) }})", struct_for).unwrap();
47 writeln!(w, "}}").unwrap();
48 writeln!(w, "{}", types.opts.fn_attributes).unwrap();
49 writeln!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice) -> {} {{", struct_for, struct_for).unwrap();
50 writeln!(w, "\tif let Ok(res) = crate::c_types::deserialize_obj(ser) {{").unwrap();
51 writeln!(w, "\t\t{} {{ inner: Box::into_raw(Box::new(res)), is_owned: true }}", struct_for).unwrap();
52 writeln!(w, "\t}} else {{").unwrap();
53 writeln!(w, "\t\t{} {{ inner: std::ptr::null_mut(), is_owned: true }}", struct_for).unwrap();
54 writeln!(w, "\t}}\n}}").unwrap();
61 /// Convert "impl trait_path for for_ty { .. }" for manually-mapped types (ie (de)serialization)
62 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) {
63 if let Some(t) = types.maybe_resolve_path(&trait_path, Some(generics)) {
66 let mut has_inner = false;
67 if let syn::Type::Path(ref p) = for_ty {
68 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
69 for_obj = format!("{}", ident);
70 full_obj_path = for_obj.clone();
71 has_inner = types.c_type_has_inner_from_path(&types.resolve_path(&p.path, Some(generics)));
74 // We assume that anything that isn't a Path is somehow a generic that ends up in our
75 // derived-types module.
76 let mut for_obj_vec = Vec::new();
77 types.write_c_type(&mut for_obj_vec, for_ty, Some(generics), false);
78 full_obj_path = String::from_utf8(for_obj_vec).unwrap();
79 assert!(full_obj_path.starts_with(TypeResolver::generated_container_path()));
80 for_obj = full_obj_path[TypeResolver::generated_container_path().len() + 2..].into();
84 "util::ser::Writeable" => {
85 writeln!(w, "{}", types.opts.fn_attributes).unwrap();
86 writeln!(w, "pub extern \"C\" fn {}_write(obj: &{}) -> crate::c_types::derived::CVec_u8Z {{", for_obj, full_obj_path).unwrap();
88 let ref_type = syn::Type::Reference(syn::TypeReference {
89 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
90 elem: Box::new(for_ty.clone()) });
91 assert!(!types.write_from_c_conversion_new_var(w, &syn::Ident::new("obj", Span::call_site()), &ref_type, Some(generics)));
93 write!(w, "\tcrate::c_types::serialize_obj(").unwrap();
94 types.write_from_c_conversion_prefix(w, &ref_type, Some(generics));
95 write!(w, "unsafe {{ &*obj }}").unwrap();
96 types.write_from_c_conversion_suffix(w, &ref_type, Some(generics));
97 writeln!(w, ")").unwrap();
99 writeln!(w, "}}").unwrap();
101 writeln!(w, "#[allow(unused)]").unwrap();
102 writeln!(w, "pub(crate) extern \"C\" fn {}_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {{", for_obj).unwrap();
103 writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &*(obj as *const native{}) }})", for_obj).unwrap();
104 writeln!(w, "}}").unwrap();
107 "util::ser::Readable"|"util::ser::ReadableArgs" => {
108 // Create the Result<Object, DecodeError> syn::Type
109 let mut err_segs = syn::punctuated::Punctuated::new();
110 err_segs.push(syn::PathSegment { ident: syn::Ident::new("ln", Span::call_site()), arguments: syn::PathArguments::None });
111 err_segs.push(syn::PathSegment { ident: syn::Ident::new("msgs", Span::call_site()), arguments: syn::PathArguments::None });
112 err_segs.push(syn::PathSegment { ident: syn::Ident::new("DecodeError", Span::call_site()), arguments: syn::PathArguments::None });
113 let mut args = syn::punctuated::Punctuated::new();
114 args.push(syn::GenericArgument::Type(for_ty.clone()));
115 args.push(syn::GenericArgument::Type(syn::Type::Path(syn::TypePath {
116 qself: None, path: syn::Path {
117 leading_colon: Some(syn::Token![::](Span::call_site())), segments: err_segs,
120 let mut res_segs = syn::punctuated::Punctuated::new();
121 res_segs.push(syn::PathSegment {
122 ident: syn::Ident::new("Result", Span::call_site()),
123 arguments: syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
124 colon2_token: None, lt_token: syn::Token![<](Span::call_site()), args, gt_token: syn::Token![>](Span::call_site()),
127 let res_ty = syn::Type::Path(syn::TypePath { qself: None, path: syn::Path {
128 leading_colon: None, segments: res_segs } });
130 writeln!(w, "{}", types.opts.fn_attributes).unwrap();
131 write!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice", for_obj).unwrap();
133 let mut arg_conv = Vec::new();
134 if t == "util::ser::ReadableArgs" {
135 write!(w, ", arg: ").unwrap();
136 assert!(trait_path.leading_colon.is_none());
137 let args_seg = trait_path.segments.iter().last().unwrap();
138 assert_eq!(format!("{}", args_seg.ident), "ReadableArgs");
139 if let syn::PathArguments::AngleBracketed(args) = &args_seg.arguments {
140 assert_eq!(args.args.len(), 1);
141 if let syn::GenericArgument::Type(args_ty) = args.args.iter().next().unwrap() {
142 types.write_c_type(w, args_ty, Some(generics), false);
144 assert!(!types.write_from_c_conversion_new_var(&mut arg_conv, &syn::Ident::new("arg", Span::call_site()), &args_ty, Some(generics)));
146 write!(&mut arg_conv, "\tlet arg_conv = ").unwrap();
147 types.write_from_c_conversion_prefix(&mut arg_conv, &args_ty, Some(generics));
148 write!(&mut arg_conv, "arg").unwrap();
149 types.write_from_c_conversion_suffix(&mut arg_conv, &args_ty, Some(generics));
150 } else { unreachable!(); }
151 } else { unreachable!(); }
153 write!(w, ") -> ").unwrap();
154 types.write_c_type(w, &res_ty, Some(generics), false);
155 writeln!(w, " {{").unwrap();
157 if t == "util::ser::ReadableArgs" {
158 w.write(&arg_conv).unwrap();
159 write!(w, ";\n\tlet res: ").unwrap();
160 // At least in one case we need type annotations here, so provide them.
161 types.write_rust_type(w, Some(generics), &res_ty);
162 writeln!(w, " = crate::c_types::deserialize_obj_arg(ser, arg_conv);").unwrap();
164 writeln!(w, "\tlet res = crate::c_types::deserialize_obj(ser);").unwrap();
166 write!(w, "\t").unwrap();
167 if types.write_to_c_conversion_new_var(w, &syn::Ident::new("res", Span::call_site()), &res_ty, Some(generics), false) {
168 write!(w, "\n\t").unwrap();
170 types.write_to_c_conversion_inline_prefix(w, &res_ty, Some(generics), false);
171 write!(w, "res").unwrap();
172 types.write_to_c_conversion_inline_suffix(w, &res_ty, Some(generics), false);
173 writeln!(w, "\n}}").unwrap();
180 /// Convert "TraitA : TraitB" to a single function name and return type.
182 /// This is (obviously) somewhat over-specialized and only useful for TraitB's that only require a
183 /// single function (eg for serialization).
184 fn convert_trait_impl_field(trait_path: &str) -> (String, &'static str) {
186 "util::ser::Writeable" => ("write".to_owned(), "crate::c_types::derived::CVec_u8Z"),
187 _ => unimplemented!(),
191 /// Companion to convert_trait_impl_field, write an assignment for the function defined by it for
192 /// `for_obj` which implements the the trait at `trait_path`.
193 fn write_trait_impl_field_assign<W: std::io::Write>(w: &mut W, trait_path: &str, for_obj: &syn::Ident) {
195 "util::ser::Writeable" => {
196 writeln!(w, "\t\twrite: {}_write_void,", for_obj).unwrap();
198 _ => unimplemented!(),
202 /// Write out the impl block for a defined trait struct which has a supertrait
203 fn do_write_impl_trait<W: std::io::Write>(w: &mut W, trait_path: &str, trait_name: &syn::Ident, for_obj: &str) {
205 "util::events::MessageSendEventsProvider" => {
206 writeln!(w, "impl lightning::{} for {} {{", trait_path, for_obj).unwrap();
207 writeln!(w, "\tfn get_and_clear_pending_msg_events(&self) -> Vec<lightning::util::events::MessageSendEvent> {{").unwrap();
208 writeln!(w, "\t\t<crate::{} as lightning::{}>::get_and_clear_pending_msg_events(&self.{})", trait_path, trait_path, trait_name).unwrap();
209 writeln!(w, "\t}}\n}}").unwrap();
211 "util::ser::Writeable" => {
212 writeln!(w, "impl lightning::{} for {} {{", trait_path, for_obj).unwrap();
213 writeln!(w, "\tfn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {{").unwrap();
214 writeln!(w, "\t\tlet vec = (self.write)(self.this_arg);").unwrap();
215 writeln!(w, "\t\tw.write_all(vec.as_slice())").unwrap();
216 writeln!(w, "\t}}\n}}").unwrap();
222 // *******************************
223 // *** Per-Type Printing Logic ***
224 // *******************************
226 macro_rules! walk_supertraits { ($t: expr, $types: expr, ($( $pat: pat => $e: expr),*) ) => { {
227 if $t.colon_token.is_some() {
228 for st in $t.supertraits.iter() {
230 syn::TypeParamBound::Trait(supertrait) => {
231 if supertrait.paren_token.is_some() || supertrait.lifetimes.is_some() {
234 // First try to resolve path to find in-crate traits, but if that doesn't work
235 // assume its a prelude trait (eg Clone, etc) and just use the single ident.
236 if let Some(path) = $types.maybe_resolve_path(&supertrait.path, None) {
237 match (&path as &str, &supertrait.path.segments.iter().last().unwrap().ident) {
240 } else if let Some(ident) = supertrait.path.get_ident() {
241 match (&format!("{}", ident) as &str, &ident) {
245 panic!("Supertrait unresolvable and not single-ident");
248 syn::TypeParamBound::Lifetime(_) => unimplemented!(),
254 /// Prints a C-mapped trait object containing a void pointer and a jump table for each function in
255 /// the original trait.
256 /// Implements the native Rust trait and relevant parent traits for the new C-mapped trait.
258 /// Finally, implements Deref<MappedTrait> for MappedTrait which allows its use in types which need
259 /// a concrete Deref to the Rust trait.
260 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) {
261 let trait_name = format!("{}", t.ident);
262 match export_status(&t.attrs) {
263 ExportStatus::Export => {},
264 ExportStatus::NoExport|ExportStatus::TestOnly => return,
266 writeln_docs(w, &t.attrs, "");
268 let mut gen_types = GenericTypes::new();
269 assert!(gen_types.learn_generics(&t.generics, types));
270 gen_types.learn_associated_types(&t, types);
272 writeln!(w, "{}", types.opts.struct_attributes).unwrap();
273 writeln!(w, "pub struct {} {{", trait_name).unwrap();
274 writeln!(w, "\tpub this_arg: *mut c_void,").unwrap();
275 let mut generated_fields = Vec::new(); // Every field's name except this_arg, used in Clone generation
276 for item in t.items.iter() {
278 &syn::TraitItem::Method(ref m) => {
279 match export_status(&m.attrs) {
280 ExportStatus::NoExport => {
281 // NoExport in this context means we'll hit an unimplemented!() at runtime,
285 ExportStatus::Export => {},
286 ExportStatus::TestOnly => continue,
288 if m.default.is_some() { unimplemented!(); }
290 gen_types.push_ctx();
291 assert!(gen_types.learn_generics(&m.sig.generics, types));
293 writeln_docs(w, &m.attrs, "\t");
295 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
296 if let syn::Type::Reference(r) = &**rtype {
297 // We have to do quite a dance for trait functions which return references
298 // - they ultimately require us to have a native Rust object stored inside
299 // our concrete trait to return a reference to. However, users may wish to
300 // update the value to be returned each time the function is called (or, to
301 // make C copies of Rust impls equivalent, we have to be able to).
303 // Thus, we store a copy of the C-mapped type (which is just a pointer to
304 // the Rust type and a flag to indicate whether deallocation needs to
305 // happen) as well as provide an Option<>al function pointer which is
306 // called when the trait method is called which allows updating on the fly.
307 write!(w, "\tpub {}: ", m.sig.ident).unwrap();
308 generated_fields.push(format!("{}", m.sig.ident));
309 types.write_c_type(w, &*r.elem, Some(&gen_types), false);
310 writeln!(w, ",").unwrap();
311 writeln!(w, "\t/// Fill in the {} field as a reference to it will be given to Rust after this returns", m.sig.ident).unwrap();
312 writeln!(w, "\t/// Note that this takes a pointer to this object, not the this_ptr like other methods do").unwrap();
313 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();
314 writeln!(w, "\tpub set_{}: Option<extern \"C\" fn(&{})>,", m.sig.ident, trait_name).unwrap();
315 generated_fields.push(format!("set_{}", m.sig.ident));
316 // Note that cbindgen will now generate
317 // typedef struct Thing {..., set_thing: (const Thing*), ...} Thing;
318 // which does not compile since Thing is not defined before it is used.
319 writeln!(extra_headers, "struct LDK{};", trait_name).unwrap();
320 writeln!(extra_headers, "typedef struct LDK{} LDK{};", trait_name, trait_name).unwrap();
324 // Sadly, this currently doesn't do what we want, but it should be easy to get
325 // cbindgen to support it. See https://github.com/eqrion/cbindgen/issues/531
326 writeln!(w, "\t#[must_use]").unwrap();
329 write!(w, "\tpub {}: extern \"C\" fn (", m.sig.ident).unwrap();
330 generated_fields.push(format!("{}", m.sig.ident));
331 write_method_params(w, &m.sig, "c_void", types, Some(&gen_types), true, false);
332 writeln!(w, ",").unwrap();
336 &syn::TraitItem::Type(_) => {},
337 _ => unimplemented!(),
340 // Add functions which may be required for supertrait implementations.
341 walk_supertraits!(t, types, (
343 writeln!(w, "\tpub clone: Option<extern \"C\" fn (this_arg: *const c_void) -> *mut c_void>,").unwrap();
344 generated_fields.push("clone".to_owned());
346 ("std::cmp::Eq", _) => {
347 writeln!(w, "\tpub eq: extern \"C\" fn (this_arg: *const c_void, other_arg: &{}) -> bool,", trait_name).unwrap();
348 writeln!(extra_headers, "typedef struct LDK{} LDK{};", trait_name, trait_name).unwrap();
349 generated_fields.push("eq".to_owned());
351 ("std::hash::Hash", _) => {
352 writeln!(w, "\tpub hash: extern \"C\" fn (this_arg: *const c_void) -> u64,").unwrap();
353 generated_fields.push("hash".to_owned());
355 ("Send", _) => {}, ("Sync", _) => {},
357 generated_fields.push(if types.crate_types.traits.get(s).is_none() {
358 let (name, ret) = convert_trait_impl_field(s);
359 writeln!(w, "\tpub {}: extern \"C\" fn (this_arg: *const c_void) -> {},", name, ret).unwrap();
362 // For in-crate supertraits, just store a C-mapped copy of the supertrait as a member.
363 writeln!(w, "\tpub {}: crate::{},", i, s).unwrap();
368 writeln!(w, "\tpub free: Option<extern \"C\" fn(this_arg: *mut c_void)>,").unwrap();
369 generated_fields.push("free".to_owned());
370 writeln!(w, "}}").unwrap();
371 // Implement supertraits for the C-mapped struct.
372 walk_supertraits!(t, types, (
373 ("Send", _) => writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap(),
374 ("Sync", _) => writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap(),
375 ("std::cmp::Eq", _) => {
376 writeln!(w, "impl std::cmp::Eq for {} {{}}", trait_name).unwrap();
377 writeln!(w, "impl std::cmp::PartialEq for {} {{", trait_name).unwrap();
378 writeln!(w, "\tfn eq(&self, o: &Self) -> bool {{ (self.eq)(self.this_arg, o) }}\n}}").unwrap();
380 ("std::hash::Hash", _) => {
381 writeln!(w, "impl std::hash::Hash for {} {{", trait_name).unwrap();
382 writeln!(w, "\tfn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {{ hasher.write_u64((self.hash)(self.this_arg)) }}\n}}").unwrap();
385 writeln!(w, "{}", types.opts.fn_attributes).unwrap();
386 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", trait_name, trait_name, trait_name).unwrap();
387 writeln!(w, "\t{} {{", trait_name).unwrap();
388 writeln!(w, "\t\tthis_arg: if let Some(f) = orig.clone {{ (f)(orig.this_arg) }} else {{ orig.this_arg }},").unwrap();
389 for field in generated_fields.iter() {
390 writeln!(w, "\t\t{}: orig.{}.clone(),", field, field).unwrap();
392 writeln!(w, "\t}}\n}}").unwrap();
393 writeln!(w, "impl Clone for {} {{", trait_name).unwrap();
394 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
395 writeln!(w, "\t\t{}_clone(self)", trait_name).unwrap();
396 writeln!(w, "\t}}\n}}").unwrap();
399 do_write_impl_trait(w, s, i, &trait_name);
403 // Finally, implement the original Rust trait for the newly created mapped trait.
404 writeln!(w, "\nuse {}::{}::{} as rust{};", types.opts.orig_crate, types.module_path, t.ident, trait_name).unwrap();
405 write!(w, "impl rust{}", t.ident).unwrap();
406 maybe_write_generics(w, &t.generics, types, false);
407 writeln!(w, " for {} {{", trait_name).unwrap();
408 for item in t.items.iter() {
410 syn::TraitItem::Method(m) => {
411 if let ExportStatus::TestOnly = export_status(&m.attrs) { continue; }
412 if m.default.is_some() { unimplemented!(); }
413 if m.sig.constness.is_some() || m.sig.asyncness.is_some() || m.sig.unsafety.is_some() ||
414 m.sig.abi.is_some() || m.sig.variadic.is_some() {
417 gen_types.push_ctx();
418 assert!(gen_types.learn_generics(&m.sig.generics, types));
419 write!(w, "\tfn {}", m.sig.ident).unwrap();
420 types.write_rust_generic_param(w, Some(&gen_types), m.sig.generics.params.iter());
421 write!(w, "(").unwrap();
422 for inp in m.sig.inputs.iter() {
424 syn::FnArg::Receiver(recv) => {
425 if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
426 write!(w, "&").unwrap();
427 if let Some(lft) = &recv.reference.as_ref().unwrap().1 {
428 write!(w, "'{} ", lft.ident).unwrap();
430 if recv.mutability.is_some() {
431 write!(w, "mut self").unwrap();
433 write!(w, "self").unwrap();
436 syn::FnArg::Typed(arg) => {
437 if !arg.attrs.is_empty() { unimplemented!(); }
439 syn::Pat::Ident(ident) => {
440 if !ident.attrs.is_empty() || ident.by_ref.is_some() ||
441 ident.mutability.is_some() || ident.subpat.is_some() {
444 write!(w, ", {}{}: ", if types.skip_arg(&*arg.ty, Some(&gen_types)) { "_" } else { "" }, ident.ident).unwrap();
446 _ => unimplemented!(),
448 types.write_rust_type(w, Some(&gen_types), &*arg.ty);
452 write!(w, ")").unwrap();
453 match &m.sig.output {
454 syn::ReturnType::Type(_, rtype) => {
455 write!(w, " -> ").unwrap();
456 types.write_rust_type(w, Some(&gen_types), &*rtype)
460 write!(w, " {{\n\t\t").unwrap();
461 match export_status(&m.attrs) {
462 ExportStatus::NoExport => {
467 if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
468 if let syn::Type::Reference(r) = &**rtype {
469 assert_eq!(m.sig.inputs.len(), 1); // Must only take self!
470 writeln!(w, "if let Some(f) = self.set_{} {{", m.sig.ident).unwrap();
471 writeln!(w, "\t\t\t(f)(self);").unwrap();
472 write!(w, "\t\t}}\n\t\t").unwrap();
473 types.write_from_c_conversion_to_ref_prefix(w, &*r.elem, Some(&gen_types));
474 write!(w, "self.{}", m.sig.ident).unwrap();
475 types.write_from_c_conversion_to_ref_suffix(w, &*r.elem, Some(&gen_types));
476 writeln!(w, "\n\t}}").unwrap();
481 write_method_var_decl_body(w, &m.sig, "\t", types, Some(&gen_types), true);
482 write!(w, "(self.{})(", m.sig.ident).unwrap();
483 write_method_call_params(w, &m.sig, "\t", types, Some(&gen_types), "", true);
485 writeln!(w, "\n\t}}").unwrap();
488 &syn::TraitItem::Type(ref t) => {
489 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
490 let mut bounds_iter = t.bounds.iter();
491 match bounds_iter.next().unwrap() {
492 syn::TypeParamBound::Trait(tr) => {
493 writeln!(w, "\ttype {} = crate::{};", t.ident, types.resolve_path(&tr.path, Some(&gen_types))).unwrap();
495 _ => unimplemented!(),
497 if bounds_iter.next().is_some() { unimplemented!(); }
499 _ => unimplemented!(),
502 writeln!(w, "}}\n").unwrap();
503 writeln!(w, "// We're essentially a pointer already, or at least a set of pointers, so allow us to be used").unwrap();
504 writeln!(w, "// directly as a Deref trait in higher-level structs:").unwrap();
505 writeln!(w, "impl std::ops::Deref for {} {{\n\ttype Target = Self;", trait_name).unwrap();
506 writeln!(w, "\tfn deref(&self) -> &Self {{\n\t\tself\n\t}}\n}}").unwrap();
508 writeln!(w, "/// Calls the free function if one is set").unwrap();
509 writeln!(w, "{}", types.opts.fn_attributes).unwrap();
510 writeln!(w, "pub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", trait_name, trait_name).unwrap();
511 writeln!(w, "impl Drop for {} {{", trait_name).unwrap();
512 writeln!(w, "\tfn drop(&mut self) {{").unwrap();
513 writeln!(w, "\t\tif let Some(f) = self.free {{").unwrap();
514 writeln!(w, "\t\t\tf(self.this_arg);").unwrap();
515 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
517 write_cpp_wrapper(cpp_headers, &trait_name, true);
518 types.trait_declared(&t.ident, t);
521 /// Write out a simple "opaque" type (eg structs) which contain a pointer to the native Rust type
522 /// and a flag to indicate whether Drop'ing the mapped struct drops the underlying Rust type.
524 /// Also writes out a _free function and a C++ wrapper which handles calling _free.
525 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) {
526 // If we directly read the original type by its original name, cbindgen hits
527 // https://github.com/eqrion/cbindgen/issues/286 Thus, instead, we import it as a temporary
528 // name and then reference it by that name, which works around the issue.
529 write!(w, "\nuse {}::{}::{} as native{}Import;\ntype native{} = native{}Import", types.opts.orig_crate, types.module_path, ident, ident, ident, ident).unwrap();
530 maybe_write_generics(w, &generics, &types, true);
531 writeln!(w, ";\n").unwrap();
532 writeln!(extra_headers, "struct native{}Opaque;\ntypedef struct native{}Opaque LDKnative{};", ident, ident, ident).unwrap();
533 writeln_docs(w, &attrs, "");
534 writeln!(w, "{}", types.opts.struct_attributes).unwrap();
535 writeln!(w, "#[must_use]\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, "{}", types.opts.fn_attributes).unwrap();
542 writeln!(w, "pub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", struct_name, struct_name).unwrap();
543 writeln!(w, "#[allow(unused)]").unwrap();
544 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
545 writeln!(w, "extern \"C\" fn {}_free_void(this_ptr: *mut c_void) {{", struct_name).unwrap();
546 writeln!(w, "\tunsafe {{ let _ = Box::from_raw(this_ptr as *mut native{}); }}\n}}", struct_name).unwrap();
547 writeln!(w, "#[allow(unused)]").unwrap();
548 writeln!(w, "/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy").unwrap();
549 writeln!(w, "impl {} {{", struct_name).unwrap();
550 writeln!(w, "\tpub(crate) fn take_inner(mut self) -> *mut native{} {{", struct_name).unwrap();
551 writeln!(w, "\t\tassert!(self.is_owned);").unwrap();
552 writeln!(w, "\t\tlet ret = self.inner;").unwrap();
553 writeln!(w, "\t\tself.inner = std::ptr::null_mut();").unwrap();
554 writeln!(w, "\t\tret").unwrap();
555 writeln!(w, "\t}}\n}}").unwrap();
557 'attr_loop: for attr in attrs.iter() {
558 let tokens_clone = attr.tokens.clone();
559 let mut token_iter = tokens_clone.into_iter();
560 if let Some(token) = token_iter.next() {
562 TokenTree::Group(g) => {
563 if format!("{}", single_ident_generic_path_to_ident(&attr.path).unwrap()) == "derive" {
564 for id in g.stream().into_iter() {
565 if let TokenTree::Ident(i) = id {
567 writeln!(w, "impl Clone for {} {{", struct_name).unwrap();
568 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
569 writeln!(w, "\t\tSelf {{").unwrap();
570 writeln!(w, "\t\t\tinner: Box::into_raw(Box::new(unsafe {{ &*self.inner }}.clone())),").unwrap();
571 writeln!(w, "\t\t\tis_owned: true,").unwrap();
572 writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
573 writeln!(w, "#[allow(unused)]").unwrap();
574 writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
575 writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", struct_name).unwrap();
576 writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", struct_name).unwrap();
577 writeln!(w, "}}").unwrap();
578 writeln!(w, "{}", types.opts.fn_attributes).unwrap();
579 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", struct_name, struct_name, struct_name).unwrap();
580 writeln!(w, "\t{} {{ inner: Box::into_raw(Box::new(unsafe {{ &*orig.inner }}.clone())), is_owned: true }}", struct_name).unwrap();
581 writeln!(w, "}}").unwrap();
593 write_cpp_wrapper(cpp_headers, &format!("{}", ident), true);
596 fn declare_struct<'a, 'b>(s: &'a syn::ItemStruct, types: &mut TypeResolver<'b, 'a>) -> bool {
597 let export = export_status(&s.attrs);
599 ExportStatus::Export => {},
600 ExportStatus::TestOnly => return false,
601 ExportStatus::NoExport => {
602 types.struct_ignored(&s.ident);
607 types.struct_imported(&s.ident, format!("{}", s.ident));
611 /// Writes out all the relevant mappings for a Rust struct, deferring to writeln_opaque to generate
612 /// the struct itself, and then writing getters and setters for public, understood-type fields and
613 /// a constructor if every field is public.
614 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) {
615 if !declare_struct(s, types) { return; }
617 let struct_name = &format!("{}", s.ident);
618 writeln_opaque(w, &s.ident, struct_name, &s.generics, &s.attrs, types, extra_headers, cpp_headers);
620 eprintln!("exporting fields for {}", struct_name);
621 if let syn::Fields::Named(fields) = &s.fields {
622 let mut gen_types = GenericTypes::new();
623 assert!(gen_types.learn_generics(&s.generics, types));
625 let mut all_fields_settable = true;
626 for field in fields.named.iter() {
627 if let syn::Visibility::Public(_) = field.vis {
628 let export = export_status(&field.attrs);
630 ExportStatus::Export => {},
631 ExportStatus::NoExport|ExportStatus::TestOnly => {
632 all_fields_settable = false;
637 if let Some(ident) = &field.ident {
638 let ref_type = syn::Type::Reference(syn::TypeReference {
639 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
640 elem: Box::new(field.ty.clone()) });
641 if types.understood_c_type(&ref_type, Some(&gen_types)) {
642 writeln_docs(w, &field.attrs, "");
643 writeln!(w, "{}", types.opts.fn_attributes).unwrap();
644 write!(w, "pub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> ", struct_name, ident, struct_name).unwrap();
645 types.write_c_type(w, &ref_type, Some(&gen_types), true);
646 write!(w, " {{\n\tlet mut inner_val = &mut unsafe {{ &mut *this_ptr.inner }}.{};\n\t", ident).unwrap();
647 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);
648 if local_var { write!(w, "\n\t").unwrap(); }
649 types.write_to_c_conversion_inline_prefix(w, &ref_type, Some(&gen_types), true);
651 write!(w, "inner_val").unwrap();
653 write!(w, "(*inner_val)").unwrap();
655 types.write_to_c_conversion_inline_suffix(w, &ref_type, Some(&gen_types), true);
656 writeln!(w, "\n}}").unwrap();
659 if types.understood_c_type(&field.ty, Some(&gen_types)) {
660 writeln_docs(w, &field.attrs, "");
661 writeln!(w, "{}", types.opts.fn_attributes).unwrap();
662 write!(w, "pub extern \"C\" fn {}_set_{}(this_ptr: &mut {}, mut val: ", struct_name, ident, struct_name).unwrap();
663 types.write_c_type(w, &field.ty, Some(&gen_types), false);
664 write!(w, ") {{\n\t").unwrap();
665 let local_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("val", Span::call_site()), &field.ty, Some(&gen_types));
666 if local_var { write!(w, "\n\t").unwrap(); }
667 write!(w, "unsafe {{ &mut *this_ptr.inner }}.{} = ", ident).unwrap();
668 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
669 write!(w, "val").unwrap();
670 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
671 writeln!(w, ";\n}}").unwrap();
672 } else { all_fields_settable = false; }
673 } else { all_fields_settable = false; }
674 } else { all_fields_settable = false; }
677 if all_fields_settable {
678 // Build a constructor!
679 writeln!(w, "{}", types.opts.fn_attributes).unwrap();
680 write!(w, "#[must_use]\npub extern \"C\" fn {}_new(", struct_name).unwrap();
681 for (idx, field) in fields.named.iter().enumerate() {
682 if idx != 0 { write!(w, ", ").unwrap(); }
683 write!(w, "mut {}_arg: ", field.ident.as_ref().unwrap()).unwrap();
684 types.write_c_type(w, &field.ty, Some(&gen_types), false);
686 write!(w, ") -> {} {{\n\t", struct_name).unwrap();
687 for field in fields.named.iter() {
688 let field_name = format!("{}_arg", field.ident.as_ref().unwrap());
689 if types.write_from_c_conversion_new_var(w, &syn::Ident::new(&field_name, Span::call_site()), &field.ty, Some(&gen_types)) {
690 write!(w, "\n\t").unwrap();
693 writeln!(w, "{} {{ inner: Box::into_raw(Box::new(native{} {{", struct_name, s.ident).unwrap();
694 for field in fields.named.iter() {
695 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
696 types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
697 write!(w, "{}_arg", field.ident.as_ref().unwrap()).unwrap();
698 types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
699 writeln!(w, ",").unwrap();
701 writeln!(w, "\t}})), is_owned: true }}\n}}").unwrap();
706 /// Prints a relevant conversion for impl *
708 /// For simple impl Struct {}s, this just outputs the wrapper functions as Struct_fn_name() { .. }.
710 /// For impl Trait for Struct{}s, this non-exported generates wrapper functions as
711 /// Trait_Struct_fn_name and a Struct_as_Trait(&struct) -> Trait function which returns a populated
712 /// Trait struct containing a pointer to the passed struct's inner field and the wrapper functions.
714 /// A few non-crate Traits are hard-coded including Default.
715 fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut TypeResolver) {
716 match export_status(&i.attrs) {
717 ExportStatus::Export => {},
718 ExportStatus::NoExport|ExportStatus::TestOnly => return,
721 if let syn::Type::Tuple(_) = &*i.self_ty {
722 if types.understood_c_type(&*i.self_ty, None) {
723 let mut gen_types = GenericTypes::new();
724 if !gen_types.learn_generics(&i.generics, types) {
725 eprintln!("Not implementing anything for impl tuple due to not understood generics");
729 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
730 if let Some(trait_path) = i.trait_.as_ref() {
731 if trait_path.0.is_some() { unimplemented!(); }
732 if types.understood_c_path(&trait_path.1) {
733 eprintln!("Not implementing anything for impl Trait for Tuple - we only support manual defines");
736 // Just do a manual implementation:
737 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
740 eprintln!("Not implementing anything for plain impl tuple block - we only support impl Trait for Tuples");
745 if let &syn::Type::Path(ref p) = &*i.self_ty {
746 if p.qself.is_some() { unimplemented!(); }
747 if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
748 if let Some(resolved_path) = types.maybe_resolve_non_ignored_ident(&ident) {
749 let mut gen_types = GenericTypes::new();
750 if !gen_types.learn_generics(&i.generics, types) {
751 eprintln!("Not implementing anything for impl {} due to not understood generics", ident);
755 if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
756 if let Some(trait_path) = i.trait_.as_ref() {
757 if trait_path.0.is_some() { unimplemented!(); }
758 if types.understood_c_path(&trait_path.1) {
759 let full_trait_path = types.resolve_path(&trait_path.1, None);
760 let trait_obj = *types.crate_types.traits.get(&full_trait_path).unwrap();
761 // We learn the associated types maping from the original trait object.
762 // That's great, except that they are unresolved idents, so if we learn
763 // mappings from a trai defined in a different file, we may mis-resolve or
764 // fail to resolve the mapped types.
765 gen_types.learn_associated_types(trait_obj, types);
766 let mut impl_associated_types = HashMap::new();
767 for item in i.items.iter() {
769 syn::ImplItem::Type(t) => {
770 if let syn::Type::Path(p) = &t.ty {
771 if let Some(id) = single_ident_generic_path_to_ident(&p.path) {
772 impl_associated_types.insert(&t.ident, id);
780 let export = export_status(&trait_obj.attrs);
782 ExportStatus::Export => {},
783 ExportStatus::NoExport|ExportStatus::TestOnly => return,
786 // For cases where we have a concrete native object which implements a
787 // trait and need to return the C-mapped version of the trait, provide a
788 // From<> implementation which does all the work to ensure free is handled
789 // properly. This way we can call this method from deep in the
790 // type-conversion logic without actually knowing the concrete native type.
791 writeln!(w, "impl From<native{}> for crate::{} {{", ident, full_trait_path).unwrap();
792 writeln!(w, "\tfn from(obj: native{}) -> Self {{", ident).unwrap();
793 writeln!(w, "\t\tlet mut rust_obj = {} {{ inner: Box::into_raw(Box::new(obj)), is_owned: true }};", ident).unwrap();
794 writeln!(w, "\t\tlet mut ret = {}_as_{}(&rust_obj);", ident, trait_obj.ident).unwrap();
795 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();
796 writeln!(w, "\t\trust_obj.inner = std::ptr::null_mut();").unwrap();
797 writeln!(w, "\t\tret.free = Some({}_free_void);", ident).unwrap();
798 writeln!(w, "\t\tret\n\t}}\n}}").unwrap();
800 writeln!(w, "{}", types.opts.fn_attributes).unwrap();
801 write!(w, "pub extern \"C\" fn {}_as_{}(this_arg: &{}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
802 writeln!(w, "\tcrate::{} {{", full_trait_path).unwrap();
803 writeln!(w, "\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
804 writeln!(w, "\t\tfree: None,").unwrap();
806 macro_rules! write_meth {
807 ($m: expr, $trait: expr, $indent: expr) => {
808 let trait_method = $trait.items.iter().filter_map(|item| {
809 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
810 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
811 match export_status(&trait_method.attrs) {
812 ExportStatus::Export => {},
813 ExportStatus::NoExport => {
814 write!(w, "{}\t\t//XXX: Need to export {}\n", $indent, $m.sig.ident).unwrap();
817 ExportStatus::TestOnly => continue,
820 let mut printed = false;
821 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
822 if let syn::Type::Reference(r) = &**rtype {
823 write!(w, "\n\t\t{}{}: ", $indent, $m.sig.ident).unwrap();
824 types.write_empty_rust_val(Some(&gen_types), w, &*r.elem);
825 writeln!(w, ",\n{}\t\tset_{}: Some({}_{}_set_{}),", $indent, $m.sig.ident, ident, trait_obj.ident, $m.sig.ident).unwrap();
830 write!(w, "{}\t\t{}: {}_{}_{},\n", $indent, $m.sig.ident, ident, trait_obj.ident, $m.sig.ident).unwrap();
834 for item in trait_obj.items.iter() {
836 syn::TraitItem::Method(m) => {
837 write_meth!(m, trait_obj, "");
842 walk_supertraits!(trait_obj, types, (
844 writeln!(w, "\t\tclone: Some({}_clone_void),", ident).unwrap();
846 ("Sync", _) => {}, ("Send", _) => {},
847 ("std::marker::Sync", _) => {}, ("std::marker::Send", _) => {},
849 if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
850 writeln!(w, "\t\t{}: crate::{} {{", t, s).unwrap();
851 writeln!(w, "\t\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
852 writeln!(w, "\t\t\tfree: None,").unwrap();
853 for item in supertrait_obj.items.iter() {
855 syn::TraitItem::Method(m) => {
856 write_meth!(m, supertrait_obj, "\t");
861 write!(w, "\t\t}},\n").unwrap();
863 write_trait_impl_field_assign(w, s, ident);
867 write!(w, "\t}}\n}}\nuse {}::{} as {}TraitImport;\n", types.opts.orig_crate, full_trait_path, trait_obj.ident).unwrap();
869 macro_rules! impl_meth {
870 ($m: expr, $trait: expr, $indent: expr) => {
871 let trait_method = $trait.items.iter().filter_map(|item| {
872 if let syn::TraitItem::Method(t_m) = item { Some(t_m) } else { None }
873 }).find(|trait_meth| trait_meth.sig.ident == $m.sig.ident).unwrap();
874 match export_status(&trait_method.attrs) {
875 ExportStatus::Export => {},
876 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
879 if let syn::ReturnType::Type(_, _) = &$m.sig.output {
880 writeln!(w, "#[must_use]").unwrap();
882 write!(w, "extern \"C\" fn {}_{}_{}(", ident, trait_obj.ident, $m.sig.ident).unwrap();
883 gen_types.push_ctx();
884 assert!(gen_types.learn_generics(&$m.sig.generics, types));
885 write_method_params(w, &$m.sig, "c_void", types, Some(&gen_types), true, true);
886 write!(w, " {{\n\t").unwrap();
887 write_method_var_decl_body(w, &$m.sig, "", types, Some(&gen_types), false);
888 let mut takes_self = false;
889 for inp in $m.sig.inputs.iter() {
890 if let syn::FnArg::Receiver(_) = inp {
895 write!(w, "unsafe {{ &mut *(this_arg as *mut native{}) }}.{}(", ident, $m.sig.ident).unwrap();
897 write!(w, "{}::{}::{}(", types.opts.orig_crate, resolved_path, $m.sig.ident).unwrap();
900 let mut real_type = "".to_string();
901 match &$m.sig.output {
902 syn::ReturnType::Type(_, rtype) => {
903 if let Some(mut remaining_path) = first_seg_self(&*rtype) {
904 if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
905 real_type = format!("{}", impl_associated_types.get(associated_seg).unwrap());
911 write_method_call_params(w, &$m.sig, "", types, Some(&gen_types), &real_type, false);
913 write!(w, "\n}}\n").unwrap();
914 if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
915 if let syn::Type::Reference(r) = &**rtype {
916 assert_eq!($m.sig.inputs.len(), 1); // Must only take self
917 writeln!(w, "extern \"C\" fn {}_{}_set_{}(trait_self_arg: &{}) {{", ident, trait_obj.ident, $m.sig.ident, trait_obj.ident).unwrap();
918 writeln!(w, "\t// This is a bit race-y in the general case, but for our specific use-cases today, we're safe").unwrap();
919 writeln!(w, "\t// Specifically, we must ensure that the first time we're called it can never be in parallel").unwrap();
920 write!(w, "\tif ").unwrap();
921 types.write_empty_rust_val_check(Some(&gen_types), w, &*r.elem, &format!("trait_self_arg.{}", $m.sig.ident));
922 writeln!(w, " {{").unwrap();
923 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();
924 writeln!(w, "\t}}").unwrap();
925 writeln!(w, "}}").unwrap();
931 for item in i.items.iter() {
933 syn::ImplItem::Method(m) => {
934 impl_meth!(m, trait_obj, "");
936 syn::ImplItem::Type(_) => {},
937 _ => unimplemented!(),
940 walk_supertraits!(trait_obj, types, (
942 if let Some(supertrait_obj) = types.crate_types.traits.get(s).cloned() {
943 writeln!(w, "use {}::{} as native{}Trait;", types.opts.orig_crate, s, t).unwrap();
944 for item in supertrait_obj.items.iter() {
946 syn::TraitItem::Method(m) => {
947 impl_meth!(m, supertrait_obj, "\t");
955 write!(w, "\n").unwrap();
956 } else if let Some(trait_ident) = trait_path.1.get_ident() {
957 //XXX: implement for other things like ToString
958 match &format!("{}", trait_ident) as &str {
961 writeln!(w, "{}", types.opts.fn_attributes).unwrap();
962 write!(w, "#[must_use]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
963 write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
964 write!(w, "}}\n").unwrap();
967 // If we have no generics, try a manual implementation:
968 _ => maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types),
971 // If we have no generics, try a manual implementation:
972 maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
975 let declared_type = (*types.get_declared_type(&ident).unwrap()).clone();
976 for item in i.items.iter() {
978 syn::ImplItem::Method(m) => {
979 if let syn::Visibility::Public(_) = m.vis {
980 match export_status(&m.attrs) {
981 ExportStatus::Export => {},
982 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
984 if m.defaultness.is_some() { unimplemented!(); }
985 writeln_docs(w, &m.attrs, "");
986 if let syn::ReturnType::Type(_, _) = &m.sig.output {
987 writeln!(w, "#[must_use]").unwrap();
989 writeln!(w, "{}", types.opts.fn_attributes).unwrap();
990 write!(w, "pub extern \"C\" fn {}_{}(", ident, m.sig.ident).unwrap();
991 let ret_type = match &declared_type {
992 DeclType::MirroredEnum => format!("{}", ident),
993 DeclType::StructImported => format!("{}", ident),
994 _ => unimplemented!(),
996 gen_types.push_ctx();
997 assert!(gen_types.learn_generics(&m.sig.generics, types));
998 write_method_params(w, &m.sig, &ret_type, types, Some(&gen_types), false, true);
999 write!(w, " {{\n\t").unwrap();
1000 write_method_var_decl_body(w, &m.sig, "", types, Some(&gen_types), false);
1001 let mut takes_self = false;
1002 let mut takes_mut_self = false;
1003 for inp in m.sig.inputs.iter() {
1004 if let syn::FnArg::Receiver(r) = inp {
1006 if r.mutability.is_some() { takes_mut_self = true; }
1010 write!(w, "unsafe {{ &mut (*(this_arg.inner as *mut native{})) }}.{}(", ident, m.sig.ident).unwrap();
1011 } else if takes_self {
1012 write!(w, "unsafe {{ &*this_arg.inner }}.{}(", m.sig.ident).unwrap();
1014 write!(w, "{}::{}::{}(", types.opts.orig_crate, resolved_path, m.sig.ident).unwrap();
1016 write_method_call_params(w, &m.sig, "", types, Some(&gen_types), &ret_type, false);
1017 gen_types.pop_ctx();
1018 writeln!(w, "\n}}\n").unwrap();
1026 eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub or its marked not exported)", ident);
1032 /// Returns true if the enum will be mapped as an opaue (ie struct with a pointer to the underlying
1033 /// type), otherwise it is mapped into a transparent, C-compatible version of itself.
1034 fn is_enum_opaque(e: &syn::ItemEnum) -> bool {
1035 for var in e.variants.iter() {
1036 if let syn::Fields::Unit = var.fields {
1037 } else if let syn::Fields::Named(fields) = &var.fields {
1038 for field in fields.named.iter() {
1039 match export_status(&field.attrs) {
1040 ExportStatus::Export|ExportStatus::TestOnly => {},
1041 ExportStatus::NoExport => return true,
1051 fn declare_enum<'a, 'b>(e: &'a syn::ItemEnum, types: &mut TypeResolver<'b, 'a>) {
1052 match export_status(&e.attrs) {
1053 ExportStatus::Export => {},
1054 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1057 if is_enum_opaque(e) {
1058 types.enum_ignored(&e.ident);
1060 types.mirrored_enum_declared(&e.ident);
1064 /// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
1065 /// is unitary), we generate an equivalent enum with all types replaced with their C mapped
1066 /// versions followed by conversion functions which map between the Rust version and the C mapped
1068 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) {
1069 match export_status(&e.attrs) {
1070 ExportStatus::Export => {},
1071 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1074 if is_enum_opaque(e) {
1075 eprintln!("Skipping enum {} as it contains non-unit fields", e.ident);
1076 writeln_opaque(w, &e.ident, &format!("{}", e.ident), &e.generics, &e.attrs, types, extra_headers, cpp_headers);
1079 writeln_docs(w, &e.attrs, "");
1081 if e.generics.lt_token.is_some() {
1085 let mut needs_free = false;
1087 writeln!(w, "{}", types.opts.struct_attributes).unwrap();
1088 writeln!(w, "#[must_use]\n#[derive(Clone)]\npub enum {} {{", e.ident).unwrap();
1089 for var in e.variants.iter() {
1090 assert_eq!(export_status(&var.attrs), ExportStatus::Export); // We can't partially-export a mirrored enum
1091 writeln_docs(w, &var.attrs, "\t");
1092 write!(w, "\t{}", var.ident).unwrap();
1093 if let syn::Fields::Named(fields) = &var.fields {
1095 writeln!(w, " {{").unwrap();
1096 for field in fields.named.iter() {
1097 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1098 write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1099 types.write_c_type(w, &field.ty, None, false);
1100 writeln!(w, ",").unwrap();
1102 write!(w, "\t}}").unwrap();
1104 if var.discriminant.is_some() { unimplemented!(); }
1105 writeln!(w, ",").unwrap();
1107 writeln!(w, "}}\nuse {}::{}::{} as native{};\nimpl {} {{", types.opts.orig_crate, types.module_path, e.ident, e.ident, e.ident).unwrap();
1109 macro_rules! write_conv {
1110 ($fn_sig: expr, $to_c: expr, $ref: expr) => {
1111 writeln!(w, "\t#[allow(unused)]\n\tpub(crate) fn {} {{\n\t\tmatch {} {{", $fn_sig, if $to_c { "native" } else { "self" }).unwrap();
1112 for var in e.variants.iter() {
1113 write!(w, "\t\t\t{}{}::{} ", if $to_c { "native" } else { "" }, e.ident, var.ident).unwrap();
1114 if let syn::Fields::Named(fields) = &var.fields {
1115 write!(w, "{{").unwrap();
1116 for field in fields.named.iter() {
1117 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1118 write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, field.ident.as_ref().unwrap()).unwrap();
1120 write!(w, "}} ").unwrap();
1122 write!(w, "=>").unwrap();
1123 if let syn::Fields::Named(fields) = &var.fields {
1124 write!(w, " {{\n\t\t\t\t").unwrap();
1125 for field in fields.named.iter() {
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.as_ref().unwrap(), &field.ty, None, false)
1132 types.write_from_c_conversion_new_var(&mut out, field.ident.as_ref().unwrap(), &field.ty, None)
1134 if $ref || new_var {
1136 write!(w, "let mut {}_nonref = (*{}).clone();\n\t\t\t\t", field.ident.as_ref().unwrap(), field.ident.as_ref().unwrap()).unwrap();
1138 let nonref_ident = syn::Ident::new(&format!("{}_nonref", field.ident.as_ref().unwrap()), 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();
1151 } else { write!(w, " ").unwrap(); }
1152 write!(w, "{}{}::{}", if $to_c { "" } else { "native" }, e.ident, var.ident).unwrap();
1153 if let syn::Fields::Named(fields) = &var.fields {
1154 write!(w, " {{").unwrap();
1155 for field in fields.named.iter() {
1156 if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
1157 write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
1159 types.write_to_c_conversion_inline_prefix(w, &field.ty, None, false);
1161 types.write_from_c_conversion_prefix(w, &field.ty, None);
1164 field.ident.as_ref().unwrap(),
1165 if $ref { "_nonref" } else { "" }).unwrap();
1167 types.write_to_c_conversion_inline_suffix(w, &field.ty, None, false);
1169 types.write_from_c_conversion_suffix(w, &field.ty, None);
1171 write!(w, ",").unwrap();
1173 writeln!(w, "\n\t\t\t\t}}").unwrap();
1174 write!(w, "\t\t\t}}").unwrap();
1176 writeln!(w, ",").unwrap();
1178 writeln!(w, "\t\t}}\n\t}}").unwrap();
1182 write_conv!(format!("to_native(&self) -> native{}", e.ident), false, true);
1183 write_conv!(format!("into_native(self) -> native{}", e.ident), false, false);
1184 write_conv!(format!("from_native(native: &native{}) -> Self", e.ident), true, true);
1185 write_conv!(format!("native_into(native: native{}) -> Self", e.ident), true, false);
1186 writeln!(w, "}}").unwrap();
1189 writeln!(w, "{}", types.opts.fn_attributes).unwrap();
1190 writeln!(w, "pub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", e.ident, e.ident).unwrap();
1192 writeln!(w, "{}", types.opts.fn_attributes).unwrap();
1193 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
1194 writeln!(w, "\torig.clone()").unwrap();
1195 writeln!(w, "}}").unwrap();
1196 write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free);
1199 fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &mut TypeResolver<'b, 'a>) {
1200 match export_status(&f.attrs) {
1201 ExportStatus::Export => {},
1202 ExportStatus::NoExport|ExportStatus::TestOnly => return,
1204 writeln_docs(w, &f.attrs, "");
1206 let mut gen_types = GenericTypes::new();
1207 if !gen_types.learn_generics(&f.sig.generics, types) { return; }
1209 writeln!(w, "{}", types.opts.fn_attributes).unwrap();
1210 write!(w, "pub extern \"C\" fn {}(", f.sig.ident).unwrap();
1211 write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
1212 write!(w, " {{\n\t").unwrap();
1213 write_method_var_decl_body(w, &f.sig, "", types, Some(&gen_types), false);
1214 write!(w, "{}::{}::{}(", types.opts.orig_crate, types.module_path, f.sig.ident).unwrap();
1215 write_method_call_params(w, &f.sig, "", types, Some(&gen_types), "", false);
1216 writeln!(w, "\n}}\n").unwrap();
1219 // ********************************
1220 // *** File/Crate Walking Logic ***
1221 // ********************************
1223 /// Simple utility to walk the modules in a crate - iterating over the modules (with file paths) in
1225 struct FileIter<'a, I: Iterator<Item = &'a syn::Item>> {
1231 impl<'a, I: Iterator<Item = &'a syn::Item>> Iterator for FileIter<'a, I> {
1232 type Item = (String, String, &'a syn::ItemMod);
1233 fn next(&mut self) -> std::option::Option<<Self as std::iter::Iterator>::Item> {
1235 match self.item_iter.next() {
1236 Some(syn::Item::Mod(m)) => {
1237 if let syn::Visibility::Public(_) = m.vis {
1238 match export_status(&m.attrs) {
1239 ExportStatus::Export => {},
1240 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1243 let f_path = format!("{}/{}.rs", (self.path.as_ref() as &Path).parent().unwrap().display(), m.ident);
1244 let new_mod = if self.module.is_empty() { format!("{}", m.ident) } else { format!("{}::{}", self.module, m.ident) };
1245 if let Ok(_) = File::open(&format!("{}/{}", self.in_dir, f_path)) {
1246 return Some((f_path, new_mod, m));
1249 format!("{}/{}/mod.rs", (self.path.as_ref() as &Path).parent().unwrap().display(), m.ident),
1255 None => return None,
1260 fn file_iter<'a>(file: &'a syn::File, in_dir: &'a str, path: &'a str, module: &'a str) ->
1261 impl Iterator<Item = (String, String, &'a syn::ItemMod)> + 'a {
1262 FileIter { in_dir, path, module, item_iter: file.items.iter() }
1265 /// A struct containing the syn::File AST for each file in the crate.
1266 struct FullLibraryAST {
1267 files: HashMap<String, syn::File>,
1270 /// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
1271 /// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
1272 /// at `module` from C.
1273 fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>, opts: &GlobalOpts, in_dir: &str, out_dir: &str, path: &str, module: &str, header_file: &mut File, cpp_header_file: &mut File) {
1274 let syntax = if let Some(ast) = libast.files.get(module) { ast } else { return };
1276 assert!(syntax.shebang.is_none()); // Not sure what this is, hope we dont have one
1278 let new_file_path = format!("{}/{}", out_dir, path);
1279 let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
1280 let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1281 .open(new_file_path).expect("Unable to open new src file");
1283 assert_eq!(export_status(&syntax.attrs), ExportStatus::Export);
1284 writeln_docs(&mut out, &syntax.attrs, "");
1286 if path.ends_with("/lib.rs") {
1287 // Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
1288 // and bitcoin hand-written modules.
1289 writeln!(out, "#![allow(unknown_lints)]").unwrap();
1290 writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
1291 writeln!(out, "#![allow(non_snake_case)]").unwrap();
1292 writeln!(out, "#![allow(unused_imports)]").unwrap();
1293 writeln!(out, "#![allow(unused_variables)]").unwrap();
1294 writeln!(out, "#![allow(unused_mut)]").unwrap();
1295 writeln!(out, "#![allow(unused_parens)]").unwrap();
1296 writeln!(out, "#![allow(unused_unsafe)]").unwrap();
1297 writeln!(out, "#![allow(unused_braces)]").unwrap();
1298 writeln!(out, "mod c_types;").unwrap();
1299 writeln!(out, "mod bitcoin;").unwrap();
1301 writeln!(out, "\nuse std::ffi::c_void;\nuse bitcoin::hashes::Hash;\nuse crate::c_types::*;\n").unwrap();
1304 for (path, new_mod, m) in file_iter(&syntax, in_dir, path, &module) {
1305 writeln_docs(&mut out, &m.attrs, "");
1306 writeln!(out, "pub mod {};", m.ident).unwrap();
1307 convert_file(libast, crate_types, opts, in_dir, out_dir, &path,
1308 &new_mod, header_file, cpp_header_file);
1311 eprintln!("Converting {} entries...", path);
1313 let mut type_resolver = TypeResolver::new(opts, module, crate_types);
1315 // First pass over the items and fill in imports and file-declared objects in the type resolver
1316 for item in syntax.items.iter() {
1318 syn::Item::Use(u) => type_resolver.process_use(&mut out, &u),
1319 syn::Item::Struct(s) => {
1320 if let syn::Visibility::Public(_) = s.vis {
1321 declare_struct(&s, &mut type_resolver);
1324 syn::Item::Enum(e) => {
1325 if let syn::Visibility::Public(_) = e.vis {
1326 declare_enum(&e, &mut type_resolver);
1333 for item in syntax.items.iter() {
1335 syn::Item::Use(_) => {}, // Handled above
1336 syn::Item::Static(_) => {},
1337 syn::Item::Enum(e) => {
1338 if let syn::Visibility::Public(_) = e.vis {
1339 writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
1342 syn::Item::Impl(i) => {
1343 writeln_impl(&mut out, &i, &mut type_resolver);
1345 syn::Item::Struct(s) => {
1346 if let syn::Visibility::Public(_) = s.vis {
1347 writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
1350 syn::Item::Trait(t) => {
1351 if let syn::Visibility::Public(_) = t.vis {
1352 writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
1355 syn::Item::Mod(_) => {}, // We don't have to do anything - the top loop handles these.
1356 syn::Item::Const(c) => {
1357 // Re-export any primitive-type constants.
1358 if let syn::Visibility::Public(_) = c.vis {
1359 if let syn::Type::Path(p) = &*c.ty {
1360 let resolved_path = type_resolver.resolve_path(&p.path, None);
1361 if type_resolver.is_primitive(&resolved_path) {
1362 writeln!(out, "\n#[no_mangle]").unwrap();
1363 writeln!(out, "pub static {}: {} = {}::{}::{};", c.ident, resolved_path, opts.orig_crate, module, c.ident).unwrap();
1368 syn::Item::Type(t) => {
1369 if let syn::Visibility::Public(_) = t.vis {
1370 match export_status(&t.attrs) {
1371 ExportStatus::Export => {},
1372 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1375 let mut process_alias = true;
1376 for tok in t.generics.params.iter() {
1377 if let syn::GenericParam::Lifetime(_) = tok {}
1378 else { process_alias = false; }
1382 syn::Type::Path(_) =>
1383 writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &t.generics, &t.attrs, &type_resolver, header_file, cpp_header_file),
1389 syn::Item::Fn(f) => {
1390 if let syn::Visibility::Public(_) = f.vis {
1391 writeln_fn(&mut out, &f, &mut type_resolver);
1394 syn::Item::Macro(m) => {
1395 if m.ident.is_none() { // If its not a macro definition
1396 convert_macro(&mut out, &m.mac.path, &m.mac.tokens, &type_resolver);
1399 syn::Item::Verbatim(_) => {},
1400 syn::Item::ExternCrate(_) => {},
1401 _ => unimplemented!(),
1405 out.flush().unwrap();
1408 /// Load the AST for each file in the crate, filling the FullLibraryAST object
1409 fn load_ast(in_dir: &str, path: &str, module: String, ast_storage: &mut FullLibraryAST) {
1410 eprintln!("Loading {}{}...", in_dir, path);
1412 let mut file = File::open(format!("{}/{}", in_dir, path)).expect("Unable to open file");
1413 let mut src = String::new();
1414 file.read_to_string(&mut src).expect("Unable to read file");
1415 let syntax = syn::parse_file(&src).expect("Unable to parse file");
1417 assert_eq!(export_status(&syntax.attrs), ExportStatus::Export);
1419 for (path, new_mod, _) in file_iter(&syntax, in_dir, path, &module) {
1420 load_ast(in_dir, &path, new_mod, ast_storage);
1422 ast_storage.files.insert(module, syntax);
1425 /// Insert ident -> absolute Path resolutions into imports from the given UseTree and path-prefix.
1426 fn process_use_intern<'a>(u: &'a syn::UseTree, mut path: syn::punctuated::Punctuated<syn::PathSegment, syn::token::Colon2>, imports: &mut HashMap<&'a syn::Ident, syn::Path>) {
1428 syn::UseTree::Path(p) => {
1429 path.push(syn::PathSegment { ident: p.ident.clone(), arguments: syn::PathArguments::None });
1430 process_use_intern(&p.tree, path, imports);
1432 syn::UseTree::Name(n) => {
1433 path.push(syn::PathSegment { ident: n.ident.clone(), arguments: syn::PathArguments::None });
1434 imports.insert(&n.ident, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path });
1436 syn::UseTree::Group(g) => {
1437 for i in g.items.iter() {
1438 process_use_intern(i, path.clone(), imports);
1445 /// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern)
1446 fn resolve_imported_refs(imports: &HashMap<&syn::Ident, syn::Path>, mut ty: syn::Type) -> syn::Type {
1448 syn::Type::Path(p) => {
1449 if let Some(ident) = p.path.get_ident() {
1450 if let Some(newpath) = imports.get(ident) {
1451 p.path = newpath.clone();
1453 } else { unimplemented!(); }
1455 syn::Type::Reference(r) => {
1456 r.elem = Box::new(resolve_imported_refs(imports, (*r.elem).clone()));
1458 syn::Type::Slice(s) => {
1459 s.elem = Box::new(resolve_imported_refs(imports, (*s.elem).clone()));
1461 syn::Type::Tuple(t) => {
1462 for e in t.elems.iter_mut() {
1463 *e = resolve_imported_refs(imports, e.clone());
1466 _ => unimplemented!(),
1471 /// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
1472 fn walk_ast<'a>(in_dir: &str, path: &str, module: String, ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
1473 let syntax = if let Some(ast) = ast_storage.files.get(&module) { ast } else { return };
1474 assert_eq!(export_status(&syntax.attrs), ExportStatus::Export);
1476 for (path, new_mod, _) in file_iter(&syntax, in_dir, path, &module) {
1477 walk_ast(in_dir, &path, new_mod, ast_storage, crate_types);
1480 let mut import_maps = HashMap::new();
1482 for item in syntax.items.iter() {
1484 syn::Item::Use(u) => {
1485 process_use_intern(&u.tree, syn::punctuated::Punctuated::new(), &mut import_maps);
1487 syn::Item::Struct(s) => {
1488 if let syn::Visibility::Public(_) = s.vis {
1489 match export_status(&s.attrs) {
1490 ExportStatus::Export => {},
1491 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1493 let struct_path = format!("{}::{}", module, s.ident);
1494 crate_types.opaques.insert(struct_path, &s.ident);
1497 syn::Item::Trait(t) => {
1498 if let syn::Visibility::Public(_) = t.vis {
1499 match export_status(&t.attrs) {
1500 ExportStatus::Export => {},
1501 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1503 let trait_path = format!("{}::{}", module, t.ident);
1504 crate_types.traits.insert(trait_path, &t);
1507 syn::Item::Type(t) => {
1508 if let syn::Visibility::Public(_) = t.vis {
1509 match export_status(&t.attrs) {
1510 ExportStatus::Export => {},
1511 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1513 let type_path = format!("{}::{}", module, t.ident);
1514 let mut process_alias = true;
1515 for tok in t.generics.params.iter() {
1516 if let syn::GenericParam::Lifetime(_) = tok {}
1517 else { process_alias = false; }
1521 syn::Type::Path(_) => {
1522 // If its a path with no generics, assume we don't map the aliased type and map it opaque
1523 crate_types.opaques.insert(type_path, &t.ident);
1526 crate_types.type_aliases.insert(type_path, resolve_imported_refs(&import_maps, (*t.ty).clone()));
1532 syn::Item::Enum(e) if is_enum_opaque(e) => {
1533 if let syn::Visibility::Public(_) = e.vis {
1534 match export_status(&e.attrs) {
1535 ExportStatus::Export => {},
1536 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1538 let enum_path = format!("{}::{}", module, e.ident);
1539 crate_types.opaques.insert(enum_path, &e.ident);
1542 syn::Item::Enum(e) => {
1543 if let syn::Visibility::Public(_) = e.vis {
1544 match export_status(&e.attrs) {
1545 ExportStatus::Export => {},
1546 ExportStatus::NoExport|ExportStatus::TestOnly => continue,
1548 let enum_path = format!("{}::{}", module, e.ident);
1549 crate_types.mirrored_enums.insert(enum_path, &e);
1557 pub struct GlobalOpts<'a> {
1558 orig_crate: &'a str,
1559 fn_attributes: &'a str,
1560 struct_attributes: &'a str,
1564 let args: Vec<String> = env::args().collect();
1565 if args.len() != 9 {
1566 eprintln!("Usage: source/dir target/dir source_crate_name derived_templates.rs extra/includes.h extra/cpp/includes.hpp fn_attribute struct_attribute");
1570 let mut derived_templates = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1571 .open(&args[4]).expect("Unable to open new header file");
1572 let mut header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1573 .open(&args[5]).expect("Unable to open new header file");
1574 let mut cpp_header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
1575 .open(&args[6]).expect("Unable to open new header file");
1577 writeln!(header_file, "#if defined(__GNUC__)").unwrap();
1578 writeln!(header_file, "#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
1579 writeln!(header_file, "#define MUST_USE_RES __attribute__((warn_unused_result))").unwrap();
1580 writeln!(header_file, "#else").unwrap();
1581 writeln!(header_file, "#define MUST_USE_STRUCT").unwrap();
1582 writeln!(header_file, "#define MUST_USE_RES").unwrap();
1583 writeln!(header_file, "#endif").unwrap();
1584 writeln!(header_file, "#if defined(__clang__)").unwrap();
1585 writeln!(header_file, "#define NONNULL_PTR _Nonnull").unwrap();
1586 writeln!(header_file, "#else").unwrap();
1587 writeln!(header_file, "#define NONNULL_PTR").unwrap();
1588 writeln!(header_file, "#endif").unwrap();
1589 writeln!(cpp_header_file, "#include <string.h>\nnamespace LDK {{").unwrap();
1591 let opts = GlobalOpts {
1592 orig_crate: &args[3],
1593 fn_attributes: &args[7],
1594 struct_attributes: &args[8],
1597 // First parse the full crate's ASTs, caching them so that we can hold references to the AST
1598 // objects in other datastructures:
1599 let mut libast = FullLibraryAST { files: HashMap::new() };
1600 load_ast(&args[1], "/lib.rs", "".to_string(), &mut libast);
1602 // ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
1603 // when parsing other file ASTs...
1604 let mut libtypes = CrateTypes { traits: HashMap::new(), opaques: HashMap::new(), mirrored_enums: HashMap::new(),
1605 type_aliases: HashMap::new(), templates_defined: HashMap::default(), template_file: &mut derived_templates };
1606 walk_ast(&args[1], "/lib.rs", "".to_string(), &libast, &mut libtypes);
1608 // ... finally, do the actual file conversion/mapping, writing out types as we go.
1609 convert_file(&libast, &mut libtypes, &opts, &args[1], &args[2], "/lib.rs", "", &mut header_file, &mut cpp_header_file);
1611 // For container templates which we created while walking the crate, make sure we add C++
1612 // mapped types so that C++ users can utilize the auto-destructors available.
1613 for (ty, has_destructor) in libtypes.templates_defined.iter() {
1614 write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor);
1616 writeln!(cpp_header_file, "}}").unwrap();
1618 header_file.flush().unwrap();
1619 cpp_header_file.flush().unwrap();
1620 derived_templates.flush().unwrap();