1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE>
5 // or the MIT license <LICENSE-MIT>, at your option.
6 // You may not use this file except in accordance with one or both of these
9 use std::cell::RefCell;
10 use std::collections::{HashMap, HashSet};
17 use proc_macro2::{TokenTree, Span};
18 use quote::format_ident;
21 // The following utils are used purely to build our known types maps - they break down all the
22 // types we need to resolve to include the given object, and no more.
24 pub fn first_seg_self<'a>(t: &'a syn::Type) -> Option<impl Iterator<Item=&syn::PathSegment> + 'a> {
26 syn::Type::Path(p) => {
27 if p.qself.is_some() || p.path.leading_colon.is_some() {
30 let mut segs = p.path.segments.iter();
31 let ty = segs.next().unwrap();
32 if !ty.arguments.is_empty() { return None; }
33 if format!("{}", ty.ident) == "Self" {
41 pub fn get_single_remaining_path_seg<'a, I: Iterator<Item=&'a syn::PathSegment>>(segs: &mut I) -> Option<&'a syn::Ident> {
42 if let Some(ty) = segs.next() {
43 if !ty.arguments.is_empty() { unimplemented!(); }
44 if segs.next().is_some() { return None; }
49 pub fn single_ident_generic_path_to_ident(p: &syn::Path) -> Option<&syn::Ident> {
50 if p.segments.len() == 1 {
51 Some(&p.segments.iter().next().unwrap().ident)
55 pub fn path_matches_nongeneric(p: &syn::Path, exp: &[&str]) -> bool {
56 if p.segments.len() != exp.len() { return false; }
57 for (seg, e) in p.segments.iter().zip(exp.iter()) {
58 if seg.arguments != syn::PathArguments::None { return false; }
59 if &format!("{}", seg.ident) != *e { return false; }
64 #[derive(Debug, PartialEq)]
65 pub enum ExportStatus {
70 /// Gets the ExportStatus of an object (struct, fn, etc) given its attributes.
71 pub fn export_status(attrs: &[syn::Attribute]) -> ExportStatus {
72 for attr in attrs.iter() {
73 let tokens_clone = attr.tokens.clone();
74 let mut token_iter = tokens_clone.into_iter();
75 if let Some(token) = token_iter.next() {
77 TokenTree::Punct(c) if c.as_char() == '=' => {
78 // Really not sure where syn gets '=' from here -
79 // it somehow represents '///' or '//!'
81 TokenTree::Group(g) => {
82 if format!("{}", single_ident_generic_path_to_ident(&attr.path).unwrap()) == "cfg" {
83 let mut iter = g.stream().into_iter();
84 if let TokenTree::Ident(i) = iter.next().unwrap() {
86 // #[cfg(any(test, feature = ""))]
87 if let TokenTree::Group(g) = iter.next().unwrap() {
88 let mut all_test = true;
89 for token in g.stream().into_iter() {
90 if let TokenTree::Ident(i) = token {
91 match format!("{}", i).as_str() {
94 _ => all_test = false,
96 } else if let TokenTree::Literal(lit) = token {
97 if format!("{}", lit) != "fuzztarget" {
102 if all_test { return ExportStatus::TestOnly; }
104 } else if i == "test" || i == "feature" {
105 // If its cfg(feature(...)) we assume its test-only
106 return ExportStatus::TestOnly;
110 continue; // eg #[derive()]
112 _ => unimplemented!(),
115 match token_iter.next().unwrap() {
116 TokenTree::Literal(lit) => {
117 let line = format!("{}", lit);
118 if line.contains("(C-not exported)") {
119 return ExportStatus::NoExport;
122 _ => unimplemented!(),
128 pub fn assert_simple_bound(bound: &syn::TraitBound) {
129 if bound.paren_token.is_some() || bound.lifetimes.is_some() { unimplemented!(); }
130 if let syn::TraitBoundModifier::Maybe(_) = bound.modifier { unimplemented!(); }
133 /// Returns true if the enum will be mapped as an opaue (ie struct with a pointer to the underlying
134 /// type), otherwise it is mapped into a transparent, C-compatible version of itself.
135 pub fn is_enum_opaque(e: &syn::ItemEnum) -> bool {
136 for var in e.variants.iter() {
137 if let syn::Fields::Named(fields) = &var.fields {
138 for field in fields.named.iter() {
139 match export_status(&field.attrs) {
140 ExportStatus::Export|ExportStatus::TestOnly => {},
141 ExportStatus::NoExport => return true,
144 } else if let syn::Fields::Unnamed(fields) = &var.fields {
145 for field in fields.unnamed.iter() {
146 match export_status(&field.attrs) {
147 ExportStatus::Export|ExportStatus::TestOnly => {},
148 ExportStatus::NoExport => return true,
156 /// A stack of sets of generic resolutions.
158 /// This tracks the template parameters for a function, struct, or trait, allowing resolution into
159 /// a concrete type. By pushing a new context onto the stack, this can track a function's template
160 /// parameters inside of a generic struct or trait.
162 /// It maps both direct types as well as Deref<Target = X>, mapping them via the provided
163 /// TypeResolver's resolve_path function (ie traits map to the concrete jump table, structs to the
164 /// concrete C container struct, etc).
166 pub struct GenericTypes<'a, 'b> {
167 self_ty: Option<(String, &'a syn::Path)>,
168 parent: Option<&'b GenericTypes<'b, 'b>>,
169 typed_generics: HashMap<&'a syn::Ident, (String, Option<&'a syn::Path>)>,
171 impl<'a, 'p: 'a> GenericTypes<'a, 'p> {
172 pub fn new(self_ty: Option<(String, &'a syn::Path)>) -> Self {
173 Self { self_ty, parent: None, typed_generics: HashMap::new(), }
176 /// push a new context onto the stack, allowing for a new set of generics to be learned which
177 /// will override any lower contexts, but which will still fall back to resoltion via lower
179 pub fn push_ctx<'c>(&'c self) -> GenericTypes<'a, 'c> {
180 GenericTypes { self_ty: None, parent: Some(self), typed_generics: HashMap::new(), }
183 /// Learn the generics in generics in the current context, given a TypeResolver.
184 pub fn learn_generics<'b, 'c>(&mut self, generics: &'a syn::Generics, types: &'b TypeResolver<'a, 'c>) -> bool {
185 // First learn simple generics...
186 for generic in generics.params.iter() {
188 syn::GenericParam::Type(type_param) => {
189 let mut non_lifetimes_processed = false;
190 for bound in type_param.bounds.iter() {
191 if let syn::TypeParamBound::Trait(trait_bound) = bound {
192 if let Some(ident) = single_ident_generic_path_to_ident(&trait_bound.path) {
193 match &format!("{}", ident) as &str { "Send" => continue, "Sync" => continue, _ => {} }
195 if path_matches_nongeneric(&trait_bound.path, &["core", "clone", "Clone"]) { continue; }
197 assert_simple_bound(&trait_bound);
198 if let Some(mut path) = types.maybe_resolve_path(&trait_bound.path, None) {
199 if types.skip_path(&path) { continue; }
200 if path == "Sized" { continue; }
201 if non_lifetimes_processed { return false; }
202 non_lifetimes_processed = true;
203 let new_ident = if path != "std::ops::Deref" {
204 path = "crate::".to_string() + &path;
205 Some(&trait_bound.path)
207 self.typed_generics.insert(&type_param.ident, (path, new_ident));
208 } else { return false; }
215 // Then find generics where we are required to pass a Deref<Target=X> and pretend its just X.
216 if let Some(wh) = &generics.where_clause {
217 for pred in wh.predicates.iter() {
218 if let syn::WherePredicate::Type(t) = pred {
219 if let syn::Type::Path(p) = &t.bounded_ty {
220 if p.qself.is_some() { return false; }
221 if p.path.leading_colon.is_some() { return false; }
222 let mut p_iter = p.path.segments.iter();
223 if let Some(gen) = self.typed_generics.get_mut(&p_iter.next().unwrap().ident) {
224 if gen.0 != "std::ops::Deref" { return false; }
225 if &format!("{}", p_iter.next().unwrap().ident) != "Target" { return false; }
227 let mut non_lifetimes_processed = false;
228 for bound in t.bounds.iter() {
229 if let syn::TypeParamBound::Trait(trait_bound) = bound {
230 if let Some(id) = trait_bound.path.get_ident() {
231 if format!("{}", id) == "Sized" { continue; }
233 if non_lifetimes_processed { return false; }
234 non_lifetimes_processed = true;
235 assert_simple_bound(&trait_bound);
236 *gen = ("crate::".to_string() + &types.resolve_path(&trait_bound.path, None),
237 Some(&trait_bound.path));
240 } else { return false; }
241 } else { return false; }
245 for (_, (_, ident)) in self.typed_generics.iter() {
246 if ident.is_none() { return false; }
251 /// Learn the associated types from the trait in the current context.
252 pub fn learn_associated_types<'b, 'c>(&mut self, t: &'a syn::ItemTrait, types: &'b TypeResolver<'a, 'c>) {
253 for item in t.items.iter() {
255 &syn::TraitItem::Type(ref t) => {
256 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
257 let mut bounds_iter = t.bounds.iter();
258 match bounds_iter.next().unwrap() {
259 syn::TypeParamBound::Trait(tr) => {
260 assert_simple_bound(&tr);
261 if let Some(mut path) = types.maybe_resolve_path(&tr.path, None) {
262 if types.skip_path(&path) { continue; }
263 // In general we handle Deref<Target=X> as if it were just X (and
264 // implement Deref<Target=Self> for relevant types). We don't
265 // bother to implement it for associated types, however, so we just
266 // ignore such bounds.
267 let new_ident = if path != "std::ops::Deref" {
268 path = "crate::".to_string() + &path;
271 self.typed_generics.insert(&t.ident, (path, new_ident));
272 } else { unimplemented!(); }
274 _ => unimplemented!(),
276 if bounds_iter.next().is_some() { unimplemented!(); }
283 /// Attempt to resolve an Ident as a generic parameter and return the full path.
284 pub fn maybe_resolve_ident<'b>(&'b self, ident: &syn::Ident) -> Option<&'b String> {
285 if let Some(ty) = &self.self_ty {
286 if format!("{}", ident) == "Self" {
290 if let Some(res) = self.typed_generics.get(ident).map(|(a, _)| a) {
293 if let Some(parent) = self.parent {
294 parent.maybe_resolve_ident(ident)
299 /// Attempt to resolve a Path as a generic parameter and return the full path. as both a string
301 pub fn maybe_resolve_path<'b>(&'b self, path: &syn::Path) -> Option<(&'b String, &'a syn::Path)> {
302 if let Some(ident) = path.get_ident() {
303 if let Some(ty) = &self.self_ty {
304 if format!("{}", ident) == "Self" {
305 return Some((&ty.0, ty.1));
308 if let Some(res) = self.typed_generics.get(ident).map(|(a, b)| (a, b.unwrap())) {
312 // Associated types are usually specified as "Self::Generic", so we check for that
314 let mut it = path.segments.iter();
315 if path.segments.len() == 2 && format!("{}", it.next().unwrap().ident) == "Self" {
316 let ident = &it.next().unwrap().ident;
317 if let Some(res) = self.typed_generics.get(ident).map(|(a, b)| (a, b.unwrap())) {
322 if let Some(parent) = self.parent {
323 parent.maybe_resolve_path(path)
330 #[derive(Clone, PartialEq)]
331 // The type of declaration and the object itself
332 pub enum DeclType<'a> {
334 Trait(&'a syn::ItemTrait),
340 pub struct ImportResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
341 crate_name: &'mod_lifetime str,
342 dependencies: &'mod_lifetime HashSet<syn::Ident>,
343 module_path: &'mod_lifetime str,
344 imports: HashMap<syn::Ident, (String, syn::Path)>,
345 declared: HashMap<syn::Ident, DeclType<'crate_lft>>,
346 priv_modules: HashSet<syn::Ident>,
348 impl<'mod_lifetime, 'crate_lft: 'mod_lifetime> ImportResolver<'mod_lifetime, 'crate_lft> {
349 fn process_use_intern(crate_name: &str, module_path: &str, dependencies: &HashSet<syn::Ident>, imports: &mut HashMap<syn::Ident, (String, syn::Path)>,
350 u: &syn::UseTree, partial_path: &str, mut path: syn::punctuated::Punctuated<syn::PathSegment, syn::token::Colon2>) {
353 macro_rules! push_path {
354 ($ident: expr, $path_suffix: expr) => {
355 if partial_path == "" && format!("{}", $ident) == "super" {
356 let mut mod_iter = module_path.rsplitn(2, "::");
357 mod_iter.next().unwrap();
358 let super_mod = mod_iter.next().unwrap();
359 new_path = format!("{}{}", super_mod, $path_suffix);
360 assert_eq!(path.len(), 0);
361 for module in super_mod.split("::") {
362 path.push(syn::PathSegment { ident: syn::Ident::new(module, Span::call_site()), arguments: syn::PathArguments::None });
364 } else if partial_path == "" && !dependencies.contains(&$ident) {
365 new_path = format!("{}::{}{}", crate_name, $ident, $path_suffix);
366 let crate_name_ident = format_ident!("{}", crate_name);
367 path.push(parse_quote!(#crate_name_ident));
369 new_path = format!("{}{}{}", partial_path, $ident, $path_suffix);
372 path.push(parse_quote!(#ident));
376 syn::UseTree::Path(p) => {
377 push_path!(p.ident, "::");
378 Self::process_use_intern(crate_name, module_path, dependencies, imports, &p.tree, &new_path, path);
380 syn::UseTree::Name(n) => {
381 push_path!(n.ident, "");
382 imports.insert(n.ident.clone(), (new_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
384 syn::UseTree::Group(g) => {
385 for i in g.items.iter() {
386 Self::process_use_intern(crate_name, module_path, dependencies, imports, i, partial_path, path.clone());
389 syn::UseTree::Rename(r) => {
390 push_path!(r.ident, "");
391 imports.insert(r.rename.clone(), (new_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
393 syn::UseTree::Glob(_) => {
394 eprintln!("Ignoring * use for {} - this may result in resolution failures", partial_path);
399 fn process_use(crate_name: &str, module_path: &str, dependencies: &HashSet<syn::Ident>, imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::ItemUse) {
400 if let syn::Visibility::Public(_) = u.vis {
401 // We actually only use these for #[cfg(fuzztarget)]
402 eprintln!("Ignoring pub(use) tree!");
405 if u.leading_colon.is_some() { eprintln!("Ignoring leading-colon use!"); return; }
406 Self::process_use_intern(crate_name, module_path, dependencies, imports, &u.tree, "", syn::punctuated::Punctuated::new());
409 fn insert_primitive(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, id: &str) {
410 let ident = format_ident!("{}", id);
411 let path = parse_quote!(#ident);
412 imports.insert(ident, (id.to_owned(), path));
415 pub fn new(crate_name: &'mod_lifetime str, dependencies: &'mod_lifetime HashSet<syn::Ident>, module_path: &'mod_lifetime str, contents: &'crate_lft [syn::Item]) -> Self {
416 Self::from_borrowed_items(crate_name, dependencies, module_path, &contents.iter().map(|a| a).collect::<Vec<_>>())
418 pub fn from_borrowed_items(crate_name: &'mod_lifetime str, dependencies: &'mod_lifetime HashSet<syn::Ident>, module_path: &'mod_lifetime str, contents: &[&'crate_lft syn::Item]) -> Self {
419 let mut imports = HashMap::new();
420 // Add primitives to the "imports" list:
421 Self::insert_primitive(&mut imports, "bool");
422 Self::insert_primitive(&mut imports, "u64");
423 Self::insert_primitive(&mut imports, "u32");
424 Self::insert_primitive(&mut imports, "u16");
425 Self::insert_primitive(&mut imports, "u8");
426 Self::insert_primitive(&mut imports, "usize");
427 Self::insert_primitive(&mut imports, "str");
428 Self::insert_primitive(&mut imports, "String");
430 // These are here to allow us to print native Rust types in trait fn impls even if we don't
432 Self::insert_primitive(&mut imports, "Result");
433 Self::insert_primitive(&mut imports, "Vec");
434 Self::insert_primitive(&mut imports, "Option");
436 let mut declared = HashMap::new();
437 let mut priv_modules = HashSet::new();
439 for item in contents.iter() {
441 syn::Item::Use(u) => Self::process_use(crate_name, module_path, dependencies, &mut imports, &u),
442 syn::Item::Struct(s) => {
443 if let syn::Visibility::Public(_) = s.vis {
444 match export_status(&s.attrs) {
445 ExportStatus::Export => { declared.insert(s.ident.clone(), DeclType::StructImported); },
446 ExportStatus::NoExport => { declared.insert(s.ident.clone(), DeclType::StructIgnored); },
447 ExportStatus::TestOnly => continue,
451 syn::Item::Type(t) if export_status(&t.attrs) == ExportStatus::Export => {
452 if let syn::Visibility::Public(_) = t.vis {
453 let mut process_alias = true;
454 for tok in t.generics.params.iter() {
455 if let syn::GenericParam::Lifetime(_) = tok {}
456 else { process_alias = false; }
459 declared.insert(t.ident.clone(), DeclType::StructImported);
463 syn::Item::Enum(e) => {
464 if let syn::Visibility::Public(_) = e.vis {
465 match export_status(&e.attrs) {
466 ExportStatus::Export if is_enum_opaque(e) => { declared.insert(e.ident.clone(), DeclType::EnumIgnored); },
467 ExportStatus::Export => { declared.insert(e.ident.clone(), DeclType::MirroredEnum); },
472 syn::Item::Trait(t) if export_status(&t.attrs) == ExportStatus::Export => {
473 if let syn::Visibility::Public(_) = t.vis {
474 declared.insert(t.ident.clone(), DeclType::Trait(t));
477 syn::Item::Mod(m) => {
478 priv_modules.insert(m.ident.clone());
484 Self { crate_name, dependencies, module_path, imports, declared, priv_modules }
487 pub fn get_declared_type(&self, ident: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
488 self.declared.get(ident)
491 pub fn maybe_resolve_declared(&self, id: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
492 self.declared.get(id)
495 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
496 if let Some((imp, _)) = self.imports.get(id) {
498 } else if self.declared.get(id).is_some() {
499 Some(self.module_path.to_string() + "::" + &format!("{}", id))
503 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
504 if let Some((imp, _)) = self.imports.get(id) {
506 } else if let Some(decl_type) = self.declared.get(id) {
508 DeclType::StructIgnored => None,
509 _ => Some(self.module_path.to_string() + "::" + &format!("{}", id)),
514 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
515 let p = if let Some(gen_types) = generics {
516 if let Some((_, synpath)) = gen_types.maybe_resolve_path(p_arg) {
521 if p.leading_colon.is_some() {
522 let mut res: String = p.segments.iter().enumerate().map(|(idx, seg)| {
523 format!("{}{}", if idx == 0 { "" } else { "::" }, seg.ident)
525 let firstseg = p.segments.iter().next().unwrap();
526 if !self.dependencies.contains(&firstseg.ident) {
527 res = self.crate_name.to_owned() + "::" + &res;
530 } else if let Some(id) = p.get_ident() {
531 self.maybe_resolve_ident(id)
533 if p.segments.len() == 1 {
534 let seg = p.segments.iter().next().unwrap();
535 return self.maybe_resolve_ident(&seg.ident);
537 let mut seg_iter = p.segments.iter();
538 let first_seg = seg_iter.next().unwrap();
539 let remaining: String = seg_iter.map(|seg| {
540 format!("::{}", seg.ident)
542 let first_seg_str = format!("{}", first_seg.ident);
543 if let Some((imp, _)) = self.imports.get(&first_seg.ident) {
545 Some(imp.clone() + &remaining)
549 } else if let Some(_) = self.priv_modules.get(&first_seg.ident) {
550 Some(format!("{}::{}{}", self.module_path, first_seg.ident, remaining))
551 } else if first_seg_str == "std" || first_seg_str == "core" || self.dependencies.contains(&first_seg.ident) {
552 Some(first_seg_str + &remaining)
557 /// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern)
558 pub fn resolve_imported_refs(&self, mut ty: syn::Type) -> syn::Type {
560 syn::Type::Path(p) => {
561 if p.path.segments.len() != 1 { unimplemented!(); }
562 let mut args = p.path.segments[0].arguments.clone();
563 if let syn::PathArguments::AngleBracketed(ref mut generics) = &mut args {
564 for arg in generics.args.iter_mut() {
565 if let syn::GenericArgument::Type(ref mut t) = arg {
566 *t = self.resolve_imported_refs(t.clone());
570 if let Some((_, newpath)) = self.imports.get(single_ident_generic_path_to_ident(&p.path).unwrap()) {
571 p.path = newpath.clone();
573 p.path.segments[0].arguments = args;
575 syn::Type::Reference(r) => {
576 r.elem = Box::new(self.resolve_imported_refs((*r.elem).clone()));
578 syn::Type::Slice(s) => {
579 s.elem = Box::new(self.resolve_imported_refs((*s.elem).clone()));
581 syn::Type::Tuple(t) => {
582 for e in t.elems.iter_mut() {
583 *e = self.resolve_imported_refs(e.clone());
586 _ => unimplemented!(),
592 // templates_defined is walked to write the C++ header, so if we use the default hashing it get
593 // reordered on each genbindings run. Instead, we use SipHasher (which defaults to 0-keys) so that
594 // the sorting is stable across runs. It is deprecated, but the "replacement" doesn't actually
595 // accomplish the same goals, so we just ignore it.
597 pub type NonRandomHash = hash::BuildHasherDefault<hash::SipHasher>;
600 pub struct ASTModule {
601 pub attrs: Vec<syn::Attribute>,
602 pub items: Vec<syn::Item>,
603 pub submods: Vec<String>,
605 /// A struct containing the syn::File AST for each file in the crate.
606 pub struct FullLibraryAST {
607 pub modules: HashMap<String, ASTModule, NonRandomHash>,
608 pub dependencies: HashSet<syn::Ident>,
610 impl FullLibraryAST {
611 fn load_module(&mut self, module: String, attrs: Vec<syn::Attribute>, mut items: Vec<syn::Item>) {
612 let mut non_mod_items = Vec::with_capacity(items.len());
613 let mut submods = Vec::with_capacity(items.len());
614 for item in items.drain(..) {
616 syn::Item::Mod(m) if m.content.is_some() => {
617 if export_status(&m.attrs) == ExportStatus::Export {
618 if let syn::Visibility::Public(_) = m.vis {
619 let modident = format!("{}", m.ident);
620 let modname = if module != "" {
621 module.clone() + "::" + &modident
625 self.load_module(modname, m.attrs, m.content.unwrap().1);
626 submods.push(modident);
628 non_mod_items.push(syn::Item::Mod(m));
632 syn::Item::Mod(_) => panic!("--pretty=expanded output should never have non-body modules"),
633 syn::Item::ExternCrate(c) => {
634 if export_status(&c.attrs) == ExportStatus::Export {
635 self.dependencies.insert(c.ident);
638 _ => { non_mod_items.push(item); }
641 self.modules.insert(module, ASTModule { attrs, items: non_mod_items, submods });
644 pub fn load_lib(lib: syn::File) -> Self {
645 assert_eq!(export_status(&lib.attrs), ExportStatus::Export);
646 let mut res = Self { modules: HashMap::default(), dependencies: HashSet::new() };
647 res.load_module("".to_owned(), lib.attrs, lib.items);
652 /// List of manually-generated types which are clonable
653 fn initial_clonable_types() -> HashSet<String> {
654 let mut res = HashSet::new();
655 res.insert("crate::c_types::u5".to_owned());
659 /// Top-level struct tracking everything which has been defined while walking the crate.
660 pub struct CrateTypes<'a> {
661 /// This may contain structs or enums, but only when either is mapped as
662 /// struct X { inner: *mut originalX, .. }
663 pub opaques: HashMap<String, &'a syn::Ident>,
664 /// Enums which are mapped as C enums with conversion functions
665 pub mirrored_enums: HashMap<String, &'a syn::ItemEnum>,
666 /// Traits which are mapped as a pointer + jump table
667 pub traits: HashMap<String, &'a syn::ItemTrait>,
668 /// Aliases from paths to some other Type
669 pub type_aliases: HashMap<String, syn::Type>,
670 /// Value is an alias to Key (maybe with some generics)
671 pub reverse_alias_map: HashMap<String, Vec<(syn::Path, syn::PathArguments)>>,
672 /// Template continer types defined, map from mangled type name -> whether a destructor fn
675 /// This is used at the end of processing to make C++ wrapper classes
676 pub templates_defined: RefCell<HashMap<String, bool, NonRandomHash>>,
677 /// The output file for any created template container types, written to as we find new
678 /// template containers which need to be defined.
679 template_file: RefCell<&'a mut File>,
680 /// Set of containers which are clonable
681 clonable_types: RefCell<HashSet<String>>,
683 pub trait_impls: HashMap<String, Vec<String>>,
684 /// The full set of modules in the crate(s)
685 pub lib_ast: &'a FullLibraryAST,
688 impl<'a> CrateTypes<'a> {
689 pub fn new(template_file: &'a mut File, libast: &'a FullLibraryAST) -> Self {
691 opaques: HashMap::new(), mirrored_enums: HashMap::new(), traits: HashMap::new(),
692 type_aliases: HashMap::new(), reverse_alias_map: HashMap::new(),
693 templates_defined: RefCell::new(HashMap::default()),
694 clonable_types: RefCell::new(initial_clonable_types()), trait_impls: HashMap::new(),
695 template_file: RefCell::new(template_file), lib_ast: &libast,
698 pub fn set_clonable(&self, object: String) {
699 self.clonable_types.borrow_mut().insert(object);
701 pub fn is_clonable(&self, object: &str) -> bool {
702 self.clonable_types.borrow().contains(object)
704 pub fn write_new_template(&self, mangled_container: String, has_destructor: bool, created_container: &[u8]) {
705 self.template_file.borrow_mut().write(created_container).unwrap();
706 self.templates_defined.borrow_mut().insert(mangled_container, has_destructor);
710 /// A struct which tracks resolving rust types into C-mapped equivalents, exists for one specific
711 /// module but contains a reference to the overall CrateTypes tracking.
712 pub struct TypeResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
713 pub module_path: &'mod_lifetime str,
714 pub crate_types: &'mod_lifetime CrateTypes<'crate_lft>,
715 types: ImportResolver<'mod_lifetime, 'crate_lft>,
718 /// Returned by write_empty_rust_val_check_suffix to indicate what type of dereferencing needs to
719 /// happen to get the inner value of a generic.
720 enum EmptyValExpectedTy {
721 /// A type which has a flag for being empty (eg an array where we treat all-0s as empty).
723 /// A pointer that we want to dereference and move out of.
725 /// A pointer which we want to convert to a reference.
730 /// Describes the appropriate place to print a general type-conversion string when converting a
732 enum ContainerPrefixLocation {
733 /// Prints a general type-conversion string prefix and suffix outside of the
734 /// container-conversion strings.
736 /// Prints a general type-conversion string prefix and suffix inside of the
737 /// container-conversion strings.
739 /// Does not print the usual type-conversion string prefix and suffix.
743 impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
744 pub fn new(module_path: &'a str, types: ImportResolver<'a, 'c>, crate_types: &'a CrateTypes<'c>) -> Self {
745 Self { module_path, types, crate_types }
748 // *************************************************
749 // *** Well know type and conversion definitions ***
750 // *************************************************
752 /// Returns true we if can just skip passing this to C entirely
753 fn skip_path(&self, full_path: &str) -> bool {
754 full_path == "bitcoin::secp256k1::Secp256k1" ||
755 full_path == "bitcoin::secp256k1::Signing" ||
756 full_path == "bitcoin::secp256k1::Verification"
758 /// Returns true we if can just skip passing this to C entirely
759 fn no_arg_path_to_rust(&self, full_path: &str) -> &str {
760 if full_path == "bitcoin::secp256k1::Secp256k1" {
761 "secp256k1::SECP256K1"
762 } else { unimplemented!(); }
765 /// Returns true if the object is a primitive and is mapped as-is with no conversion
767 pub fn is_primitive(&self, full_path: &str) -> bool {
778 pub fn is_clonable(&self, ty: &str) -> bool {
779 if self.crate_types.is_clonable(ty) { return true; }
780 if self.is_primitive(ty) { return true; }
783 "crate::c_types::Signature" => true,
784 "crate::c_types::RecoverableSignature" => true,
785 "crate::c_types::TxOut" => true,
789 /// Gets the C-mapped type for types which are outside of the crate, or which are manually
790 /// ignored by for some reason need mapping anyway.
791 fn c_type_from_path<'b>(&self, full_path: &'b str, is_ref: bool, _ptr_for_ref: bool) -> Option<&'b str> {
792 if self.is_primitive(full_path) {
793 return Some(full_path);
796 "Result" => Some("crate::c_types::derived::CResult"),
797 "Vec" if !is_ref => Some("crate::c_types::derived::CVec"),
798 "Option" => Some(""),
800 // Note that no !is_ref types can map to an array because Rust and C's call semantics
801 // for arrays are different (https://github.com/eqrion/cbindgen/issues/528)
803 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
804 "[u8; 20]" if !is_ref => Some("crate::c_types::TwentyBytes"),
805 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes"),
806 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes"),
807 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes"),
808 "[u8; 3]" if !is_ref => Some("crate::c_types::ThreeBytes"), // Used for RGB values
810 "str" if is_ref => Some("crate::c_types::Str"),
811 "String" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
812 "String" if is_ref => Some("crate::c_types::Str"),
814 "std::time::Duration" => Some("u64"),
815 "std::time::SystemTime" => Some("u64"),
816 "std::io::Error" => Some("crate::c_types::IOError"),
818 "bech32::u5" => Some("crate::c_types::u5"),
820 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
821 => Some("crate::c_types::PublicKey"),
822 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature"),
823 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some("crate::c_types::RecoverableSignature"),
824 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
825 if is_ref => Some("*const [u8; 32]"),
826 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
827 if !is_ref => Some("crate::c_types::SecretKey"),
828 "bitcoin::secp256k1::Error"|"secp256k1::Error"
829 if !is_ref => Some("crate::c_types::Secp256k1Error"),
830 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice"),
831 "bitcoin::blockdata::script::Script" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
832 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::lightning::chain::transaction::OutPoint"),
833 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction"),
834 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut"),
835 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network"),
836 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("*const [u8; 80]"),
837 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice"),
839 // Newtypes that we just expose in their original form.
840 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
841 if is_ref => Some("*const [u8; 32]"),
842 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
843 if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
844 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
845 "lightning::ln::PaymentHash" if is_ref => Some("*const [u8; 32]"),
846 "lightning::ln::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
847 "lightning::ln::PaymentPreimage" if is_ref => Some("*const [u8; 32]"),
848 "lightning::ln::PaymentPreimage" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
849 "lightning::ln::PaymentSecret" if is_ref => Some("crate::c_types::ThirtyTwoBytes"),
850 "lightning::ln::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
852 // Override the default since Records contain an fmt with a lifetime:
853 "lightning::util::logger::Record" => Some("*const std::os::raw::c_char"),
859 fn from_c_conversion_new_var_from_path<'b>(&self, _full_path: &str, _is_ref: bool) -> Option<(&'b str, &'b str)> {
862 fn from_c_conversion_prefix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
863 if self.is_primitive(full_path) {
864 return Some("".to_owned());
867 "Vec" if !is_ref => Some("local_"),
868 "Result" if !is_ref => Some("local_"),
869 "Option" if is_ref => Some("&local_"),
870 "Option" => Some("local_"),
872 "[u8; 32]" if is_ref => Some("unsafe { &*"),
873 "[u8; 32]" if !is_ref => Some(""),
874 "[u8; 20]" if !is_ref => Some(""),
875 "[u8; 16]" if !is_ref => Some(""),
876 "[u8; 10]" if !is_ref => Some(""),
877 "[u8; 4]" if !is_ref => Some(""),
878 "[u8; 3]" if !is_ref => Some(""),
880 "[u8]" if is_ref => Some(""),
881 "[usize]" if is_ref => Some(""),
883 "str" if is_ref => Some(""),
884 "String" if !is_ref => Some("String::from_utf8("),
885 // Note that we'll panic for String if is_ref, as we only have non-owned memory, we
886 // cannot create a &String.
888 "std::time::Duration" => Some("std::time::Duration::from_secs("),
889 "std::time::SystemTime" => Some("(::std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs("),
891 "bech32::u5" => Some(""),
893 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
894 if is_ref => Some("&"),
895 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
897 "bitcoin::secp256k1::Signature" if is_ref => Some("&"),
898 "bitcoin::secp256k1::Signature" => Some(""),
899 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(""),
900 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
901 if is_ref => Some("&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *"),
902 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
903 if !is_ref => Some(""),
904 "bitcoin::blockdata::script::Script" if is_ref => Some("&::bitcoin::blockdata::script::Script::from(Vec::from("),
905 "bitcoin::blockdata::script::Script" if !is_ref => Some("::bitcoin::blockdata::script::Script::from("),
906 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some("&"),
907 "bitcoin::blockdata::transaction::Transaction" => Some(""),
908 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(""),
909 "bitcoin::network::constants::Network" => Some(""),
910 "bitcoin::blockdata::block::BlockHeader" => Some("&::bitcoin::consensus::encode::deserialize(unsafe { &*"),
911 "bitcoin::blockdata::block::Block" if is_ref => Some("&::bitcoin::consensus::encode::deserialize("),
913 // Newtypes that we just expose in their original form.
914 "bitcoin::hash_types::Txid" if is_ref => Some("&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*"),
915 "bitcoin::hash_types::Txid" if !is_ref => Some("::bitcoin::hash_types::Txid::from_slice(&"),
916 "bitcoin::hash_types::BlockHash" => Some("::bitcoin::hash_types::BlockHash::from_slice(&"),
917 "lightning::ln::PaymentHash" if !is_ref => Some("::lightning::ln::PaymentHash("),
918 "lightning::ln::PaymentHash" if is_ref => Some("&::lightning::ln::PaymentHash(unsafe { *"),
919 "lightning::ln::PaymentPreimage" if !is_ref => Some("::lightning::ln::PaymentPreimage("),
920 "lightning::ln::PaymentPreimage" if is_ref => Some("&::lightning::ln::PaymentPreimage(unsafe { *"),
921 "lightning::ln::PaymentSecret" => Some("::lightning::ln::PaymentSecret("),
923 // List of traits we map (possibly during processing of other files):
924 "crate::util::logger::Logger" => Some(""),
927 }.map(|s| s.to_owned())
929 fn from_c_conversion_suffix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
930 if self.is_primitive(full_path) {
931 return Some("".to_owned());
934 "Vec" if !is_ref => Some(""),
935 "Option" => Some(""),
936 "Result" if !is_ref => Some(""),
938 "[u8; 32]" if is_ref => Some("}"),
939 "[u8; 32]" if !is_ref => Some(".data"),
940 "[u8; 20]" if !is_ref => Some(".data"),
941 "[u8; 16]" if !is_ref => Some(".data"),
942 "[u8; 10]" if !is_ref => Some(".data"),
943 "[u8; 4]" if !is_ref => Some(".data"),
944 "[u8; 3]" if !is_ref => Some(".data"),
946 "[u8]" if is_ref => Some(".to_slice()"),
947 "[usize]" if is_ref => Some(".to_slice()"),
949 "str" if is_ref => Some(".into()"),
950 "String" if !is_ref => Some(".into_rust()).unwrap()"),
952 "std::time::Duration" => Some(")"),
953 "std::time::SystemTime" => Some("))"),
955 "bech32::u5" => Some(".into()"),
957 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
958 => Some(".into_rust()"),
959 "bitcoin::secp256k1::Signature" => Some(".into_rust()"),
960 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(".into_rust()"),
961 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
962 if !is_ref => Some(".into_rust()"),
963 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
964 if is_ref => Some("}[..]).unwrap()"),
965 "bitcoin::blockdata::script::Script" if is_ref => Some(".to_slice()))"),
966 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_rust())"),
967 "bitcoin::blockdata::transaction::Transaction" => Some(".into_bitcoin()"),
968 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(".into_rust()"),
969 "bitcoin::network::constants::Network" => Some(".into_bitcoin()"),
970 "bitcoin::blockdata::block::BlockHeader" => Some(" }).unwrap()"),
971 "bitcoin::blockdata::block::Block" => Some(".to_slice()).unwrap()"),
973 // Newtypes that we just expose in their original form.
974 "bitcoin::hash_types::Txid" if is_ref => Some(" }[..]).unwrap()"),
975 "bitcoin::hash_types::Txid" => Some(".data[..]).unwrap()"),
976 "bitcoin::hash_types::BlockHash" if !is_ref => Some(".data[..]).unwrap()"),
977 "lightning::ln::PaymentHash" if !is_ref => Some(".data)"),
978 "lightning::ln::PaymentHash" if is_ref => Some(" })"),
979 "lightning::ln::PaymentPreimage" if !is_ref => Some(".data)"),
980 "lightning::ln::PaymentPreimage" if is_ref => Some(" })"),
981 "lightning::ln::PaymentSecret" => Some(".data)"),
983 // List of traits we map (possibly during processing of other files):
984 "crate::util::logger::Logger" => Some(""),
987 }.map(|s| s.to_owned())
990 fn to_c_conversion_new_var_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<(&'b str, &'b str)> {
991 if self.is_primitive(full_path) {
995 "[u8]" if is_ref => Some(("crate::c_types::u8slice::from_slice(", ")")),
996 "[usize]" if is_ref => Some(("crate::c_types::usizeslice::from_slice(", ")")),
998 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(("{ let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(", ")); s }")),
999 "bitcoin::blockdata::block::Block" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
1000 "bitcoin::hash_types::Txid" => None,
1002 // Override the default since Records contain an fmt with a lifetime:
1003 // TODO: We should include the other record fields
1004 "lightning::util::logger::Record" => Some(("std::ffi::CString::new(format!(\"{}\", ", ".args)).unwrap()")),
1006 }.map(|s| s.to_owned())
1008 fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
1009 if self.is_primitive(full_path) {
1010 return Some("".to_owned());
1013 "Result" if !is_ref => Some("local_"),
1014 "Vec" if !is_ref => Some("local_"),
1015 "Option" => Some("local_"),
1017 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1018 "[u8; 32]" if is_ref => Some(""),
1019 "[u8; 20]" if !is_ref => Some("crate::c_types::TwentyBytes { data: "),
1020 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes { data: "),
1021 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes { data: "),
1022 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes { data: "),
1023 "[u8; 3]" if is_ref => Some(""),
1025 "[u8]" if is_ref => Some("local_"),
1026 "[usize]" if is_ref => Some("local_"),
1028 "str" if is_ref => Some(""),
1029 "String" => Some(""),
1031 "std::time::Duration" => Some(""),
1032 "std::time::SystemTime" => Some(""),
1033 "std::io::Error" if !is_ref => Some("crate::c_types::IOError::from_rust("),
1035 "bech32::u5" => Some(""),
1037 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1038 => Some("crate::c_types::PublicKey::from_rust(&"),
1039 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature::from_rust(&"),
1040 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some("crate::c_types::RecoverableSignature::from_rust(&"),
1041 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1042 if is_ref => Some(""),
1043 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1044 if !is_ref => Some("crate::c_types::SecretKey::from_rust("),
1045 "bitcoin::secp256k1::Error"|"secp256k1::Error"
1046 if !is_ref => Some("crate::c_types::Secp256k1Error::from_rust("),
1047 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice::from_slice(&"),
1048 "bitcoin::blockdata::script::Script" if !is_ref => Some(""),
1049 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some("crate::c_types::Transaction::from_bitcoin("),
1050 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction::from_bitcoin(&"),
1051 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::c_types::bitcoin_to_C_outpoint("),
1052 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut::from_rust("),
1053 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network::from_bitcoin("),
1054 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("&local_"),
1055 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice::from_slice(&local_"),
1057 "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1059 // Newtypes that we just expose in their original form.
1060 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1061 if is_ref => Some(""),
1062 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1063 if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1064 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1065 "lightning::ln::PaymentHash" if is_ref => Some("&"),
1066 "lightning::ln::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1067 "lightning::ln::PaymentPreimage" if is_ref => Some("&"),
1068 "lightning::ln::PaymentPreimage" => Some("crate::c_types::ThirtyTwoBytes { data: "),
1069 "lightning::ln::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1071 // Override the default since Records contain an fmt with a lifetime:
1072 "lightning::util::logger::Record" => Some("local_"),
1075 }.map(|s| s.to_owned())
1077 fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
1078 if self.is_primitive(full_path) {
1079 return Some("".to_owned());
1082 "Result" if !is_ref => Some(""),
1083 "Vec" if !is_ref => Some(".into()"),
1084 "Option" => Some(""),
1086 "[u8; 32]" if !is_ref => Some(" }"),
1087 "[u8; 32]" if is_ref => Some(""),
1088 "[u8; 20]" if !is_ref => Some(" }"),
1089 "[u8; 16]" if !is_ref => Some(" }"),
1090 "[u8; 10]" if !is_ref => Some(" }"),
1091 "[u8; 4]" if !is_ref => Some(" }"),
1092 "[u8; 3]" if is_ref => Some(""),
1094 "[u8]" if is_ref => Some(""),
1095 "[usize]" if is_ref => Some(""),
1097 "str" if is_ref => Some(".into()"),
1098 "String" if !is_ref => Some(".into_bytes().into()"),
1099 "String" if is_ref => Some(".as_str().into()"),
1101 "std::time::Duration" => Some(".as_secs()"),
1102 "std::time::SystemTime" => Some(".duration_since(::std::time::SystemTime::UNIX_EPOCH).expect(\"Times must be post-1970\").as_secs()"),
1103 "std::io::Error" if !is_ref => Some(")"),
1105 "bech32::u5" => Some(".into()"),
1107 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1109 "bitcoin::secp256k1::Signature" => Some(")"),
1110 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(")"),
1111 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1112 if !is_ref => Some(")"),
1113 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1114 if is_ref => Some(".as_ref()"),
1115 "bitcoin::secp256k1::Error"|"secp256k1::Error"
1116 if !is_ref => Some(")"),
1117 "bitcoin::blockdata::script::Script" if is_ref => Some("[..])"),
1118 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_bytes().into()"),
1119 "bitcoin::blockdata::transaction::Transaction" => Some(")"),
1120 "bitcoin::blockdata::transaction::OutPoint" => Some(")"),
1121 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(")"),
1122 "bitcoin::network::constants::Network" => Some(")"),
1123 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(""),
1124 "bitcoin::blockdata::block::Block" if is_ref => Some(")"),
1126 "bitcoin::hash_types::Txid" if !is_ref => Some(".into_inner() }"),
1128 // Newtypes that we just expose in their original form.
1129 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1130 if is_ref => Some(".as_inner()"),
1131 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1132 if !is_ref => Some(".into_inner() }"),
1133 "bitcoin::secp256k1::Message" if !is_ref => Some(".as_ref().clone() }"),
1134 "lightning::ln::PaymentHash" if is_ref => Some(".0"),
1135 "lightning::ln::PaymentHash" => Some(".0 }"),
1136 "lightning::ln::PaymentPreimage" if is_ref => Some(".0"),
1137 "lightning::ln::PaymentPreimage" => Some(".0 }"),
1138 "lightning::ln::PaymentSecret" if !is_ref => Some(".0 }"),
1140 // Override the default since Records contain an fmt with a lifetime:
1141 "lightning::util::logger::Record" => Some(".as_ptr()"),
1144 }.map(|s| s.to_owned())
1147 fn empty_val_check_suffix_from_path(&self, full_path: &str) -> Option<&str> {
1149 "lightning::ln::PaymentSecret" => Some(".data == [0; 32]"),
1150 "secp256k1::key::PublicKey"|"bitcoin::secp256k1::key::PublicKey" => Some(".is_null()"),
1151 "bitcoin::secp256k1::Signature" => Some(".is_null()"),
1156 // ****************************
1157 // *** Container Processing ***
1158 // ****************************
1160 /// Returns the module path in the generated mapping crate to the containers which we generate
1161 /// when writing to CrateTypes::template_file.
1162 pub fn generated_container_path() -> &'static str {
1163 "crate::c_types::derived"
1165 /// Returns the module path in the generated mapping crate to the container templates, which
1166 /// are then concretized and put in the generated container path/template_file.
1167 fn container_templ_path() -> &'static str {
1171 /// Returns true if the path containing the given args is a "transparent" container, ie an
1172 /// Option or a container which does not require a generated continer class.
1173 fn is_transparent_container<'i, I: Iterator<Item=&'i syn::Type>>(&self, full_path: &str, _is_ref: bool, mut args: I) -> bool {
1174 if full_path == "Option" {
1175 let inner = args.next().unwrap();
1176 assert!(args.next().is_none());
1178 syn::Type::Reference(_) => true,
1179 syn::Type::Path(p) => {
1180 if let Some(resolved) = self.maybe_resolve_path(&p.path, None) {
1181 if self.is_primitive(&resolved) { false } else { true }
1184 syn::Type::Tuple(_) => false,
1185 _ => unimplemented!(),
1189 /// Returns true if the path is a "transparent" container, ie an Option or a container which does
1190 /// not require a generated continer class.
1191 fn is_path_transparent_container(&self, full_path: &syn::Path, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
1192 let inner_iter = match &full_path.segments.last().unwrap().arguments {
1193 syn::PathArguments::None => return false,
1194 syn::PathArguments::AngleBracketed(args) => args.args.iter().map(|arg| {
1195 if let syn::GenericArgument::Type(ref ty) = arg {
1197 } else { unimplemented!() }
1199 syn::PathArguments::Parenthesized(_) => unimplemented!(),
1201 self.is_transparent_container(&self.resolve_path(full_path, generics), is_ref, inner_iter)
1203 /// Returns true if this is a known, supported, non-transparent container.
1204 fn is_known_container(&self, full_path: &str, is_ref: bool) -> bool {
1205 (full_path == "Result" && !is_ref) || (full_path == "Vec" && !is_ref) || full_path.ends_with("Tuple") || full_path == "Option"
1207 fn to_c_conversion_container_new_var<'b>(&self, generics: Option<&GenericTypes>, full_path: &str, is_ref: bool, single_contained: Option<&syn::Type>, var_name: &syn::Ident, var_access: &str)
1208 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1209 // expecting one element in the vec per generic type, each of which is inline-converted
1210 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1212 "Result" if !is_ref => {
1214 vec![(" { Ok(mut o) => crate::c_types::CResultTempl::ok(".to_string(), "o".to_string()),
1215 (").into(), Err(mut e) => crate::c_types::CResultTempl::err(".to_string(), "e".to_string())],
1216 ").into() }", ContainerPrefixLocation::PerConv))
1218 "Vec" if !is_ref => {
1219 Some(("Vec::new(); for mut item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1222 // We should only get here if the single contained has an inner
1223 assert!(self.c_type_has_inner(single_contained.unwrap()));
1224 Some(("Vec::new(); for mut item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "*item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1227 Some(("Vec::new(); for item in ", vec![(format!(".iter() {{ local_{}.push(", var_name), "*item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1230 if let Some(syn::Type::Path(p)) = single_contained {
1231 let inner_path = self.resolve_path(&p.path, generics);
1232 if self.is_primitive(&inner_path) {
1233 return Some(("if ", vec![
1234 (format!(".is_none() {{ {}::COption_{}Z::None }} else {{ ", Self::generated_container_path(), inner_path),
1235 format!("{}::COption_{}Z::Some({}.unwrap())", Self::generated_container_path(), inner_path, var_access))
1236 ], " }", ContainerPrefixLocation::NoPrefix));
1237 } else if self.c_type_has_inner_from_path(&inner_path) {
1239 return Some(("if ", vec![
1240 (".is_none() { std::ptr::null() } else { ".to_owned(), format!("({}.as_ref().unwrap())", var_access))
1241 ], " }", ContainerPrefixLocation::OutsideConv));
1243 return Some(("if ", vec![
1244 (".is_none() { std::ptr::null_mut() } else { ".to_owned(), format!("({}.unwrap())", var_access))
1245 ], " }", ContainerPrefixLocation::OutsideConv));
1249 if let Some(t) = single_contained {
1250 let mut v = Vec::new();
1251 self.write_empty_rust_val(generics, &mut v, t);
1252 let s = String::from_utf8(v).unwrap();
1253 return Some(("if ", vec![
1254 (format!(".is_none() {{ {} }} else {{ ", s), format!("({}.unwrap())", var_access))
1255 ], " }", ContainerPrefixLocation::PerConv));
1256 } else { unreachable!(); }
1262 /// only_contained_has_inner implies that there is only one contained element in the container
1263 /// and it has an inner field (ie is an "opaque" type we've defined).
1264 fn from_c_conversion_container_new_var<'b>(&self, generics: Option<&GenericTypes>, full_path: &str, is_ref: bool, single_contained: Option<&syn::Type>, var_name: &syn::Ident, var_access: &str)
1265 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1266 // expecting one element in the vec per generic type, each of which is inline-converted
1267 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1269 "Result" if !is_ref => {
1271 vec![(".result_ok { true => Ok(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.result)) }})", var_access)),
1272 ("), false => Err(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.err)) }})", var_access))],
1273 ")}", ContainerPrefixLocation::PerConv))
1275 "Slice" if is_ref => {
1276 Some(("Vec::new(); for mut item in ", vec![(format!(".as_slice().iter() {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1279 Some(("Vec::new(); for mut item in ", vec![(format!(".into_rust().drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1282 if let Some(syn::Type::Path(p)) = single_contained {
1283 let inner_path = self.resolve_path(&p.path, generics);
1284 if self.is_primitive(&inner_path) {
1285 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::NoPrefix))
1286 } else if self.c_type_has_inner_from_path(&inner_path) {
1288 return Some(("if ", vec![(".inner.is_null() { None } else { Some((*".to_string(), format!("{}", var_access))], ").clone()) }", ContainerPrefixLocation::PerConv))
1290 return Some(("if ", vec![(".inner.is_null() { None } else { Some(".to_string(), format!("{}", var_access))], ") }", ContainerPrefixLocation::PerConv));
1295 if let Some(t) = single_contained {
1297 syn::Type::Reference(_)|syn::Type::Path(_)|syn::Type::Slice(_) => {
1298 let mut v = Vec::new();
1299 let ret_ref = self.write_empty_rust_val_check_suffix(generics, &mut v, t);
1300 let s = String::from_utf8(v).unwrap();
1302 EmptyValExpectedTy::ReferenceAsPointer =>
1303 return Some(("if ", vec![
1304 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ &mut *{} }}", var_access))
1305 ], ") }", ContainerPrefixLocation::NoPrefix)),
1306 EmptyValExpectedTy::OwnedPointer => {
1307 if let syn::Type::Slice(_) = t {
1310 return Some(("if ", vec![
1311 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ *Box::from_raw({}) }}", var_access))
1312 ], ") }", ContainerPrefixLocation::NoPrefix));
1314 EmptyValExpectedTy::NonPointer =>
1315 return Some(("if ", vec![
1316 (format!("{} {{ None }} else {{ Some(", s), format!("{}", var_access))
1317 ], ") }", ContainerPrefixLocation::PerConv)),
1320 syn::Type::Tuple(_) => {
1321 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::PerConv))
1323 _ => unimplemented!(),
1325 } else { unreachable!(); }
1331 // *************************************************
1332 // *** Type definition during main.rs processing ***
1333 // *************************************************
1335 pub fn get_declared_type(&'a self, ident: &syn::Ident) -> Option<&'a DeclType<'c>> {
1336 self.types.get_declared_type(ident)
1338 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1339 pub fn c_type_has_inner_from_path(&self, full_path: &str) -> bool {
1340 self.crate_types.opaques.get(full_path).is_some()
1342 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1343 pub fn c_type_has_inner(&self, ty: &syn::Type) -> bool {
1345 syn::Type::Path(p) => {
1346 let full_path = self.resolve_path(&p.path, None);
1347 self.c_type_has_inner_from_path(&full_path)
1353 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
1354 self.types.maybe_resolve_ident(id)
1357 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
1358 self.types.maybe_resolve_non_ignored_ident(id)
1361 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
1362 self.types.maybe_resolve_path(p_arg, generics)
1364 pub fn resolve_path(&self, p: &syn::Path, generics: Option<&GenericTypes>) -> String {
1365 self.maybe_resolve_path(p, generics).unwrap()
1368 // ***********************************
1369 // *** Original Rust Type Printing ***
1370 // ***********************************
1372 fn in_rust_prelude(resolved_path: &str) -> bool {
1373 match resolved_path {
1381 fn write_rust_path<W: std::io::Write>(&self, w: &mut W, generics_resolver: Option<&GenericTypes>, path: &syn::Path) {
1382 if let Some(resolved) = self.maybe_resolve_path(&path, generics_resolver) {
1383 if self.is_primitive(&resolved) {
1384 write!(w, "{}", path.get_ident().unwrap()).unwrap();
1386 // TODO: We should have a generic "is from a dependency" check here instead of
1387 // checking for "bitcoin" explicitly.
1388 if resolved.starts_with("bitcoin::") || Self::in_rust_prelude(&resolved) {
1389 write!(w, "{}", resolved).unwrap();
1390 // If we're printing a generic argument, it needs to reference the crate, otherwise
1391 // the original crate:
1392 } else if self.maybe_resolve_path(&path, None).as_ref() == Some(&resolved) {
1393 write!(w, "{}", resolved).unwrap();
1395 write!(w, "crate::{}", resolved).unwrap();
1398 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().last().unwrap().arguments {
1399 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1402 if path.leading_colon.is_some() {
1403 write!(w, "::").unwrap();
1405 for (idx, seg) in path.segments.iter().enumerate() {
1406 if idx != 0 { write!(w, "::").unwrap(); }
1407 write!(w, "{}", seg.ident).unwrap();
1408 if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
1409 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1414 pub fn write_rust_generic_param<'b, W: std::io::Write>(&self, w: &mut W, generics_resolver: Option<&GenericTypes>, generics: impl Iterator<Item=&'b syn::GenericParam>) {
1415 let mut had_params = false;
1416 for (idx, arg) in generics.enumerate() {
1417 if idx != 0 { write!(w, ", ").unwrap(); } else { write!(w, "<").unwrap(); }
1420 syn::GenericParam::Lifetime(lt) => write!(w, "'{}", lt.lifetime.ident).unwrap(),
1421 syn::GenericParam::Type(t) => {
1422 write!(w, "{}", t.ident).unwrap();
1423 if t.colon_token.is_some() { write!(w, ":").unwrap(); }
1424 for (idx, bound) in t.bounds.iter().enumerate() {
1425 if idx != 0 { write!(w, " + ").unwrap(); }
1427 syn::TypeParamBound::Trait(tb) => {
1428 if tb.paren_token.is_some() || tb.lifetimes.is_some() { unimplemented!(); }
1429 self.write_rust_path(w, generics_resolver, &tb.path);
1431 _ => unimplemented!(),
1434 if t.eq_token.is_some() || t.default.is_some() { unimplemented!(); }
1436 _ => unimplemented!(),
1439 if had_params { write!(w, ">").unwrap(); }
1442 pub fn write_rust_generic_arg<'b, W: std::io::Write>(&self, w: &mut W, generics_resolver: Option<&GenericTypes>, generics: impl Iterator<Item=&'b syn::GenericArgument>) {
1443 write!(w, "<").unwrap();
1444 for (idx, arg) in generics.enumerate() {
1445 if idx != 0 { write!(w, ", ").unwrap(); }
1447 syn::GenericArgument::Type(t) => self.write_rust_type(w, generics_resolver, t),
1448 _ => unimplemented!(),
1451 write!(w, ">").unwrap();
1453 pub fn write_rust_type<W: std::io::Write>(&self, w: &mut W, generics: Option<&GenericTypes>, t: &syn::Type) {
1455 syn::Type::Path(p) => {
1456 if p.qself.is_some() {
1459 self.write_rust_path(w, generics, &p.path);
1461 syn::Type::Reference(r) => {
1462 write!(w, "&").unwrap();
1463 if let Some(lft) = &r.lifetime {
1464 write!(w, "'{} ", lft.ident).unwrap();
1466 if r.mutability.is_some() {
1467 write!(w, "mut ").unwrap();
1469 self.write_rust_type(w, generics, &*r.elem);
1471 syn::Type::Array(a) => {
1472 write!(w, "[").unwrap();
1473 self.write_rust_type(w, generics, &a.elem);
1474 if let syn::Expr::Lit(l) = &a.len {
1475 if let syn::Lit::Int(i) = &l.lit {
1476 write!(w, "; {}]", i).unwrap();
1477 } else { unimplemented!(); }
1478 } else { unimplemented!(); }
1480 syn::Type::Slice(s) => {
1481 write!(w, "[").unwrap();
1482 self.write_rust_type(w, generics, &s.elem);
1483 write!(w, "]").unwrap();
1485 syn::Type::Tuple(s) => {
1486 write!(w, "(").unwrap();
1487 for (idx, t) in s.elems.iter().enumerate() {
1488 if idx != 0 { write!(w, ", ").unwrap(); }
1489 self.write_rust_type(w, generics, &t);
1491 write!(w, ")").unwrap();
1493 _ => unimplemented!(),
1497 /// Prints a constructor for something which is "uninitialized" (but obviously not actually
1498 /// unint'd memory).
1499 pub fn write_empty_rust_val<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) {
1501 syn::Type::Path(p) => {
1502 let resolved = self.resolve_path(&p.path, generics);
1503 if self.crate_types.opaques.get(&resolved).is_some() {
1504 write!(w, "crate::{} {{ inner: std::ptr::null_mut(), is_owned: true }}", resolved).unwrap();
1506 // Assume its a manually-mapped C type, where we can just define an null() fn
1507 write!(w, "{}::null()", self.c_type_from_path(&resolved, false, false).unwrap()).unwrap();
1510 syn::Type::Array(a) => {
1511 if let syn::Expr::Lit(l) = &a.len {
1512 if let syn::Lit::Int(i) = &l.lit {
1513 if i.base10_digits().parse::<usize>().unwrap() < 32 {
1514 // Blindly assume that if we're trying to create an empty value for an
1515 // array < 32 entries that all-0s may be a valid state.
1518 let arrty = format!("[u8; {}]", i.base10_digits());
1519 write!(w, "{}", self.to_c_conversion_inline_prefix_from_path(&arrty, false, false).unwrap()).unwrap();
1520 write!(w, "[0; {}]", i.base10_digits()).unwrap();
1521 write!(w, "{}", self.to_c_conversion_inline_suffix_from_path(&arrty, false, false).unwrap()).unwrap();
1522 } else { unimplemented!(); }
1523 } else { unimplemented!(); }
1525 _ => unimplemented!(),
1529 fn is_real_type_array(&self, resolved_type: &str) -> Option<syn::Type> {
1530 if let Some(real_ty) = self.c_type_from_path(&resolved_type, true, false) {
1531 if real_ty.ends_with("]") && real_ty.starts_with("*const [u8; ") {
1532 let mut split = real_ty.split("; ");
1533 split.next().unwrap();
1534 let tail_str = split.next().unwrap();
1535 assert!(split.next().is_none());
1536 let len = usize::from_str_radix(&tail_str[..tail_str.len() - 1], 10).unwrap();
1537 Some(parse_quote!([u8; #len]))
1542 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1543 /// See EmptyValExpectedTy for information on return types.
1544 fn write_empty_rust_val_check_suffix<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) -> EmptyValExpectedTy {
1546 syn::Type::Path(p) => {
1547 let resolved = self.resolve_path(&p.path, generics);
1548 if let Some(arr_ty) = self.is_real_type_array(&resolved) {
1549 write!(w, ".data").unwrap();
1550 return self.write_empty_rust_val_check_suffix(generics, w, &arr_ty);
1552 if self.crate_types.opaques.get(&resolved).is_some() {
1553 write!(w, ".inner.is_null()").unwrap();
1554 EmptyValExpectedTy::NonPointer
1556 if let Some(suffix) = self.empty_val_check_suffix_from_path(&resolved) {
1557 write!(w, "{}", suffix).unwrap();
1558 // We may eventually need to allow empty_val_check_suffix_from_path to specify if we need a deref or not
1559 EmptyValExpectedTy::NonPointer
1561 write!(w, " == std::ptr::null_mut()").unwrap();
1562 EmptyValExpectedTy::OwnedPointer
1566 syn::Type::Array(a) => {
1567 if let syn::Expr::Lit(l) = &a.len {
1568 if let syn::Lit::Int(i) = &l.lit {
1569 write!(w, " == [0; {}]", i.base10_digits()).unwrap();
1570 EmptyValExpectedTy::NonPointer
1571 } else { unimplemented!(); }
1572 } else { unimplemented!(); }
1574 syn::Type::Slice(_) => {
1575 // Option<[]> always implies that we want to treat len() == 0 differently from
1576 // None, so we always map an Option<[]> into a pointer.
1577 write!(w, " == std::ptr::null_mut()").unwrap();
1578 EmptyValExpectedTy::ReferenceAsPointer
1580 _ => unimplemented!(),
1584 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1585 pub fn write_empty_rust_val_check<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type, var_access: &str) {
1587 syn::Type::Path(_) => {
1588 write!(w, "{}", var_access).unwrap();
1589 self.write_empty_rust_val_check_suffix(generics, w, t);
1591 syn::Type::Array(a) => {
1592 if let syn::Expr::Lit(l) = &a.len {
1593 if let syn::Lit::Int(i) = &l.lit {
1594 let arrty = format!("[u8; {}]", i.base10_digits());
1595 // We don't (yet) support a new-var conversion here.
1596 assert!(self.from_c_conversion_new_var_from_path(&arrty, false).is_none());
1598 self.from_c_conversion_prefix_from_path(&arrty, false).unwrap(),
1600 self.from_c_conversion_suffix_from_path(&arrty, false).unwrap()).unwrap();
1601 self.write_empty_rust_val_check_suffix(generics, w, t);
1602 } else { unimplemented!(); }
1603 } else { unimplemented!(); }
1605 _ => unimplemented!(),
1609 // ********************************
1610 // *** Type conversion printing ***
1611 // ********************************
1613 /// Returns true we if can just skip passing this to C entirely
1614 pub fn skip_arg(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
1616 syn::Type::Path(p) => {
1617 if p.qself.is_some() { unimplemented!(); }
1618 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1619 self.skip_path(&full_path)
1622 syn::Type::Reference(r) => {
1623 self.skip_arg(&*r.elem, generics)
1628 pub fn no_arg_to_rust<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1630 syn::Type::Path(p) => {
1631 if p.qself.is_some() { unimplemented!(); }
1632 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1633 write!(w, "{}", self.no_arg_path_to_rust(&full_path)).unwrap();
1636 syn::Type::Reference(r) => {
1637 self.no_arg_to_rust(w, &*r.elem, generics);
1643 fn write_conversion_inline_intern<W: std::io::Write,
1644 LP: Fn(&str, bool, bool) -> Option<String>, DL: Fn(&mut W, &DeclType, &str, bool, bool), SC: Fn(bool, Option<&str>) -> String>
1645 (&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool,
1646 tupleconv: &str, prefix: bool, sliceconv: SC, path_lookup: LP, decl_lookup: DL) {
1648 syn::Type::Reference(r) => {
1649 self.write_conversion_inline_intern(w, &*r.elem, generics, true, r.mutability.is_some(),
1650 ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1652 syn::Type::Path(p) => {
1653 if p.qself.is_some() {
1657 let resolved_path = self.resolve_path(&p.path, generics);
1658 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1659 return self.write_conversion_inline_intern(w, aliased_type, None, is_ref, is_mut, ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1660 } else if self.is_primitive(&resolved_path) {
1661 if is_ref && prefix {
1662 write!(w, "*").unwrap();
1664 } else if let Some(c_type) = path_lookup(&resolved_path, is_ref, ptr_for_ref) {
1665 write!(w, "{}", c_type).unwrap();
1666 } else if self.crate_types.opaques.get(&resolved_path).is_some() {
1667 decl_lookup(w, &DeclType::StructImported, &resolved_path, is_ref, is_mut);
1668 } else if self.crate_types.mirrored_enums.get(&resolved_path).is_some() {
1669 decl_lookup(w, &DeclType::MirroredEnum, &resolved_path, is_ref, is_mut);
1670 } else if let Some(t) = self.crate_types.traits.get(&resolved_path) {
1671 decl_lookup(w, &DeclType::Trait(t), &resolved_path, is_ref, is_mut);
1672 } else if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
1673 if let Some(decl_type) = self.types.maybe_resolve_declared(ident) {
1674 decl_lookup(w, decl_type, &self.maybe_resolve_ident(ident).unwrap(), is_ref, is_mut);
1675 } else { unimplemented!(); }
1676 } else { unimplemented!(); }
1678 syn::Type::Array(a) => {
1679 // We assume all arrays contain only [int_literal; X]s.
1680 // This may result in some outputs not compiling.
1681 if let syn::Expr::Lit(l) = &a.len {
1682 if let syn::Lit::Int(i) = &l.lit {
1683 write!(w, "{}", path_lookup(&format!("[u8; {}]", i.base10_digits()), is_ref, ptr_for_ref).unwrap()).unwrap();
1684 } else { unimplemented!(); }
1685 } else { unimplemented!(); }
1687 syn::Type::Slice(s) => {
1688 // We assume all slices contain only literals or references.
1689 // This may result in some outputs not compiling.
1690 if let syn::Type::Path(p) = &*s.elem {
1691 let resolved = self.resolve_path(&p.path, generics);
1692 assert!(self.is_primitive(&resolved));
1693 write!(w, "{}", path_lookup("[u8]", is_ref, ptr_for_ref).unwrap()).unwrap();
1694 } else if let syn::Type::Reference(r) = &*s.elem {
1695 if let syn::Type::Path(p) = &*r.elem {
1696 write!(w, "{}", sliceconv(self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)), None)).unwrap();
1697 } else { unimplemented!(); }
1698 } else if let syn::Type::Tuple(t) = &*s.elem {
1699 assert!(!t.elems.is_empty());
1701 write!(w, "{}", sliceconv(false, None)).unwrap();
1703 let mut needs_map = false;
1704 for e in t.elems.iter() {
1705 if let syn::Type::Reference(_) = e {
1710 let mut map_str = Vec::new();
1711 write!(&mut map_str, ".map(|(").unwrap();
1712 for i in 0..t.elems.len() {
1713 write!(&mut map_str, "{}{}", if i != 0 { ", " } else { "" }, ('a' as u8 + i as u8) as char).unwrap();
1715 write!(&mut map_str, ")| (").unwrap();
1716 for (idx, e) in t.elems.iter().enumerate() {
1717 if let syn::Type::Reference(_) = e {
1718 write!(&mut map_str, "{}{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1719 } else if let syn::Type::Path(_) = e {
1720 write!(&mut map_str, "{}*{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1721 } else { unimplemented!(); }
1723 write!(&mut map_str, "))").unwrap();
1724 write!(w, "{}", sliceconv(false, Some(&String::from_utf8(map_str).unwrap()))).unwrap();
1726 write!(w, "{}", sliceconv(false, None)).unwrap();
1729 } else { unimplemented!(); }
1731 syn::Type::Tuple(t) => {
1732 if t.elems.is_empty() {
1733 // cbindgen has poor support for (), see, eg https://github.com/eqrion/cbindgen/issues/527
1734 // so work around it by just pretending its a 0u8
1735 write!(w, "{}", tupleconv).unwrap();
1737 if prefix { write!(w, "local_").unwrap(); }
1740 _ => unimplemented!(),
1744 fn write_to_c_conversion_inline_prefix_inner<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, ptr_for_ref: bool, from_ptr: bool) {
1745 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "() /*", true, |_, _| "local_".to_owned(),
1746 |a, b, c| self.to_c_conversion_inline_prefix_from_path(a, b, c),
1747 |w, decl_type, decl_path, is_ref, _is_mut| {
1749 DeclType::MirroredEnum if is_ref && ptr_for_ref => write!(w, "crate::{}::from_native(", decl_path).unwrap(),
1750 DeclType::MirroredEnum if is_ref => write!(w, "&crate::{}::from_native(", decl_path).unwrap(),
1751 DeclType::MirroredEnum => write!(w, "crate::{}::native_into(", decl_path).unwrap(),
1752 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1753 write!(w, "crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1754 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1755 write!(w, "crate::{} {{ inner: unsafe {{ ( (&(*", decl_path).unwrap(),
1756 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1757 write!(w, "&crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1758 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1759 write!(w, "crate::{} {{ inner: ", decl_path).unwrap(),
1760 DeclType::EnumIgnored|DeclType::StructImported if !is_ref =>
1761 write!(w, "crate::{} {{ inner: Box::into_raw(Box::new(", decl_path).unwrap(),
1762 DeclType::Trait(_) if is_ref => write!(w, "").unwrap(),
1763 DeclType::Trait(_) if !is_ref => {},
1764 _ => panic!("{:?}", decl_path),
1768 pub fn write_to_c_conversion_inline_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) {
1769 self.write_to_c_conversion_inline_prefix_inner(w, t, generics, false, ptr_for_ref, false);
1771 fn write_to_c_conversion_inline_suffix_inner<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, ptr_for_ref: bool, from_ptr: bool) {
1772 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "*/", false, |_, _| ".into()".to_owned(),
1773 |a, b, c| self.to_c_conversion_inline_suffix_from_path(a, b, c),
1774 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1775 DeclType::MirroredEnum => write!(w, ")").unwrap(),
1776 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1777 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1778 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1779 write!(w, ") as *const _) as *mut _) }}, is_owned: false }}").unwrap(),
1780 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1781 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1782 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1783 write!(w, ", is_owned: true }}").unwrap(),
1784 DeclType::EnumIgnored|DeclType::StructImported if !is_ref => write!(w, ")), is_owned: true }}").unwrap(),
1785 DeclType::Trait(_) if is_ref => {},
1786 DeclType::Trait(_) => {
1787 // This is used when we're converting a concrete Rust type into a C trait
1788 // for use when a Rust trait method returns an associated type.
1789 // Because all of our C traits implement From<RustTypesImplementingTraits>
1790 // we can just call .into() here and be done.
1791 write!(w, ".into()").unwrap()
1793 _ => unimplemented!(),
1796 pub fn write_to_c_conversion_inline_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) {
1797 self.write_to_c_conversion_inline_suffix_inner(w, t, generics, false, ptr_for_ref, false);
1800 fn write_from_c_conversion_prefix_inner<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, ptr_for_ref: bool) {
1801 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "() /*", true, |_, _| "&local_".to_owned(),
1802 |a, b, _c| self.from_c_conversion_prefix_from_path(a, b),
1803 |w, decl_type, _full_path, is_ref, is_mut| match decl_type {
1804 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, "unsafe {{ &*(*").unwrap(),
1805 DeclType::StructImported if is_mut && is_ref => write!(w, "unsafe {{ &mut *").unwrap(),
1806 DeclType::StructImported if is_ref => write!(w, "unsafe {{ &*").unwrap(),
1807 DeclType::StructImported if !is_ref => write!(w, "*unsafe {{ Box::from_raw(").unwrap(),
1808 DeclType::MirroredEnum if is_ref => write!(w, "&").unwrap(),
1809 DeclType::MirroredEnum => {},
1810 DeclType::Trait(_) => {},
1811 _ => unimplemented!(),
1814 pub fn write_from_c_conversion_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1815 self.write_from_c_conversion_prefix_inner(w, t, generics, false, false);
1817 fn write_from_c_conversion_suffix_inner<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, ptr_for_ref: bool) {
1818 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "*/", false,
1819 |has_inner, map_str_opt| match (has_inner, map_str_opt) {
1820 (false, Some(map_str)) => format!(".iter(){}.collect::<Vec<_>>()[..]", map_str),
1821 (false, None) => ".iter().collect::<Vec<_>>()[..]".to_owned(),
1822 (true, None) => "[..]".to_owned(),
1823 (true, Some(_)) => unreachable!(),
1825 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1826 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1827 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, ").inner }}").unwrap(),
1828 DeclType::StructImported if is_ref => write!(w, ".inner }}").unwrap(),
1829 DeclType::StructImported if !is_ref => write!(w, ".take_inner()) }}").unwrap(),
1830 DeclType::MirroredEnum if is_ref => write!(w, ".to_native()").unwrap(),
1831 DeclType::MirroredEnum => write!(w, ".into_native()").unwrap(),
1832 DeclType::Trait(_) => {},
1833 _ => unimplemented!(),
1836 pub fn write_from_c_conversion_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1837 self.write_from_c_conversion_suffix_inner(w, t, generics, false, false);
1839 // Note that compared to the above conversion functions, the following two are generally
1840 // significantly undertested:
1841 pub fn write_from_c_conversion_to_ref_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1842 self.write_conversion_inline_intern(w, t, generics, false, false, false, "() /*", true, |_, _| "&local_".to_owned(),
1844 if let Some(conv) = self.from_c_conversion_prefix_from_path(a, b) {
1845 Some(format!("&{}", conv))
1848 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1849 DeclType::StructImported if !is_ref => write!(w, "unsafe {{ &*").unwrap(),
1850 _ => unimplemented!(),
1853 pub fn write_from_c_conversion_to_ref_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1854 self.write_conversion_inline_intern(w, t, generics, false, false, false, "*/", false,
1855 |has_inner, map_str_opt| match (has_inner, map_str_opt) {
1856 (false, Some(map_str)) => format!(".iter(){}.collect::<Vec<_>>()[..]", map_str),
1857 (false, None) => ".iter().collect::<Vec<_>>()[..]".to_owned(),
1858 (true, None) => "[..]".to_owned(),
1859 (true, Some(_)) => unreachable!(),
1861 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1862 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1863 DeclType::StructImported if !is_ref => write!(w, ".inner }}").unwrap(),
1864 _ => unimplemented!(),
1868 fn write_conversion_new_var_intern<'b, W: std::io::Write,
1869 LP: Fn(&str, bool) -> Option<(&str, &str)>,
1870 LC: Fn(&str, bool, Option<&syn::Type>, &syn::Ident, &str) -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)>,
1871 VP: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool),
1872 VS: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool)>
1873 (&self, w: &mut W, ident: &syn::Ident, var: &str, t: &syn::Type, generics: Option<&GenericTypes>,
1874 mut is_ref: bool, mut ptr_for_ref: bool, to_c: bool,
1875 path_lookup: &LP, container_lookup: &LC, var_prefix: &VP, var_suffix: &VS) -> bool {
1877 macro_rules! convert_container {
1878 ($container_type: expr, $args_len: expr, $args_iter: expr) => { {
1879 // For slices (and Options), we refuse to directly map them as is_ref when they
1880 // aren't opaque types containing an inner pointer. This is due to the fact that,
1881 // in both cases, the actual higher-level type is non-is_ref.
1882 let ty_has_inner = if $args_len == 1 {
1883 let ty = $args_iter().next().unwrap();
1884 if $container_type == "Slice" && to_c {
1885 // "To C ptr_for_ref" means "return the regular object with is_owned
1886 // set to false", which is totally what we want in a slice if we're about to
1887 // set ty_has_inner.
1890 if let syn::Type::Reference(t) = ty {
1891 if let syn::Type::Path(p) = &*t.elem {
1892 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1894 } else if let syn::Type::Path(p) = ty {
1895 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1899 // Options get a bunch of special handling, since in general we map Option<>al
1900 // types into the same C type as non-Option-wrapped types. This ends up being
1901 // pretty manual here and most of the below special-cases are for Options.
1902 let mut needs_ref_map = false;
1903 let mut only_contained_type = None;
1904 let mut only_contained_has_inner = false;
1905 let mut contains_slice = false;
1907 only_contained_has_inner = ty_has_inner;
1908 let arg = $args_iter().next().unwrap();
1909 if let syn::Type::Reference(t) = arg {
1910 only_contained_type = Some(&*t.elem);
1911 if let syn::Type::Path(_) = &*t.elem {
1913 } else if let syn::Type::Slice(_) = &*t.elem {
1914 contains_slice = true;
1915 } else { return false; }
1916 // If the inner element contains an inner pointer, we will just use that,
1917 // avoiding the need to map elements to references. Otherwise we'll need to
1918 // do an extra mapping step.
1919 needs_ref_map = !only_contained_has_inner;
1921 only_contained_type = Some(&arg);
1925 if let Some((prefix, conversions, suffix, prefix_location)) = container_lookup(&$container_type, is_ref && ty_has_inner, only_contained_type, ident, var) {
1926 assert_eq!(conversions.len(), $args_len);
1927 write!(w, "let mut local_{}{} = ", ident, if !to_c && needs_ref_map {"_base"} else { "" }).unwrap();
1928 if prefix_location == ContainerPrefixLocation::OutsideConv {
1929 var_prefix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
1931 write!(w, "{}{}", prefix, var).unwrap();
1933 for ((pfx, var_name), (idx, ty)) in conversions.iter().zip($args_iter().enumerate()) {
1934 let mut var = std::io::Cursor::new(Vec::new());
1935 write!(&mut var, "{}", var_name).unwrap();
1936 let var_access = String::from_utf8(var.into_inner()).unwrap();
1938 let conv_ty = if needs_ref_map { only_contained_type.as_ref().unwrap() } else { ty };
1940 write!(w, "{} {{ ", pfx).unwrap();
1941 let new_var_name = format!("{}_{}", ident, idx);
1942 let new_var = self.write_conversion_new_var_intern(w, &format_ident!("{}", new_var_name),
1943 &var_access, conv_ty, generics, contains_slice || (is_ref && ty_has_inner), ptr_for_ref, to_c, path_lookup, container_lookup, var_prefix, var_suffix);
1944 if new_var { write!(w, " ").unwrap(); }
1946 if prefix_location == ContainerPrefixLocation::PerConv {
1947 var_prefix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1948 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
1949 write!(w, "Box::into_raw(Box::new(").unwrap();
1952 write!(w, "{}{}", if contains_slice { "local_" } else { "" }, if new_var { new_var_name } else { var_access }).unwrap();
1953 if prefix_location == ContainerPrefixLocation::PerConv {
1954 var_suffix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1955 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
1956 write!(w, "))").unwrap();
1958 write!(w, " }}").unwrap();
1960 write!(w, "{}", suffix).unwrap();
1961 if prefix_location == ContainerPrefixLocation::OutsideConv {
1962 var_suffix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
1964 write!(w, ";").unwrap();
1965 if !to_c && needs_ref_map {
1966 write!(w, " let mut local_{} = local_{}_base.as_ref()", ident, ident).unwrap();
1968 write!(w, ".map(|a| &a[..])").unwrap();
1970 write!(w, ";").unwrap();
1978 syn::Type::Reference(r) => {
1979 if let syn::Type::Slice(_) = &*r.elem {
1980 self.write_conversion_new_var_intern(w, ident, var, &*r.elem, generics, is_ref, ptr_for_ref, to_c, path_lookup, container_lookup, var_prefix, var_suffix)
1982 self.write_conversion_new_var_intern(w, ident, var, &*r.elem, generics, true, ptr_for_ref, to_c, path_lookup, container_lookup, var_prefix, var_suffix)
1985 syn::Type::Path(p) => {
1986 if p.qself.is_some() {
1989 let resolved_path = self.resolve_path(&p.path, generics);
1990 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1991 return self.write_conversion_new_var_intern(w, ident, var, aliased_type, None, is_ref, ptr_for_ref, to_c, path_lookup, container_lookup, var_prefix, var_suffix);
1993 if self.is_known_container(&resolved_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
1994 if let syn::PathArguments::AngleBracketed(args) = &p.path.segments.iter().next().unwrap().arguments {
1995 convert_container!(resolved_path, args.args.len(), || args.args.iter().map(|arg| {
1996 if let syn::GenericArgument::Type(ty) = arg {
1998 } else { unimplemented!(); }
2000 } else { unimplemented!(); }
2002 if self.is_primitive(&resolved_path) {
2004 } else if let Some(ty_ident) = single_ident_generic_path_to_ident(&p.path) {
2005 if let Some((prefix, suffix)) = path_lookup(&resolved_path, is_ref) {
2006 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
2008 } else if self.types.maybe_resolve_declared(ty_ident).is_some() {
2013 syn::Type::Array(_) => {
2014 // We assume all arrays contain only primitive types.
2015 // This may result in some outputs not compiling.
2018 syn::Type::Slice(s) => {
2019 if let syn::Type::Path(p) = &*s.elem {
2020 let resolved = self.resolve_path(&p.path, generics);
2021 assert!(self.is_primitive(&resolved));
2022 let slice_path = format!("[{}]", resolved);
2023 if let Some((prefix, suffix)) = path_lookup(&slice_path, true) {
2024 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
2027 } else if let syn::Type::Reference(ty) = &*s.elem {
2028 let tyref = [&*ty.elem];
2030 convert_container!("Slice", 1, || tyref.iter().map(|t| *t));
2031 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
2032 } else if let syn::Type::Tuple(t) = &*s.elem {
2033 // When mapping into a temporary new var, we need to own all the underlying objects.
2034 // Thus, we drop any references inside the tuple and convert with non-reference types.
2035 let mut elems = syn::punctuated::Punctuated::new();
2036 for elem in t.elems.iter() {
2037 if let syn::Type::Reference(r) = elem {
2038 elems.push((*r.elem).clone());
2040 elems.push(elem.clone());
2043 let ty = [syn::Type::Tuple(syn::TypeTuple {
2044 paren_token: t.paren_token, elems
2048 convert_container!("Slice", 1, || ty.iter());
2049 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
2050 } else { unimplemented!() }
2052 syn::Type::Tuple(t) => {
2053 if !t.elems.is_empty() {
2054 // We don't (yet) support tuple elements which cannot be converted inline
2055 write!(w, "let (").unwrap();
2056 for idx in 0..t.elems.len() {
2057 if idx != 0 { write!(w, ", ").unwrap(); }
2058 write!(w, "{} orig_{}_{}", if is_ref { "ref" } else { "mut" }, ident, idx).unwrap();
2060 write!(w, ") = {}{}; ", var, if !to_c { ".to_rust()" } else { "" }).unwrap();
2061 // Like other template types, tuples are always mapped as their non-ref
2062 // versions for types which have different ref mappings. Thus, we convert to
2063 // non-ref versions and handle opaque types with inner pointers manually.
2064 for (idx, elem) in t.elems.iter().enumerate() {
2065 if let syn::Type::Path(p) = elem {
2066 let v_name = format!("orig_{}_{}", ident, idx);
2067 let tuple_elem_ident = format_ident!("{}", &v_name);
2068 if self.write_conversion_new_var_intern(w, &tuple_elem_ident, &v_name, elem, generics,
2069 false, ptr_for_ref, to_c,
2070 path_lookup, container_lookup, var_prefix, var_suffix) {
2071 write!(w, " ").unwrap();
2072 // Opaque types with inner pointers shouldn't ever create new stack
2073 // variables, so we don't handle it and just assert that it doesn't
2075 assert!(!self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)));
2079 write!(w, "let mut local_{} = (", ident).unwrap();
2080 for (idx, elem) in t.elems.iter().enumerate() {
2081 let ty_has_inner = {
2083 // "To C ptr_for_ref" means "return the regular object with
2084 // is_owned set to false", which is totally what we want
2085 // if we're about to set ty_has_inner.
2088 if let syn::Type::Reference(t) = elem {
2089 if let syn::Type::Path(p) = &*t.elem {
2090 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2092 } else if let syn::Type::Path(p) = elem {
2093 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2096 if idx != 0 { write!(w, ", ").unwrap(); }
2097 var_prefix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2098 if is_ref && ty_has_inner {
2099 // For ty_has_inner, the regular var_prefix mapping will take a
2100 // reference, so deref once here to make sure we keep the original ref.
2101 write!(w, "*").unwrap();
2103 write!(w, "orig_{}_{}", ident, idx).unwrap();
2104 if is_ref && !ty_has_inner {
2105 // If we don't have an inner variable's reference to maintain, just
2106 // hope the type is Clonable and use that.
2107 write!(w, ".clone()").unwrap();
2109 var_suffix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2111 write!(w, "){};", if to_c { ".into()" } else { "" }).unwrap();
2115 _ => unimplemented!(),
2119 pub fn write_to_c_conversion_new_var_inner<W: std::io::Write>(&self, w: &mut W, ident: &syn::Ident, var_access: &str, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) -> bool {
2120 self.write_conversion_new_var_intern(w, ident, var_access, t, generics, false, ptr_for_ref, true,
2121 &|a, b| self.to_c_conversion_new_var_from_path(a, b),
2122 &|a, b, c, d, e| self.to_c_conversion_container_new_var(generics, a, b, c, d, e),
2123 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
2124 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_prefix_inner(a, b, c, d, e, f),
2125 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_suffix_inner(a, b, c, d, e, f))
2127 pub fn write_to_c_conversion_new_var<W: std::io::Write>(&self, w: &mut W, ident: &syn::Ident, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) -> bool {
2128 self.write_to_c_conversion_new_var_inner(w, ident, &format!("{}", ident), t, generics, ptr_for_ref)
2130 pub fn write_from_c_conversion_new_var<W: std::io::Write>(&self, w: &mut W, ident: &syn::Ident, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
2131 self.write_conversion_new_var_intern(w, ident, &format!("{}", ident), t, generics, false, false, false,
2132 &|a, b| self.from_c_conversion_new_var_from_path(a, b),
2133 &|a, b, c, d, e| self.from_c_conversion_container_new_var(generics, a, b, c, d, e),
2134 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
2135 &|a, b, c, d, e, _f| self.write_from_c_conversion_prefix_inner(a, b, c, d, e),
2136 &|a, b, c, d, e, _f| self.write_from_c_conversion_suffix_inner(a, b, c, d, e))
2139 // ******************************************************
2140 // *** C Container Type Equivalent and alias Printing ***
2141 // ******************************************************
2143 fn write_template_generics<'b, W: std::io::Write>(&self, w: &mut W, args: &mut dyn Iterator<Item=&'b syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
2144 for (idx, t) in args.enumerate() {
2146 write!(w, ", ").unwrap();
2148 if let syn::Type::Reference(r_arg) = t {
2149 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2151 if !self.write_c_type_intern(w, &*r_arg.elem, generics, false, false, false) { return false; }
2153 // While write_c_type_intern, above is correct, we don't want to blindly convert a
2154 // reference to something stupid, so check that the container is either opaque or a
2155 // predefined type (currently only Transaction).
2156 if let syn::Type::Path(p_arg) = &*r_arg.elem {
2157 let resolved = self.resolve_path(&p_arg.path, generics);
2158 assert!(self.crate_types.opaques.get(&resolved).is_some() ||
2159 self.c_type_from_path(&resolved, true, true).is_some(), "Template generics should be opaque or have a predefined mapping");
2160 } else { unimplemented!(); }
2161 } else if let syn::Type::Path(p_arg) = t {
2162 if let Some(resolved) = self.maybe_resolve_path(&p_arg.path, generics) {
2163 if !self.is_primitive(&resolved) {
2164 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2167 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2169 if !self.write_c_type_intern(w, t, generics, false, false, false) { return false; }
2171 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2172 if !self.write_c_type_intern(w, t, generics, false, false, false) { return false; }
2177 fn check_create_container(&self, mangled_container: String, container_type: &str, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
2178 if !self.crate_types.templates_defined.borrow().get(&mangled_container).is_some() {
2179 let mut created_container: Vec<u8> = Vec::new();
2181 if container_type == "Result" {
2182 let mut a_ty: Vec<u8> = Vec::new();
2183 if let syn::Type::Tuple(tup) = args.iter().next().unwrap() {
2184 if tup.elems.is_empty() {
2185 write!(&mut a_ty, "()").unwrap();
2187 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
2190 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
2193 let mut b_ty: Vec<u8> = Vec::new();
2194 if let syn::Type::Tuple(tup) = args.iter().skip(1).next().unwrap() {
2195 if tup.elems.is_empty() {
2196 write!(&mut b_ty, "()").unwrap();
2198 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
2201 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
2204 let ok_str = String::from_utf8(a_ty).unwrap();
2205 let err_str = String::from_utf8(b_ty).unwrap();
2206 let is_clonable = self.is_clonable(&ok_str) && self.is_clonable(&err_str);
2207 write_result_block(&mut created_container, &mangled_container, &ok_str, &err_str, is_clonable);
2209 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2211 } else if container_type == "Vec" {
2212 let mut a_ty: Vec<u8> = Vec::new();
2213 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2214 let ty = String::from_utf8(a_ty).unwrap();
2215 let is_clonable = self.is_clonable(&ty);
2216 write_vec_block(&mut created_container, &mangled_container, &ty, is_clonable);
2218 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2220 } else if container_type.ends_with("Tuple") {
2221 let mut tuple_args = Vec::new();
2222 let mut is_clonable = true;
2223 for arg in args.iter() {
2224 let mut ty: Vec<u8> = Vec::new();
2225 if !self.write_template_generics(&mut ty, &mut [arg].iter().map(|t| **t), generics, is_ref) { return false; }
2226 let ty_str = String::from_utf8(ty).unwrap();
2227 if !self.is_clonable(&ty_str) {
2228 is_clonable = false;
2230 tuple_args.push(ty_str);
2232 write_tuple_block(&mut created_container, &mangled_container, &tuple_args, is_clonable);
2234 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2236 } else if container_type == "Option" {
2237 let mut a_ty: Vec<u8> = Vec::new();
2238 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2239 let ty = String::from_utf8(a_ty).unwrap();
2240 let is_clonable = self.is_clonable(&ty);
2241 write_option_block(&mut created_container, &mangled_container, &ty, is_clonable);
2243 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2248 self.crate_types.write_new_template(mangled_container.clone(), true, &created_container);
2252 fn path_to_generic_args(path: &syn::Path) -> Vec<&syn::Type> {
2253 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().next().unwrap().arguments {
2254 args.args.iter().map(|gen| if let syn::GenericArgument::Type(t) = gen { t } else { unimplemented!() }).collect()
2255 } else { unimplemented!(); }
2257 fn write_c_mangled_container_path_intern<W: std::io::Write>
2258 (&self, w: &mut W, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, ident: &str, is_ref: bool, is_mut: bool, ptr_for_ref: bool, in_type: bool) -> bool {
2259 let mut mangled_type: Vec<u8> = Vec::new();
2260 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2261 write!(w, "C{}_", ident).unwrap();
2262 write!(mangled_type, "C{}_", ident).unwrap();
2263 } else { assert_eq!(args.len(), 1); }
2264 for arg in args.iter() {
2265 macro_rules! write_path {
2266 ($p_arg: expr, $extra_write: expr) => {
2267 if let Some(subtype) = self.maybe_resolve_path(&$p_arg.path, generics) {
2268 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2270 if self.c_type_has_inner_from_path(&subtype) {
2271 if !self.write_c_path_intern(w, &$p_arg.path, generics, is_ref, is_mut, ptr_for_ref) { return false; }
2273 if let Some(arr_ty) = self.is_real_type_array(&subtype) {
2274 if !self.write_c_type_intern(w, &arr_ty, generics, false, true, false) { return false; }
2276 // Option<T> needs to be converted to a *mut T, ie mut ptr-for-ref
2277 if !self.write_c_path_intern(w, &$p_arg.path, generics, true, true, true) { return false; }
2281 write!(w, "{}", $p_arg.path.segments.last().unwrap().ident).unwrap();
2283 } else if self.is_known_container(&subtype, is_ref) || self.is_path_transparent_container(&$p_arg.path, generics, is_ref) {
2284 if !self.write_c_mangled_container_path_intern(w, Self::path_to_generic_args(&$p_arg.path), generics,
2285 &subtype, is_ref, is_mut, ptr_for_ref, true) {
2288 self.write_c_mangled_container_path_intern(&mut mangled_type, Self::path_to_generic_args(&$p_arg.path),
2289 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2290 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2291 self.write_c_mangled_container_path_intern(w2, Self::path_to_generic_args(&$p_arg.path),
2292 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2295 let id = subtype.rsplitn(2, ':').next().unwrap(); // Get the "Base" name of the resolved type
2296 write!(w, "{}", id).unwrap();
2297 write!(mangled_type, "{}", id).unwrap();
2298 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2299 write!(w2, "{}", id).unwrap();
2302 } else { return false; }
2305 if let syn::Type::Tuple(tuple) = arg {
2306 if tuple.elems.len() == 0 {
2307 write!(w, "None").unwrap();
2308 write!(mangled_type, "None").unwrap();
2310 let mut mangled_tuple_type: Vec<u8> = Vec::new();
2312 // Figure out what the mangled type should look like. To disambiguate
2313 // ((A, B), C) and (A, B, C) we prefix the generic args with a _ and suffix
2314 // them with a Z. Ideally we wouldn't use Z, but not many special chars are
2315 // available for use in type names.
2316 write!(w, "C{}Tuple_", tuple.elems.len()).unwrap();
2317 write!(mangled_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2318 write!(mangled_tuple_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2319 for elem in tuple.elems.iter() {
2320 if let syn::Type::Path(p) = elem {
2321 write_path!(p, Some(&mut mangled_tuple_type));
2322 } else if let syn::Type::Reference(refelem) = elem {
2323 if let syn::Type::Path(p) = &*refelem.elem {
2324 write_path!(p, Some(&mut mangled_tuple_type));
2325 } else { return false; }
2326 } else { return false; }
2328 write!(w, "Z").unwrap();
2329 write!(mangled_type, "Z").unwrap();
2330 write!(mangled_tuple_type, "Z").unwrap();
2331 if !self.check_create_container(String::from_utf8(mangled_tuple_type).unwrap(),
2332 &format!("{}Tuple", tuple.elems.len()), tuple.elems.iter().collect(), generics, is_ref) {
2336 } else if let syn::Type::Path(p_arg) = arg {
2337 write_path!(p_arg, None);
2338 } else if let syn::Type::Reference(refty) = arg {
2339 if let syn::Type::Path(p_arg) = &*refty.elem {
2340 write_path!(p_arg, None);
2341 } else if let syn::Type::Slice(_) = &*refty.elem {
2342 // write_c_type will actually do exactly what we want here, we just need to
2343 // make it a pointer so that its an option. Note that we cannot always convert
2344 // the Vec-as-slice (ie non-ref types) containers, so sometimes need to be able
2345 // to edit it, hence we use *mut here instead of *const.
2346 if args.len() != 1 { return false; }
2347 write!(w, "*mut ").unwrap();
2348 self.write_c_type(w, arg, None, true);
2349 } else { return false; }
2350 } else if let syn::Type::Array(a) = arg {
2351 if let syn::Type::Path(p_arg) = &*a.elem {
2352 let resolved = self.resolve_path(&p_arg.path, generics);
2353 if !self.is_primitive(&resolved) { return false; }
2354 if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(len), .. }) = &a.len {
2355 if self.c_type_from_path(&format!("[{}; {}]", resolved, len.base10_digits()), is_ref, ptr_for_ref).is_none() { return false; }
2356 write!(w, "_{}{}", resolved, len.base10_digits()).unwrap();
2357 write!(mangled_type, "_{}{}", resolved, len.base10_digits()).unwrap();
2358 } else { return false; }
2359 } else { return false; }
2360 } else { return false; }
2362 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) { return true; }
2363 // Push the "end of type" Z
2364 write!(w, "Z").unwrap();
2365 write!(mangled_type, "Z").unwrap();
2367 // Make sure the type is actually defined:
2368 self.check_create_container(String::from_utf8(mangled_type).unwrap(), ident, args, generics, is_ref)
2370 fn write_c_mangled_container_path<W: std::io::Write>(&self, w: &mut W, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, ident: &str, is_ref: bool, is_mut: bool, ptr_for_ref: bool) -> bool {
2371 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2372 write!(w, "{}::", Self::generated_container_path()).unwrap();
2374 self.write_c_mangled_container_path_intern(w, args, generics, ident, is_ref, is_mut, ptr_for_ref, false)
2376 pub fn get_c_mangled_container_type(&self, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, template_name: &str) -> Option<String> {
2377 let mut out = Vec::new();
2378 if !self.write_c_mangled_container_path(&mut out, args, generics, template_name, false, false, false) {
2381 Some(String::from_utf8(out).unwrap())
2384 // **********************************
2385 // *** C Type Equivalent Printing ***
2386 // **********************************
2388 fn write_c_path_intern<W: std::io::Write>(&self, w: &mut W, path: &syn::Path, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool) -> bool {
2389 let full_path = match self.maybe_resolve_path(&path, generics) {
2390 Some(path) => path, None => return false };
2391 if let Some(c_type) = self.c_type_from_path(&full_path, is_ref, ptr_for_ref) {
2392 write!(w, "{}", c_type).unwrap();
2394 } else if self.crate_types.traits.get(&full_path).is_some() {
2395 if is_ref && ptr_for_ref {
2396 write!(w, "*{} crate::{}", if is_mut { "mut" } else { "const" }, full_path).unwrap();
2398 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2400 write!(w, "crate::{}", full_path).unwrap();
2403 } else if self.crate_types.opaques.get(&full_path).is_some() || self.crate_types.mirrored_enums.get(&full_path).is_some() {
2404 if is_ref && ptr_for_ref {
2405 // ptr_for_ref implies we're returning the object, which we can't really do for
2406 // opaque or mirrored types without box'ing them, which is quite a waste, so return
2407 // the actual object itself (for opaque types we'll set the pointer to the actual
2408 // type and note that its a reference).
2409 write!(w, "crate::{}", full_path).unwrap();
2411 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2413 write!(w, "crate::{}", full_path).unwrap();
2420 fn write_c_type_intern<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool) -> bool {
2422 syn::Type::Path(p) => {
2423 if p.qself.is_some() {
2426 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
2427 if self.is_known_container(&full_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
2428 return self.write_c_mangled_container_path(w, Self::path_to_generic_args(&p.path), generics, &full_path, is_ref, is_mut, ptr_for_ref);
2430 if let Some(aliased_type) = self.crate_types.type_aliases.get(&full_path).cloned() {
2431 return self.write_c_type_intern(w, &aliased_type, None, is_ref, is_mut, ptr_for_ref);
2434 self.write_c_path_intern(w, &p.path, generics, is_ref, is_mut, ptr_for_ref)
2436 syn::Type::Reference(r) => {
2437 self.write_c_type_intern(w, &*r.elem, generics, true, r.mutability.is_some(), ptr_for_ref)
2439 syn::Type::Array(a) => {
2440 if is_ref && is_mut {
2441 write!(w, "*mut [").unwrap();
2442 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2444 write!(w, "*const [").unwrap();
2445 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2447 let mut typecheck = Vec::new();
2448 if !self.write_c_type_intern(&mut typecheck, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2449 if typecheck[..] != ['u' as u8, '8' as u8] { return false; }
2451 if let syn::Expr::Lit(l) = &a.len {
2452 if let syn::Lit::Int(i) = &l.lit {
2454 if let Some(ty) = self.c_type_from_path(&format!("[u8; {}]", i.base10_digits()), false, ptr_for_ref) {
2455 write!(w, "{}", ty).unwrap();
2459 write!(w, "; {}]", i).unwrap();
2465 syn::Type::Slice(s) => {
2466 if !is_ref || is_mut { return false; }
2467 if let syn::Type::Path(p) = &*s.elem {
2468 let resolved = self.resolve_path(&p.path, generics);
2469 if self.is_primitive(&resolved) {
2470 write!(w, "{}::{}slice", Self::container_templ_path(), resolved).unwrap();
2473 } else if let syn::Type::Reference(r) = &*s.elem {
2474 if let syn::Type::Path(p) = &*r.elem {
2475 // Slices with "real types" inside are mapped as the equivalent non-ref Vec
2476 let resolved = self.resolve_path(&p.path, generics);
2477 let mangled_container = if let Some(ident) = self.crate_types.opaques.get(&resolved) {
2478 format!("CVec_{}Z", ident)
2479 } else if let Some(en) = self.crate_types.mirrored_enums.get(&resolved) {
2480 format!("CVec_{}Z", en.ident)
2481 } else if let Some(id) = p.path.get_ident() {
2482 format!("CVec_{}Z", id)
2483 } else { return false; };
2484 write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
2485 self.check_create_container(mangled_container, "Vec", vec![&*r.elem], generics, false)
2487 } else if let syn::Type::Tuple(_) = &*s.elem {
2488 let mut args = syn::punctuated::Punctuated::<_, syn::token::Comma>::new();
2489 args.push(syn::GenericArgument::Type((*s.elem).clone()));
2490 let mut segments = syn::punctuated::Punctuated::new();
2491 segments.push(parse_quote!(Vec<#args>));
2492 self.write_c_type_intern(w, &syn::Type::Path(syn::TypePath { qself: None, path: syn::Path { leading_colon: None, segments } }), generics, false, is_mut, ptr_for_ref)
2495 syn::Type::Tuple(t) => {
2496 if t.elems.len() == 0 {
2499 self.write_c_mangled_container_path(w, t.elems.iter().collect(), generics,
2500 &format!("{}Tuple", t.elems.len()), is_ref, is_mut, ptr_for_ref)
2506 pub fn write_c_type<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) {
2507 assert!(self.write_c_type_intern(w, t, generics, false, false, ptr_for_ref));
2509 pub fn understood_c_path(&self, p: &syn::Path) -> bool {
2510 if p.leading_colon.is_some() { return false; }
2511 self.write_c_path_intern(&mut std::io::sink(), p, None, false, false, false)
2513 pub fn understood_c_type(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
2514 self.write_c_type_intern(&mut std::io::sink(), t, generics, false, false, false)