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>)>,
170 default_generics: HashMap<&'a syn::Ident, (&'a syn::Type, syn::Type)>,
172 impl<'a, 'p: 'a> GenericTypes<'a, 'p> {
173 pub fn new(self_ty: Option<(String, &'a syn::Path)>) -> Self {
174 Self { self_ty, parent: None, typed_generics: HashMap::new(), default_generics: HashMap::new(), }
177 /// push a new context onto the stack, allowing for a new set of generics to be learned which
178 /// will override any lower contexts, but which will still fall back to resoltion via lower
180 pub fn push_ctx<'c>(&'c self) -> GenericTypes<'a, 'c> {
181 GenericTypes { self_ty: None, parent: Some(self), typed_generics: HashMap::new(), default_generics: HashMap::new(), }
184 /// Learn the generics in generics in the current context, given a TypeResolver.
185 pub fn learn_generics<'b, 'c>(&mut self, generics: &'a syn::Generics, types: &'b TypeResolver<'a, 'c>) -> bool {
186 // First learn simple generics...
187 for generic in generics.params.iter() {
189 syn::GenericParam::Type(type_param) => {
190 let mut non_lifetimes_processed = false;
191 for bound in type_param.bounds.iter() {
192 if let syn::TypeParamBound::Trait(trait_bound) = bound {
193 if let Some(ident) = single_ident_generic_path_to_ident(&trait_bound.path) {
194 match &format!("{}", ident) as &str { "Send" => continue, "Sync" => continue, _ => {} }
196 if path_matches_nongeneric(&trait_bound.path, &["core", "clone", "Clone"]) { continue; }
198 assert_simple_bound(&trait_bound);
199 if let Some(mut path) = types.maybe_resolve_path(&trait_bound.path, None) {
200 if types.skip_path(&path) { continue; }
201 if path == "Sized" { continue; }
202 if non_lifetimes_processed { return false; }
203 non_lifetimes_processed = true;
204 let new_ident = if path != "std::ops::Deref" {
205 path = "crate::".to_string() + &path;
206 Some(&trait_bound.path)
208 self.typed_generics.insert(&type_param.ident, (path, new_ident));
209 } else { return false; }
212 if let Some(default) = type_param.default.as_ref() {
213 assert!(type_param.bounds.is_empty());
214 self.default_generics.insert(&type_param.ident, (default, parse_quote!(&#default)));
220 // Then find generics where we are required to pass a Deref<Target=X> and pretend its just X.
221 if let Some(wh) = &generics.where_clause {
222 for pred in wh.predicates.iter() {
223 if let syn::WherePredicate::Type(t) = pred {
224 if let syn::Type::Path(p) = &t.bounded_ty {
225 if p.qself.is_some() { return false; }
226 if p.path.leading_colon.is_some() { return false; }
227 let mut p_iter = p.path.segments.iter();
228 if let Some(gen) = self.typed_generics.get_mut(&p_iter.next().unwrap().ident) {
229 if gen.0 != "std::ops::Deref" { return false; }
230 if &format!("{}", p_iter.next().unwrap().ident) != "Target" { return false; }
232 let mut non_lifetimes_processed = false;
233 for bound in t.bounds.iter() {
234 if let syn::TypeParamBound::Trait(trait_bound) = bound {
235 if let Some(id) = trait_bound.path.get_ident() {
236 if format!("{}", id) == "Sized" { continue; }
238 if non_lifetimes_processed { return false; }
239 non_lifetimes_processed = true;
240 assert_simple_bound(&trait_bound);
241 *gen = ("crate::".to_string() + &types.resolve_path(&trait_bound.path, None),
242 Some(&trait_bound.path));
245 } else { return false; }
246 } else { return false; }
250 for (_, (_, ident)) in self.typed_generics.iter() {
251 if ident.is_none() { return false; }
256 /// Learn the associated types from the trait in the current context.
257 pub fn learn_associated_types<'b, 'c>(&mut self, t: &'a syn::ItemTrait, types: &'b TypeResolver<'a, 'c>) {
258 for item in t.items.iter() {
260 &syn::TraitItem::Type(ref t) => {
261 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
262 let mut bounds_iter = t.bounds.iter();
263 match bounds_iter.next().unwrap() {
264 syn::TypeParamBound::Trait(tr) => {
265 assert_simple_bound(&tr);
266 if let Some(mut path) = types.maybe_resolve_path(&tr.path, None) {
267 if types.skip_path(&path) { continue; }
268 // In general we handle Deref<Target=X> as if it were just X (and
269 // implement Deref<Target=Self> for relevant types). We don't
270 // bother to implement it for associated types, however, so we just
271 // ignore such bounds.
272 let new_ident = if path != "std::ops::Deref" {
273 path = "crate::".to_string() + &path;
276 self.typed_generics.insert(&t.ident, (path, new_ident));
277 } else { unimplemented!(); }
279 _ => unimplemented!(),
281 if bounds_iter.next().is_some() { unimplemented!(); }
288 /// Attempt to resolve an Ident as a generic parameter and return the full path.
289 pub fn maybe_resolve_ident<'b>(&'b self, ident: &syn::Ident) -> Option<&'b String> {
290 if let Some(ty) = &self.self_ty {
291 if format!("{}", ident) == "Self" {
295 if let Some(res) = self.typed_generics.get(ident).map(|(a, _)| a) {
298 if let Some(parent) = self.parent {
299 parent.maybe_resolve_ident(ident)
305 /// Attempt to resolve a Path as a generic parameter and return the full path. as both a string
307 pub fn maybe_resolve_path<'b>(&'b self, path: &syn::Path) -> Option<(&'b String, &'a syn::Path)> {
308 if let Some(ident) = path.get_ident() {
309 if let Some(ty) = &self.self_ty {
310 if format!("{}", ident) == "Self" {
311 return Some((&ty.0, ty.1));
314 if let Some(res) = self.typed_generics.get(ident).map(|(a, b)| (a, b.unwrap())) {
318 // Associated types are usually specified as "Self::Generic", so we check for that
320 let mut it = path.segments.iter();
321 if path.segments.len() == 2 && format!("{}", it.next().unwrap().ident) == "Self" {
322 let ident = &it.next().unwrap().ident;
323 if let Some(res) = self.typed_generics.get(ident).map(|(a, b)| (a, b.unwrap())) {
328 if let Some(parent) = self.parent {
329 parent.maybe_resolve_path(path)
336 trait ResolveType<'a> { fn resolve_type(&'a self, ty: &'a syn::Type) -> &'a syn::Type; }
337 impl<'a, 'b, 'c: 'a + 'b> ResolveType<'c> for Option<&GenericTypes<'a, 'b>> {
338 fn resolve_type(&'c self, ty: &'c syn::Type) -> &'c syn::Type {
339 if let Some(us) = self {
341 syn::Type::Path(p) => {
342 if let Some(ident) = p.path.get_ident() {
343 if let Some((ty, _)) = us.default_generics.get(ident) {
348 syn::Type::Reference(syn::TypeReference { elem, .. }) => {
349 if let syn::Type::Path(p) = &**elem {
350 if let Some(ident) = p.path.get_ident() {
351 if let Some((_, refty)) = us.default_generics.get(ident) {
364 #[derive(Clone, PartialEq)]
365 // The type of declaration and the object itself
366 pub enum DeclType<'a> {
368 Trait(&'a syn::ItemTrait),
374 pub struct ImportResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
375 crate_name: &'mod_lifetime str,
376 dependencies: &'mod_lifetime HashSet<syn::Ident>,
377 module_path: &'mod_lifetime str,
378 imports: HashMap<syn::Ident, (String, syn::Path)>,
379 declared: HashMap<syn::Ident, DeclType<'crate_lft>>,
380 priv_modules: HashSet<syn::Ident>,
382 impl<'mod_lifetime, 'crate_lft: 'mod_lifetime> ImportResolver<'mod_lifetime, 'crate_lft> {
383 fn process_use_intern(crate_name: &str, module_path: &str, dependencies: &HashSet<syn::Ident>, imports: &mut HashMap<syn::Ident, (String, syn::Path)>,
384 u: &syn::UseTree, partial_path: &str, mut path: syn::punctuated::Punctuated<syn::PathSegment, syn::token::Colon2>) {
387 macro_rules! push_path {
388 ($ident: expr, $path_suffix: expr) => {
389 if partial_path == "" && format!("{}", $ident) == "super" {
390 let mut mod_iter = module_path.rsplitn(2, "::");
391 mod_iter.next().unwrap();
392 let super_mod = mod_iter.next().unwrap();
393 new_path = format!("{}{}", super_mod, $path_suffix);
394 assert_eq!(path.len(), 0);
395 for module in super_mod.split("::") {
396 path.push(syn::PathSegment { ident: syn::Ident::new(module, Span::call_site()), arguments: syn::PathArguments::None });
398 } else if partial_path == "" && !dependencies.contains(&$ident) {
399 new_path = format!("{}::{}{}", crate_name, $ident, $path_suffix);
400 let crate_name_ident = format_ident!("{}", crate_name);
401 path.push(parse_quote!(#crate_name_ident));
403 new_path = format!("{}{}{}", partial_path, $ident, $path_suffix);
406 path.push(parse_quote!(#ident));
410 syn::UseTree::Path(p) => {
411 push_path!(p.ident, "::");
412 Self::process_use_intern(crate_name, module_path, dependencies, imports, &p.tree, &new_path, path);
414 syn::UseTree::Name(n) => {
415 push_path!(n.ident, "");
416 imports.insert(n.ident.clone(), (new_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
418 syn::UseTree::Group(g) => {
419 for i in g.items.iter() {
420 Self::process_use_intern(crate_name, module_path, dependencies, imports, i, partial_path, path.clone());
423 syn::UseTree::Rename(r) => {
424 push_path!(r.ident, "");
425 imports.insert(r.rename.clone(), (new_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
427 syn::UseTree::Glob(_) => {
428 eprintln!("Ignoring * use for {} - this may result in resolution failures", partial_path);
433 fn process_use(crate_name: &str, module_path: &str, dependencies: &HashSet<syn::Ident>, imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::ItemUse) {
434 if let syn::Visibility::Public(_) = u.vis {
435 // We actually only use these for #[cfg(fuzztarget)]
436 eprintln!("Ignoring pub(use) tree!");
439 if u.leading_colon.is_some() { eprintln!("Ignoring leading-colon use!"); return; }
440 Self::process_use_intern(crate_name, module_path, dependencies, imports, &u.tree, "", syn::punctuated::Punctuated::new());
443 fn insert_primitive(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, id: &str) {
444 let ident = format_ident!("{}", id);
445 let path = parse_quote!(#ident);
446 imports.insert(ident, (id.to_owned(), path));
449 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 {
450 Self::from_borrowed_items(crate_name, dependencies, module_path, &contents.iter().map(|a| a).collect::<Vec<_>>())
452 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 {
453 let mut imports = HashMap::new();
454 // Add primitives to the "imports" list:
455 Self::insert_primitive(&mut imports, "bool");
456 Self::insert_primitive(&mut imports, "u64");
457 Self::insert_primitive(&mut imports, "u32");
458 Self::insert_primitive(&mut imports, "u16");
459 Self::insert_primitive(&mut imports, "u8");
460 Self::insert_primitive(&mut imports, "usize");
461 Self::insert_primitive(&mut imports, "str");
462 Self::insert_primitive(&mut imports, "String");
464 // These are here to allow us to print native Rust types in trait fn impls even if we don't
466 Self::insert_primitive(&mut imports, "Result");
467 Self::insert_primitive(&mut imports, "Vec");
468 Self::insert_primitive(&mut imports, "Option");
470 let mut declared = HashMap::new();
471 let mut priv_modules = HashSet::new();
473 for item in contents.iter() {
475 syn::Item::Use(u) => Self::process_use(crate_name, module_path, dependencies, &mut imports, &u),
476 syn::Item::Struct(s) => {
477 if let syn::Visibility::Public(_) = s.vis {
478 match export_status(&s.attrs) {
479 ExportStatus::Export => { declared.insert(s.ident.clone(), DeclType::StructImported); },
480 ExportStatus::NoExport => { declared.insert(s.ident.clone(), DeclType::StructIgnored); },
481 ExportStatus::TestOnly => continue,
485 syn::Item::Type(t) if export_status(&t.attrs) == ExportStatus::Export => {
486 if let syn::Visibility::Public(_) = t.vis {
487 let mut process_alias = true;
488 for tok in t.generics.params.iter() {
489 if let syn::GenericParam::Lifetime(_) = tok {}
490 else { process_alias = false; }
493 declared.insert(t.ident.clone(), DeclType::StructImported);
497 syn::Item::Enum(e) => {
498 if let syn::Visibility::Public(_) = e.vis {
499 match export_status(&e.attrs) {
500 ExportStatus::Export if is_enum_opaque(e) => { declared.insert(e.ident.clone(), DeclType::EnumIgnored); },
501 ExportStatus::Export => { declared.insert(e.ident.clone(), DeclType::MirroredEnum); },
506 syn::Item::Trait(t) if export_status(&t.attrs) == ExportStatus::Export => {
507 if let syn::Visibility::Public(_) = t.vis {
508 declared.insert(t.ident.clone(), DeclType::Trait(t));
511 syn::Item::Mod(m) => {
512 priv_modules.insert(m.ident.clone());
518 Self { crate_name, dependencies, module_path, imports, declared, priv_modules }
521 pub fn get_declared_type(&self, ident: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
522 self.declared.get(ident)
525 pub fn maybe_resolve_declared(&self, id: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
526 self.declared.get(id)
529 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
530 if let Some((imp, _)) = self.imports.get(id) {
532 } else if self.declared.get(id).is_some() {
533 Some(self.module_path.to_string() + "::" + &format!("{}", id))
537 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
538 if let Some((imp, _)) = self.imports.get(id) {
540 } else if let Some(decl_type) = self.declared.get(id) {
542 DeclType::StructIgnored => None,
543 _ => Some(self.module_path.to_string() + "::" + &format!("{}", id)),
548 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
549 let p = if let Some(gen_types) = generics {
550 if let Some((_, synpath)) = gen_types.maybe_resolve_path(p_arg) {
555 if p.leading_colon.is_some() {
556 let mut res: String = p.segments.iter().enumerate().map(|(idx, seg)| {
557 format!("{}{}", if idx == 0 { "" } else { "::" }, seg.ident)
559 let firstseg = p.segments.iter().next().unwrap();
560 if !self.dependencies.contains(&firstseg.ident) {
561 res = self.crate_name.to_owned() + "::" + &res;
564 } else if let Some(id) = p.get_ident() {
565 self.maybe_resolve_ident(id)
567 if p.segments.len() == 1 {
568 let seg = p.segments.iter().next().unwrap();
569 return self.maybe_resolve_ident(&seg.ident);
571 let mut seg_iter = p.segments.iter();
572 let first_seg = seg_iter.next().unwrap();
573 let remaining: String = seg_iter.map(|seg| {
574 format!("::{}", seg.ident)
576 let first_seg_str = format!("{}", first_seg.ident);
577 if let Some((imp, _)) = self.imports.get(&first_seg.ident) {
579 Some(imp.clone() + &remaining)
583 } else if let Some(_) = self.priv_modules.get(&first_seg.ident) {
584 Some(format!("{}::{}{}", self.module_path, first_seg.ident, remaining))
585 } else if first_seg_str == "std" || first_seg_str == "core" || self.dependencies.contains(&first_seg.ident) {
586 Some(first_seg_str + &remaining)
591 /// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern)
592 pub fn resolve_imported_refs(&self, mut ty: syn::Type) -> syn::Type {
594 syn::Type::Path(p) => {
595 if p.path.segments.len() != 1 { unimplemented!(); }
596 let mut args = p.path.segments[0].arguments.clone();
597 if let syn::PathArguments::AngleBracketed(ref mut generics) = &mut args {
598 for arg in generics.args.iter_mut() {
599 if let syn::GenericArgument::Type(ref mut t) = arg {
600 *t = self.resolve_imported_refs(t.clone());
604 if let Some((_, newpath)) = self.imports.get(single_ident_generic_path_to_ident(&p.path).unwrap()) {
605 p.path = newpath.clone();
607 p.path.segments[0].arguments = args;
609 syn::Type::Reference(r) => {
610 r.elem = Box::new(self.resolve_imported_refs((*r.elem).clone()));
612 syn::Type::Slice(s) => {
613 s.elem = Box::new(self.resolve_imported_refs((*s.elem).clone()));
615 syn::Type::Tuple(t) => {
616 for e in t.elems.iter_mut() {
617 *e = self.resolve_imported_refs(e.clone());
620 _ => unimplemented!(),
626 // templates_defined is walked to write the C++ header, so if we use the default hashing it get
627 // reordered on each genbindings run. Instead, we use SipHasher (which defaults to 0-keys) so that
628 // the sorting is stable across runs. It is deprecated, but the "replacement" doesn't actually
629 // accomplish the same goals, so we just ignore it.
631 pub type NonRandomHash = hash::BuildHasherDefault<hash::SipHasher>;
634 pub struct ASTModule {
635 pub attrs: Vec<syn::Attribute>,
636 pub items: Vec<syn::Item>,
637 pub submods: Vec<String>,
639 /// A struct containing the syn::File AST for each file in the crate.
640 pub struct FullLibraryAST {
641 pub modules: HashMap<String, ASTModule, NonRandomHash>,
642 pub dependencies: HashSet<syn::Ident>,
644 impl FullLibraryAST {
645 fn load_module(&mut self, module: String, attrs: Vec<syn::Attribute>, mut items: Vec<syn::Item>) {
646 let mut non_mod_items = Vec::with_capacity(items.len());
647 let mut submods = Vec::with_capacity(items.len());
648 for item in items.drain(..) {
650 syn::Item::Mod(m) if m.content.is_some() => {
651 if export_status(&m.attrs) == ExportStatus::Export {
652 if let syn::Visibility::Public(_) = m.vis {
653 let modident = format!("{}", m.ident);
654 let modname = if module != "" {
655 module.clone() + "::" + &modident
659 self.load_module(modname, m.attrs, m.content.unwrap().1);
660 submods.push(modident);
662 non_mod_items.push(syn::Item::Mod(m));
666 syn::Item::Mod(_) => panic!("--pretty=expanded output should never have non-body modules"),
667 syn::Item::ExternCrate(c) => {
668 if export_status(&c.attrs) == ExportStatus::Export {
669 self.dependencies.insert(c.ident);
672 _ => { non_mod_items.push(item); }
675 self.modules.insert(module, ASTModule { attrs, items: non_mod_items, submods });
678 pub fn load_lib(lib: syn::File) -> Self {
679 assert_eq!(export_status(&lib.attrs), ExportStatus::Export);
680 let mut res = Self { modules: HashMap::default(), dependencies: HashSet::new() };
681 res.load_module("".to_owned(), lib.attrs, lib.items);
686 /// List of manually-generated types which are clonable
687 fn initial_clonable_types() -> HashSet<String> {
688 let mut res = HashSet::new();
689 res.insert("crate::c_types::u5".to_owned());
693 /// Top-level struct tracking everything which has been defined while walking the crate.
694 pub struct CrateTypes<'a> {
695 /// This may contain structs or enums, but only when either is mapped as
696 /// struct X { inner: *mut originalX, .. }
697 pub opaques: HashMap<String, &'a syn::Ident>,
698 /// Enums which are mapped as C enums with conversion functions
699 pub mirrored_enums: HashMap<String, &'a syn::ItemEnum>,
700 /// Traits which are mapped as a pointer + jump table
701 pub traits: HashMap<String, &'a syn::ItemTrait>,
702 /// Aliases from paths to some other Type
703 pub type_aliases: HashMap<String, syn::Type>,
704 /// Value is an alias to Key (maybe with some generics)
705 pub reverse_alias_map: HashMap<String, Vec<(syn::Path, syn::PathArguments)>>,
706 /// Template continer types defined, map from mangled type name -> whether a destructor fn
709 /// This is used at the end of processing to make C++ wrapper classes
710 pub templates_defined: RefCell<HashMap<String, bool, NonRandomHash>>,
711 /// The output file for any created template container types, written to as we find new
712 /// template containers which need to be defined.
713 template_file: RefCell<&'a mut File>,
714 /// Set of containers which are clonable
715 clonable_types: RefCell<HashSet<String>>,
717 pub trait_impls: HashMap<String, Vec<String>>,
718 /// The full set of modules in the crate(s)
719 pub lib_ast: &'a FullLibraryAST,
722 impl<'a> CrateTypes<'a> {
723 pub fn new(template_file: &'a mut File, libast: &'a FullLibraryAST) -> Self {
725 opaques: HashMap::new(), mirrored_enums: HashMap::new(), traits: HashMap::new(),
726 type_aliases: HashMap::new(), reverse_alias_map: HashMap::new(),
727 templates_defined: RefCell::new(HashMap::default()),
728 clonable_types: RefCell::new(initial_clonable_types()), trait_impls: HashMap::new(),
729 template_file: RefCell::new(template_file), lib_ast: &libast,
732 pub fn set_clonable(&self, object: String) {
733 self.clonable_types.borrow_mut().insert(object);
735 pub fn is_clonable(&self, object: &str) -> bool {
736 self.clonable_types.borrow().contains(object)
738 pub fn write_new_template(&self, mangled_container: String, has_destructor: bool, created_container: &[u8]) {
739 self.template_file.borrow_mut().write(created_container).unwrap();
740 self.templates_defined.borrow_mut().insert(mangled_container, has_destructor);
744 /// A struct which tracks resolving rust types into C-mapped equivalents, exists for one specific
745 /// module but contains a reference to the overall CrateTypes tracking.
746 pub struct TypeResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
747 pub module_path: &'mod_lifetime str,
748 pub crate_types: &'mod_lifetime CrateTypes<'crate_lft>,
749 types: ImportResolver<'mod_lifetime, 'crate_lft>,
752 /// Returned by write_empty_rust_val_check_suffix to indicate what type of dereferencing needs to
753 /// happen to get the inner value of a generic.
754 enum EmptyValExpectedTy {
755 /// A type which has a flag for being empty (eg an array where we treat all-0s as empty).
757 /// A pointer that we want to dereference and move out of.
759 /// A pointer which we want to convert to a reference.
764 /// Describes the appropriate place to print a general type-conversion string when converting a
766 enum ContainerPrefixLocation {
767 /// Prints a general type-conversion string prefix and suffix outside of the
768 /// container-conversion strings.
770 /// Prints a general type-conversion string prefix and suffix inside of the
771 /// container-conversion strings.
773 /// Does not print the usual type-conversion string prefix and suffix.
777 impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
778 pub fn new(module_path: &'a str, types: ImportResolver<'a, 'c>, crate_types: &'a CrateTypes<'c>) -> Self {
779 Self { module_path, types, crate_types }
782 // *************************************************
783 // *** Well know type and conversion definitions ***
784 // *************************************************
786 /// Returns true we if can just skip passing this to C entirely
787 fn skip_path(&self, full_path: &str) -> bool {
788 full_path == "bitcoin::secp256k1::Secp256k1" ||
789 full_path == "bitcoin::secp256k1::Signing" ||
790 full_path == "bitcoin::secp256k1::Verification"
792 /// Returns true we if can just skip passing this to C entirely
793 fn no_arg_path_to_rust(&self, full_path: &str) -> &str {
794 if full_path == "bitcoin::secp256k1::Secp256k1" {
795 "secp256k1::SECP256K1"
796 } else { unimplemented!(); }
799 /// Returns true if the object is a primitive and is mapped as-is with no conversion
801 pub fn is_primitive(&self, full_path: &str) -> bool {
812 pub fn is_clonable(&self, ty: &str) -> bool {
813 if self.crate_types.is_clonable(ty) { return true; }
814 if self.is_primitive(ty) { return true; }
817 "crate::c_types::Signature" => true,
818 "crate::c_types::RecoverableSignature" => true,
819 "crate::c_types::TxOut" => true,
823 /// Gets the C-mapped type for types which are outside of the crate, or which are manually
824 /// ignored by for some reason need mapping anyway.
825 fn c_type_from_path<'b>(&self, full_path: &'b str, is_ref: bool, _ptr_for_ref: bool) -> Option<&'b str> {
826 if self.is_primitive(full_path) {
827 return Some(full_path);
830 "Result" => Some("crate::c_types::derived::CResult"),
831 "Vec" if !is_ref => Some("crate::c_types::derived::CVec"),
832 "Option" => Some(""),
834 // Note that no !is_ref types can map to an array because Rust and C's call semantics
835 // for arrays are different (https://github.com/eqrion/cbindgen/issues/528)
837 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
838 "[u8; 20]" if !is_ref => Some("crate::c_types::TwentyBytes"),
839 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes"),
840 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes"),
841 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes"),
842 "[u8; 3]" if !is_ref => Some("crate::c_types::ThreeBytes"), // Used for RGB values
844 "str" if is_ref => Some("crate::c_types::Str"),
845 "String" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
846 "String" if is_ref => Some("crate::c_types::Str"),
848 "std::time::Duration" => Some("u64"),
849 "std::time::SystemTime" => Some("u64"),
850 "std::io::Error" => Some("crate::c_types::IOError"),
852 "bech32::u5" => Some("crate::c_types::u5"),
854 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
855 => Some("crate::c_types::PublicKey"),
856 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature"),
857 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some("crate::c_types::RecoverableSignature"),
858 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
859 if is_ref => Some("*const [u8; 32]"),
860 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
861 if !is_ref => Some("crate::c_types::SecretKey"),
862 "bitcoin::secp256k1::Error"|"secp256k1::Error"
863 if !is_ref => Some("crate::c_types::Secp256k1Error"),
864 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice"),
865 "bitcoin::blockdata::script::Script" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
866 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::lightning::chain::transaction::OutPoint"),
867 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction"),
868 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut"),
869 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network"),
870 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("*const [u8; 80]"),
871 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice"),
873 // Newtypes that we just expose in their original form.
874 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
875 if is_ref => Some("*const [u8; 32]"),
876 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
877 if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
878 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
879 "lightning::ln::PaymentHash" if is_ref => Some("*const [u8; 32]"),
880 "lightning::ln::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
881 "lightning::ln::PaymentPreimage" if is_ref => Some("*const [u8; 32]"),
882 "lightning::ln::PaymentPreimage" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
883 "lightning::ln::PaymentSecret" if is_ref => Some("crate::c_types::ThirtyTwoBytes"),
884 "lightning::ln::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
886 // Override the default since Records contain an fmt with a lifetime:
887 "lightning::util::logger::Record" => Some("*const std::os::raw::c_char"),
893 fn from_c_conversion_new_var_from_path<'b>(&self, _full_path: &str, _is_ref: bool) -> Option<(&'b str, &'b str)> {
896 fn from_c_conversion_prefix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
897 if self.is_primitive(full_path) {
898 return Some("".to_owned());
901 "Vec" if !is_ref => Some("local_"),
902 "Result" if !is_ref => Some("local_"),
903 "Option" if is_ref => Some("&local_"),
904 "Option" => Some("local_"),
906 "[u8; 32]" if is_ref => Some("unsafe { &*"),
907 "[u8; 32]" if !is_ref => Some(""),
908 "[u8; 20]" if !is_ref => Some(""),
909 "[u8; 16]" if !is_ref => Some(""),
910 "[u8; 10]" if !is_ref => Some(""),
911 "[u8; 4]" if !is_ref => Some(""),
912 "[u8; 3]" if !is_ref => Some(""),
914 "[u8]" if is_ref => Some(""),
915 "[usize]" if is_ref => Some(""),
917 "str" if is_ref => Some(""),
918 "String" if !is_ref => Some("String::from_utf8("),
919 // Note that we'll panic for String if is_ref, as we only have non-owned memory, we
920 // cannot create a &String.
922 "std::time::Duration" => Some("std::time::Duration::from_secs("),
923 "std::time::SystemTime" => Some("(::std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs("),
925 "bech32::u5" => Some(""),
927 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
928 if is_ref => Some("&"),
929 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
931 "bitcoin::secp256k1::Signature" if is_ref => Some("&"),
932 "bitcoin::secp256k1::Signature" => Some(""),
933 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(""),
934 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
935 if is_ref => Some("&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *"),
936 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
937 if !is_ref => Some(""),
938 "bitcoin::blockdata::script::Script" if is_ref => Some("&::bitcoin::blockdata::script::Script::from(Vec::from("),
939 "bitcoin::blockdata::script::Script" if !is_ref => Some("::bitcoin::blockdata::script::Script::from("),
940 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some("&"),
941 "bitcoin::blockdata::transaction::Transaction" => Some(""),
942 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(""),
943 "bitcoin::network::constants::Network" => Some(""),
944 "bitcoin::blockdata::block::BlockHeader" => Some("&::bitcoin::consensus::encode::deserialize(unsafe { &*"),
945 "bitcoin::blockdata::block::Block" if is_ref => Some("&::bitcoin::consensus::encode::deserialize("),
947 // Newtypes that we just expose in their original form.
948 "bitcoin::hash_types::Txid" if is_ref => Some("&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*"),
949 "bitcoin::hash_types::Txid" if !is_ref => Some("::bitcoin::hash_types::Txid::from_slice(&"),
950 "bitcoin::hash_types::BlockHash" => Some("::bitcoin::hash_types::BlockHash::from_slice(&"),
951 "lightning::ln::PaymentHash" if !is_ref => Some("::lightning::ln::PaymentHash("),
952 "lightning::ln::PaymentHash" if is_ref => Some("&::lightning::ln::PaymentHash(unsafe { *"),
953 "lightning::ln::PaymentPreimage" if !is_ref => Some("::lightning::ln::PaymentPreimage("),
954 "lightning::ln::PaymentPreimage" if is_ref => Some("&::lightning::ln::PaymentPreimage(unsafe { *"),
955 "lightning::ln::PaymentSecret" => Some("::lightning::ln::PaymentSecret("),
957 // List of traits we map (possibly during processing of other files):
958 "crate::util::logger::Logger" => Some(""),
961 }.map(|s| s.to_owned())
963 fn from_c_conversion_suffix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
964 if self.is_primitive(full_path) {
965 return Some("".to_owned());
968 "Vec" if !is_ref => Some(""),
969 "Option" => Some(""),
970 "Result" if !is_ref => Some(""),
972 "[u8; 32]" if is_ref => Some("}"),
973 "[u8; 32]" if !is_ref => Some(".data"),
974 "[u8; 20]" if !is_ref => Some(".data"),
975 "[u8; 16]" if !is_ref => Some(".data"),
976 "[u8; 10]" if !is_ref => Some(".data"),
977 "[u8; 4]" if !is_ref => Some(".data"),
978 "[u8; 3]" if !is_ref => Some(".data"),
980 "[u8]" if is_ref => Some(".to_slice()"),
981 "[usize]" if is_ref => Some(".to_slice()"),
983 "str" if is_ref => Some(".into()"),
984 "String" if !is_ref => Some(".into_rust()).unwrap()"),
986 "std::time::Duration" => Some(")"),
987 "std::time::SystemTime" => Some("))"),
989 "bech32::u5" => Some(".into()"),
991 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
992 => Some(".into_rust()"),
993 "bitcoin::secp256k1::Signature" => Some(".into_rust()"),
994 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(".into_rust()"),
995 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
996 if !is_ref => Some(".into_rust()"),
997 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
998 if is_ref => Some("}[..]).unwrap()"),
999 "bitcoin::blockdata::script::Script" if is_ref => Some(".to_slice()))"),
1000 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_rust())"),
1001 "bitcoin::blockdata::transaction::Transaction" => Some(".into_bitcoin()"),
1002 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(".into_rust()"),
1003 "bitcoin::network::constants::Network" => Some(".into_bitcoin()"),
1004 "bitcoin::blockdata::block::BlockHeader" => Some(" }).unwrap()"),
1005 "bitcoin::blockdata::block::Block" => Some(".to_slice()).unwrap()"),
1007 // Newtypes that we just expose in their original form.
1008 "bitcoin::hash_types::Txid" if is_ref => Some(" }[..]).unwrap()"),
1009 "bitcoin::hash_types::Txid" => Some(".data[..]).unwrap()"),
1010 "bitcoin::hash_types::BlockHash" if !is_ref => Some(".data[..]).unwrap()"),
1011 "lightning::ln::PaymentHash" if !is_ref => Some(".data)"),
1012 "lightning::ln::PaymentHash" if is_ref => Some(" })"),
1013 "lightning::ln::PaymentPreimage" if !is_ref => Some(".data)"),
1014 "lightning::ln::PaymentPreimage" if is_ref => Some(" })"),
1015 "lightning::ln::PaymentSecret" => Some(".data)"),
1017 // List of traits we map (possibly during processing of other files):
1018 "crate::util::logger::Logger" => Some(""),
1021 }.map(|s| s.to_owned())
1024 fn to_c_conversion_new_var_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<(&'b str, &'b str)> {
1025 if self.is_primitive(full_path) {
1029 "[u8]" if is_ref => Some(("crate::c_types::u8slice::from_slice(", ")")),
1030 "[usize]" if is_ref => Some(("crate::c_types::usizeslice::from_slice(", ")")),
1032 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(("{ let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(", ")); s }")),
1033 "bitcoin::blockdata::block::Block" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
1034 "bitcoin::hash_types::Txid" => None,
1036 // Override the default since Records contain an fmt with a lifetime:
1037 // TODO: We should include the other record fields
1038 "lightning::util::logger::Record" => Some(("std::ffi::CString::new(format!(\"{}\", ", ".args)).unwrap()")),
1040 }.map(|s| s.to_owned())
1042 fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
1043 if self.is_primitive(full_path) {
1044 return Some("".to_owned());
1047 "Result" if !is_ref => Some("local_"),
1048 "Vec" if !is_ref => Some("local_"),
1049 "Option" => Some("local_"),
1051 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1052 "[u8; 32]" if is_ref => Some(""),
1053 "[u8; 20]" if !is_ref => Some("crate::c_types::TwentyBytes { data: "),
1054 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes { data: "),
1055 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes { data: "),
1056 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes { data: "),
1057 "[u8; 3]" if is_ref => Some(""),
1059 "[u8]" if is_ref => Some("local_"),
1060 "[usize]" if is_ref => Some("local_"),
1062 "str" if is_ref => Some(""),
1063 "String" => Some(""),
1065 "std::time::Duration" => Some(""),
1066 "std::time::SystemTime" => Some(""),
1067 "std::io::Error" if !is_ref => Some("crate::c_types::IOError::from_rust("),
1069 "bech32::u5" => Some(""),
1071 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1072 => Some("crate::c_types::PublicKey::from_rust(&"),
1073 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature::from_rust(&"),
1074 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some("crate::c_types::RecoverableSignature::from_rust(&"),
1075 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1076 if is_ref => Some(""),
1077 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1078 if !is_ref => Some("crate::c_types::SecretKey::from_rust("),
1079 "bitcoin::secp256k1::Error"|"secp256k1::Error"
1080 if !is_ref => Some("crate::c_types::Secp256k1Error::from_rust("),
1081 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice::from_slice(&"),
1082 "bitcoin::blockdata::script::Script" if !is_ref => Some(""),
1083 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some("crate::c_types::Transaction::from_bitcoin("),
1084 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction::from_bitcoin(&"),
1085 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::c_types::bitcoin_to_C_outpoint("),
1086 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut::from_rust("),
1087 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network::from_bitcoin("),
1088 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("&local_"),
1089 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice::from_slice(&local_"),
1091 "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1093 // Newtypes that we just expose in their original form.
1094 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1095 if is_ref => Some(""),
1096 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1097 if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1098 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1099 "lightning::ln::PaymentHash" if is_ref => Some("&"),
1100 "lightning::ln::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1101 "lightning::ln::PaymentPreimage" if is_ref => Some("&"),
1102 "lightning::ln::PaymentPreimage" => Some("crate::c_types::ThirtyTwoBytes { data: "),
1103 "lightning::ln::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1105 // Override the default since Records contain an fmt with a lifetime:
1106 "lightning::util::logger::Record" => Some("local_"),
1109 }.map(|s| s.to_owned())
1111 fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
1112 if self.is_primitive(full_path) {
1113 return Some("".to_owned());
1116 "Result" if !is_ref => Some(""),
1117 "Vec" if !is_ref => Some(".into()"),
1118 "Option" => Some(""),
1120 "[u8; 32]" if !is_ref => Some(" }"),
1121 "[u8; 32]" if is_ref => Some(""),
1122 "[u8; 20]" if !is_ref => Some(" }"),
1123 "[u8; 16]" if !is_ref => Some(" }"),
1124 "[u8; 10]" if !is_ref => Some(" }"),
1125 "[u8; 4]" if !is_ref => Some(" }"),
1126 "[u8; 3]" if is_ref => Some(""),
1128 "[u8]" if is_ref => Some(""),
1129 "[usize]" if is_ref => Some(""),
1131 "str" if is_ref => Some(".into()"),
1132 "String" if !is_ref => Some(".into_bytes().into()"),
1133 "String" if is_ref => Some(".as_str().into()"),
1135 "std::time::Duration" => Some(".as_secs()"),
1136 "std::time::SystemTime" => Some(".duration_since(::std::time::SystemTime::UNIX_EPOCH).expect(\"Times must be post-1970\").as_secs()"),
1137 "std::io::Error" if !is_ref => Some(")"),
1139 "bech32::u5" => Some(".into()"),
1141 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1143 "bitcoin::secp256k1::Signature" => Some(")"),
1144 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(")"),
1145 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1146 if !is_ref => Some(")"),
1147 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1148 if is_ref => Some(".as_ref()"),
1149 "bitcoin::secp256k1::Error"|"secp256k1::Error"
1150 if !is_ref => Some(")"),
1151 "bitcoin::blockdata::script::Script" if is_ref => Some("[..])"),
1152 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_bytes().into()"),
1153 "bitcoin::blockdata::transaction::Transaction" => Some(")"),
1154 "bitcoin::blockdata::transaction::OutPoint" => Some(")"),
1155 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(")"),
1156 "bitcoin::network::constants::Network" => Some(")"),
1157 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(""),
1158 "bitcoin::blockdata::block::Block" if is_ref => Some(")"),
1160 "bitcoin::hash_types::Txid" if !is_ref => Some(".into_inner() }"),
1162 // Newtypes that we just expose in their original form.
1163 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1164 if is_ref => Some(".as_inner()"),
1165 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1166 if !is_ref => Some(".into_inner() }"),
1167 "bitcoin::secp256k1::Message" if !is_ref => Some(".as_ref().clone() }"),
1168 "lightning::ln::PaymentHash" if is_ref => Some(".0"),
1169 "lightning::ln::PaymentHash" => Some(".0 }"),
1170 "lightning::ln::PaymentPreimage" if is_ref => Some(".0"),
1171 "lightning::ln::PaymentPreimage" => Some(".0 }"),
1172 "lightning::ln::PaymentSecret" if !is_ref => Some(".0 }"),
1174 // Override the default since Records contain an fmt with a lifetime:
1175 "lightning::util::logger::Record" => Some(".as_ptr()"),
1178 }.map(|s| s.to_owned())
1181 fn empty_val_check_suffix_from_path(&self, full_path: &str) -> Option<&str> {
1183 "lightning::ln::PaymentSecret" => Some(".data == [0; 32]"),
1184 "secp256k1::key::PublicKey"|"bitcoin::secp256k1::key::PublicKey" => Some(".is_null()"),
1185 "bitcoin::secp256k1::Signature" => Some(".is_null()"),
1190 // ****************************
1191 // *** Container Processing ***
1192 // ****************************
1194 /// Returns the module path in the generated mapping crate to the containers which we generate
1195 /// when writing to CrateTypes::template_file.
1196 pub fn generated_container_path() -> &'static str {
1197 "crate::c_types::derived"
1199 /// Returns the module path in the generated mapping crate to the container templates, which
1200 /// are then concretized and put in the generated container path/template_file.
1201 fn container_templ_path() -> &'static str {
1205 /// Returns true if the path containing the given args is a "transparent" container, ie an
1206 /// Option or a container which does not require a generated continer class.
1207 fn is_transparent_container<'i, I: Iterator<Item=&'i syn::Type>>(&self, full_path: &str, _is_ref: bool, mut args: I) -> bool {
1208 if full_path == "Option" {
1209 let inner = args.next().unwrap();
1210 assert!(args.next().is_none());
1212 syn::Type::Reference(_) => true,
1213 syn::Type::Path(p) => {
1214 if let Some(resolved) = self.maybe_resolve_path(&p.path, None) {
1215 if self.is_primitive(&resolved) { false } else { true }
1218 syn::Type::Tuple(_) => false,
1219 _ => unimplemented!(),
1223 /// Returns true if the path is a "transparent" container, ie an Option or a container which does
1224 /// not require a generated continer class.
1225 fn is_path_transparent_container(&self, full_path: &syn::Path, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
1226 let inner_iter = match &full_path.segments.last().unwrap().arguments {
1227 syn::PathArguments::None => return false,
1228 syn::PathArguments::AngleBracketed(args) => args.args.iter().map(|arg| {
1229 if let syn::GenericArgument::Type(ref ty) = arg {
1231 } else { unimplemented!() }
1233 syn::PathArguments::Parenthesized(_) => unimplemented!(),
1235 self.is_transparent_container(&self.resolve_path(full_path, generics), is_ref, inner_iter)
1237 /// Returns true if this is a known, supported, non-transparent container.
1238 fn is_known_container(&self, full_path: &str, is_ref: bool) -> bool {
1239 (full_path == "Result" && !is_ref) || (full_path == "Vec" && !is_ref) || full_path.ends_with("Tuple") || full_path == "Option"
1241 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)
1242 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1243 // expecting one element in the vec per generic type, each of which is inline-converted
1244 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1246 "Result" if !is_ref => {
1248 vec![(" { Ok(mut o) => crate::c_types::CResultTempl::ok(".to_string(), "o".to_string()),
1249 (").into(), Err(mut e) => crate::c_types::CResultTempl::err(".to_string(), "e".to_string())],
1250 ").into() }", ContainerPrefixLocation::PerConv))
1252 "Vec" if !is_ref => {
1253 Some(("Vec::new(); for mut item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1256 // We should only get here if the single contained has an inner
1257 assert!(self.c_type_has_inner(single_contained.unwrap()));
1258 Some(("Vec::new(); for mut item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "*item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1261 Some(("Vec::new(); for item in ", vec![(format!(".iter() {{ local_{}.push(", var_name), "*item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1264 if let Some(syn::Type::Path(p)) = single_contained {
1265 let inner_path = self.resolve_path(&p.path, generics);
1266 if self.is_primitive(&inner_path) {
1267 return Some(("if ", vec![
1268 (format!(".is_none() {{ {}::COption_{}Z::None }} else {{ ", Self::generated_container_path(), inner_path),
1269 format!("{}::COption_{}Z::Some({}.unwrap())", Self::generated_container_path(), inner_path, var_access))
1270 ], " }", ContainerPrefixLocation::NoPrefix));
1271 } else if self.c_type_has_inner_from_path(&inner_path) {
1273 return Some(("if ", vec![
1274 (".is_none() { std::ptr::null() } else { ".to_owned(), format!("({}.as_ref().unwrap())", var_access))
1275 ], " }", ContainerPrefixLocation::OutsideConv));
1277 return Some(("if ", vec![
1278 (".is_none() { std::ptr::null_mut() } else { ".to_owned(), format!("({}.unwrap())", var_access))
1279 ], " }", ContainerPrefixLocation::OutsideConv));
1283 if let Some(t) = single_contained {
1284 let mut v = Vec::new();
1285 self.write_empty_rust_val(generics, &mut v, t);
1286 let s = String::from_utf8(v).unwrap();
1287 return Some(("if ", vec![
1288 (format!(".is_none() {{ {} }} else {{ ", s), format!("({}.unwrap())", var_access))
1289 ], " }", ContainerPrefixLocation::PerConv));
1290 } else { unreachable!(); }
1296 /// only_contained_has_inner implies that there is only one contained element in the container
1297 /// and it has an inner field (ie is an "opaque" type we've defined).
1298 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)
1299 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1300 // expecting one element in the vec per generic type, each of which is inline-converted
1301 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1303 "Result" if !is_ref => {
1305 vec![(".result_ok { true => Ok(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.result)) }})", var_access)),
1306 ("), false => Err(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.err)) }})", var_access))],
1307 ")}", ContainerPrefixLocation::PerConv))
1309 "Slice" if is_ref => {
1310 Some(("Vec::new(); for mut item in ", vec![(format!(".as_slice().iter() {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1313 Some(("Vec::new(); for mut item in ", vec![(format!(".into_rust().drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1316 if let Some(syn::Type::Path(p)) = single_contained {
1317 let inner_path = self.resolve_path(&p.path, generics);
1318 if self.is_primitive(&inner_path) {
1319 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::NoPrefix))
1320 } else if self.c_type_has_inner_from_path(&inner_path) {
1322 return Some(("if ", vec![(".inner.is_null() { None } else { Some((*".to_string(), format!("{}", var_access))], ").clone()) }", ContainerPrefixLocation::PerConv))
1324 return Some(("if ", vec![(".inner.is_null() { None } else { Some(".to_string(), format!("{}", var_access))], ") }", ContainerPrefixLocation::PerConv));
1329 if let Some(t) = single_contained {
1331 syn::Type::Reference(_)|syn::Type::Path(_)|syn::Type::Slice(_) => {
1332 let mut v = Vec::new();
1333 let ret_ref = self.write_empty_rust_val_check_suffix(generics, &mut v, t);
1334 let s = String::from_utf8(v).unwrap();
1336 EmptyValExpectedTy::ReferenceAsPointer =>
1337 return Some(("if ", vec![
1338 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ &mut *{} }}", var_access))
1339 ], ") }", ContainerPrefixLocation::NoPrefix)),
1340 EmptyValExpectedTy::OwnedPointer => {
1341 if let syn::Type::Slice(_) = t {
1344 return Some(("if ", vec![
1345 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ *Box::from_raw({}) }}", var_access))
1346 ], ") }", ContainerPrefixLocation::NoPrefix));
1348 EmptyValExpectedTy::NonPointer =>
1349 return Some(("if ", vec![
1350 (format!("{} {{ None }} else {{ Some(", s), format!("{}", var_access))
1351 ], ") }", ContainerPrefixLocation::PerConv)),
1354 syn::Type::Tuple(_) => {
1355 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::PerConv))
1357 _ => unimplemented!(),
1359 } else { unreachable!(); }
1365 // *************************************************
1366 // *** Type definition during main.rs processing ***
1367 // *************************************************
1369 pub fn get_declared_type(&'a self, ident: &syn::Ident) -> Option<&'a DeclType<'c>> {
1370 self.types.get_declared_type(ident)
1372 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1373 pub fn c_type_has_inner_from_path(&self, full_path: &str) -> bool {
1374 self.crate_types.opaques.get(full_path).is_some()
1376 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1377 pub fn c_type_has_inner(&self, ty: &syn::Type) -> bool {
1379 syn::Type::Path(p) => {
1380 let full_path = self.resolve_path(&p.path, None);
1381 self.c_type_has_inner_from_path(&full_path)
1387 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
1388 self.types.maybe_resolve_ident(id)
1391 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
1392 self.types.maybe_resolve_non_ignored_ident(id)
1395 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
1396 self.types.maybe_resolve_path(p_arg, generics)
1398 pub fn resolve_path(&self, p: &syn::Path, generics: Option<&GenericTypes>) -> String {
1399 self.maybe_resolve_path(p, generics).unwrap()
1402 // ***********************************
1403 // *** Original Rust Type Printing ***
1404 // ***********************************
1406 fn in_rust_prelude(resolved_path: &str) -> bool {
1407 match resolved_path {
1415 fn write_rust_path<W: std::io::Write>(&self, w: &mut W, generics_resolver: Option<&GenericTypes>, path: &syn::Path) {
1416 if let Some(resolved) = self.maybe_resolve_path(&path, generics_resolver) {
1417 if self.is_primitive(&resolved) {
1418 write!(w, "{}", path.get_ident().unwrap()).unwrap();
1420 // TODO: We should have a generic "is from a dependency" check here instead of
1421 // checking for "bitcoin" explicitly.
1422 if resolved.starts_with("bitcoin::") || Self::in_rust_prelude(&resolved) {
1423 write!(w, "{}", resolved).unwrap();
1424 // If we're printing a generic argument, it needs to reference the crate, otherwise
1425 // the original crate:
1426 } else if self.maybe_resolve_path(&path, None).as_ref() == Some(&resolved) {
1427 write!(w, "{}", resolved).unwrap();
1429 write!(w, "crate::{}", resolved).unwrap();
1432 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().last().unwrap().arguments {
1433 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1436 if path.leading_colon.is_some() {
1437 write!(w, "::").unwrap();
1439 for (idx, seg) in path.segments.iter().enumerate() {
1440 if idx != 0 { write!(w, "::").unwrap(); }
1441 write!(w, "{}", seg.ident).unwrap();
1442 if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
1443 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1448 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>) {
1449 let mut had_params = false;
1450 for (idx, arg) in generics.enumerate() {
1451 if idx != 0 { write!(w, ", ").unwrap(); } else { write!(w, "<").unwrap(); }
1454 syn::GenericParam::Lifetime(lt) => write!(w, "'{}", lt.lifetime.ident).unwrap(),
1455 syn::GenericParam::Type(t) => {
1456 write!(w, "{}", t.ident).unwrap();
1457 if t.colon_token.is_some() { write!(w, ":").unwrap(); }
1458 for (idx, bound) in t.bounds.iter().enumerate() {
1459 if idx != 0 { write!(w, " + ").unwrap(); }
1461 syn::TypeParamBound::Trait(tb) => {
1462 if tb.paren_token.is_some() || tb.lifetimes.is_some() { unimplemented!(); }
1463 self.write_rust_path(w, generics_resolver, &tb.path);
1465 _ => unimplemented!(),
1468 if t.eq_token.is_some() || t.default.is_some() { unimplemented!(); }
1470 _ => unimplemented!(),
1473 if had_params { write!(w, ">").unwrap(); }
1476 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>) {
1477 write!(w, "<").unwrap();
1478 for (idx, arg) in generics.enumerate() {
1479 if idx != 0 { write!(w, ", ").unwrap(); }
1481 syn::GenericArgument::Type(t) => self.write_rust_type(w, generics_resolver, t),
1482 _ => unimplemented!(),
1485 write!(w, ">").unwrap();
1487 pub fn write_rust_type<W: std::io::Write>(&self, w: &mut W, generics: Option<&GenericTypes>, t: &syn::Type) {
1489 syn::Type::Path(p) => {
1490 if p.qself.is_some() {
1493 self.write_rust_path(w, generics, &p.path);
1495 syn::Type::Reference(r) => {
1496 write!(w, "&").unwrap();
1497 if let Some(lft) = &r.lifetime {
1498 write!(w, "'{} ", lft.ident).unwrap();
1500 if r.mutability.is_some() {
1501 write!(w, "mut ").unwrap();
1503 self.write_rust_type(w, generics, &*r.elem);
1505 syn::Type::Array(a) => {
1506 write!(w, "[").unwrap();
1507 self.write_rust_type(w, generics, &a.elem);
1508 if let syn::Expr::Lit(l) = &a.len {
1509 if let syn::Lit::Int(i) = &l.lit {
1510 write!(w, "; {}]", i).unwrap();
1511 } else { unimplemented!(); }
1512 } else { unimplemented!(); }
1514 syn::Type::Slice(s) => {
1515 write!(w, "[").unwrap();
1516 self.write_rust_type(w, generics, &s.elem);
1517 write!(w, "]").unwrap();
1519 syn::Type::Tuple(s) => {
1520 write!(w, "(").unwrap();
1521 for (idx, t) in s.elems.iter().enumerate() {
1522 if idx != 0 { write!(w, ", ").unwrap(); }
1523 self.write_rust_type(w, generics, &t);
1525 write!(w, ")").unwrap();
1527 _ => unimplemented!(),
1531 /// Prints a constructor for something which is "uninitialized" (but obviously not actually
1532 /// unint'd memory).
1533 pub fn write_empty_rust_val<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) {
1535 syn::Type::Path(p) => {
1536 let resolved = self.resolve_path(&p.path, generics);
1537 if self.crate_types.opaques.get(&resolved).is_some() {
1538 write!(w, "crate::{} {{ inner: std::ptr::null_mut(), is_owned: true }}", resolved).unwrap();
1540 // Assume its a manually-mapped C type, where we can just define an null() fn
1541 write!(w, "{}::null()", self.c_type_from_path(&resolved, false, false).unwrap()).unwrap();
1544 syn::Type::Array(a) => {
1545 if let syn::Expr::Lit(l) = &a.len {
1546 if let syn::Lit::Int(i) = &l.lit {
1547 if i.base10_digits().parse::<usize>().unwrap() < 32 {
1548 // Blindly assume that if we're trying to create an empty value for an
1549 // array < 32 entries that all-0s may be a valid state.
1552 let arrty = format!("[u8; {}]", i.base10_digits());
1553 write!(w, "{}", self.to_c_conversion_inline_prefix_from_path(&arrty, false, false).unwrap()).unwrap();
1554 write!(w, "[0; {}]", i.base10_digits()).unwrap();
1555 write!(w, "{}", self.to_c_conversion_inline_suffix_from_path(&arrty, false, false).unwrap()).unwrap();
1556 } else { unimplemented!(); }
1557 } else { unimplemented!(); }
1559 _ => unimplemented!(),
1563 fn is_real_type_array(&self, resolved_type: &str) -> Option<syn::Type> {
1564 if let Some(real_ty) = self.c_type_from_path(&resolved_type, true, false) {
1565 if real_ty.ends_with("]") && real_ty.starts_with("*const [u8; ") {
1566 let mut split = real_ty.split("; ");
1567 split.next().unwrap();
1568 let tail_str = split.next().unwrap();
1569 assert!(split.next().is_none());
1570 let len = usize::from_str_radix(&tail_str[..tail_str.len() - 1], 10).unwrap();
1571 Some(parse_quote!([u8; #len]))
1576 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1577 /// See EmptyValExpectedTy for information on return types.
1578 fn write_empty_rust_val_check_suffix<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) -> EmptyValExpectedTy {
1580 syn::Type::Path(p) => {
1581 let resolved = self.resolve_path(&p.path, generics);
1582 if let Some(arr_ty) = self.is_real_type_array(&resolved) {
1583 write!(w, ".data").unwrap();
1584 return self.write_empty_rust_val_check_suffix(generics, w, &arr_ty);
1586 if self.crate_types.opaques.get(&resolved).is_some() {
1587 write!(w, ".inner.is_null()").unwrap();
1588 EmptyValExpectedTy::NonPointer
1590 if let Some(suffix) = self.empty_val_check_suffix_from_path(&resolved) {
1591 write!(w, "{}", suffix).unwrap();
1592 // We may eventually need to allow empty_val_check_suffix_from_path to specify if we need a deref or not
1593 EmptyValExpectedTy::NonPointer
1595 write!(w, " == std::ptr::null_mut()").unwrap();
1596 EmptyValExpectedTy::OwnedPointer
1600 syn::Type::Array(a) => {
1601 if let syn::Expr::Lit(l) = &a.len {
1602 if let syn::Lit::Int(i) = &l.lit {
1603 write!(w, " == [0; {}]", i.base10_digits()).unwrap();
1604 EmptyValExpectedTy::NonPointer
1605 } else { unimplemented!(); }
1606 } else { unimplemented!(); }
1608 syn::Type::Slice(_) => {
1609 // Option<[]> always implies that we want to treat len() == 0 differently from
1610 // None, so we always map an Option<[]> into a pointer.
1611 write!(w, " == std::ptr::null_mut()").unwrap();
1612 EmptyValExpectedTy::ReferenceAsPointer
1614 _ => unimplemented!(),
1618 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1619 pub fn write_empty_rust_val_check<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type, var_access: &str) {
1621 syn::Type::Path(_) => {
1622 write!(w, "{}", var_access).unwrap();
1623 self.write_empty_rust_val_check_suffix(generics, w, t);
1625 syn::Type::Array(a) => {
1626 if let syn::Expr::Lit(l) = &a.len {
1627 if let syn::Lit::Int(i) = &l.lit {
1628 let arrty = format!("[u8; {}]", i.base10_digits());
1629 // We don't (yet) support a new-var conversion here.
1630 assert!(self.from_c_conversion_new_var_from_path(&arrty, false).is_none());
1632 self.from_c_conversion_prefix_from_path(&arrty, false).unwrap(),
1634 self.from_c_conversion_suffix_from_path(&arrty, false).unwrap()).unwrap();
1635 self.write_empty_rust_val_check_suffix(generics, w, t);
1636 } else { unimplemented!(); }
1637 } else { unimplemented!(); }
1639 _ => unimplemented!(),
1643 // ********************************
1644 // *** Type conversion printing ***
1645 // ********************************
1647 /// Returns true we if can just skip passing this to C entirely
1648 pub fn skip_arg(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
1650 syn::Type::Path(p) => {
1651 if p.qself.is_some() { unimplemented!(); }
1652 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1653 self.skip_path(&full_path)
1656 syn::Type::Reference(r) => {
1657 self.skip_arg(&*r.elem, generics)
1662 pub fn no_arg_to_rust<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1664 syn::Type::Path(p) => {
1665 if p.qself.is_some() { unimplemented!(); }
1666 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1667 write!(w, "{}", self.no_arg_path_to_rust(&full_path)).unwrap();
1670 syn::Type::Reference(r) => {
1671 self.no_arg_to_rust(w, &*r.elem, generics);
1677 fn write_conversion_inline_intern<W: std::io::Write,
1678 LP: Fn(&str, bool, bool) -> Option<String>, DL: Fn(&mut W, &DeclType, &str, bool, bool), SC: Fn(bool, Option<&str>) -> String>
1679 (&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool,
1680 tupleconv: &str, prefix: bool, sliceconv: SC, path_lookup: LP, decl_lookup: DL) {
1681 match generics.resolve_type(t) {
1682 syn::Type::Reference(r) => {
1683 self.write_conversion_inline_intern(w, &*r.elem, generics, true, r.mutability.is_some(),
1684 ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1686 syn::Type::Path(p) => {
1687 if p.qself.is_some() {
1691 let resolved_path = self.resolve_path(&p.path, generics);
1692 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1693 return self.write_conversion_inline_intern(w, aliased_type, None, is_ref, is_mut, ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1694 } else if self.is_primitive(&resolved_path) {
1695 if is_ref && prefix {
1696 write!(w, "*").unwrap();
1698 } else if let Some(c_type) = path_lookup(&resolved_path, is_ref, ptr_for_ref) {
1699 write!(w, "{}", c_type).unwrap();
1700 } else if self.crate_types.opaques.get(&resolved_path).is_some() {
1701 decl_lookup(w, &DeclType::StructImported, &resolved_path, is_ref, is_mut);
1702 } else if self.crate_types.mirrored_enums.get(&resolved_path).is_some() {
1703 decl_lookup(w, &DeclType::MirroredEnum, &resolved_path, is_ref, is_mut);
1704 } else if let Some(t) = self.crate_types.traits.get(&resolved_path) {
1705 decl_lookup(w, &DeclType::Trait(t), &resolved_path, is_ref, is_mut);
1706 } else if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
1707 if let Some(decl_type) = self.types.maybe_resolve_declared(ident) {
1708 decl_lookup(w, decl_type, &self.maybe_resolve_ident(ident).unwrap(), is_ref, is_mut);
1709 } else { unimplemented!(); }
1710 } else { unimplemented!(); }
1712 syn::Type::Array(a) => {
1713 // We assume all arrays contain only [int_literal; X]s.
1714 // This may result in some outputs not compiling.
1715 if let syn::Expr::Lit(l) = &a.len {
1716 if let syn::Lit::Int(i) = &l.lit {
1717 write!(w, "{}", path_lookup(&format!("[u8; {}]", i.base10_digits()), is_ref, ptr_for_ref).unwrap()).unwrap();
1718 } else { unimplemented!(); }
1719 } else { unimplemented!(); }
1721 syn::Type::Slice(s) => {
1722 // We assume all slices contain only literals or references.
1723 // This may result in some outputs not compiling.
1724 if let syn::Type::Path(p) = &*s.elem {
1725 let resolved = self.resolve_path(&p.path, generics);
1726 assert!(self.is_primitive(&resolved));
1727 write!(w, "{}", path_lookup("[u8]", is_ref, ptr_for_ref).unwrap()).unwrap();
1728 } else if let syn::Type::Reference(r) = &*s.elem {
1729 if let syn::Type::Path(p) = &*r.elem {
1730 write!(w, "{}", sliceconv(self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)), None)).unwrap();
1731 } else { unimplemented!(); }
1732 } else if let syn::Type::Tuple(t) = &*s.elem {
1733 assert!(!t.elems.is_empty());
1735 write!(w, "{}", sliceconv(false, None)).unwrap();
1737 let mut needs_map = false;
1738 for e in t.elems.iter() {
1739 if let syn::Type::Reference(_) = e {
1744 let mut map_str = Vec::new();
1745 write!(&mut map_str, ".map(|(").unwrap();
1746 for i in 0..t.elems.len() {
1747 write!(&mut map_str, "{}{}", if i != 0 { ", " } else { "" }, ('a' as u8 + i as u8) as char).unwrap();
1749 write!(&mut map_str, ")| (").unwrap();
1750 for (idx, e) in t.elems.iter().enumerate() {
1751 if let syn::Type::Reference(_) = e {
1752 write!(&mut map_str, "{}{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1753 } else if let syn::Type::Path(_) = e {
1754 write!(&mut map_str, "{}*{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1755 } else { unimplemented!(); }
1757 write!(&mut map_str, "))").unwrap();
1758 write!(w, "{}", sliceconv(false, Some(&String::from_utf8(map_str).unwrap()))).unwrap();
1760 write!(w, "{}", sliceconv(false, None)).unwrap();
1763 } else { unimplemented!(); }
1765 syn::Type::Tuple(t) => {
1766 if t.elems.is_empty() {
1767 // cbindgen has poor support for (), see, eg https://github.com/eqrion/cbindgen/issues/527
1768 // so work around it by just pretending its a 0u8
1769 write!(w, "{}", tupleconv).unwrap();
1771 if prefix { write!(w, "local_").unwrap(); }
1774 _ => unimplemented!(),
1778 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) {
1779 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "() /*", true, |_, _| "local_".to_owned(),
1780 |a, b, c| self.to_c_conversion_inline_prefix_from_path(a, b, c),
1781 |w, decl_type, decl_path, is_ref, _is_mut| {
1783 DeclType::MirroredEnum if is_ref && ptr_for_ref => write!(w, "crate::{}::from_native(", decl_path).unwrap(),
1784 DeclType::MirroredEnum if is_ref => write!(w, "&crate::{}::from_native(", decl_path).unwrap(),
1785 DeclType::MirroredEnum => write!(w, "crate::{}::native_into(", decl_path).unwrap(),
1786 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1787 write!(w, "crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1788 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1789 write!(w, "crate::{} {{ inner: unsafe {{ ( (&(*", decl_path).unwrap(),
1790 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1791 write!(w, "&crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1792 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1793 write!(w, "crate::{} {{ inner: ", decl_path).unwrap(),
1794 DeclType::EnumIgnored|DeclType::StructImported if !is_ref =>
1795 write!(w, "crate::{} {{ inner: Box::into_raw(Box::new(", decl_path).unwrap(),
1796 DeclType::Trait(_) if is_ref => write!(w, "").unwrap(),
1797 DeclType::Trait(_) if !is_ref => {},
1798 _ => panic!("{:?}", decl_path),
1802 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) {
1803 self.write_to_c_conversion_inline_prefix_inner(w, t, generics, false, ptr_for_ref, false);
1805 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) {
1806 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "*/", false, |_, _| ".into()".to_owned(),
1807 |a, b, c| self.to_c_conversion_inline_suffix_from_path(a, b, c),
1808 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1809 DeclType::MirroredEnum => write!(w, ")").unwrap(),
1810 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1811 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1812 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1813 write!(w, ") as *const _) as *mut _) }}, is_owned: false }}").unwrap(),
1814 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1815 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1816 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1817 write!(w, ", is_owned: true }}").unwrap(),
1818 DeclType::EnumIgnored|DeclType::StructImported if !is_ref => write!(w, ")), is_owned: true }}").unwrap(),
1819 DeclType::Trait(_) if is_ref => {},
1820 DeclType::Trait(_) => {
1821 // This is used when we're converting a concrete Rust type into a C trait
1822 // for use when a Rust trait method returns an associated type.
1823 // Because all of our C traits implement From<RustTypesImplementingTraits>
1824 // we can just call .into() here and be done.
1825 write!(w, ".into()").unwrap()
1827 _ => unimplemented!(),
1830 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) {
1831 self.write_to_c_conversion_inline_suffix_inner(w, t, generics, false, ptr_for_ref, false);
1834 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) {
1835 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "() /*", true, |_, _| "&local_".to_owned(),
1836 |a, b, _c| self.from_c_conversion_prefix_from_path(a, b),
1837 |w, decl_type, _full_path, is_ref, is_mut| match decl_type {
1838 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, "unsafe {{ &*(*").unwrap(),
1839 DeclType::StructImported if is_mut && is_ref => write!(w, "unsafe {{ &mut *").unwrap(),
1840 DeclType::StructImported if is_ref => write!(w, "unsafe {{ &*").unwrap(),
1841 DeclType::StructImported if !is_ref => write!(w, "*unsafe {{ Box::from_raw(").unwrap(),
1842 DeclType::MirroredEnum if is_ref => write!(w, "&").unwrap(),
1843 DeclType::MirroredEnum => {},
1844 DeclType::Trait(_) => {},
1845 _ => unimplemented!(),
1848 pub fn write_from_c_conversion_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1849 self.write_from_c_conversion_prefix_inner(w, t, generics, false, false);
1851 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) {
1852 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "*/", false,
1853 |has_inner, map_str_opt| match (has_inner, map_str_opt) {
1854 (false, Some(map_str)) => format!(".iter(){}.collect::<Vec<_>>()[..]", map_str),
1855 (false, None) => ".iter().collect::<Vec<_>>()[..]".to_owned(),
1856 (true, None) => "[..]".to_owned(),
1857 (true, Some(_)) => unreachable!(),
1859 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1860 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1861 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, ").inner }}").unwrap(),
1862 DeclType::StructImported if is_ref => write!(w, ".inner }}").unwrap(),
1863 DeclType::StructImported if !is_ref => write!(w, ".take_inner()) }}").unwrap(),
1864 DeclType::MirroredEnum if is_ref => write!(w, ".to_native()").unwrap(),
1865 DeclType::MirroredEnum => write!(w, ".into_native()").unwrap(),
1866 DeclType::Trait(_) => {},
1867 _ => unimplemented!(),
1870 pub fn write_from_c_conversion_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1871 self.write_from_c_conversion_suffix_inner(w, t, generics, false, false);
1873 // Note that compared to the above conversion functions, the following two are generally
1874 // significantly undertested:
1875 pub fn write_from_c_conversion_to_ref_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1876 self.write_conversion_inline_intern(w, t, generics, false, false, false, "() /*", true, |_, _| "&local_".to_owned(),
1878 if let Some(conv) = self.from_c_conversion_prefix_from_path(a, b) {
1879 Some(format!("&{}", conv))
1882 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1883 DeclType::StructImported if !is_ref => write!(w, "unsafe {{ &*").unwrap(),
1884 _ => unimplemented!(),
1887 pub fn write_from_c_conversion_to_ref_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1888 self.write_conversion_inline_intern(w, t, generics, false, false, false, "*/", false,
1889 |has_inner, map_str_opt| match (has_inner, map_str_opt) {
1890 (false, Some(map_str)) => format!(".iter(){}.collect::<Vec<_>>()[..]", map_str),
1891 (false, None) => ".iter().collect::<Vec<_>>()[..]".to_owned(),
1892 (true, None) => "[..]".to_owned(),
1893 (true, Some(_)) => unreachable!(),
1895 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1896 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1897 DeclType::StructImported if !is_ref => write!(w, ".inner }}").unwrap(),
1898 _ => unimplemented!(),
1902 fn write_conversion_new_var_intern<'b, W: std::io::Write,
1903 LP: Fn(&str, bool) -> Option<(&str, &str)>,
1904 LC: Fn(&str, bool, Option<&syn::Type>, &syn::Ident, &str) -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)>,
1905 VP: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool),
1906 VS: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool)>
1907 (&self, w: &mut W, ident: &syn::Ident, var: &str, t: &syn::Type, generics: Option<&GenericTypes>,
1908 mut is_ref: bool, mut ptr_for_ref: bool, to_c: bool,
1909 path_lookup: &LP, container_lookup: &LC, var_prefix: &VP, var_suffix: &VS) -> bool {
1911 macro_rules! convert_container {
1912 ($container_type: expr, $args_len: expr, $args_iter: expr) => { {
1913 // For slices (and Options), we refuse to directly map them as is_ref when they
1914 // aren't opaque types containing an inner pointer. This is due to the fact that,
1915 // in both cases, the actual higher-level type is non-is_ref.
1916 let ty_has_inner = if $args_len == 1 {
1917 let ty = $args_iter().next().unwrap();
1918 if $container_type == "Slice" && to_c {
1919 // "To C ptr_for_ref" means "return the regular object with is_owned
1920 // set to false", which is totally what we want in a slice if we're about to
1921 // set ty_has_inner.
1924 if let syn::Type::Reference(t) = ty {
1925 if let syn::Type::Path(p) = &*t.elem {
1926 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1928 } else if let syn::Type::Path(p) = ty {
1929 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1933 // Options get a bunch of special handling, since in general we map Option<>al
1934 // types into the same C type as non-Option-wrapped types. This ends up being
1935 // pretty manual here and most of the below special-cases are for Options.
1936 let mut needs_ref_map = false;
1937 let mut only_contained_type = None;
1938 let mut only_contained_has_inner = false;
1939 let mut contains_slice = false;
1941 only_contained_has_inner = ty_has_inner;
1942 let arg = $args_iter().next().unwrap();
1943 if let syn::Type::Reference(t) = arg {
1944 only_contained_type = Some(&*t.elem);
1945 if let syn::Type::Path(_) = &*t.elem {
1947 } else if let syn::Type::Slice(_) = &*t.elem {
1948 contains_slice = true;
1949 } else { return false; }
1950 // If the inner element contains an inner pointer, we will just use that,
1951 // avoiding the need to map elements to references. Otherwise we'll need to
1952 // do an extra mapping step.
1953 needs_ref_map = !only_contained_has_inner;
1955 only_contained_type = Some(&arg);
1959 if let Some((prefix, conversions, suffix, prefix_location)) = container_lookup(&$container_type, is_ref && ty_has_inner, only_contained_type, ident, var) {
1960 assert_eq!(conversions.len(), $args_len);
1961 write!(w, "let mut local_{}{} = ", ident, if !to_c && needs_ref_map {"_base"} else { "" }).unwrap();
1962 if prefix_location == ContainerPrefixLocation::OutsideConv {
1963 var_prefix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
1965 write!(w, "{}{}", prefix, var).unwrap();
1967 for ((pfx, var_name), (idx, ty)) in conversions.iter().zip($args_iter().enumerate()) {
1968 let mut var = std::io::Cursor::new(Vec::new());
1969 write!(&mut var, "{}", var_name).unwrap();
1970 let var_access = String::from_utf8(var.into_inner()).unwrap();
1972 let conv_ty = if needs_ref_map { only_contained_type.as_ref().unwrap() } else { ty };
1974 write!(w, "{} {{ ", pfx).unwrap();
1975 let new_var_name = format!("{}_{}", ident, idx);
1976 let new_var = self.write_conversion_new_var_intern(w, &format_ident!("{}", new_var_name),
1977 &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);
1978 if new_var { write!(w, " ").unwrap(); }
1980 if prefix_location == ContainerPrefixLocation::PerConv {
1981 var_prefix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1982 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
1983 write!(w, "Box::into_raw(Box::new(").unwrap();
1986 write!(w, "{}{}", if contains_slice { "local_" } else { "" }, if new_var { new_var_name } else { var_access }).unwrap();
1987 if prefix_location == ContainerPrefixLocation::PerConv {
1988 var_suffix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1989 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
1990 write!(w, "))").unwrap();
1992 write!(w, " }}").unwrap();
1994 write!(w, "{}", suffix).unwrap();
1995 if prefix_location == ContainerPrefixLocation::OutsideConv {
1996 var_suffix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
1998 write!(w, ";").unwrap();
1999 if !to_c && needs_ref_map {
2000 write!(w, " let mut local_{} = local_{}_base.as_ref()", ident, ident).unwrap();
2002 write!(w, ".map(|a| &a[..])").unwrap();
2004 write!(w, ";").unwrap();
2011 match generics.resolve_type(t) {
2012 syn::Type::Reference(r) => {
2013 if let syn::Type::Slice(_) = &*r.elem {
2014 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)
2016 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)
2019 syn::Type::Path(p) => {
2020 if p.qself.is_some() {
2023 let resolved_path = self.resolve_path(&p.path, generics);
2024 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
2025 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);
2027 if self.is_known_container(&resolved_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
2028 if let syn::PathArguments::AngleBracketed(args) = &p.path.segments.iter().next().unwrap().arguments {
2029 convert_container!(resolved_path, args.args.len(), || args.args.iter().map(|arg| {
2030 if let syn::GenericArgument::Type(ty) = arg {
2032 } else { unimplemented!(); }
2034 } else { unimplemented!(); }
2036 if self.is_primitive(&resolved_path) {
2038 } else if let Some(ty_ident) = single_ident_generic_path_to_ident(&p.path) {
2039 if let Some((prefix, suffix)) = path_lookup(&resolved_path, is_ref) {
2040 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
2042 } else if self.types.maybe_resolve_declared(ty_ident).is_some() {
2047 syn::Type::Array(_) => {
2048 // We assume all arrays contain only primitive types.
2049 // This may result in some outputs not compiling.
2052 syn::Type::Slice(s) => {
2053 if let syn::Type::Path(p) = &*s.elem {
2054 let resolved = self.resolve_path(&p.path, generics);
2055 assert!(self.is_primitive(&resolved));
2056 let slice_path = format!("[{}]", resolved);
2057 if let Some((prefix, suffix)) = path_lookup(&slice_path, true) {
2058 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
2061 } else if let syn::Type::Reference(ty) = &*s.elem {
2062 let tyref = [&*ty.elem];
2064 convert_container!("Slice", 1, || tyref.iter().map(|t| *t));
2065 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
2066 } else if let syn::Type::Tuple(t) = &*s.elem {
2067 // When mapping into a temporary new var, we need to own all the underlying objects.
2068 // Thus, we drop any references inside the tuple and convert with non-reference types.
2069 let mut elems = syn::punctuated::Punctuated::new();
2070 for elem in t.elems.iter() {
2071 if let syn::Type::Reference(r) = elem {
2072 elems.push((*r.elem).clone());
2074 elems.push(elem.clone());
2077 let ty = [syn::Type::Tuple(syn::TypeTuple {
2078 paren_token: t.paren_token, elems
2082 convert_container!("Slice", 1, || ty.iter());
2083 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
2084 } else { unimplemented!() }
2086 syn::Type::Tuple(t) => {
2087 if !t.elems.is_empty() {
2088 // We don't (yet) support tuple elements which cannot be converted inline
2089 write!(w, "let (").unwrap();
2090 for idx in 0..t.elems.len() {
2091 if idx != 0 { write!(w, ", ").unwrap(); }
2092 write!(w, "{} orig_{}_{}", if is_ref { "ref" } else { "mut" }, ident, idx).unwrap();
2094 write!(w, ") = {}{}; ", var, if !to_c { ".to_rust()" } else { "" }).unwrap();
2095 // Like other template types, tuples are always mapped as their non-ref
2096 // versions for types which have different ref mappings. Thus, we convert to
2097 // non-ref versions and handle opaque types with inner pointers manually.
2098 for (idx, elem) in t.elems.iter().enumerate() {
2099 if let syn::Type::Path(p) = elem {
2100 let v_name = format!("orig_{}_{}", ident, idx);
2101 let tuple_elem_ident = format_ident!("{}", &v_name);
2102 if self.write_conversion_new_var_intern(w, &tuple_elem_ident, &v_name, elem, generics,
2103 false, ptr_for_ref, to_c,
2104 path_lookup, container_lookup, var_prefix, var_suffix) {
2105 write!(w, " ").unwrap();
2106 // Opaque types with inner pointers shouldn't ever create new stack
2107 // variables, so we don't handle it and just assert that it doesn't
2109 assert!(!self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)));
2113 write!(w, "let mut local_{} = (", ident).unwrap();
2114 for (idx, elem) in t.elems.iter().enumerate() {
2115 let ty_has_inner = {
2117 // "To C ptr_for_ref" means "return the regular object with
2118 // is_owned set to false", which is totally what we want
2119 // if we're about to set ty_has_inner.
2122 if let syn::Type::Reference(t) = elem {
2123 if let syn::Type::Path(p) = &*t.elem {
2124 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2126 } else if let syn::Type::Path(p) = elem {
2127 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2130 if idx != 0 { write!(w, ", ").unwrap(); }
2131 var_prefix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2132 if is_ref && ty_has_inner {
2133 // For ty_has_inner, the regular var_prefix mapping will take a
2134 // reference, so deref once here to make sure we keep the original ref.
2135 write!(w, "*").unwrap();
2137 write!(w, "orig_{}_{}", ident, idx).unwrap();
2138 if is_ref && !ty_has_inner {
2139 // If we don't have an inner variable's reference to maintain, just
2140 // hope the type is Clonable and use that.
2141 write!(w, ".clone()").unwrap();
2143 var_suffix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2145 write!(w, "){};", if to_c { ".into()" } else { "" }).unwrap();
2149 _ => unimplemented!(),
2153 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 {
2154 self.write_conversion_new_var_intern(w, ident, var_access, t, generics, false, ptr_for_ref, true,
2155 &|a, b| self.to_c_conversion_new_var_from_path(a, b),
2156 &|a, b, c, d, e| self.to_c_conversion_container_new_var(generics, a, b, c, d, e),
2157 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
2158 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_prefix_inner(a, b, c, d, e, f),
2159 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_suffix_inner(a, b, c, d, e, f))
2161 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 {
2162 self.write_to_c_conversion_new_var_inner(w, ident, &format!("{}", ident), t, generics, ptr_for_ref)
2164 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 {
2165 self.write_conversion_new_var_intern(w, ident, &format!("{}", ident), t, generics, false, false, false,
2166 &|a, b| self.from_c_conversion_new_var_from_path(a, b),
2167 &|a, b, c, d, e| self.from_c_conversion_container_new_var(generics, a, b, c, d, e),
2168 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
2169 &|a, b, c, d, e, _f| self.write_from_c_conversion_prefix_inner(a, b, c, d, e),
2170 &|a, b, c, d, e, _f| self.write_from_c_conversion_suffix_inner(a, b, c, d, e))
2173 // ******************************************************
2174 // *** C Container Type Equivalent and alias Printing ***
2175 // ******************************************************
2177 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 {
2178 for (idx, t) in args.enumerate() {
2180 write!(w, ", ").unwrap();
2182 if let syn::Type::Reference(r_arg) = t {
2183 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2185 if !self.write_c_type_intern(w, &*r_arg.elem, generics, false, false, false) { return false; }
2187 // While write_c_type_intern, above is correct, we don't want to blindly convert a
2188 // reference to something stupid, so check that the container is either opaque or a
2189 // predefined type (currently only Transaction).
2190 if let syn::Type::Path(p_arg) = &*r_arg.elem {
2191 let resolved = self.resolve_path(&p_arg.path, generics);
2192 assert!(self.crate_types.opaques.get(&resolved).is_some() ||
2193 self.c_type_from_path(&resolved, true, true).is_some(), "Template generics should be opaque or have a predefined mapping");
2194 } else { unimplemented!(); }
2195 } else if let syn::Type::Path(p_arg) = t {
2196 if let Some(resolved) = self.maybe_resolve_path(&p_arg.path, generics) {
2197 if !self.is_primitive(&resolved) {
2198 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2201 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2203 if !self.write_c_type_intern(w, t, generics, false, false, false) { return false; }
2205 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2206 if !self.write_c_type_intern(w, t, generics, false, false, false) { return false; }
2211 fn check_create_container(&self, mangled_container: String, container_type: &str, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
2212 if !self.crate_types.templates_defined.borrow().get(&mangled_container).is_some() {
2213 let mut created_container: Vec<u8> = Vec::new();
2215 if container_type == "Result" {
2216 let mut a_ty: Vec<u8> = Vec::new();
2217 if let syn::Type::Tuple(tup) = args.iter().next().unwrap() {
2218 if tup.elems.is_empty() {
2219 write!(&mut a_ty, "()").unwrap();
2221 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
2224 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
2227 let mut b_ty: Vec<u8> = Vec::new();
2228 if let syn::Type::Tuple(tup) = args.iter().skip(1).next().unwrap() {
2229 if tup.elems.is_empty() {
2230 write!(&mut b_ty, "()").unwrap();
2232 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
2235 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
2238 let ok_str = String::from_utf8(a_ty).unwrap();
2239 let err_str = String::from_utf8(b_ty).unwrap();
2240 let is_clonable = self.is_clonable(&ok_str) && self.is_clonable(&err_str);
2241 write_result_block(&mut created_container, &mangled_container, &ok_str, &err_str, is_clonable);
2243 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2245 } else if container_type == "Vec" {
2246 let mut a_ty: Vec<u8> = Vec::new();
2247 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2248 let ty = String::from_utf8(a_ty).unwrap();
2249 let is_clonable = self.is_clonable(&ty);
2250 write_vec_block(&mut created_container, &mangled_container, &ty, is_clonable);
2252 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2254 } else if container_type.ends_with("Tuple") {
2255 let mut tuple_args = Vec::new();
2256 let mut is_clonable = true;
2257 for arg in args.iter() {
2258 let mut ty: Vec<u8> = Vec::new();
2259 if !self.write_template_generics(&mut ty, &mut [arg].iter().map(|t| **t), generics, is_ref) { return false; }
2260 let ty_str = String::from_utf8(ty).unwrap();
2261 if !self.is_clonable(&ty_str) {
2262 is_clonable = false;
2264 tuple_args.push(ty_str);
2266 write_tuple_block(&mut created_container, &mangled_container, &tuple_args, is_clonable);
2268 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2270 } else if container_type == "Option" {
2271 let mut a_ty: Vec<u8> = Vec::new();
2272 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2273 let ty = String::from_utf8(a_ty).unwrap();
2274 let is_clonable = self.is_clonable(&ty);
2275 write_option_block(&mut created_container, &mangled_container, &ty, is_clonable);
2277 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2282 self.crate_types.write_new_template(mangled_container.clone(), true, &created_container);
2286 fn path_to_generic_args(path: &syn::Path) -> Vec<&syn::Type> {
2287 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().next().unwrap().arguments {
2288 args.args.iter().map(|gen| if let syn::GenericArgument::Type(t) = gen { t } else { unimplemented!() }).collect()
2289 } else { unimplemented!(); }
2291 fn write_c_mangled_container_path_intern<W: std::io::Write>
2292 (&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 {
2293 let mut mangled_type: Vec<u8> = Vec::new();
2294 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2295 write!(w, "C{}_", ident).unwrap();
2296 write!(mangled_type, "C{}_", ident).unwrap();
2297 } else { assert_eq!(args.len(), 1); }
2298 for arg in args.iter() {
2299 macro_rules! write_path {
2300 ($p_arg: expr, $extra_write: expr) => {
2301 if let Some(subtype) = self.maybe_resolve_path(&$p_arg.path, generics) {
2302 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2304 if self.c_type_has_inner_from_path(&subtype) {
2305 if !self.write_c_path_intern(w, &$p_arg.path, generics, is_ref, is_mut, ptr_for_ref) { return false; }
2307 if let Some(arr_ty) = self.is_real_type_array(&subtype) {
2308 if !self.write_c_type_intern(w, &arr_ty, generics, false, true, false) { return false; }
2310 // Option<T> needs to be converted to a *mut T, ie mut ptr-for-ref
2311 if !self.write_c_path_intern(w, &$p_arg.path, generics, true, true, true) { return false; }
2315 write!(w, "{}", $p_arg.path.segments.last().unwrap().ident).unwrap();
2317 } else if self.is_known_container(&subtype, is_ref) || self.is_path_transparent_container(&$p_arg.path, generics, is_ref) {
2318 if !self.write_c_mangled_container_path_intern(w, Self::path_to_generic_args(&$p_arg.path), generics,
2319 &subtype, is_ref, is_mut, ptr_for_ref, true) {
2322 self.write_c_mangled_container_path_intern(&mut mangled_type, Self::path_to_generic_args(&$p_arg.path),
2323 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2324 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2325 self.write_c_mangled_container_path_intern(w2, Self::path_to_generic_args(&$p_arg.path),
2326 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2329 let id = subtype.rsplitn(2, ':').next().unwrap(); // Get the "Base" name of the resolved type
2330 write!(w, "{}", id).unwrap();
2331 write!(mangled_type, "{}", id).unwrap();
2332 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2333 write!(w2, "{}", id).unwrap();
2336 } else { return false; }
2339 if let syn::Type::Tuple(tuple) = arg {
2340 if tuple.elems.len() == 0 {
2341 write!(w, "None").unwrap();
2342 write!(mangled_type, "None").unwrap();
2344 let mut mangled_tuple_type: Vec<u8> = Vec::new();
2346 // Figure out what the mangled type should look like. To disambiguate
2347 // ((A, B), C) and (A, B, C) we prefix the generic args with a _ and suffix
2348 // them with a Z. Ideally we wouldn't use Z, but not many special chars are
2349 // available for use in type names.
2350 write!(w, "C{}Tuple_", tuple.elems.len()).unwrap();
2351 write!(mangled_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2352 write!(mangled_tuple_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2353 for elem in tuple.elems.iter() {
2354 if let syn::Type::Path(p) = elem {
2355 write_path!(p, Some(&mut mangled_tuple_type));
2356 } else if let syn::Type::Reference(refelem) = elem {
2357 if let syn::Type::Path(p) = &*refelem.elem {
2358 write_path!(p, Some(&mut mangled_tuple_type));
2359 } else { return false; }
2360 } else { return false; }
2362 write!(w, "Z").unwrap();
2363 write!(mangled_type, "Z").unwrap();
2364 write!(mangled_tuple_type, "Z").unwrap();
2365 if !self.check_create_container(String::from_utf8(mangled_tuple_type).unwrap(),
2366 &format!("{}Tuple", tuple.elems.len()), tuple.elems.iter().collect(), generics, is_ref) {
2370 } else if let syn::Type::Path(p_arg) = arg {
2371 write_path!(p_arg, None);
2372 } else if let syn::Type::Reference(refty) = arg {
2373 if let syn::Type::Path(p_arg) = &*refty.elem {
2374 write_path!(p_arg, None);
2375 } else if let syn::Type::Slice(_) = &*refty.elem {
2376 // write_c_type will actually do exactly what we want here, we just need to
2377 // make it a pointer so that its an option. Note that we cannot always convert
2378 // the Vec-as-slice (ie non-ref types) containers, so sometimes need to be able
2379 // to edit it, hence we use *mut here instead of *const.
2380 if args.len() != 1 { return false; }
2381 write!(w, "*mut ").unwrap();
2382 self.write_c_type(w, arg, None, true);
2383 } else { return false; }
2384 } else if let syn::Type::Array(a) = arg {
2385 if let syn::Type::Path(p_arg) = &*a.elem {
2386 let resolved = self.resolve_path(&p_arg.path, generics);
2387 if !self.is_primitive(&resolved) { return false; }
2388 if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(len), .. }) = &a.len {
2389 if self.c_type_from_path(&format!("[{}; {}]", resolved, len.base10_digits()), is_ref, ptr_for_ref).is_none() { return false; }
2390 write!(w, "_{}{}", resolved, len.base10_digits()).unwrap();
2391 write!(mangled_type, "_{}{}", resolved, len.base10_digits()).unwrap();
2392 } else { return false; }
2393 } else { return false; }
2394 } else { return false; }
2396 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) { return true; }
2397 // Push the "end of type" Z
2398 write!(w, "Z").unwrap();
2399 write!(mangled_type, "Z").unwrap();
2401 // Make sure the type is actually defined:
2402 self.check_create_container(String::from_utf8(mangled_type).unwrap(), ident, args, generics, is_ref)
2404 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 {
2405 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2406 write!(w, "{}::", Self::generated_container_path()).unwrap();
2408 self.write_c_mangled_container_path_intern(w, args, generics, ident, is_ref, is_mut, ptr_for_ref, false)
2410 pub fn get_c_mangled_container_type(&self, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, template_name: &str) -> Option<String> {
2411 let mut out = Vec::new();
2412 if !self.write_c_mangled_container_path(&mut out, args, generics, template_name, false, false, false) {
2415 Some(String::from_utf8(out).unwrap())
2418 // **********************************
2419 // *** C Type Equivalent Printing ***
2420 // **********************************
2422 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 {
2423 let full_path = match self.maybe_resolve_path(&path, generics) {
2424 Some(path) => path, None => return false };
2425 if let Some(c_type) = self.c_type_from_path(&full_path, is_ref, ptr_for_ref) {
2426 write!(w, "{}", c_type).unwrap();
2428 } else if self.crate_types.traits.get(&full_path).is_some() {
2429 if is_ref && ptr_for_ref {
2430 write!(w, "*{} crate::{}", if is_mut { "mut" } else { "const" }, full_path).unwrap();
2432 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2434 write!(w, "crate::{}", full_path).unwrap();
2437 } else if self.crate_types.opaques.get(&full_path).is_some() || self.crate_types.mirrored_enums.get(&full_path).is_some() {
2438 if is_ref && ptr_for_ref {
2439 // ptr_for_ref implies we're returning the object, which we can't really do for
2440 // opaque or mirrored types without box'ing them, which is quite a waste, so return
2441 // the actual object itself (for opaque types we'll set the pointer to the actual
2442 // type and note that its a reference).
2443 write!(w, "crate::{}", full_path).unwrap();
2445 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2447 write!(w, "crate::{}", full_path).unwrap();
2454 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 {
2455 match generics.resolve_type(t) {
2456 syn::Type::Path(p) => {
2457 if p.qself.is_some() {
2460 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
2461 if self.is_known_container(&full_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
2462 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);
2464 if let Some(aliased_type) = self.crate_types.type_aliases.get(&full_path).cloned() {
2465 return self.write_c_type_intern(w, &aliased_type, None, is_ref, is_mut, ptr_for_ref);
2468 self.write_c_path_intern(w, &p.path, generics, is_ref, is_mut, ptr_for_ref)
2470 syn::Type::Reference(r) => {
2471 self.write_c_type_intern(w, &*r.elem, generics, true, r.mutability.is_some(), ptr_for_ref)
2473 syn::Type::Array(a) => {
2474 if is_ref && is_mut {
2475 write!(w, "*mut [").unwrap();
2476 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2478 write!(w, "*const [").unwrap();
2479 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2481 let mut typecheck = Vec::new();
2482 if !self.write_c_type_intern(&mut typecheck, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2483 if typecheck[..] != ['u' as u8, '8' as u8] { return false; }
2485 if let syn::Expr::Lit(l) = &a.len {
2486 if let syn::Lit::Int(i) = &l.lit {
2488 if let Some(ty) = self.c_type_from_path(&format!("[u8; {}]", i.base10_digits()), false, ptr_for_ref) {
2489 write!(w, "{}", ty).unwrap();
2493 write!(w, "; {}]", i).unwrap();
2499 syn::Type::Slice(s) => {
2500 if !is_ref || is_mut { return false; }
2501 if let syn::Type::Path(p) = &*s.elem {
2502 let resolved = self.resolve_path(&p.path, generics);
2503 if self.is_primitive(&resolved) {
2504 write!(w, "{}::{}slice", Self::container_templ_path(), resolved).unwrap();
2507 } else if let syn::Type::Reference(r) = &*s.elem {
2508 if let syn::Type::Path(p) = &*r.elem {
2509 // Slices with "real types" inside are mapped as the equivalent non-ref Vec
2510 let resolved = self.resolve_path(&p.path, generics);
2511 let mangled_container = if let Some(ident) = self.crate_types.opaques.get(&resolved) {
2512 format!("CVec_{}Z", ident)
2513 } else if let Some(en) = self.crate_types.mirrored_enums.get(&resolved) {
2514 format!("CVec_{}Z", en.ident)
2515 } else if let Some(id) = p.path.get_ident() {
2516 format!("CVec_{}Z", id)
2517 } else { return false; };
2518 write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
2519 self.check_create_container(mangled_container, "Vec", vec![&*r.elem], generics, false)
2521 } else if let syn::Type::Tuple(_) = &*s.elem {
2522 let mut args = syn::punctuated::Punctuated::<_, syn::token::Comma>::new();
2523 args.push(syn::GenericArgument::Type((*s.elem).clone()));
2524 let mut segments = syn::punctuated::Punctuated::new();
2525 segments.push(parse_quote!(Vec<#args>));
2526 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)
2529 syn::Type::Tuple(t) => {
2530 if t.elems.len() == 0 {
2533 self.write_c_mangled_container_path(w, t.elems.iter().collect(), generics,
2534 &format!("{}Tuple", t.elems.len()), is_ref, is_mut, ptr_for_ref)
2540 pub fn write_c_type<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) {
2541 assert!(self.write_c_type_intern(w, t, generics, false, false, ptr_for_ref));
2543 pub fn understood_c_path(&self, p: &syn::Path) -> bool {
2544 if p.leading_colon.is_some() { return false; }
2545 self.write_c_path_intern(&mut std::io::sink(), p, None, false, false, false)
2547 pub fn understood_c_type(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
2548 self.write_c_type_intern(&mut std::io::sink(), t, generics, false, false, false)