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" => Some("crate::c_types::Str"),
847 "std::time::Duration" => Some("u64"),
848 "std::time::SystemTime" => Some("u64"),
849 "std::io::Error" => Some("crate::c_types::IOError"),
851 "bech32::u5" => Some("crate::c_types::u5"),
853 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
854 => Some("crate::c_types::PublicKey"),
855 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature"),
856 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some("crate::c_types::RecoverableSignature"),
857 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
858 if is_ref => Some("*const [u8; 32]"),
859 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
860 if !is_ref => Some("crate::c_types::SecretKey"),
861 "bitcoin::secp256k1::Error"|"secp256k1::Error"
862 if !is_ref => Some("crate::c_types::Secp256k1Error"),
863 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice"),
864 "bitcoin::blockdata::script::Script" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
865 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::lightning::chain::transaction::OutPoint"),
866 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction"),
867 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut"),
868 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network"),
869 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("*const [u8; 80]"),
870 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice"),
872 // Newtypes that we just expose in their original form.
873 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
874 if is_ref => Some("*const [u8; 32]"),
875 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
876 if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
877 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
878 "lightning::ln::PaymentHash" if is_ref => Some("*const [u8; 32]"),
879 "lightning::ln::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
880 "lightning::ln::PaymentPreimage" if is_ref => Some("*const [u8; 32]"),
881 "lightning::ln::PaymentPreimage" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
882 "lightning::ln::PaymentSecret" => Some("crate::c_types::ThirtyTwoBytes"),
884 // Override the default since Records contain an fmt with a lifetime:
885 "lightning::util::logger::Record" => Some("*const std::os::raw::c_char"),
891 fn from_c_conversion_new_var_from_path<'b>(&self, _full_path: &str, _is_ref: bool) -> Option<(&'b str, &'b str)> {
894 fn from_c_conversion_prefix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
895 if self.is_primitive(full_path) {
896 return Some("".to_owned());
899 "Vec" if !is_ref => Some("local_"),
900 "Result" if !is_ref => Some("local_"),
901 "Option" if is_ref => Some("&local_"),
902 "Option" => Some("local_"),
904 "[u8; 32]" if is_ref => Some("unsafe { &*"),
905 "[u8; 32]" if !is_ref => Some(""),
906 "[u8; 20]" if !is_ref => Some(""),
907 "[u8; 16]" if !is_ref => Some(""),
908 "[u8; 10]" if !is_ref => Some(""),
909 "[u8; 4]" if !is_ref => Some(""),
910 "[u8; 3]" if !is_ref => Some(""),
912 "[u8]" if is_ref => Some(""),
913 "[usize]" if is_ref => Some(""),
915 "str" if is_ref => Some(""),
916 "String" => Some(""),
917 // Note that we'll panic for String if is_ref, as we only have non-owned memory, we
918 // cannot create a &String.
920 "std::time::Duration" => Some("std::time::Duration::from_secs("),
921 "std::time::SystemTime" => Some("(::std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs("),
923 "bech32::u5" => Some(""),
925 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
926 if is_ref => Some("&"),
927 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
929 "bitcoin::secp256k1::Signature" if is_ref => Some("&"),
930 "bitcoin::secp256k1::Signature" => Some(""),
931 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(""),
932 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
933 if is_ref => Some("&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *"),
934 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
935 if !is_ref => Some(""),
936 "bitcoin::blockdata::script::Script" if is_ref => Some("&::bitcoin::blockdata::script::Script::from(Vec::from("),
937 "bitcoin::blockdata::script::Script" if !is_ref => Some("::bitcoin::blockdata::script::Script::from("),
938 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some("&"),
939 "bitcoin::blockdata::transaction::Transaction" => Some(""),
940 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(""),
941 "bitcoin::network::constants::Network" => Some(""),
942 "bitcoin::blockdata::block::BlockHeader" => Some("&::bitcoin::consensus::encode::deserialize(unsafe { &*"),
943 "bitcoin::blockdata::block::Block" if is_ref => Some("&::bitcoin::consensus::encode::deserialize("),
945 // Newtypes that we just expose in their original form.
946 "bitcoin::hash_types::Txid" if is_ref => Some("&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*"),
947 "bitcoin::hash_types::Txid" if !is_ref => Some("::bitcoin::hash_types::Txid::from_slice(&"),
948 "bitcoin::hash_types::BlockHash" => Some("::bitcoin::hash_types::BlockHash::from_slice(&"),
949 "lightning::ln::PaymentHash" if !is_ref => Some("::lightning::ln::PaymentHash("),
950 "lightning::ln::PaymentHash" if is_ref => Some("&::lightning::ln::PaymentHash(unsafe { *"),
951 "lightning::ln::PaymentPreimage" if !is_ref => Some("::lightning::ln::PaymentPreimage("),
952 "lightning::ln::PaymentPreimage" if is_ref => Some("&::lightning::ln::PaymentPreimage(unsafe { *"),
953 "lightning::ln::PaymentSecret" => Some("::lightning::ln::PaymentSecret("),
955 // List of traits we map (possibly during processing of other files):
956 "crate::util::logger::Logger" => Some(""),
959 }.map(|s| s.to_owned())
961 fn from_c_conversion_suffix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
962 if self.is_primitive(full_path) {
963 return Some("".to_owned());
966 "Vec" if !is_ref => Some(""),
967 "Option" => Some(""),
968 "Result" if !is_ref => Some(""),
970 "[u8; 32]" if is_ref => Some("}"),
971 "[u8; 32]" if !is_ref => Some(".data"),
972 "[u8; 20]" if !is_ref => Some(".data"),
973 "[u8; 16]" if !is_ref => Some(".data"),
974 "[u8; 10]" if !is_ref => Some(".data"),
975 "[u8; 4]" if !is_ref => Some(".data"),
976 "[u8; 3]" if !is_ref => Some(".data"),
978 "[u8]" if is_ref => Some(".to_slice()"),
979 "[usize]" if is_ref => Some(".to_slice()"),
981 "str" if is_ref => Some(".into_str()"),
982 "String" => Some(".into_string()"),
984 "std::time::Duration" => Some(")"),
985 "std::time::SystemTime" => Some("))"),
987 "bech32::u5" => Some(".into()"),
989 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
990 => Some(".into_rust()"),
991 "bitcoin::secp256k1::Signature" => Some(".into_rust()"),
992 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(".into_rust()"),
993 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
994 if !is_ref => Some(".into_rust()"),
995 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
996 if is_ref => Some("}[..]).unwrap()"),
997 "bitcoin::blockdata::script::Script" if is_ref => Some(".to_slice()))"),
998 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_rust())"),
999 "bitcoin::blockdata::transaction::Transaction" => Some(".into_bitcoin()"),
1000 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(".into_rust()"),
1001 "bitcoin::network::constants::Network" => Some(".into_bitcoin()"),
1002 "bitcoin::blockdata::block::BlockHeader" => Some(" }).unwrap()"),
1003 "bitcoin::blockdata::block::Block" => Some(".to_slice()).unwrap()"),
1005 // Newtypes that we just expose in their original form.
1006 "bitcoin::hash_types::Txid" if is_ref => Some(" }[..]).unwrap()"),
1007 "bitcoin::hash_types::Txid" => Some(".data[..]).unwrap()"),
1008 "bitcoin::hash_types::BlockHash" if !is_ref => Some(".data[..]).unwrap()"),
1009 "lightning::ln::PaymentHash" if !is_ref => Some(".data)"),
1010 "lightning::ln::PaymentHash" if is_ref => Some(" })"),
1011 "lightning::ln::PaymentPreimage" if !is_ref => Some(".data)"),
1012 "lightning::ln::PaymentPreimage" if is_ref => Some(" })"),
1013 "lightning::ln::PaymentSecret" => Some(".data)"),
1015 // List of traits we map (possibly during processing of other files):
1016 "crate::util::logger::Logger" => Some(""),
1019 }.map(|s| s.to_owned())
1022 fn to_c_conversion_new_var_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<(&'b str, &'b str)> {
1023 if self.is_primitive(full_path) {
1027 "[u8]" if is_ref => Some(("crate::c_types::u8slice::from_slice(", ")")),
1028 "[usize]" if is_ref => Some(("crate::c_types::usizeslice::from_slice(", ")")),
1030 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(("{ let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(", ")); s }")),
1031 "bitcoin::blockdata::block::Block" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
1032 "bitcoin::hash_types::Txid" => None,
1034 // Override the default since Records contain an fmt with a lifetime:
1035 // TODO: We should include the other record fields
1036 "lightning::util::logger::Record" => Some(("std::ffi::CString::new(format!(\"{}\", ", ".args)).unwrap()")),
1038 }.map(|s| s.to_owned())
1040 fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
1041 if self.is_primitive(full_path) {
1042 return Some("".to_owned());
1045 "Result" if !is_ref => Some("local_"),
1046 "Vec" if !is_ref => Some("local_"),
1047 "Option" => Some("local_"),
1049 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1050 "[u8; 32]" if is_ref => Some(""),
1051 "[u8; 20]" if !is_ref => Some("crate::c_types::TwentyBytes { data: "),
1052 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes { data: "),
1053 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes { data: "),
1054 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes { data: "),
1055 "[u8; 3]" if is_ref => Some(""),
1057 "[u8]" if is_ref => Some("local_"),
1058 "[usize]" if is_ref => Some("local_"),
1060 "str" if is_ref => Some(""),
1061 "String" => Some(""),
1063 "std::time::Duration" => Some(""),
1064 "std::time::SystemTime" => Some(""),
1065 "std::io::Error" if !is_ref => Some("crate::c_types::IOError::from_rust("),
1067 "bech32::u5" => Some(""),
1069 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1070 => Some("crate::c_types::PublicKey::from_rust(&"),
1071 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature::from_rust(&"),
1072 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some("crate::c_types::RecoverableSignature::from_rust(&"),
1073 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1074 if is_ref => Some(""),
1075 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1076 if !is_ref => Some("crate::c_types::SecretKey::from_rust("),
1077 "bitcoin::secp256k1::Error"|"secp256k1::Error"
1078 if !is_ref => Some("crate::c_types::Secp256k1Error::from_rust("),
1079 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice::from_slice(&"),
1080 "bitcoin::blockdata::script::Script" if !is_ref => Some(""),
1081 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some("crate::c_types::Transaction::from_bitcoin("),
1082 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction::from_bitcoin(&"),
1083 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::c_types::bitcoin_to_C_outpoint("),
1084 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut::from_rust("),
1085 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network::from_bitcoin("),
1086 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("&local_"),
1087 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice::from_slice(&local_"),
1089 "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1091 // Newtypes that we just expose in their original form.
1092 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1093 if is_ref => Some(""),
1094 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1095 if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1096 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1097 "lightning::ln::PaymentHash" if is_ref => Some("&"),
1098 "lightning::ln::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1099 "lightning::ln::PaymentPreimage" if is_ref => Some("&"),
1100 "lightning::ln::PaymentPreimage" => Some("crate::c_types::ThirtyTwoBytes { data: "),
1101 "lightning::ln::PaymentSecret" => Some("crate::c_types::ThirtyTwoBytes { data: "),
1103 // Override the default since Records contain an fmt with a lifetime:
1104 "lightning::util::logger::Record" => Some("local_"),
1107 }.map(|s| s.to_owned())
1109 fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
1110 if self.is_primitive(full_path) {
1111 return Some("".to_owned());
1114 "Result" if !is_ref => Some(""),
1115 "Vec" if !is_ref => Some(".into()"),
1116 "Option" => Some(""),
1118 "[u8; 32]" if !is_ref => Some(" }"),
1119 "[u8; 32]" if is_ref => Some(""),
1120 "[u8; 20]" if !is_ref => Some(" }"),
1121 "[u8; 16]" if !is_ref => Some(" }"),
1122 "[u8; 10]" if !is_ref => Some(" }"),
1123 "[u8; 4]" if !is_ref => Some(" }"),
1124 "[u8; 3]" if is_ref => Some(""),
1126 "[u8]" if is_ref => Some(""),
1127 "[usize]" if is_ref => Some(""),
1129 "str" if is_ref => Some(".into()"),
1130 "String" if is_ref => Some(".as_str().into()"),
1131 "String" => Some(".into()"),
1133 "std::time::Duration" => Some(".as_secs()"),
1134 "std::time::SystemTime" => Some(".duration_since(::std::time::SystemTime::UNIX_EPOCH).expect(\"Times must be post-1970\").as_secs()"),
1135 "std::io::Error" if !is_ref => Some(")"),
1137 "bech32::u5" => Some(".into()"),
1139 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1141 "bitcoin::secp256k1::Signature" => Some(")"),
1142 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(")"),
1143 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1144 if !is_ref => Some(")"),
1145 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1146 if is_ref => Some(".as_ref()"),
1147 "bitcoin::secp256k1::Error"|"secp256k1::Error"
1148 if !is_ref => Some(")"),
1149 "bitcoin::blockdata::script::Script" if is_ref => Some("[..])"),
1150 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_bytes().into()"),
1151 "bitcoin::blockdata::transaction::Transaction" => Some(")"),
1152 "bitcoin::blockdata::transaction::OutPoint" => Some(")"),
1153 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(")"),
1154 "bitcoin::network::constants::Network" => Some(")"),
1155 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(""),
1156 "bitcoin::blockdata::block::Block" if is_ref => Some(")"),
1158 "bitcoin::hash_types::Txid" if !is_ref => Some(".into_inner() }"),
1160 // Newtypes that we just expose in their original form.
1161 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1162 if is_ref => Some(".as_inner()"),
1163 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1164 if !is_ref => Some(".into_inner() }"),
1165 "bitcoin::secp256k1::Message" if !is_ref => Some(".as_ref().clone() }"),
1166 "lightning::ln::PaymentHash" if is_ref => Some(".0"),
1167 "lightning::ln::PaymentHash" => Some(".0 }"),
1168 "lightning::ln::PaymentPreimage" if is_ref => Some(".0"),
1169 "lightning::ln::PaymentPreimage" => Some(".0 }"),
1170 "lightning::ln::PaymentSecret" => Some(".0 }"),
1172 // Override the default since Records contain an fmt with a lifetime:
1173 "lightning::util::logger::Record" => Some(".as_ptr()"),
1176 }.map(|s| s.to_owned())
1179 fn empty_val_check_suffix_from_path(&self, full_path: &str) -> Option<&str> {
1181 "lightning::ln::PaymentSecret" => Some(".data == [0; 32]"),
1182 "secp256k1::key::PublicKey"|"bitcoin::secp256k1::key::PublicKey" => Some(".is_null()"),
1183 "bitcoin::secp256k1::Signature" => Some(".is_null()"),
1188 // ****************************
1189 // *** Container Processing ***
1190 // ****************************
1192 /// Returns the module path in the generated mapping crate to the containers which we generate
1193 /// when writing to CrateTypes::template_file.
1194 pub fn generated_container_path() -> &'static str {
1195 "crate::c_types::derived"
1197 /// Returns the module path in the generated mapping crate to the container templates, which
1198 /// are then concretized and put in the generated container path/template_file.
1199 fn container_templ_path() -> &'static str {
1203 /// Returns true if the path containing the given args is a "transparent" container, ie an
1204 /// Option or a container which does not require a generated continer class.
1205 fn is_transparent_container<'i, I: Iterator<Item=&'i syn::Type>>(&self, full_path: &str, _is_ref: bool, mut args: I) -> bool {
1206 if full_path == "Option" {
1207 let inner = args.next().unwrap();
1208 assert!(args.next().is_none());
1210 syn::Type::Reference(_) => true,
1211 syn::Type::Path(p) => {
1212 if let Some(resolved) = self.maybe_resolve_path(&p.path, None) {
1213 if self.is_primitive(&resolved) { false } else { true }
1216 syn::Type::Tuple(_) => false,
1217 _ => unimplemented!(),
1221 /// Returns true if the path is a "transparent" container, ie an Option or a container which does
1222 /// not require a generated continer class.
1223 fn is_path_transparent_container(&self, full_path: &syn::Path, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
1224 let inner_iter = match &full_path.segments.last().unwrap().arguments {
1225 syn::PathArguments::None => return false,
1226 syn::PathArguments::AngleBracketed(args) => args.args.iter().map(|arg| {
1227 if let syn::GenericArgument::Type(ref ty) = arg {
1229 } else { unimplemented!() }
1231 syn::PathArguments::Parenthesized(_) => unimplemented!(),
1233 self.is_transparent_container(&self.resolve_path(full_path, generics), is_ref, inner_iter)
1235 /// Returns true if this is a known, supported, non-transparent container.
1236 fn is_known_container(&self, full_path: &str, is_ref: bool) -> bool {
1237 (full_path == "Result" && !is_ref) || (full_path == "Vec" && !is_ref) || full_path.ends_with("Tuple") || full_path == "Option"
1239 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)
1240 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1241 // expecting one element in the vec per generic type, each of which is inline-converted
1242 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1244 "Result" if !is_ref => {
1246 vec![(" { Ok(mut o) => crate::c_types::CResultTempl::ok(".to_string(), "o".to_string()),
1247 (").into(), Err(mut e) => crate::c_types::CResultTempl::err(".to_string(), "e".to_string())],
1248 ").into() }", ContainerPrefixLocation::PerConv))
1250 "Vec" if !is_ref => {
1251 Some(("Vec::new(); for mut item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1254 // We should only get here if the single contained has an inner
1255 assert!(self.c_type_has_inner(single_contained.unwrap()));
1256 Some(("Vec::new(); for mut item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "*item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1259 Some(("Vec::new(); for item in ", vec![(format!(".iter() {{ local_{}.push(", var_name), "*item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1262 let contained_struct = if let Some(syn::Type::Path(p)) = single_contained {
1263 Some(self.resolve_path(&p.path, generics))
1264 } else if let Some(syn::Type::Reference(r)) = single_contained {
1265 if let syn::Type::Path(p) = &*r.elem {
1266 Some(self.resolve_path(&p.path, generics))
1269 if let Some(inner_path) = contained_struct {
1270 if self.is_primitive(&inner_path) {
1271 return Some(("if ", vec![
1272 (format!(".is_none() {{ {}::COption_{}Z::None }} else {{ ", Self::generated_container_path(), inner_path),
1273 format!("{}::COption_{}Z::Some({}.unwrap())", Self::generated_container_path(), inner_path, var_access))
1274 ], " }", ContainerPrefixLocation::NoPrefix));
1275 } else if self.c_type_has_inner_from_path(&inner_path) {
1276 let is_inner_ref = if let Some(syn::Type::Reference(_)) = single_contained { true } else { false };
1278 return Some(("if ", vec![
1279 (".is_none() { std::ptr::null() } else { ".to_owned(),
1280 format!("({}{}.unwrap())", var_access, if is_inner_ref { "" } else { ".as_ref()" }))
1281 ], " }", ContainerPrefixLocation::OutsideConv));
1283 return Some(("if ", vec![
1284 (".is_none() { std::ptr::null_mut() } else { ".to_owned(), format!("({}.unwrap())", var_access))
1285 ], " }", ContainerPrefixLocation::OutsideConv));
1289 if let Some(t) = single_contained {
1290 let mut v = Vec::new();
1291 self.write_empty_rust_val(generics, &mut v, t);
1292 let s = String::from_utf8(v).unwrap();
1293 return Some(("if ", vec![
1294 (format!(".is_none() {{ {} }} else {{ ", s), format!("({}.unwrap())", var_access))
1295 ], " }", ContainerPrefixLocation::PerConv));
1296 } else { unreachable!(); }
1302 /// only_contained_has_inner implies that there is only one contained element in the container
1303 /// and it has an inner field (ie is an "opaque" type we've defined).
1304 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)
1305 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1306 // expecting one element in the vec per generic type, each of which is inline-converted
1307 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1309 "Result" if !is_ref => {
1311 vec![(".result_ok { true => Ok(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.result)) }})", var_access)),
1312 ("), false => Err(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.err)) }})", var_access))],
1313 ")}", ContainerPrefixLocation::PerConv))
1315 "Slice" if is_ref => {
1316 Some(("Vec::new(); for mut item in ", vec![(format!(".as_slice().iter() {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1319 Some(("Vec::new(); for mut item in ", vec![(format!(".into_rust().drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1322 if let Some(syn::Type::Path(p)) = single_contained {
1323 let inner_path = self.resolve_path(&p.path, generics);
1324 if self.is_primitive(&inner_path) {
1325 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::NoPrefix))
1326 } else if self.c_type_has_inner_from_path(&inner_path) {
1328 return Some(("if ", vec![(".inner.is_null() { None } else { Some((*".to_string(), format!("{}", var_access))], ").clone()) }", ContainerPrefixLocation::PerConv))
1330 return Some(("if ", vec![(".inner.is_null() { None } else { Some(".to_string(), format!("{}", var_access))], ") }", ContainerPrefixLocation::PerConv));
1335 if let Some(t) = single_contained {
1337 syn::Type::Reference(_)|syn::Type::Path(_)|syn::Type::Slice(_) => {
1338 let mut v = Vec::new();
1339 let ret_ref = self.write_empty_rust_val_check_suffix(generics, &mut v, t);
1340 let s = String::from_utf8(v).unwrap();
1342 EmptyValExpectedTy::ReferenceAsPointer =>
1343 return Some(("if ", vec![
1344 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ &mut *{} }}", var_access))
1345 ], ") }", ContainerPrefixLocation::NoPrefix)),
1346 EmptyValExpectedTy::OwnedPointer => {
1347 if let syn::Type::Slice(_) = t {
1350 return Some(("if ", vec![
1351 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ *Box::from_raw({}) }}", var_access))
1352 ], ") }", ContainerPrefixLocation::NoPrefix));
1354 EmptyValExpectedTy::NonPointer =>
1355 return Some(("if ", vec![
1356 (format!("{} {{ None }} else {{ Some(", s), format!("{}", var_access))
1357 ], ") }", ContainerPrefixLocation::PerConv)),
1360 syn::Type::Tuple(_) => {
1361 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::PerConv))
1363 _ => unimplemented!(),
1365 } else { unreachable!(); }
1371 // *************************************************
1372 // *** Type definition during main.rs processing ***
1373 // *************************************************
1375 pub fn get_declared_type(&'a self, ident: &syn::Ident) -> Option<&'a DeclType<'c>> {
1376 self.types.get_declared_type(ident)
1378 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1379 pub fn c_type_has_inner_from_path(&self, full_path: &str) -> bool {
1380 self.crate_types.opaques.get(full_path).is_some()
1382 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1383 pub fn c_type_has_inner(&self, ty: &syn::Type) -> bool {
1385 syn::Type::Path(p) => {
1386 let full_path = self.resolve_path(&p.path, None);
1387 self.c_type_has_inner_from_path(&full_path)
1389 syn::Type::Reference(r) => {
1390 self.c_type_has_inner(&*r.elem)
1396 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
1397 self.types.maybe_resolve_ident(id)
1400 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
1401 self.types.maybe_resolve_non_ignored_ident(id)
1404 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
1405 self.types.maybe_resolve_path(p_arg, generics)
1407 pub fn resolve_path(&self, p: &syn::Path, generics: Option<&GenericTypes>) -> String {
1408 self.maybe_resolve_path(p, generics).unwrap()
1411 // ***********************************
1412 // *** Original Rust Type Printing ***
1413 // ***********************************
1415 fn in_rust_prelude(resolved_path: &str) -> bool {
1416 match resolved_path {
1424 fn write_rust_path<W: std::io::Write>(&self, w: &mut W, generics_resolver: Option<&GenericTypes>, path: &syn::Path) {
1425 if let Some(resolved) = self.maybe_resolve_path(&path, generics_resolver) {
1426 if self.is_primitive(&resolved) {
1427 write!(w, "{}", path.get_ident().unwrap()).unwrap();
1429 // TODO: We should have a generic "is from a dependency" check here instead of
1430 // checking for "bitcoin" explicitly.
1431 if resolved.starts_with("bitcoin::") || Self::in_rust_prelude(&resolved) {
1432 write!(w, "{}", resolved).unwrap();
1433 // If we're printing a generic argument, it needs to reference the crate, otherwise
1434 // the original crate:
1435 } else if self.maybe_resolve_path(&path, None).as_ref() == Some(&resolved) {
1436 write!(w, "{}", resolved).unwrap();
1438 write!(w, "crate::{}", resolved).unwrap();
1441 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().last().unwrap().arguments {
1442 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1445 if path.leading_colon.is_some() {
1446 write!(w, "::").unwrap();
1448 for (idx, seg) in path.segments.iter().enumerate() {
1449 if idx != 0 { write!(w, "::").unwrap(); }
1450 write!(w, "{}", seg.ident).unwrap();
1451 if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
1452 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1457 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>) {
1458 let mut had_params = false;
1459 for (idx, arg) in generics.enumerate() {
1460 if idx != 0 { write!(w, ", ").unwrap(); } else { write!(w, "<").unwrap(); }
1463 syn::GenericParam::Lifetime(lt) => write!(w, "'{}", lt.lifetime.ident).unwrap(),
1464 syn::GenericParam::Type(t) => {
1465 write!(w, "{}", t.ident).unwrap();
1466 if t.colon_token.is_some() { write!(w, ":").unwrap(); }
1467 for (idx, bound) in t.bounds.iter().enumerate() {
1468 if idx != 0 { write!(w, " + ").unwrap(); }
1470 syn::TypeParamBound::Trait(tb) => {
1471 if tb.paren_token.is_some() || tb.lifetimes.is_some() { unimplemented!(); }
1472 self.write_rust_path(w, generics_resolver, &tb.path);
1474 _ => unimplemented!(),
1477 if t.eq_token.is_some() || t.default.is_some() { unimplemented!(); }
1479 _ => unimplemented!(),
1482 if had_params { write!(w, ">").unwrap(); }
1485 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>) {
1486 write!(w, "<").unwrap();
1487 for (idx, arg) in generics.enumerate() {
1488 if idx != 0 { write!(w, ", ").unwrap(); }
1490 syn::GenericArgument::Type(t) => self.write_rust_type(w, generics_resolver, t),
1491 _ => unimplemented!(),
1494 write!(w, ">").unwrap();
1496 pub fn write_rust_type<W: std::io::Write>(&self, w: &mut W, generics: Option<&GenericTypes>, t: &syn::Type) {
1498 syn::Type::Path(p) => {
1499 if p.qself.is_some() {
1502 self.write_rust_path(w, generics, &p.path);
1504 syn::Type::Reference(r) => {
1505 write!(w, "&").unwrap();
1506 if let Some(lft) = &r.lifetime {
1507 write!(w, "'{} ", lft.ident).unwrap();
1509 if r.mutability.is_some() {
1510 write!(w, "mut ").unwrap();
1512 self.write_rust_type(w, generics, &*r.elem);
1514 syn::Type::Array(a) => {
1515 write!(w, "[").unwrap();
1516 self.write_rust_type(w, generics, &a.elem);
1517 if let syn::Expr::Lit(l) = &a.len {
1518 if let syn::Lit::Int(i) = &l.lit {
1519 write!(w, "; {}]", i).unwrap();
1520 } else { unimplemented!(); }
1521 } else { unimplemented!(); }
1523 syn::Type::Slice(s) => {
1524 write!(w, "[").unwrap();
1525 self.write_rust_type(w, generics, &s.elem);
1526 write!(w, "]").unwrap();
1528 syn::Type::Tuple(s) => {
1529 write!(w, "(").unwrap();
1530 for (idx, t) in s.elems.iter().enumerate() {
1531 if idx != 0 { write!(w, ", ").unwrap(); }
1532 self.write_rust_type(w, generics, &t);
1534 write!(w, ")").unwrap();
1536 _ => unimplemented!(),
1540 /// Prints a constructor for something which is "uninitialized" (but obviously not actually
1541 /// unint'd memory).
1542 pub fn write_empty_rust_val<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) {
1544 syn::Type::Reference(r) => {
1545 self.write_empty_rust_val(generics, w, &*r.elem)
1547 syn::Type::Path(p) => {
1548 let resolved = self.resolve_path(&p.path, generics);
1549 if self.crate_types.opaques.get(&resolved).is_some() {
1550 write!(w, "crate::{} {{ inner: std::ptr::null_mut(), is_owned: true }}", resolved).unwrap();
1552 // Assume its a manually-mapped C type, where we can just define an null() fn
1553 write!(w, "{}::null()", self.c_type_from_path(&resolved, false, false).unwrap()).unwrap();
1556 syn::Type::Array(a) => {
1557 if let syn::Expr::Lit(l) = &a.len {
1558 if let syn::Lit::Int(i) = &l.lit {
1559 if i.base10_digits().parse::<usize>().unwrap() < 32 {
1560 // Blindly assume that if we're trying to create an empty value for an
1561 // array < 32 entries that all-0s may be a valid state.
1564 let arrty = format!("[u8; {}]", i.base10_digits());
1565 write!(w, "{}", self.to_c_conversion_inline_prefix_from_path(&arrty, false, false).unwrap()).unwrap();
1566 write!(w, "[0; {}]", i.base10_digits()).unwrap();
1567 write!(w, "{}", self.to_c_conversion_inline_suffix_from_path(&arrty, false, false).unwrap()).unwrap();
1568 } else { unimplemented!(); }
1569 } else { unimplemented!(); }
1571 _ => unimplemented!(),
1575 fn is_real_type_array(&self, resolved_type: &str) -> Option<syn::Type> {
1576 if let Some(real_ty) = self.c_type_from_path(&resolved_type, true, false) {
1577 if real_ty.ends_with("]") && real_ty.starts_with("*const [u8; ") {
1578 let mut split = real_ty.split("; ");
1579 split.next().unwrap();
1580 let tail_str = split.next().unwrap();
1581 assert!(split.next().is_none());
1582 let len = usize::from_str_radix(&tail_str[..tail_str.len() - 1], 10).unwrap();
1583 Some(parse_quote!([u8; #len]))
1588 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1589 /// See EmptyValExpectedTy for information on return types.
1590 fn write_empty_rust_val_check_suffix<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) -> EmptyValExpectedTy {
1592 syn::Type::Reference(r) => {
1593 return self.write_empty_rust_val_check_suffix(generics, w, &*r.elem);
1595 syn::Type::Path(p) => {
1596 let resolved = self.resolve_path(&p.path, generics);
1597 if let Some(arr_ty) = self.is_real_type_array(&resolved) {
1598 write!(w, ".data").unwrap();
1599 return self.write_empty_rust_val_check_suffix(generics, w, &arr_ty);
1601 if self.crate_types.opaques.get(&resolved).is_some() {
1602 write!(w, ".inner.is_null()").unwrap();
1603 EmptyValExpectedTy::NonPointer
1605 if let Some(suffix) = self.empty_val_check_suffix_from_path(&resolved) {
1606 write!(w, "{}", suffix).unwrap();
1607 // We may eventually need to allow empty_val_check_suffix_from_path to specify if we need a deref or not
1608 EmptyValExpectedTy::NonPointer
1610 write!(w, " == std::ptr::null_mut()").unwrap();
1611 EmptyValExpectedTy::OwnedPointer
1615 syn::Type::Array(a) => {
1616 if let syn::Expr::Lit(l) = &a.len {
1617 if let syn::Lit::Int(i) = &l.lit {
1618 write!(w, " == [0; {}]", i.base10_digits()).unwrap();
1619 EmptyValExpectedTy::NonPointer
1620 } else { unimplemented!(); }
1621 } else { unimplemented!(); }
1623 syn::Type::Slice(_) => {
1624 // Option<[]> always implies that we want to treat len() == 0 differently from
1625 // None, so we always map an Option<[]> into a pointer.
1626 write!(w, " == std::ptr::null_mut()").unwrap();
1627 EmptyValExpectedTy::ReferenceAsPointer
1629 _ => unimplemented!(),
1633 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1634 pub fn write_empty_rust_val_check<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type, var_access: &str) {
1636 syn::Type::Reference(r) => {
1637 self.write_empty_rust_val_check(generics, w, &*r.elem, var_access);
1639 syn::Type::Path(_) => {
1640 write!(w, "{}", var_access).unwrap();
1641 self.write_empty_rust_val_check_suffix(generics, w, t);
1643 syn::Type::Array(a) => {
1644 if let syn::Expr::Lit(l) = &a.len {
1645 if let syn::Lit::Int(i) = &l.lit {
1646 let arrty = format!("[u8; {}]", i.base10_digits());
1647 // We don't (yet) support a new-var conversion here.
1648 assert!(self.from_c_conversion_new_var_from_path(&arrty, false).is_none());
1650 self.from_c_conversion_prefix_from_path(&arrty, false).unwrap(),
1652 self.from_c_conversion_suffix_from_path(&arrty, false).unwrap()).unwrap();
1653 self.write_empty_rust_val_check_suffix(generics, w, t);
1654 } else { unimplemented!(); }
1655 } else { unimplemented!(); }
1657 _ => unimplemented!(),
1661 // ********************************
1662 // *** Type conversion printing ***
1663 // ********************************
1665 /// Returns true we if can just skip passing this to C entirely
1666 pub fn skip_arg(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
1668 syn::Type::Path(p) => {
1669 if p.qself.is_some() { unimplemented!(); }
1670 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1671 self.skip_path(&full_path)
1674 syn::Type::Reference(r) => {
1675 self.skip_arg(&*r.elem, generics)
1680 pub fn no_arg_to_rust<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1682 syn::Type::Path(p) => {
1683 if p.qself.is_some() { unimplemented!(); }
1684 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1685 write!(w, "{}", self.no_arg_path_to_rust(&full_path)).unwrap();
1688 syn::Type::Reference(r) => {
1689 self.no_arg_to_rust(w, &*r.elem, generics);
1695 fn write_conversion_inline_intern<W: std::io::Write,
1696 LP: Fn(&str, bool, bool) -> Option<String>, DL: Fn(&mut W, &DeclType, &str, bool, bool), SC: Fn(bool, Option<&str>) -> String>
1697 (&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool,
1698 tupleconv: &str, prefix: bool, sliceconv: SC, path_lookup: LP, decl_lookup: DL) {
1699 match generics.resolve_type(t) {
1700 syn::Type::Reference(r) => {
1701 self.write_conversion_inline_intern(w, &*r.elem, generics, true, r.mutability.is_some(),
1702 ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1704 syn::Type::Path(p) => {
1705 if p.qself.is_some() {
1709 let resolved_path = self.resolve_path(&p.path, generics);
1710 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1711 return self.write_conversion_inline_intern(w, aliased_type, None, is_ref, is_mut, ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1712 } else if self.is_primitive(&resolved_path) {
1713 if is_ref && prefix {
1714 write!(w, "*").unwrap();
1716 } else if let Some(c_type) = path_lookup(&resolved_path, is_ref, ptr_for_ref) {
1717 write!(w, "{}", c_type).unwrap();
1718 } else if self.crate_types.opaques.get(&resolved_path).is_some() {
1719 decl_lookup(w, &DeclType::StructImported, &resolved_path, is_ref, is_mut);
1720 } else if self.crate_types.mirrored_enums.get(&resolved_path).is_some() {
1721 decl_lookup(w, &DeclType::MirroredEnum, &resolved_path, is_ref, is_mut);
1722 } else if let Some(t) = self.crate_types.traits.get(&resolved_path) {
1723 decl_lookup(w, &DeclType::Trait(t), &resolved_path, is_ref, is_mut);
1724 } else if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
1725 if let Some(decl_type) = self.types.maybe_resolve_declared(ident) {
1726 decl_lookup(w, decl_type, &self.maybe_resolve_ident(ident).unwrap(), is_ref, is_mut);
1727 } else { unimplemented!(); }
1728 } else { unimplemented!(); }
1730 syn::Type::Array(a) => {
1731 // We assume all arrays contain only [int_literal; X]s.
1732 // This may result in some outputs not compiling.
1733 if let syn::Expr::Lit(l) = &a.len {
1734 if let syn::Lit::Int(i) = &l.lit {
1735 write!(w, "{}", path_lookup(&format!("[u8; {}]", i.base10_digits()), is_ref, ptr_for_ref).unwrap()).unwrap();
1736 } else { unimplemented!(); }
1737 } else { unimplemented!(); }
1739 syn::Type::Slice(s) => {
1740 // We assume all slices contain only literals or references.
1741 // This may result in some outputs not compiling.
1742 if let syn::Type::Path(p) = &*s.elem {
1743 let resolved = self.resolve_path(&p.path, generics);
1744 assert!(self.is_primitive(&resolved));
1745 write!(w, "{}", path_lookup("[u8]", is_ref, ptr_for_ref).unwrap()).unwrap();
1746 } else if let syn::Type::Reference(r) = &*s.elem {
1747 if let syn::Type::Path(p) = &*r.elem {
1748 write!(w, "{}", sliceconv(self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)), None)).unwrap();
1749 } else { unimplemented!(); }
1750 } else if let syn::Type::Tuple(t) = &*s.elem {
1751 assert!(!t.elems.is_empty());
1753 write!(w, "{}", sliceconv(false, None)).unwrap();
1755 let mut needs_map = false;
1756 for e in t.elems.iter() {
1757 if let syn::Type::Reference(_) = e {
1762 let mut map_str = Vec::new();
1763 write!(&mut map_str, ".map(|(").unwrap();
1764 for i in 0..t.elems.len() {
1765 write!(&mut map_str, "{}{}", if i != 0 { ", " } else { "" }, ('a' as u8 + i as u8) as char).unwrap();
1767 write!(&mut map_str, ")| (").unwrap();
1768 for (idx, e) in t.elems.iter().enumerate() {
1769 if let syn::Type::Reference(_) = e {
1770 write!(&mut map_str, "{}{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1771 } else if let syn::Type::Path(_) = e {
1772 write!(&mut map_str, "{}*{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1773 } else { unimplemented!(); }
1775 write!(&mut map_str, "))").unwrap();
1776 write!(w, "{}", sliceconv(false, Some(&String::from_utf8(map_str).unwrap()))).unwrap();
1778 write!(w, "{}", sliceconv(false, None)).unwrap();
1781 } else { unimplemented!(); }
1783 syn::Type::Tuple(t) => {
1784 if t.elems.is_empty() {
1785 // cbindgen has poor support for (), see, eg https://github.com/eqrion/cbindgen/issues/527
1786 // so work around it by just pretending its a 0u8
1787 write!(w, "{}", tupleconv).unwrap();
1789 if prefix { write!(w, "local_").unwrap(); }
1792 _ => unimplemented!(),
1796 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) {
1797 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "() /*", true, |_, _| "local_".to_owned(),
1798 |a, b, c| self.to_c_conversion_inline_prefix_from_path(a, b, c),
1799 |w, decl_type, decl_path, is_ref, _is_mut| {
1801 DeclType::MirroredEnum if is_ref && ptr_for_ref => write!(w, "crate::{}::from_native(", decl_path).unwrap(),
1802 DeclType::MirroredEnum if is_ref => write!(w, "&crate::{}::from_native(", decl_path).unwrap(),
1803 DeclType::MirroredEnum => write!(w, "crate::{}::native_into(", decl_path).unwrap(),
1804 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1805 write!(w, "crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1806 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1807 write!(w, "crate::{} {{ inner: unsafe {{ ( (&(*", decl_path).unwrap(),
1808 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1809 write!(w, "&crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1810 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1811 write!(w, "crate::{} {{ inner: ", decl_path).unwrap(),
1812 DeclType::EnumIgnored|DeclType::StructImported if !is_ref =>
1813 write!(w, "crate::{} {{ inner: Box::into_raw(Box::new(", decl_path).unwrap(),
1814 DeclType::Trait(_) if is_ref => write!(w, "").unwrap(),
1815 DeclType::Trait(_) if !is_ref => {},
1816 _ => panic!("{:?}", decl_path),
1820 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) {
1821 self.write_to_c_conversion_inline_prefix_inner(w, t, generics, false, ptr_for_ref, false);
1823 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) {
1824 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "*/", false, |_, _| ".into()".to_owned(),
1825 |a, b, c| self.to_c_conversion_inline_suffix_from_path(a, b, c),
1826 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1827 DeclType::MirroredEnum => write!(w, ")").unwrap(),
1828 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1829 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1830 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1831 write!(w, ") as *const _) as *mut _) }}, is_owned: false }}").unwrap(),
1832 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1833 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1834 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1835 write!(w, ", is_owned: true }}").unwrap(),
1836 DeclType::EnumIgnored|DeclType::StructImported if !is_ref => write!(w, ")), is_owned: true }}").unwrap(),
1837 DeclType::Trait(_) if is_ref => {},
1838 DeclType::Trait(_) => {
1839 // This is used when we're converting a concrete Rust type into a C trait
1840 // for use when a Rust trait method returns an associated type.
1841 // Because all of our C traits implement From<RustTypesImplementingTraits>
1842 // we can just call .into() here and be done.
1843 write!(w, ".into()").unwrap()
1845 _ => unimplemented!(),
1848 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) {
1849 self.write_to_c_conversion_inline_suffix_inner(w, t, generics, false, ptr_for_ref, false);
1852 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) {
1853 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "() /*", true, |_, _| "&local_".to_owned(),
1854 |a, b, _c| self.from_c_conversion_prefix_from_path(a, b),
1855 |w, decl_type, _full_path, is_ref, is_mut| match decl_type {
1856 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, "unsafe {{ &*(*").unwrap(),
1857 DeclType::StructImported if is_mut && is_ref => write!(w, "unsafe {{ &mut *").unwrap(),
1858 DeclType::StructImported if is_ref => write!(w, "unsafe {{ &*").unwrap(),
1859 DeclType::StructImported if !is_ref => write!(w, "*unsafe {{ Box::from_raw(").unwrap(),
1860 DeclType::MirroredEnum if is_ref => write!(w, "&").unwrap(),
1861 DeclType::MirroredEnum => {},
1862 DeclType::Trait(_) => {},
1863 _ => unimplemented!(),
1866 pub fn write_from_c_conversion_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1867 self.write_from_c_conversion_prefix_inner(w, t, generics, false, false);
1869 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) {
1870 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "*/", false,
1871 |has_inner, map_str_opt| match (has_inner, map_str_opt) {
1872 (false, Some(map_str)) => format!(".iter(){}.collect::<Vec<_>>()[..]", map_str),
1873 (false, None) => ".iter().collect::<Vec<_>>()[..]".to_owned(),
1874 (true, None) => "[..]".to_owned(),
1875 (true, Some(_)) => unreachable!(),
1877 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1878 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1879 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, ").inner }}").unwrap(),
1880 DeclType::StructImported if is_ref => write!(w, ".inner }}").unwrap(),
1881 DeclType::StructImported if !is_ref => write!(w, ".take_inner()) }}").unwrap(),
1882 DeclType::MirroredEnum if is_ref => write!(w, ".to_native()").unwrap(),
1883 DeclType::MirroredEnum => write!(w, ".into_native()").unwrap(),
1884 DeclType::Trait(_) => {},
1885 _ => unimplemented!(),
1888 pub fn write_from_c_conversion_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1889 self.write_from_c_conversion_suffix_inner(w, t, generics, false, false);
1891 // Note that compared to the above conversion functions, the following two are generally
1892 // significantly undertested:
1893 pub fn write_from_c_conversion_to_ref_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1894 self.write_conversion_inline_intern(w, t, generics, false, false, false, "() /*", true, |_, _| "&local_".to_owned(),
1896 if let Some(conv) = self.from_c_conversion_prefix_from_path(a, b) {
1897 Some(format!("&{}", conv))
1900 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1901 DeclType::StructImported if !is_ref => write!(w, "unsafe {{ &*").unwrap(),
1902 _ => unimplemented!(),
1905 pub fn write_from_c_conversion_to_ref_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1906 self.write_conversion_inline_intern(w, t, generics, false, false, false, "*/", false,
1907 |has_inner, map_str_opt| match (has_inner, map_str_opt) {
1908 (false, Some(map_str)) => format!(".iter(){}.collect::<Vec<_>>()[..]", map_str),
1909 (false, None) => ".iter().collect::<Vec<_>>()[..]".to_owned(),
1910 (true, None) => "[..]".to_owned(),
1911 (true, Some(_)) => unreachable!(),
1913 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1914 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1915 DeclType::StructImported if !is_ref => write!(w, ".inner }}").unwrap(),
1916 _ => unimplemented!(),
1920 fn write_conversion_new_var_intern<'b, W: std::io::Write,
1921 LP: Fn(&str, bool) -> Option<(&str, &str)>,
1922 LC: Fn(&str, bool, Option<&syn::Type>, &syn::Ident, &str) -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)>,
1923 VP: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool),
1924 VS: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool)>
1925 (&self, w: &mut W, ident: &syn::Ident, var: &str, t: &syn::Type, generics: Option<&GenericTypes>,
1926 mut is_ref: bool, mut ptr_for_ref: bool, to_c: bool,
1927 path_lookup: &LP, container_lookup: &LC, var_prefix: &VP, var_suffix: &VS) -> bool {
1929 macro_rules! convert_container {
1930 ($container_type: expr, $args_len: expr, $args_iter: expr) => { {
1931 // For slices (and Options), we refuse to directly map them as is_ref when they
1932 // aren't opaque types containing an inner pointer. This is due to the fact that,
1933 // in both cases, the actual higher-level type is non-is_ref.
1934 let ty_has_inner = if $args_len == 1 {
1935 let ty = $args_iter().next().unwrap();
1936 if $container_type == "Slice" && to_c {
1937 // "To C ptr_for_ref" means "return the regular object with is_owned
1938 // set to false", which is totally what we want in a slice if we're about to
1939 // set ty_has_inner.
1942 if let syn::Type::Reference(t) = ty {
1943 if let syn::Type::Path(p) = &*t.elem {
1944 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1946 } else if let syn::Type::Path(p) = ty {
1947 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1951 // Options get a bunch of special handling, since in general we map Option<>al
1952 // types into the same C type as non-Option-wrapped types. This ends up being
1953 // pretty manual here and most of the below special-cases are for Options.
1954 let mut needs_ref_map = false;
1955 let mut only_contained_type = None;
1956 let mut only_contained_type_nonref = None;
1957 let mut only_contained_has_inner = false;
1958 let mut contains_slice = false;
1960 only_contained_has_inner = ty_has_inner;
1961 let arg = $args_iter().next().unwrap();
1962 if let syn::Type::Reference(t) = arg {
1963 only_contained_type = Some(arg);
1964 only_contained_type_nonref = Some(&*t.elem);
1965 if let syn::Type::Path(_) = &*t.elem {
1967 } else if let syn::Type::Slice(_) = &*t.elem {
1968 contains_slice = true;
1969 } else { return false; }
1970 // If the inner element contains an inner pointer, we will just use that,
1971 // avoiding the need to map elements to references. Otherwise we'll need to
1972 // do an extra mapping step.
1973 needs_ref_map = !only_contained_has_inner;
1975 only_contained_type = Some(arg);
1976 only_contained_type_nonref = Some(arg);
1980 if let Some((prefix, conversions, suffix, prefix_location)) = container_lookup(&$container_type, is_ref && ty_has_inner, only_contained_type, ident, var) {
1981 assert_eq!(conversions.len(), $args_len);
1982 write!(w, "let mut local_{}{} = ", ident, if !to_c && needs_ref_map {"_base"} else { "" }).unwrap();
1983 if prefix_location == ContainerPrefixLocation::OutsideConv {
1984 var_prefix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
1986 write!(w, "{}{}", prefix, var).unwrap();
1988 for ((pfx, var_name), (idx, ty)) in conversions.iter().zip($args_iter().enumerate()) {
1989 let mut var = std::io::Cursor::new(Vec::new());
1990 write!(&mut var, "{}", var_name).unwrap();
1991 let var_access = String::from_utf8(var.into_inner()).unwrap();
1993 let conv_ty = if needs_ref_map { only_contained_type_nonref.as_ref().unwrap() } else { ty };
1995 write!(w, "{} {{ ", pfx).unwrap();
1996 let new_var_name = format!("{}_{}", ident, idx);
1997 let new_var = self.write_conversion_new_var_intern(w, &format_ident!("{}", new_var_name),
1998 &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);
1999 if new_var { write!(w, " ").unwrap(); }
2001 if prefix_location == ContainerPrefixLocation::PerConv {
2002 var_prefix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2003 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
2004 write!(w, "Box::into_raw(Box::new(").unwrap();
2007 write!(w, "{}{}", if contains_slice { "local_" } else { "" }, if new_var { new_var_name } else { var_access }).unwrap();
2008 if prefix_location == ContainerPrefixLocation::PerConv {
2009 var_suffix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2010 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
2011 write!(w, "))").unwrap();
2013 write!(w, " }}").unwrap();
2015 write!(w, "{}", suffix).unwrap();
2016 if prefix_location == ContainerPrefixLocation::OutsideConv {
2017 var_suffix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
2019 write!(w, ";").unwrap();
2020 if !to_c && needs_ref_map {
2021 write!(w, " let mut local_{} = local_{}_base.as_ref()", ident, ident).unwrap();
2023 write!(w, ".map(|a| &a[..])").unwrap();
2025 write!(w, ";").unwrap();
2032 match generics.resolve_type(t) {
2033 syn::Type::Reference(r) => {
2034 if let syn::Type::Slice(_) = &*r.elem {
2035 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)
2037 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)
2040 syn::Type::Path(p) => {
2041 if p.qself.is_some() {
2044 let resolved_path = self.resolve_path(&p.path, generics);
2045 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
2046 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);
2048 if self.is_known_container(&resolved_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
2049 if let syn::PathArguments::AngleBracketed(args) = &p.path.segments.iter().next().unwrap().arguments {
2050 convert_container!(resolved_path, args.args.len(), || args.args.iter().map(|arg| {
2051 if let syn::GenericArgument::Type(ty) = arg {
2053 } else { unimplemented!(); }
2055 } else { unimplemented!(); }
2057 if self.is_primitive(&resolved_path) {
2059 } else if let Some(ty_ident) = single_ident_generic_path_to_ident(&p.path) {
2060 if let Some((prefix, suffix)) = path_lookup(&resolved_path, is_ref) {
2061 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
2063 } else if self.types.maybe_resolve_declared(ty_ident).is_some() {
2068 syn::Type::Array(_) => {
2069 // We assume all arrays contain only primitive types.
2070 // This may result in some outputs not compiling.
2073 syn::Type::Slice(s) => {
2074 if let syn::Type::Path(p) = &*s.elem {
2075 let resolved = self.resolve_path(&p.path, generics);
2076 assert!(self.is_primitive(&resolved));
2077 let slice_path = format!("[{}]", resolved);
2078 if let Some((prefix, suffix)) = path_lookup(&slice_path, true) {
2079 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
2082 } else if let syn::Type::Reference(ty) = &*s.elem {
2083 let tyref = [&*ty.elem];
2085 convert_container!("Slice", 1, || tyref.iter().map(|t| *t));
2086 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
2087 } else if let syn::Type::Tuple(t) = &*s.elem {
2088 // When mapping into a temporary new var, we need to own all the underlying objects.
2089 // Thus, we drop any references inside the tuple and convert with non-reference types.
2090 let mut elems = syn::punctuated::Punctuated::new();
2091 for elem in t.elems.iter() {
2092 if let syn::Type::Reference(r) = elem {
2093 elems.push((*r.elem).clone());
2095 elems.push(elem.clone());
2098 let ty = [syn::Type::Tuple(syn::TypeTuple {
2099 paren_token: t.paren_token, elems
2103 convert_container!("Slice", 1, || ty.iter());
2104 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
2105 } else { unimplemented!() }
2107 syn::Type::Tuple(t) => {
2108 if !t.elems.is_empty() {
2109 // We don't (yet) support tuple elements which cannot be converted inline
2110 write!(w, "let (").unwrap();
2111 for idx in 0..t.elems.len() {
2112 if idx != 0 { write!(w, ", ").unwrap(); }
2113 write!(w, "{} orig_{}_{}", if is_ref { "ref" } else { "mut" }, ident, idx).unwrap();
2115 write!(w, ") = {}{}; ", var, if !to_c { ".to_rust()" } else { "" }).unwrap();
2116 // Like other template types, tuples are always mapped as their non-ref
2117 // versions for types which have different ref mappings. Thus, we convert to
2118 // non-ref versions and handle opaque types with inner pointers manually.
2119 for (idx, elem) in t.elems.iter().enumerate() {
2120 if let syn::Type::Path(p) = elem {
2121 let v_name = format!("orig_{}_{}", ident, idx);
2122 let tuple_elem_ident = format_ident!("{}", &v_name);
2123 if self.write_conversion_new_var_intern(w, &tuple_elem_ident, &v_name, elem, generics,
2124 false, ptr_for_ref, to_c,
2125 path_lookup, container_lookup, var_prefix, var_suffix) {
2126 write!(w, " ").unwrap();
2127 // Opaque types with inner pointers shouldn't ever create new stack
2128 // variables, so we don't handle it and just assert that it doesn't
2130 assert!(!self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)));
2134 write!(w, "let mut local_{} = (", ident).unwrap();
2135 for (idx, elem) in t.elems.iter().enumerate() {
2136 let ty_has_inner = {
2138 // "To C ptr_for_ref" means "return the regular object with
2139 // is_owned set to false", which is totally what we want
2140 // if we're about to set ty_has_inner.
2143 if let syn::Type::Reference(t) = elem {
2144 if let syn::Type::Path(p) = &*t.elem {
2145 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2147 } else if let syn::Type::Path(p) = elem {
2148 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2151 if idx != 0 { write!(w, ", ").unwrap(); }
2152 var_prefix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2153 if is_ref && ty_has_inner {
2154 // For ty_has_inner, the regular var_prefix mapping will take a
2155 // reference, so deref once here to make sure we keep the original ref.
2156 write!(w, "*").unwrap();
2158 write!(w, "orig_{}_{}", ident, idx).unwrap();
2159 if is_ref && !ty_has_inner {
2160 // If we don't have an inner variable's reference to maintain, just
2161 // hope the type is Clonable and use that.
2162 write!(w, ".clone()").unwrap();
2164 var_suffix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2166 write!(w, "){};", if to_c { ".into()" } else { "" }).unwrap();
2170 _ => unimplemented!(),
2174 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 {
2175 self.write_conversion_new_var_intern(w, ident, var_access, t, generics, false, ptr_for_ref, true,
2176 &|a, b| self.to_c_conversion_new_var_from_path(a, b),
2177 &|a, b, c, d, e| self.to_c_conversion_container_new_var(generics, a, b, c, d, e),
2178 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
2179 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_prefix_inner(a, b, c, d, e, f),
2180 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_suffix_inner(a, b, c, d, e, f))
2182 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 {
2183 self.write_to_c_conversion_new_var_inner(w, ident, &format!("{}", ident), t, generics, ptr_for_ref)
2185 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 {
2186 self.write_conversion_new_var_intern(w, ident, &format!("{}", ident), t, generics, false, false, false,
2187 &|a, b| self.from_c_conversion_new_var_from_path(a, b),
2188 &|a, b, c, d, e| self.from_c_conversion_container_new_var(generics, a, b, c, d, e),
2189 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
2190 &|a, b, c, d, e, _f| self.write_from_c_conversion_prefix_inner(a, b, c, d, e),
2191 &|a, b, c, d, e, _f| self.write_from_c_conversion_suffix_inner(a, b, c, d, e))
2194 // ******************************************************
2195 // *** C Container Type Equivalent and alias Printing ***
2196 // ******************************************************
2198 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 {
2199 for (idx, t) in args.enumerate() {
2201 write!(w, ", ").unwrap();
2203 if let syn::Type::Reference(r_arg) = t {
2204 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2206 if !self.write_c_type_intern(w, &*r_arg.elem, generics, false, false, false) { return false; }
2208 // While write_c_type_intern, above is correct, we don't want to blindly convert a
2209 // reference to something stupid, so check that the container is either opaque or a
2210 // predefined type (currently only Transaction).
2211 if let syn::Type::Path(p_arg) = &*r_arg.elem {
2212 let resolved = self.resolve_path(&p_arg.path, generics);
2213 assert!(self.crate_types.opaques.get(&resolved).is_some() ||
2214 self.c_type_from_path(&resolved, true, true).is_some(), "Template generics should be opaque or have a predefined mapping");
2215 } else { unimplemented!(); }
2216 } else if let syn::Type::Path(p_arg) = t {
2217 if let Some(resolved) = self.maybe_resolve_path(&p_arg.path, generics) {
2218 if !self.is_primitive(&resolved) {
2219 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2222 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2224 if !self.write_c_type_intern(w, t, generics, false, false, false) { return false; }
2226 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2227 if !self.write_c_type_intern(w, t, generics, false, false, false) { return false; }
2232 fn check_create_container(&self, mangled_container: String, container_type: &str, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
2233 if !self.crate_types.templates_defined.borrow().get(&mangled_container).is_some() {
2234 let mut created_container: Vec<u8> = Vec::new();
2236 if container_type == "Result" {
2237 let mut a_ty: Vec<u8> = Vec::new();
2238 if let syn::Type::Tuple(tup) = args.iter().next().unwrap() {
2239 if tup.elems.is_empty() {
2240 write!(&mut a_ty, "()").unwrap();
2242 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
2245 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
2248 let mut b_ty: Vec<u8> = Vec::new();
2249 if let syn::Type::Tuple(tup) = args.iter().skip(1).next().unwrap() {
2250 if tup.elems.is_empty() {
2251 write!(&mut b_ty, "()").unwrap();
2253 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
2256 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
2259 let ok_str = String::from_utf8(a_ty).unwrap();
2260 let err_str = String::from_utf8(b_ty).unwrap();
2261 let is_clonable = self.is_clonable(&ok_str) && self.is_clonable(&err_str);
2262 write_result_block(&mut created_container, &mangled_container, &ok_str, &err_str, is_clonable);
2264 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2266 } else if container_type == "Vec" {
2267 let mut a_ty: Vec<u8> = Vec::new();
2268 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2269 let ty = String::from_utf8(a_ty).unwrap();
2270 let is_clonable = self.is_clonable(&ty);
2271 write_vec_block(&mut created_container, &mangled_container, &ty, is_clonable);
2273 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2275 } else if container_type.ends_with("Tuple") {
2276 let mut tuple_args = Vec::new();
2277 let mut is_clonable = true;
2278 for arg in args.iter() {
2279 let mut ty: Vec<u8> = Vec::new();
2280 if !self.write_template_generics(&mut ty, &mut [arg].iter().map(|t| **t), generics, is_ref) { return false; }
2281 let ty_str = String::from_utf8(ty).unwrap();
2282 if !self.is_clonable(&ty_str) {
2283 is_clonable = false;
2285 tuple_args.push(ty_str);
2287 write_tuple_block(&mut created_container, &mangled_container, &tuple_args, is_clonable);
2289 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2291 } else if container_type == "Option" {
2292 let mut a_ty: Vec<u8> = Vec::new();
2293 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2294 let ty = String::from_utf8(a_ty).unwrap();
2295 let is_clonable = self.is_clonable(&ty);
2296 write_option_block(&mut created_container, &mangled_container, &ty, is_clonable);
2298 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2303 self.crate_types.write_new_template(mangled_container.clone(), true, &created_container);
2307 fn path_to_generic_args(path: &syn::Path) -> Vec<&syn::Type> {
2308 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().next().unwrap().arguments {
2309 args.args.iter().map(|gen| if let syn::GenericArgument::Type(t) = gen { t } else { unimplemented!() }).collect()
2310 } else { unimplemented!(); }
2312 fn write_c_mangled_container_path_intern<W: std::io::Write>
2313 (&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 {
2314 let mut mangled_type: Vec<u8> = Vec::new();
2315 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2316 write!(w, "C{}_", ident).unwrap();
2317 write!(mangled_type, "C{}_", ident).unwrap();
2318 } else { assert_eq!(args.len(), 1); }
2319 for arg in args.iter() {
2320 macro_rules! write_path {
2321 ($p_arg: expr, $extra_write: expr) => {
2322 if let Some(subtype) = self.maybe_resolve_path(&$p_arg.path, generics) {
2323 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2325 if self.c_type_has_inner_from_path(&subtype) {
2326 if !self.write_c_path_intern(w, &$p_arg.path, generics, is_ref, is_mut, ptr_for_ref) { return false; }
2328 if let Some(arr_ty) = self.is_real_type_array(&subtype) {
2329 if !self.write_c_type_intern(w, &arr_ty, generics, false, true, false) { return false; }
2331 // Option<T> needs to be converted to a *mut T, ie mut ptr-for-ref
2332 if !self.write_c_path_intern(w, &$p_arg.path, generics, true, true, true) { return false; }
2336 write!(w, "{}", $p_arg.path.segments.last().unwrap().ident).unwrap();
2338 } else if self.is_known_container(&subtype, is_ref) || self.is_path_transparent_container(&$p_arg.path, generics, is_ref) {
2339 if !self.write_c_mangled_container_path_intern(w, Self::path_to_generic_args(&$p_arg.path), generics,
2340 &subtype, is_ref, is_mut, ptr_for_ref, true) {
2343 self.write_c_mangled_container_path_intern(&mut mangled_type, Self::path_to_generic_args(&$p_arg.path),
2344 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2345 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2346 self.write_c_mangled_container_path_intern(w2, Self::path_to_generic_args(&$p_arg.path),
2347 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2350 let id = subtype.rsplitn(2, ':').next().unwrap(); // Get the "Base" name of the resolved type
2351 write!(w, "{}", id).unwrap();
2352 write!(mangled_type, "{}", id).unwrap();
2353 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2354 write!(w2, "{}", id).unwrap();
2357 } else { return false; }
2360 if let syn::Type::Tuple(tuple) = arg {
2361 if tuple.elems.len() == 0 {
2362 write!(w, "None").unwrap();
2363 write!(mangled_type, "None").unwrap();
2365 let mut mangled_tuple_type: Vec<u8> = Vec::new();
2367 // Figure out what the mangled type should look like. To disambiguate
2368 // ((A, B), C) and (A, B, C) we prefix the generic args with a _ and suffix
2369 // them with a Z. Ideally we wouldn't use Z, but not many special chars are
2370 // available for use in type names.
2371 write!(w, "C{}Tuple_", tuple.elems.len()).unwrap();
2372 write!(mangled_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2373 write!(mangled_tuple_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2374 for elem in tuple.elems.iter() {
2375 if let syn::Type::Path(p) = elem {
2376 write_path!(p, Some(&mut mangled_tuple_type));
2377 } else if let syn::Type::Reference(refelem) = elem {
2378 if let syn::Type::Path(p) = &*refelem.elem {
2379 write_path!(p, Some(&mut mangled_tuple_type));
2380 } else { return false; }
2381 } else { return false; }
2383 write!(w, "Z").unwrap();
2384 write!(mangled_type, "Z").unwrap();
2385 write!(mangled_tuple_type, "Z").unwrap();
2386 if !self.check_create_container(String::from_utf8(mangled_tuple_type).unwrap(),
2387 &format!("{}Tuple", tuple.elems.len()), tuple.elems.iter().collect(), generics, is_ref) {
2391 } else if let syn::Type::Path(p_arg) = arg {
2392 write_path!(p_arg, None);
2393 } else if let syn::Type::Reference(refty) = arg {
2394 if let syn::Type::Path(p_arg) = &*refty.elem {
2395 write_path!(p_arg, None);
2396 } else if let syn::Type::Slice(_) = &*refty.elem {
2397 // write_c_type will actually do exactly what we want here, we just need to
2398 // make it a pointer so that its an option. Note that we cannot always convert
2399 // the Vec-as-slice (ie non-ref types) containers, so sometimes need to be able
2400 // to edit it, hence we use *mut here instead of *const.
2401 if args.len() != 1 { return false; }
2402 write!(w, "*mut ").unwrap();
2403 self.write_c_type(w, arg, None, true);
2404 } else { return false; }
2405 } else if let syn::Type::Array(a) = arg {
2406 if let syn::Type::Path(p_arg) = &*a.elem {
2407 let resolved = self.resolve_path(&p_arg.path, generics);
2408 if !self.is_primitive(&resolved) { return false; }
2409 if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(len), .. }) = &a.len {
2410 if self.c_type_from_path(&format!("[{}; {}]", resolved, len.base10_digits()), is_ref, ptr_for_ref).is_none() { return false; }
2411 write!(w, "_{}{}", resolved, len.base10_digits()).unwrap();
2412 write!(mangled_type, "_{}{}", resolved, len.base10_digits()).unwrap();
2413 } else { return false; }
2414 } else { return false; }
2415 } else { return false; }
2417 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) { return true; }
2418 // Push the "end of type" Z
2419 write!(w, "Z").unwrap();
2420 write!(mangled_type, "Z").unwrap();
2422 // Make sure the type is actually defined:
2423 self.check_create_container(String::from_utf8(mangled_type).unwrap(), ident, args, generics, is_ref)
2425 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 {
2426 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2427 write!(w, "{}::", Self::generated_container_path()).unwrap();
2429 self.write_c_mangled_container_path_intern(w, args, generics, ident, is_ref, is_mut, ptr_for_ref, false)
2431 pub fn get_c_mangled_container_type(&self, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, template_name: &str) -> Option<String> {
2432 let mut out = Vec::new();
2433 if !self.write_c_mangled_container_path(&mut out, args, generics, template_name, false, false, false) {
2436 Some(String::from_utf8(out).unwrap())
2439 // **********************************
2440 // *** C Type Equivalent Printing ***
2441 // **********************************
2443 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 {
2444 let full_path = match self.maybe_resolve_path(&path, generics) {
2445 Some(path) => path, None => return false };
2446 if let Some(c_type) = self.c_type_from_path(&full_path, is_ref, ptr_for_ref) {
2447 write!(w, "{}", c_type).unwrap();
2449 } else if self.crate_types.traits.get(&full_path).is_some() {
2450 if is_ref && ptr_for_ref {
2451 write!(w, "*{} crate::{}", if is_mut { "mut" } else { "const" }, full_path).unwrap();
2453 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2455 write!(w, "crate::{}", full_path).unwrap();
2458 } else if self.crate_types.opaques.get(&full_path).is_some() || self.crate_types.mirrored_enums.get(&full_path).is_some() {
2459 if is_ref && ptr_for_ref {
2460 // ptr_for_ref implies we're returning the object, which we can't really do for
2461 // opaque or mirrored types without box'ing them, which is quite a waste, so return
2462 // the actual object itself (for opaque types we'll set the pointer to the actual
2463 // type and note that its a reference).
2464 write!(w, "crate::{}", full_path).unwrap();
2466 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2468 write!(w, "crate::{}", full_path).unwrap();
2475 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 {
2476 match generics.resolve_type(t) {
2477 syn::Type::Path(p) => {
2478 if p.qself.is_some() {
2481 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
2482 if self.is_known_container(&full_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
2483 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);
2485 if let Some(aliased_type) = self.crate_types.type_aliases.get(&full_path).cloned() {
2486 return self.write_c_type_intern(w, &aliased_type, None, is_ref, is_mut, ptr_for_ref);
2489 self.write_c_path_intern(w, &p.path, generics, is_ref, is_mut, ptr_for_ref)
2491 syn::Type::Reference(r) => {
2492 self.write_c_type_intern(w, &*r.elem, generics, true, r.mutability.is_some(), ptr_for_ref)
2494 syn::Type::Array(a) => {
2495 if is_ref && is_mut {
2496 write!(w, "*mut [").unwrap();
2497 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2499 write!(w, "*const [").unwrap();
2500 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2502 let mut typecheck = Vec::new();
2503 if !self.write_c_type_intern(&mut typecheck, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2504 if typecheck[..] != ['u' as u8, '8' as u8] { return false; }
2506 if let syn::Expr::Lit(l) = &a.len {
2507 if let syn::Lit::Int(i) = &l.lit {
2509 if let Some(ty) = self.c_type_from_path(&format!("[u8; {}]", i.base10_digits()), false, ptr_for_ref) {
2510 write!(w, "{}", ty).unwrap();
2514 write!(w, "; {}]", i).unwrap();
2520 syn::Type::Slice(s) => {
2521 if !is_ref || is_mut { return false; }
2522 if let syn::Type::Path(p) = &*s.elem {
2523 let resolved = self.resolve_path(&p.path, generics);
2524 if self.is_primitive(&resolved) {
2525 write!(w, "{}::{}slice", Self::container_templ_path(), resolved).unwrap();
2528 } else if let syn::Type::Reference(r) = &*s.elem {
2529 if let syn::Type::Path(p) = &*r.elem {
2530 // Slices with "real types" inside are mapped as the equivalent non-ref Vec
2531 let resolved = self.resolve_path(&p.path, generics);
2532 let mangled_container = if let Some(ident) = self.crate_types.opaques.get(&resolved) {
2533 format!("CVec_{}Z", ident)
2534 } else if let Some(en) = self.crate_types.mirrored_enums.get(&resolved) {
2535 format!("CVec_{}Z", en.ident)
2536 } else if let Some(id) = p.path.get_ident() {
2537 format!("CVec_{}Z", id)
2538 } else { return false; };
2539 write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
2540 self.check_create_container(mangled_container, "Vec", vec![&*r.elem], generics, false)
2542 } else if let syn::Type::Tuple(_) = &*s.elem {
2543 let mut args = syn::punctuated::Punctuated::<_, syn::token::Comma>::new();
2544 args.push(syn::GenericArgument::Type((*s.elem).clone()));
2545 let mut segments = syn::punctuated::Punctuated::new();
2546 segments.push(parse_quote!(Vec<#args>));
2547 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)
2550 syn::Type::Tuple(t) => {
2551 if t.elems.len() == 0 {
2554 self.write_c_mangled_container_path(w, t.elems.iter().collect(), generics,
2555 &format!("{}Tuple", t.elems.len()), is_ref, is_mut, ptr_for_ref)
2561 pub fn write_c_type<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) {
2562 assert!(self.write_c_type_intern(w, t, generics, false, false, ptr_for_ref));
2564 pub fn understood_c_path(&self, p: &syn::Path) -> bool {
2565 if p.leading_colon.is_some() { return false; }
2566 self.write_c_path_intern(&mut std::io::sink(), p, None, false, false, false)
2568 pub fn understood_c_type(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
2569 self.write_c_type_intern(&mut std::io::sink(), t, generics, false, false, false)