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 {
69 /// This is used only for traits to indicate that users should not be able to implement their
70 /// own version of a trait, but we should export Rust implementations of the trait (and the
72 /// Concretly, this means that we do not implement the Rust trait for the C trait struct.
75 /// Gets the ExportStatus of an object (struct, fn, etc) given its attributes.
76 pub fn export_status(attrs: &[syn::Attribute]) -> ExportStatus {
77 for attr in attrs.iter() {
78 let tokens_clone = attr.tokens.clone();
79 let mut token_iter = tokens_clone.into_iter();
80 if let Some(token) = token_iter.next() {
82 TokenTree::Punct(c) if c.as_char() == '=' => {
83 // Really not sure where syn gets '=' from here -
84 // it somehow represents '///' or '//!'
86 TokenTree::Group(g) => {
87 if format!("{}", single_ident_generic_path_to_ident(&attr.path).unwrap()) == "cfg" {
88 let mut iter = g.stream().into_iter();
89 if let TokenTree::Ident(i) = iter.next().unwrap() {
91 // #[cfg(any(test, feature = ""))]
92 if let TokenTree::Group(g) = iter.next().unwrap() {
93 let mut all_test = true;
94 for token in g.stream().into_iter() {
95 if let TokenTree::Ident(i) = token {
96 match format!("{}", i).as_str() {
99 _ => all_test = false,
101 } else if let TokenTree::Literal(lit) = token {
102 if format!("{}", lit) != "fuzztarget" {
107 if all_test { return ExportStatus::TestOnly; }
109 } else if i == "test" || i == "feature" {
110 // If its cfg(feature(...)) we assume its test-only
111 return ExportStatus::TestOnly;
115 continue; // eg #[derive()]
117 _ => unimplemented!(),
120 match token_iter.next().unwrap() {
121 TokenTree::Literal(lit) => {
122 let line = format!("{}", lit);
123 if line.contains("(C-not exported)") {
124 return ExportStatus::NoExport;
125 } else if line.contains("(C-not implementable)") {
126 return ExportStatus::NotImplementable;
129 _ => unimplemented!(),
135 pub fn assert_simple_bound(bound: &syn::TraitBound) {
136 if bound.paren_token.is_some() || bound.lifetimes.is_some() { unimplemented!(); }
137 if let syn::TraitBoundModifier::Maybe(_) = bound.modifier { unimplemented!(); }
140 /// Returns true if the enum will be mapped as an opaue (ie struct with a pointer to the underlying
141 /// type), otherwise it is mapped into a transparent, C-compatible version of itself.
142 pub fn is_enum_opaque(e: &syn::ItemEnum) -> bool {
143 for var in e.variants.iter() {
144 if let syn::Fields::Named(fields) = &var.fields {
145 for field in fields.named.iter() {
146 match export_status(&field.attrs) {
147 ExportStatus::Export|ExportStatus::TestOnly => {},
148 ExportStatus::NotImplementable => panic!("(C-not implementable) should only appear on traits!"),
149 ExportStatus::NoExport => return true,
152 } else if let syn::Fields::Unnamed(fields) = &var.fields {
153 for field in fields.unnamed.iter() {
154 match export_status(&field.attrs) {
155 ExportStatus::Export|ExportStatus::TestOnly => {},
156 ExportStatus::NotImplementable => panic!("(C-not implementable) should only appear on traits!"),
157 ExportStatus::NoExport => return true,
165 /// A stack of sets of generic resolutions.
167 /// This tracks the template parameters for a function, struct, or trait, allowing resolution into
168 /// a concrete type. By pushing a new context onto the stack, this can track a function's template
169 /// parameters inside of a generic struct or trait.
171 /// It maps both direct types as well as Deref<Target = X>, mapping them via the provided
172 /// TypeResolver's resolve_path function (ie traits map to the concrete jump table, structs to the
173 /// concrete C container struct, etc).
175 pub struct GenericTypes<'a, 'b> {
176 self_ty: Option<(String, &'a syn::Path)>,
177 parent: Option<&'b GenericTypes<'b, 'b>>,
178 typed_generics: HashMap<&'a syn::Ident, (String, Option<&'a syn::Path>)>,
179 default_generics: HashMap<&'a syn::Ident, (syn::Type, syn::Type)>,
181 impl<'a, 'p: 'a> GenericTypes<'a, 'p> {
182 pub fn new(self_ty: Option<(String, &'a syn::Path)>) -> Self {
183 Self { self_ty, parent: None, typed_generics: HashMap::new(), default_generics: HashMap::new(), }
186 /// push a new context onto the stack, allowing for a new set of generics to be learned which
187 /// will override any lower contexts, but which will still fall back to resoltion via lower
189 pub fn push_ctx<'c>(&'c self) -> GenericTypes<'a, 'c> {
190 GenericTypes { self_ty: None, parent: Some(self), typed_generics: HashMap::new(), default_generics: HashMap::new(), }
193 /// Learn the generics in generics in the current context, given a TypeResolver.
194 pub fn learn_generics<'b, 'c>(&mut self, generics: &'a syn::Generics, types: &'b TypeResolver<'a, 'c>) -> bool {
195 // First learn simple generics...
196 for generic in generics.params.iter() {
198 syn::GenericParam::Type(type_param) => {
199 let mut non_lifetimes_processed = false;
200 'bound_loop: for bound in type_param.bounds.iter() {
201 if let syn::TypeParamBound::Trait(trait_bound) = bound {
202 if let Some(ident) = single_ident_generic_path_to_ident(&trait_bound.path) {
203 match &format!("{}", ident) as &str { "Send" => continue, "Sync" => continue, _ => {} }
205 if path_matches_nongeneric(&trait_bound.path, &["core", "clone", "Clone"]) { continue; }
207 assert_simple_bound(&trait_bound);
208 if let Some(mut path) = types.maybe_resolve_path(&trait_bound.path, None) {
209 if types.skip_path(&path) { continue; }
210 if path == "Sized" { continue; }
211 if non_lifetimes_processed { return false; }
212 non_lifetimes_processed = true;
213 let new_ident = if path != "std::ops::Deref" && path != "core::ops::Deref" {
214 path = "crate::".to_string() + &path;
215 Some(&trait_bound.path)
216 } else if trait_bound.path.segments.len() == 1 {
217 // If we're templated on Deref<Target = ConcreteThing>, store
218 // the reference type in `default_generics` which handles full
219 // types and not just paths.
220 if let syn::PathArguments::AngleBracketed(ref args) =
221 trait_bound.path.segments[0].arguments {
222 for subargument in args.args.iter() {
224 syn::GenericArgument::Lifetime(_) => {},
225 syn::GenericArgument::Binding(ref b) => {
226 if &format!("{}", b.ident) != "Target" { return false; }
228 self.default_generics.insert(&type_param.ident, (parse_quote!(&#default), parse_quote!(&#default)));
231 _ => unimplemented!(),
237 self.typed_generics.insert(&type_param.ident, (path, new_ident));
238 } else { return false; }
241 if let Some(default) = type_param.default.as_ref() {
242 assert!(type_param.bounds.is_empty());
243 self.default_generics.insert(&type_param.ident, (default.clone(), parse_quote!(&#default)));
249 // Then find generics where we are required to pass a Deref<Target=X> and pretend its just X.
250 if let Some(wh) = &generics.where_clause {
251 for pred in wh.predicates.iter() {
252 if let syn::WherePredicate::Type(t) = pred {
253 if let syn::Type::Path(p) = &t.bounded_ty {
254 if p.qself.is_some() { return false; }
255 if p.path.leading_colon.is_some() { return false; }
256 let mut p_iter = p.path.segments.iter();
257 if let Some(gen) = self.typed_generics.get_mut(&p_iter.next().unwrap().ident) {
258 if gen.0 != "std::ops::Deref" && gen.0 != "core::ops::Deref" { return false; }
259 if &format!("{}", p_iter.next().unwrap().ident) != "Target" { return false; }
261 let mut non_lifetimes_processed = false;
262 for bound in t.bounds.iter() {
263 if let syn::TypeParamBound::Trait(trait_bound) = bound {
264 if let Some(id) = trait_bound.path.get_ident() {
265 if format!("{}", id) == "Sized" { continue; }
267 if non_lifetimes_processed { return false; }
268 non_lifetimes_processed = true;
269 assert_simple_bound(&trait_bound);
270 *gen = ("crate::".to_string() + &types.resolve_path(&trait_bound.path, None),
271 Some(&trait_bound.path));
274 } else { return false; }
275 } else { return false; }
279 for (_, (_, ident)) in self.typed_generics.iter() {
280 if ident.is_none() { return false; }
285 /// Learn the associated types from the trait in the current context.
286 pub fn learn_associated_types<'b, 'c>(&mut self, t: &'a syn::ItemTrait, types: &'b TypeResolver<'a, 'c>) {
287 for item in t.items.iter() {
289 &syn::TraitItem::Type(ref t) => {
290 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
291 let mut bounds_iter = t.bounds.iter();
292 match bounds_iter.next().unwrap() {
293 syn::TypeParamBound::Trait(tr) => {
294 assert_simple_bound(&tr);
295 if let Some(mut path) = types.maybe_resolve_path(&tr.path, None) {
296 if types.skip_path(&path) { continue; }
297 // In general we handle Deref<Target=X> as if it were just X (and
298 // implement Deref<Target=Self> for relevant types). We don't
299 // bother to implement it for associated types, however, so we just
300 // ignore such bounds.
301 let new_ident = if path != "std::ops::Deref" && path != "core::ops::Deref" {
302 path = "crate::".to_string() + &path;
305 self.typed_generics.insert(&t.ident, (path, new_ident));
306 } else { unimplemented!(); }
308 _ => unimplemented!(),
310 if bounds_iter.next().is_some() { unimplemented!(); }
317 /// Attempt to resolve an Ident as a generic parameter and return the full path.
318 pub fn maybe_resolve_ident<'b>(&'b self, ident: &syn::Ident) -> Option<&'b String> {
319 if let Some(ty) = &self.self_ty {
320 if format!("{}", ident) == "Self" {
324 if let Some(res) = self.typed_generics.get(ident).map(|(a, _)| a) {
327 if let Some(parent) = self.parent {
328 parent.maybe_resolve_ident(ident)
334 /// Attempt to resolve a Path as a generic parameter and return the full path. as both a string
336 pub fn maybe_resolve_path<'b>(&'b self, path: &syn::Path) -> Option<(&'b String, &'a syn::Path)> {
337 if let Some(ident) = path.get_ident() {
338 if let Some(ty) = &self.self_ty {
339 if format!("{}", ident) == "Self" {
340 return Some((&ty.0, ty.1));
343 if let Some(res) = self.typed_generics.get(ident).map(|(a, b)| (a, b.unwrap())) {
347 // Associated types are usually specified as "Self::Generic", so we check for that
349 let mut it = path.segments.iter();
350 if path.segments.len() == 2 && format!("{}", it.next().unwrap().ident) == "Self" {
351 let ident = &it.next().unwrap().ident;
352 if let Some(res) = self.typed_generics.get(ident).map(|(a, b)| (a, b.unwrap())) {
357 if let Some(parent) = self.parent {
358 parent.maybe_resolve_path(path)
365 trait ResolveType<'a> { fn resolve_type(&'a self, ty: &'a syn::Type) -> &'a syn::Type; }
366 impl<'a, 'b, 'c: 'a + 'b> ResolveType<'c> for Option<&GenericTypes<'a, 'b>> {
367 fn resolve_type(&'c self, ty: &'c syn::Type) -> &'c syn::Type {
368 if let Some(us) = self {
370 syn::Type::Path(p) => {
371 if let Some(ident) = p.path.get_ident() {
372 if let Some((ty, _)) = us.default_generics.get(ident) {
377 syn::Type::Reference(syn::TypeReference { elem, .. }) => {
378 if let syn::Type::Path(p) = &**elem {
379 if let Some(ident) = p.path.get_ident() {
380 if let Some((_, refty)) = us.default_generics.get(ident) {
393 #[derive(Clone, PartialEq)]
394 // The type of declaration and the object itself
395 pub enum DeclType<'a> {
397 Trait(&'a syn::ItemTrait),
403 pub struct ImportResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
404 crate_name: &'mod_lifetime str,
405 dependencies: &'mod_lifetime HashSet<syn::Ident>,
406 module_path: &'mod_lifetime str,
407 imports: HashMap<syn::Ident, (String, syn::Path)>,
408 declared: HashMap<syn::Ident, DeclType<'crate_lft>>,
409 priv_modules: HashSet<syn::Ident>,
411 impl<'mod_lifetime, 'crate_lft: 'mod_lifetime> ImportResolver<'mod_lifetime, 'crate_lft> {
412 fn process_use_intern(crate_name: &str, module_path: &str, dependencies: &HashSet<syn::Ident>, imports: &mut HashMap<syn::Ident, (String, syn::Path)>,
413 u: &syn::UseTree, partial_path: &str, mut path: syn::punctuated::Punctuated<syn::PathSegment, syn::token::Colon2>) {
416 macro_rules! push_path {
417 ($ident: expr, $path_suffix: expr) => {
418 if partial_path == "" && format!("{}", $ident) == "super" {
419 let mut mod_iter = module_path.rsplitn(2, "::");
420 mod_iter.next().unwrap();
421 let super_mod = mod_iter.next().unwrap();
422 new_path = format!("{}{}", super_mod, $path_suffix);
423 assert_eq!(path.len(), 0);
424 for module in super_mod.split("::") {
425 path.push(syn::PathSegment { ident: syn::Ident::new(module, Span::call_site()), arguments: syn::PathArguments::None });
427 } else if partial_path == "" && !dependencies.contains(&$ident) {
428 new_path = format!("{}::{}{}", crate_name, $ident, $path_suffix);
429 let crate_name_ident = format_ident!("{}", crate_name);
430 path.push(parse_quote!(#crate_name_ident));
432 new_path = format!("{}{}{}", partial_path, $ident, $path_suffix);
435 path.push(parse_quote!(#ident));
439 syn::UseTree::Path(p) => {
440 push_path!(p.ident, "::");
441 Self::process_use_intern(crate_name, module_path, dependencies, imports, &p.tree, &new_path, path);
443 syn::UseTree::Name(n) => {
444 push_path!(n.ident, "");
445 imports.insert(n.ident.clone(), (new_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
447 syn::UseTree::Group(g) => {
448 for i in g.items.iter() {
449 Self::process_use_intern(crate_name, module_path, dependencies, imports, i, partial_path, path.clone());
452 syn::UseTree::Rename(r) => {
453 push_path!(r.ident, "");
454 imports.insert(r.rename.clone(), (new_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
456 syn::UseTree::Glob(_) => {
457 eprintln!("Ignoring * use for {} - this may result in resolution failures", partial_path);
462 fn process_use(crate_name: &str, module_path: &str, dependencies: &HashSet<syn::Ident>, imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::ItemUse) {
463 if let syn::Visibility::Public(_) = u.vis {
464 // We actually only use these for #[cfg(fuzztarget)]
465 eprintln!("Ignoring pub(use) tree!");
468 if u.leading_colon.is_some() { eprintln!("Ignoring leading-colon use!"); return; }
469 Self::process_use_intern(crate_name, module_path, dependencies, imports, &u.tree, "", syn::punctuated::Punctuated::new());
472 fn insert_primitive(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, id: &str) {
473 let ident = format_ident!("{}", id);
474 let path = parse_quote!(#ident);
475 imports.insert(ident, (id.to_owned(), path));
478 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 {
479 Self::from_borrowed_items(crate_name, dependencies, module_path, &contents.iter().map(|a| a).collect::<Vec<_>>())
481 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 {
482 let mut imports = HashMap::new();
483 // Add primitives to the "imports" list:
484 Self::insert_primitive(&mut imports, "bool");
485 Self::insert_primitive(&mut imports, "u64");
486 Self::insert_primitive(&mut imports, "u32");
487 Self::insert_primitive(&mut imports, "u16");
488 Self::insert_primitive(&mut imports, "u8");
489 Self::insert_primitive(&mut imports, "usize");
490 Self::insert_primitive(&mut imports, "str");
491 Self::insert_primitive(&mut imports, "String");
493 // These are here to allow us to print native Rust types in trait fn impls even if we don't
495 Self::insert_primitive(&mut imports, "Result");
496 Self::insert_primitive(&mut imports, "Vec");
497 Self::insert_primitive(&mut imports, "Option");
499 let mut declared = HashMap::new();
500 let mut priv_modules = HashSet::new();
502 for item in contents.iter() {
504 syn::Item::Use(u) => Self::process_use(crate_name, module_path, dependencies, &mut imports, &u),
505 syn::Item::Struct(s) => {
506 if let syn::Visibility::Public(_) = s.vis {
507 match export_status(&s.attrs) {
508 ExportStatus::Export => { declared.insert(s.ident.clone(), DeclType::StructImported); },
509 ExportStatus::NoExport => { declared.insert(s.ident.clone(), DeclType::StructIgnored); },
510 ExportStatus::TestOnly => continue,
511 ExportStatus::NotImplementable => panic!("(C-not implementable) should only appear on traits!"),
515 syn::Item::Type(t) if export_status(&t.attrs) == ExportStatus::Export => {
516 if let syn::Visibility::Public(_) = t.vis {
517 let mut process_alias = true;
518 for tok in t.generics.params.iter() {
519 if let syn::GenericParam::Lifetime(_) = tok {}
520 else { process_alias = false; }
523 declared.insert(t.ident.clone(), DeclType::StructImported);
527 syn::Item::Enum(e) => {
528 if let syn::Visibility::Public(_) = e.vis {
529 match export_status(&e.attrs) {
530 ExportStatus::Export if is_enum_opaque(e) => { declared.insert(e.ident.clone(), DeclType::EnumIgnored); },
531 ExportStatus::Export => { declared.insert(e.ident.clone(), DeclType::MirroredEnum); },
532 ExportStatus::NotImplementable => panic!("(C-not implementable) should only appear on traits!"),
537 syn::Item::Trait(t) => {
538 match export_status(&t.attrs) {
539 ExportStatus::Export|ExportStatus::NotImplementable => {
540 if let syn::Visibility::Public(_) = t.vis {
541 declared.insert(t.ident.clone(), DeclType::Trait(t));
547 syn::Item::Mod(m) => {
548 priv_modules.insert(m.ident.clone());
554 Self { crate_name, dependencies, module_path, imports, declared, priv_modules }
557 pub fn get_declared_type(&self, ident: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
558 self.declared.get(ident)
561 pub fn maybe_resolve_declared(&self, id: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
562 self.declared.get(id)
565 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
566 if let Some((imp, _)) = self.imports.get(id) {
568 } else if self.declared.get(id).is_some() {
569 Some(self.module_path.to_string() + "::" + &format!("{}", id))
573 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
574 if let Some((imp, _)) = self.imports.get(id) {
576 } else if let Some(decl_type) = self.declared.get(id) {
578 DeclType::StructIgnored => None,
579 _ => Some(self.module_path.to_string() + "::" + &format!("{}", id)),
584 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
585 let p = if let Some(gen_types) = generics {
586 if let Some((_, synpath)) = gen_types.maybe_resolve_path(p_arg) {
591 if p.leading_colon.is_some() {
592 let mut res: String = p.segments.iter().enumerate().map(|(idx, seg)| {
593 format!("{}{}", if idx == 0 { "" } else { "::" }, seg.ident)
595 let firstseg = p.segments.iter().next().unwrap();
596 if !self.dependencies.contains(&firstseg.ident) {
597 res = self.crate_name.to_owned() + "::" + &res;
600 } else if let Some(id) = p.get_ident() {
601 self.maybe_resolve_ident(id)
603 if p.segments.len() == 1 {
604 let seg = p.segments.iter().next().unwrap();
605 return self.maybe_resolve_ident(&seg.ident);
607 let mut seg_iter = p.segments.iter();
608 let first_seg = seg_iter.next().unwrap();
609 let remaining: String = seg_iter.map(|seg| {
610 format!("::{}", seg.ident)
612 let first_seg_str = format!("{}", first_seg.ident);
613 if let Some((imp, _)) = self.imports.get(&first_seg.ident) {
615 Some(imp.clone() + &remaining)
619 } else if let Some(_) = self.priv_modules.get(&first_seg.ident) {
620 Some(format!("{}::{}{}", self.module_path, first_seg.ident, remaining))
621 } else if first_seg_str == "std" || first_seg_str == "core" || self.dependencies.contains(&first_seg.ident) {
622 Some(first_seg_str + &remaining)
627 /// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern)
628 pub fn resolve_imported_refs(&self, mut ty: syn::Type) -> syn::Type {
630 syn::Type::Path(p) => {
631 if p.path.segments.len() != 1 { unimplemented!(); }
632 let mut args = p.path.segments[0].arguments.clone();
633 if let syn::PathArguments::AngleBracketed(ref mut generics) = &mut args {
634 for arg in generics.args.iter_mut() {
635 if let syn::GenericArgument::Type(ref mut t) = arg {
636 *t = self.resolve_imported_refs(t.clone());
640 if let Some((_, newpath)) = self.imports.get(single_ident_generic_path_to_ident(&p.path).unwrap()) {
641 p.path = newpath.clone();
643 p.path.segments[0].arguments = args;
645 syn::Type::Reference(r) => {
646 r.elem = Box::new(self.resolve_imported_refs((*r.elem).clone()));
648 syn::Type::Slice(s) => {
649 s.elem = Box::new(self.resolve_imported_refs((*s.elem).clone()));
651 syn::Type::Tuple(t) => {
652 for e in t.elems.iter_mut() {
653 *e = self.resolve_imported_refs(e.clone());
656 _ => unimplemented!(),
662 // templates_defined is walked to write the C++ header, so if we use the default hashing it get
663 // reordered on each genbindings run. Instead, we use SipHasher (which defaults to 0-keys) so that
664 // the sorting is stable across runs. It is deprecated, but the "replacement" doesn't actually
665 // accomplish the same goals, so we just ignore it.
667 pub type NonRandomHash = hash::BuildHasherDefault<hash::SipHasher>;
670 pub struct ASTModule {
671 pub attrs: Vec<syn::Attribute>,
672 pub items: Vec<syn::Item>,
673 pub submods: Vec<String>,
675 /// A struct containing the syn::File AST for each file in the crate.
676 pub struct FullLibraryAST {
677 pub modules: HashMap<String, ASTModule, NonRandomHash>,
678 pub dependencies: HashSet<syn::Ident>,
680 impl FullLibraryAST {
681 fn load_module(&mut self, module: String, attrs: Vec<syn::Attribute>, mut items: Vec<syn::Item>) {
682 let mut non_mod_items = Vec::with_capacity(items.len());
683 let mut submods = Vec::with_capacity(items.len());
684 for item in items.drain(..) {
686 syn::Item::Mod(m) if m.content.is_some() => {
687 if export_status(&m.attrs) == ExportStatus::Export {
688 if let syn::Visibility::Public(_) = m.vis {
689 let modident = format!("{}", m.ident);
690 let modname = if module != "" {
691 module.clone() + "::" + &modident
695 self.load_module(modname, m.attrs, m.content.unwrap().1);
696 submods.push(modident);
698 non_mod_items.push(syn::Item::Mod(m));
702 syn::Item::Mod(_) => panic!("--pretty=expanded output should never have non-body modules"),
703 syn::Item::ExternCrate(c) => {
704 if export_status(&c.attrs) == ExportStatus::Export {
705 self.dependencies.insert(c.ident);
708 _ => { non_mod_items.push(item); }
711 self.modules.insert(module, ASTModule { attrs, items: non_mod_items, submods });
714 pub fn load_lib(lib: syn::File) -> Self {
715 assert_eq!(export_status(&lib.attrs), ExportStatus::Export);
716 let mut res = Self { modules: HashMap::default(), dependencies: HashSet::new() };
717 res.load_module("".to_owned(), lib.attrs, lib.items);
722 /// List of manually-generated types which are clonable
723 fn initial_clonable_types() -> HashSet<String> {
724 let mut res = HashSet::new();
725 res.insert("crate::c_types::u5".to_owned());
729 /// Top-level struct tracking everything which has been defined while walking the crate.
730 pub struct CrateTypes<'a> {
731 /// This may contain structs or enums, but only when either is mapped as
732 /// struct X { inner: *mut originalX, .. }
733 pub opaques: HashMap<String, &'a syn::Ident>,
734 /// Enums which are mapped as C enums with conversion functions
735 pub mirrored_enums: HashMap<String, &'a syn::ItemEnum>,
736 /// Traits which are mapped as a pointer + jump table
737 pub traits: HashMap<String, &'a syn::ItemTrait>,
738 /// Aliases from paths to some other Type
739 pub type_aliases: HashMap<String, syn::Type>,
740 /// Value is an alias to Key (maybe with some generics)
741 pub reverse_alias_map: HashMap<String, Vec<(syn::Path, syn::PathArguments)>>,
742 /// Template continer types defined, map from mangled type name -> whether a destructor fn
745 /// This is used at the end of processing to make C++ wrapper classes
746 pub templates_defined: RefCell<HashMap<String, bool, NonRandomHash>>,
747 /// The output file for any created template container types, written to as we find new
748 /// template containers which need to be defined.
749 template_file: RefCell<&'a mut File>,
750 /// Set of containers which are clonable
751 clonable_types: RefCell<HashSet<String>>,
753 pub trait_impls: HashMap<String, Vec<String>>,
754 /// The full set of modules in the crate(s)
755 pub lib_ast: &'a FullLibraryAST,
758 impl<'a> CrateTypes<'a> {
759 pub fn new(template_file: &'a mut File, libast: &'a FullLibraryAST) -> Self {
761 opaques: HashMap::new(), mirrored_enums: HashMap::new(), traits: HashMap::new(),
762 type_aliases: HashMap::new(), reverse_alias_map: HashMap::new(),
763 templates_defined: RefCell::new(HashMap::default()),
764 clonable_types: RefCell::new(initial_clonable_types()), trait_impls: HashMap::new(),
765 template_file: RefCell::new(template_file), lib_ast: &libast,
768 pub fn set_clonable(&self, object: String) {
769 self.clonable_types.borrow_mut().insert(object);
771 pub fn is_clonable(&self, object: &str) -> bool {
772 self.clonable_types.borrow().contains(object)
774 pub fn write_new_template(&self, mangled_container: String, has_destructor: bool, created_container: &[u8]) {
775 self.template_file.borrow_mut().write(created_container).unwrap();
776 self.templates_defined.borrow_mut().insert(mangled_container, has_destructor);
780 /// A struct which tracks resolving rust types into C-mapped equivalents, exists for one specific
781 /// module but contains a reference to the overall CrateTypes tracking.
782 pub struct TypeResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
783 pub module_path: &'mod_lifetime str,
784 pub crate_types: &'mod_lifetime CrateTypes<'crate_lft>,
785 types: ImportResolver<'mod_lifetime, 'crate_lft>,
788 /// Returned by write_empty_rust_val_check_suffix to indicate what type of dereferencing needs to
789 /// happen to get the inner value of a generic.
790 enum EmptyValExpectedTy {
791 /// A type which has a flag for being empty (eg an array where we treat all-0s as empty).
793 /// A pointer that we want to dereference and move out of.
795 /// A pointer which we want to convert to a reference.
800 /// Describes the appropriate place to print a general type-conversion string when converting a
802 enum ContainerPrefixLocation {
803 /// Prints a general type-conversion string prefix and suffix outside of the
804 /// container-conversion strings.
806 /// Prints a general type-conversion string prefix and suffix inside of the
807 /// container-conversion strings.
809 /// Does not print the usual type-conversion string prefix and suffix.
813 impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
814 pub fn new(module_path: &'a str, types: ImportResolver<'a, 'c>, crate_types: &'a CrateTypes<'c>) -> Self {
815 Self { module_path, types, crate_types }
818 // *************************************************
819 // *** Well know type and conversion definitions ***
820 // *************************************************
822 /// Returns true we if can just skip passing this to C entirely
823 fn skip_path(&self, full_path: &str) -> bool {
824 full_path == "bitcoin::secp256k1::Secp256k1" ||
825 full_path == "bitcoin::secp256k1::Signing" ||
826 full_path == "bitcoin::secp256k1::Verification"
828 /// Returns true we if can just skip passing this to C entirely
829 fn no_arg_path_to_rust(&self, full_path: &str) -> &str {
830 if full_path == "bitcoin::secp256k1::Secp256k1" {
831 "secp256k1::SECP256K1"
832 } else { unimplemented!(); }
835 /// Returns true if the object is a primitive and is mapped as-is with no conversion
837 pub fn is_primitive(&self, full_path: &str) -> bool {
848 pub fn is_clonable(&self, ty: &str) -> bool {
849 if self.crate_types.is_clonable(ty) { return true; }
850 if self.is_primitive(ty) { return true; }
853 "crate::c_types::Signature" => true,
854 "crate::c_types::RecoverableSignature" => true,
855 "crate::c_types::TxOut" => true,
859 /// Gets the C-mapped type for types which are outside of the crate, or which are manually
860 /// ignored by for some reason need mapping anyway.
861 fn c_type_from_path<'b>(&self, full_path: &'b str, is_ref: bool, _ptr_for_ref: bool) -> Option<&'b str> {
862 if self.is_primitive(full_path) {
863 return Some(full_path);
866 "Result" => Some("crate::c_types::derived::CResult"),
867 "Vec" if !is_ref => Some("crate::c_types::derived::CVec"),
868 "Option" => Some(""),
870 // Note that no !is_ref types can map to an array because Rust and C's call semantics
871 // for arrays are different (https://github.com/eqrion/cbindgen/issues/528)
873 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
874 "[u8; 20]" if !is_ref => Some("crate::c_types::TwentyBytes"),
875 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes"),
876 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes"),
877 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes"),
878 "[u8; 3]" if !is_ref => Some("crate::c_types::ThreeBytes"), // Used for RGB values
880 "str" if is_ref => Some("crate::c_types::Str"),
881 "alloc::string::String"|"String" => Some("crate::c_types::Str"),
883 "std::time::Duration"|"core::time::Duration" => Some("u64"),
884 "std::time::SystemTime" => Some("u64"),
885 "std::io::Error" => Some("crate::c_types::IOError"),
887 "bech32::u5" => Some("crate::c_types::u5"),
889 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
890 => Some("crate::c_types::PublicKey"),
891 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature"),
892 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some("crate::c_types::RecoverableSignature"),
893 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
894 if is_ref => Some("*const [u8; 32]"),
895 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
896 if !is_ref => Some("crate::c_types::SecretKey"),
897 "bitcoin::secp256k1::Error"|"secp256k1::Error"
898 if !is_ref => Some("crate::c_types::Secp256k1Error"),
899 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice"),
900 "bitcoin::blockdata::script::Script" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
901 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::lightning::chain::transaction::OutPoint"),
902 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction"),
903 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut"),
904 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network"),
905 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("*const [u8; 80]"),
906 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice"),
908 // Newtypes that we just expose in their original form.
909 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
910 if is_ref => Some("*const [u8; 32]"),
911 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
912 if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
913 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
914 "lightning::ln::PaymentHash" if is_ref => Some("*const [u8; 32]"),
915 "lightning::ln::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
916 "lightning::ln::PaymentPreimage" if is_ref => Some("*const [u8; 32]"),
917 "lightning::ln::PaymentPreimage" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
918 "lightning::ln::PaymentSecret" => Some("crate::c_types::ThirtyTwoBytes"),
920 // Override the default since Records contain an fmt with a lifetime:
921 "lightning::util::logger::Record" => Some("*const std::os::raw::c_char"),
927 fn from_c_conversion_new_var_from_path<'b>(&self, _full_path: &str, _is_ref: bool) -> Option<(&'b str, &'b str)> {
930 fn from_c_conversion_prefix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
931 if self.is_primitive(full_path) {
932 return Some("".to_owned());
935 "Vec" if !is_ref => Some("local_"),
936 "Result" if !is_ref => Some("local_"),
937 "Option" if is_ref => Some("&local_"),
938 "Option" => Some("local_"),
940 "[u8; 32]" if is_ref => Some("unsafe { &*"),
941 "[u8; 32]" if !is_ref => Some(""),
942 "[u8; 20]" if !is_ref => Some(""),
943 "[u8; 16]" if !is_ref => Some(""),
944 "[u8; 10]" if !is_ref => Some(""),
945 "[u8; 4]" if !is_ref => Some(""),
946 "[u8; 3]" if !is_ref => Some(""),
948 "[u8]" if is_ref => Some(""),
949 "[usize]" if is_ref => Some(""),
951 "str" if is_ref => Some(""),
952 "alloc::string::String"|"String" => Some(""),
953 // Note that we'll panic for String if is_ref, as we only have non-owned memory, we
954 // cannot create a &String.
956 "std::time::Duration"|"core::time::Duration" => Some("std::time::Duration::from_secs("),
957 "std::time::SystemTime" => Some("(::std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs("),
959 "bech32::u5" => Some(""),
961 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
962 if is_ref => Some("&"),
963 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
965 "bitcoin::secp256k1::Signature" if is_ref => Some("&"),
966 "bitcoin::secp256k1::Signature" => Some(""),
967 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(""),
968 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
969 if is_ref => Some("&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *"),
970 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
971 if !is_ref => Some(""),
972 "bitcoin::blockdata::script::Script" if is_ref => Some("&::bitcoin::blockdata::script::Script::from(Vec::from("),
973 "bitcoin::blockdata::script::Script" if !is_ref => Some("::bitcoin::blockdata::script::Script::from("),
974 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some("&"),
975 "bitcoin::blockdata::transaction::Transaction" => Some(""),
976 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(""),
977 "bitcoin::network::constants::Network" => Some(""),
978 "bitcoin::blockdata::block::BlockHeader" => Some("&::bitcoin::consensus::encode::deserialize(unsafe { &*"),
979 "bitcoin::blockdata::block::Block" if is_ref => Some("&::bitcoin::consensus::encode::deserialize("),
981 // Newtypes that we just expose in their original form.
982 "bitcoin::hash_types::Txid" if is_ref => Some("&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*"),
983 "bitcoin::hash_types::Txid" if !is_ref => Some("::bitcoin::hash_types::Txid::from_slice(&"),
984 "bitcoin::hash_types::BlockHash" => Some("::bitcoin::hash_types::BlockHash::from_slice(&"),
985 "lightning::ln::PaymentHash" if !is_ref => Some("::lightning::ln::PaymentHash("),
986 "lightning::ln::PaymentHash" if is_ref => Some("&::lightning::ln::PaymentHash(unsafe { *"),
987 "lightning::ln::PaymentPreimage" if !is_ref => Some("::lightning::ln::PaymentPreimage("),
988 "lightning::ln::PaymentPreimage" if is_ref => Some("&::lightning::ln::PaymentPreimage(unsafe { *"),
989 "lightning::ln::PaymentSecret" => Some("::lightning::ln::PaymentSecret("),
991 // List of traits we map (possibly during processing of other files):
992 "crate::util::logger::Logger" => Some(""),
995 }.map(|s| s.to_owned())
997 fn from_c_conversion_suffix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
998 if self.is_primitive(full_path) {
999 return Some("".to_owned());
1002 "Vec" if !is_ref => Some(""),
1003 "Option" => Some(""),
1004 "Result" if !is_ref => Some(""),
1006 "[u8; 32]" if is_ref => Some("}"),
1007 "[u8; 32]" if !is_ref => Some(".data"),
1008 "[u8; 20]" if !is_ref => Some(".data"),
1009 "[u8; 16]" if !is_ref => Some(".data"),
1010 "[u8; 10]" if !is_ref => Some(".data"),
1011 "[u8; 4]" if !is_ref => Some(".data"),
1012 "[u8; 3]" if !is_ref => Some(".data"),
1014 "[u8]" if is_ref => Some(".to_slice()"),
1015 "[usize]" if is_ref => Some(".to_slice()"),
1017 "str" if is_ref => Some(".into_str()"),
1018 "alloc::string::String"|"String" => Some(".into_string()"),
1020 "std::time::Duration"|"core::time::Duration" => Some(")"),
1021 "std::time::SystemTime" => Some("))"),
1023 "bech32::u5" => Some(".into()"),
1025 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1026 => Some(".into_rust()"),
1027 "bitcoin::secp256k1::Signature" => Some(".into_rust()"),
1028 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(".into_rust()"),
1029 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1030 if !is_ref => Some(".into_rust()"),
1031 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1032 if is_ref => Some("}[..]).unwrap()"),
1033 "bitcoin::blockdata::script::Script" if is_ref => Some(".to_slice()))"),
1034 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_rust())"),
1035 "bitcoin::blockdata::transaction::Transaction" => Some(".into_bitcoin()"),
1036 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(".into_rust()"),
1037 "bitcoin::network::constants::Network" => Some(".into_bitcoin()"),
1038 "bitcoin::blockdata::block::BlockHeader" => Some(" }).unwrap()"),
1039 "bitcoin::blockdata::block::Block" => Some(".to_slice()).unwrap()"),
1041 // Newtypes that we just expose in their original form.
1042 "bitcoin::hash_types::Txid" if is_ref => Some(" }[..]).unwrap()"),
1043 "bitcoin::hash_types::Txid" => Some(".data[..]).unwrap()"),
1044 "bitcoin::hash_types::BlockHash" if !is_ref => Some(".data[..]).unwrap()"),
1045 "lightning::ln::PaymentHash" if !is_ref => Some(".data)"),
1046 "lightning::ln::PaymentHash" if is_ref => Some(" })"),
1047 "lightning::ln::PaymentPreimage" if !is_ref => Some(".data)"),
1048 "lightning::ln::PaymentPreimage" if is_ref => Some(" })"),
1049 "lightning::ln::PaymentSecret" => Some(".data)"),
1051 // List of traits we map (possibly during processing of other files):
1052 "crate::util::logger::Logger" => Some(""),
1055 }.map(|s| s.to_owned())
1058 fn to_c_conversion_new_var_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<(&'b str, &'b str)> {
1059 if self.is_primitive(full_path) {
1063 "[u8]" if is_ref => Some(("crate::c_types::u8slice::from_slice(", ")")),
1064 "[usize]" if is_ref => Some(("crate::c_types::usizeslice::from_slice(", ")")),
1066 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(("{ let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(", ")); s }")),
1067 "bitcoin::blockdata::block::Block" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
1068 "bitcoin::hash_types::Txid" => None,
1070 // Override the default since Records contain an fmt with a lifetime:
1071 // TODO: We should include the other record fields
1072 "lightning::util::logger::Record" => Some(("std::ffi::CString::new(format!(\"{}\", ", ".args)).unwrap()")),
1074 }.map(|s| s.to_owned())
1076 fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
1077 if self.is_primitive(full_path) {
1078 return Some("".to_owned());
1081 "Result" if !is_ref => Some("local_"),
1082 "Vec" if !is_ref => Some("local_"),
1083 "Option" => Some("local_"),
1085 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1086 "[u8; 32]" if is_ref => Some(""),
1087 "[u8; 20]" if !is_ref => Some("crate::c_types::TwentyBytes { data: "),
1088 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes { data: "),
1089 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes { data: "),
1090 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes { data: "),
1091 "[u8; 3]" if is_ref => Some(""),
1093 "[u8]" if is_ref => Some("local_"),
1094 "[usize]" if is_ref => Some("local_"),
1096 "str" if is_ref => Some(""),
1097 "alloc::string::String"|"String" => Some(""),
1099 "std::time::Duration"|"core::time::Duration" => Some(""),
1100 "std::time::SystemTime" => Some(""),
1101 "std::io::Error" if !is_ref => Some("crate::c_types::IOError::from_rust("),
1103 "bech32::u5" => Some(""),
1105 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1106 => Some("crate::c_types::PublicKey::from_rust(&"),
1107 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature::from_rust(&"),
1108 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some("crate::c_types::RecoverableSignature::from_rust(&"),
1109 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1110 if is_ref => Some(""),
1111 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1112 if !is_ref => Some("crate::c_types::SecretKey::from_rust("),
1113 "bitcoin::secp256k1::Error"|"secp256k1::Error"
1114 if !is_ref => Some("crate::c_types::Secp256k1Error::from_rust("),
1115 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice::from_slice(&"),
1116 "bitcoin::blockdata::script::Script" if !is_ref => Some(""),
1117 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some("crate::c_types::Transaction::from_bitcoin("),
1118 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction::from_bitcoin(&"),
1119 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::c_types::bitcoin_to_C_outpoint("),
1120 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut::from_rust("),
1121 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network::from_bitcoin("),
1122 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("&local_"),
1123 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice::from_slice(&local_"),
1125 "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1127 // Newtypes that we just expose in their original form.
1128 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1129 if is_ref => Some(""),
1130 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1131 if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1132 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1133 "lightning::ln::PaymentHash" if is_ref => Some("&"),
1134 "lightning::ln::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1135 "lightning::ln::PaymentPreimage" if is_ref => Some("&"),
1136 "lightning::ln::PaymentPreimage" => Some("crate::c_types::ThirtyTwoBytes { data: "),
1137 "lightning::ln::PaymentSecret" => Some("crate::c_types::ThirtyTwoBytes { data: "),
1139 // Override the default since Records contain an fmt with a lifetime:
1140 "lightning::util::logger::Record" => Some("local_"),
1143 }.map(|s| s.to_owned())
1145 fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
1146 if self.is_primitive(full_path) {
1147 return Some("".to_owned());
1150 "Result" if !is_ref => Some(""),
1151 "Vec" if !is_ref => Some(".into()"),
1152 "Option" => Some(""),
1154 "[u8; 32]" if !is_ref => Some(" }"),
1155 "[u8; 32]" if is_ref => Some(""),
1156 "[u8; 20]" if !is_ref => Some(" }"),
1157 "[u8; 16]" if !is_ref => Some(" }"),
1158 "[u8; 10]" if !is_ref => Some(" }"),
1159 "[u8; 4]" if !is_ref => Some(" }"),
1160 "[u8; 3]" if is_ref => Some(""),
1162 "[u8]" if is_ref => Some(""),
1163 "[usize]" if is_ref => Some(""),
1165 "str" if is_ref => Some(".into()"),
1166 "alloc::string::String"|"String" if is_ref => Some(".as_str().into()"),
1167 "alloc::string::String"|"String" => Some(".into()"),
1169 "std::time::Duration"|"core::time::Duration" => Some(".as_secs()"),
1170 "std::time::SystemTime" => Some(".duration_since(::std::time::SystemTime::UNIX_EPOCH).expect(\"Times must be post-1970\").as_secs()"),
1171 "std::io::Error" if !is_ref => Some(")"),
1173 "bech32::u5" => Some(".into()"),
1175 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1177 "bitcoin::secp256k1::Signature" => Some(")"),
1178 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(")"),
1179 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1180 if !is_ref => Some(")"),
1181 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1182 if is_ref => Some(".as_ref()"),
1183 "bitcoin::secp256k1::Error"|"secp256k1::Error"
1184 if !is_ref => Some(")"),
1185 "bitcoin::blockdata::script::Script" if is_ref => Some("[..])"),
1186 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_bytes().into()"),
1187 "bitcoin::blockdata::transaction::Transaction" => Some(")"),
1188 "bitcoin::blockdata::transaction::OutPoint" => Some(")"),
1189 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(")"),
1190 "bitcoin::network::constants::Network" => Some(")"),
1191 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(""),
1192 "bitcoin::blockdata::block::Block" if is_ref => Some(")"),
1194 "bitcoin::hash_types::Txid" if !is_ref => Some(".into_inner() }"),
1196 // Newtypes that we just expose in their original form.
1197 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1198 if is_ref => Some(".as_inner()"),
1199 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1200 if !is_ref => Some(".into_inner() }"),
1201 "bitcoin::secp256k1::Message" if !is_ref => Some(".as_ref().clone() }"),
1202 "lightning::ln::PaymentHash" if is_ref => Some(".0"),
1203 "lightning::ln::PaymentHash" => Some(".0 }"),
1204 "lightning::ln::PaymentPreimage" if is_ref => Some(".0"),
1205 "lightning::ln::PaymentPreimage" => Some(".0 }"),
1206 "lightning::ln::PaymentSecret" => Some(".0 }"),
1208 // Override the default since Records contain an fmt with a lifetime:
1209 "lightning::util::logger::Record" => Some(".as_ptr()"),
1212 }.map(|s| s.to_owned())
1215 fn empty_val_check_suffix_from_path(&self, full_path: &str) -> Option<&str> {
1217 "lightning::ln::PaymentSecret" => Some(".data == [0; 32]"),
1218 "secp256k1::key::PublicKey"|"bitcoin::secp256k1::key::PublicKey" => Some(".is_null()"),
1219 "bitcoin::secp256k1::Signature" => Some(".is_null()"),
1224 // ****************************
1225 // *** Container Processing ***
1226 // ****************************
1228 /// Returns the module path in the generated mapping crate to the containers which we generate
1229 /// when writing to CrateTypes::template_file.
1230 pub fn generated_container_path() -> &'static str {
1231 "crate::c_types::derived"
1233 /// Returns the module path in the generated mapping crate to the container templates, which
1234 /// are then concretized and put in the generated container path/template_file.
1235 fn container_templ_path() -> &'static str {
1239 /// Returns true if the path containing the given args is a "transparent" container, ie an
1240 /// Option or a container which does not require a generated continer class.
1241 fn is_transparent_container<'i, I: Iterator<Item=&'i syn::Type>>(&self, full_path: &str, _is_ref: bool, mut args: I) -> bool {
1242 if full_path == "Option" {
1243 let inner = args.next().unwrap();
1244 assert!(args.next().is_none());
1246 syn::Type::Reference(_) => true,
1247 syn::Type::Path(p) => {
1248 if let Some(resolved) = self.maybe_resolve_path(&p.path, None) {
1249 if self.is_primitive(&resolved) { false } else { true }
1252 syn::Type::Tuple(_) => false,
1253 _ => unimplemented!(),
1257 /// Returns true if the path is a "transparent" container, ie an Option or a container which does
1258 /// not require a generated continer class.
1259 fn is_path_transparent_container(&self, full_path: &syn::Path, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
1260 let inner_iter = match &full_path.segments.last().unwrap().arguments {
1261 syn::PathArguments::None => return false,
1262 syn::PathArguments::AngleBracketed(args) => args.args.iter().map(|arg| {
1263 if let syn::GenericArgument::Type(ref ty) = arg {
1265 } else { unimplemented!() }
1267 syn::PathArguments::Parenthesized(_) => unimplemented!(),
1269 self.is_transparent_container(&self.resolve_path(full_path, generics), is_ref, inner_iter)
1271 /// Returns true if this is a known, supported, non-transparent container.
1272 fn is_known_container(&self, full_path: &str, is_ref: bool) -> bool {
1273 (full_path == "Result" && !is_ref) || (full_path == "Vec" && !is_ref) || full_path.ends_with("Tuple") || full_path == "Option"
1275 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)
1276 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1277 // expecting one element in the vec per generic type, each of which is inline-converted
1278 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1280 "Result" if !is_ref => {
1282 vec![(" { Ok(mut o) => crate::c_types::CResultTempl::ok(".to_string(), "o".to_string()),
1283 (").into(), Err(mut e) => crate::c_types::CResultTempl::err(".to_string(), "e".to_string())],
1284 ").into() }", ContainerPrefixLocation::PerConv))
1286 "Vec" if !is_ref => {
1287 Some(("Vec::new(); for mut item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1290 // We should only get here if the single contained has an inner
1291 assert!(self.c_type_has_inner(single_contained.unwrap()));
1292 Some(("Vec::new(); for mut item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "*item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1295 Some(("Vec::new(); for item in ", vec![(format!(".iter() {{ local_{}.push(", var_name), "*item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1298 let contained_struct = if let Some(syn::Type::Path(p)) = single_contained {
1299 Some(self.resolve_path(&p.path, generics))
1300 } else if let Some(syn::Type::Reference(r)) = single_contained {
1301 if let syn::Type::Path(p) = &*r.elem {
1302 Some(self.resolve_path(&p.path, generics))
1305 if let Some(inner_path) = contained_struct {
1306 if self.is_primitive(&inner_path) {
1307 return Some(("if ", vec![
1308 (format!(".is_none() {{ {}::COption_{}Z::None }} else {{ ", Self::generated_container_path(), inner_path),
1309 format!("{}::COption_{}Z::Some({}.unwrap())", Self::generated_container_path(), inner_path, var_access))
1310 ], " }", ContainerPrefixLocation::NoPrefix));
1311 } else if self.c_type_has_inner_from_path(&inner_path) {
1312 let is_inner_ref = if let Some(syn::Type::Reference(_)) = single_contained { true } else { false };
1314 return Some(("if ", vec![
1315 (".is_none() { std::ptr::null() } else { ".to_owned(),
1316 format!("({}{}.unwrap())", var_access, if is_inner_ref { "" } else { ".as_ref()" }))
1317 ], " }", ContainerPrefixLocation::OutsideConv));
1319 return Some(("if ", vec![
1320 (".is_none() { std::ptr::null_mut() } else { ".to_owned(), format!("({}.unwrap())", var_access))
1321 ], " }", ContainerPrefixLocation::OutsideConv));
1325 if let Some(t) = single_contained {
1326 let mut v = Vec::new();
1327 self.write_empty_rust_val(generics, &mut v, t);
1328 let s = String::from_utf8(v).unwrap();
1329 return Some(("if ", vec![
1330 (format!(".is_none() {{ {} }} else {{ ", s), format!("({}.unwrap())", var_access))
1331 ], " }", ContainerPrefixLocation::PerConv));
1332 } else { unreachable!(); }
1338 /// only_contained_has_inner implies that there is only one contained element in the container
1339 /// and it has an inner field (ie is an "opaque" type we've defined).
1340 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)
1341 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1342 // expecting one element in the vec per generic type, each of which is inline-converted
1343 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1345 "Result" if !is_ref => {
1347 vec![(".result_ok { true => Ok(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.result)) }})", var_access)),
1348 ("), false => Err(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.err)) }})", var_access))],
1349 ")}", ContainerPrefixLocation::PerConv))
1351 "Slice" if is_ref => {
1352 Some(("Vec::new(); for mut item in ", vec![(format!(".as_slice().iter() {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1355 Some(("Vec::new(); for mut item in ", vec![(format!(".into_rust().drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1358 if let Some(syn::Type::Path(p)) = single_contained {
1359 let inner_path = self.resolve_path(&p.path, generics);
1360 if self.is_primitive(&inner_path) {
1361 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::NoPrefix))
1362 } else if self.c_type_has_inner_from_path(&inner_path) {
1364 return Some(("if ", vec![(".inner.is_null() { None } else { Some((*".to_string(), format!("{}", var_access))], ").clone()) }", ContainerPrefixLocation::PerConv))
1366 return Some(("if ", vec![(".inner.is_null() { None } else { Some(".to_string(), format!("{}", var_access))], ") }", ContainerPrefixLocation::PerConv));
1371 if let Some(t) = single_contained {
1373 syn::Type::Reference(_)|syn::Type::Path(_)|syn::Type::Slice(_) => {
1374 let mut v = Vec::new();
1375 let ret_ref = self.write_empty_rust_val_check_suffix(generics, &mut v, t);
1376 let s = String::from_utf8(v).unwrap();
1378 EmptyValExpectedTy::ReferenceAsPointer =>
1379 return Some(("if ", vec![
1380 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ &mut *{} }}", var_access))
1381 ], ") }", ContainerPrefixLocation::NoPrefix)),
1382 EmptyValExpectedTy::OwnedPointer => {
1383 if let syn::Type::Slice(_) = t {
1386 return Some(("if ", vec![
1387 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ *Box::from_raw({}) }}", var_access))
1388 ], ") }", ContainerPrefixLocation::NoPrefix));
1390 EmptyValExpectedTy::NonPointer =>
1391 return Some(("if ", vec![
1392 (format!("{} {{ None }} else {{ Some(", s), format!("{}", var_access))
1393 ], ") }", ContainerPrefixLocation::PerConv)),
1396 syn::Type::Tuple(_) => {
1397 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::PerConv))
1399 _ => unimplemented!(),
1401 } else { unreachable!(); }
1407 // *************************************************
1408 // *** Type definition during main.rs processing ***
1409 // *************************************************
1411 pub fn get_declared_type(&'a self, ident: &syn::Ident) -> Option<&'a DeclType<'c>> {
1412 self.types.get_declared_type(ident)
1414 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1415 pub fn c_type_has_inner_from_path(&self, full_path: &str) -> bool {
1416 self.crate_types.opaques.get(full_path).is_some()
1418 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1419 pub fn c_type_has_inner(&self, ty: &syn::Type) -> bool {
1421 syn::Type::Path(p) => {
1422 let full_path = self.resolve_path(&p.path, None);
1423 self.c_type_has_inner_from_path(&full_path)
1425 syn::Type::Reference(r) => {
1426 self.c_type_has_inner(&*r.elem)
1432 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
1433 self.types.maybe_resolve_ident(id)
1436 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
1437 self.types.maybe_resolve_non_ignored_ident(id)
1440 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
1441 self.types.maybe_resolve_path(p_arg, generics)
1443 pub fn resolve_path(&self, p: &syn::Path, generics: Option<&GenericTypes>) -> String {
1444 self.maybe_resolve_path(p, generics).unwrap()
1447 // ***********************************
1448 // *** Original Rust Type Printing ***
1449 // ***********************************
1451 fn in_rust_prelude(resolved_path: &str) -> bool {
1452 match resolved_path {
1460 fn write_rust_path<W: std::io::Write>(&self, w: &mut W, generics_resolver: Option<&GenericTypes>, path: &syn::Path) {
1461 if let Some(resolved) = self.maybe_resolve_path(&path, generics_resolver) {
1462 if self.is_primitive(&resolved) {
1463 write!(w, "{}", path.get_ident().unwrap()).unwrap();
1465 // TODO: We should have a generic "is from a dependency" check here instead of
1466 // checking for "bitcoin" explicitly.
1467 if resolved.starts_with("bitcoin::") || Self::in_rust_prelude(&resolved) {
1468 write!(w, "{}", resolved).unwrap();
1469 // If we're printing a generic argument, it needs to reference the crate, otherwise
1470 // the original crate:
1471 } else if self.maybe_resolve_path(&path, None).as_ref() == Some(&resolved) {
1472 write!(w, "{}", resolved).unwrap();
1474 write!(w, "crate::{}", resolved).unwrap();
1477 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().last().unwrap().arguments {
1478 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1481 if path.leading_colon.is_some() {
1482 write!(w, "::").unwrap();
1484 for (idx, seg) in path.segments.iter().enumerate() {
1485 if idx != 0 { write!(w, "::").unwrap(); }
1486 write!(w, "{}", seg.ident).unwrap();
1487 if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
1488 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1493 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>) {
1494 let mut had_params = false;
1495 for (idx, arg) in generics.enumerate() {
1496 if idx != 0 { write!(w, ", ").unwrap(); } else { write!(w, "<").unwrap(); }
1499 syn::GenericParam::Lifetime(lt) => write!(w, "'{}", lt.lifetime.ident).unwrap(),
1500 syn::GenericParam::Type(t) => {
1501 write!(w, "{}", t.ident).unwrap();
1502 if t.colon_token.is_some() { write!(w, ":").unwrap(); }
1503 for (idx, bound) in t.bounds.iter().enumerate() {
1504 if idx != 0 { write!(w, " + ").unwrap(); }
1506 syn::TypeParamBound::Trait(tb) => {
1507 if tb.paren_token.is_some() || tb.lifetimes.is_some() { unimplemented!(); }
1508 self.write_rust_path(w, generics_resolver, &tb.path);
1510 _ => unimplemented!(),
1513 if t.eq_token.is_some() || t.default.is_some() { unimplemented!(); }
1515 _ => unimplemented!(),
1518 if had_params { write!(w, ">").unwrap(); }
1521 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>) {
1522 write!(w, "<").unwrap();
1523 for (idx, arg) in generics.enumerate() {
1524 if idx != 0 { write!(w, ", ").unwrap(); }
1526 syn::GenericArgument::Type(t) => self.write_rust_type(w, generics_resolver, t),
1527 _ => unimplemented!(),
1530 write!(w, ">").unwrap();
1532 pub fn write_rust_type<W: std::io::Write>(&self, w: &mut W, generics: Option<&GenericTypes>, t: &syn::Type) {
1534 syn::Type::Path(p) => {
1535 if p.qself.is_some() {
1538 self.write_rust_path(w, generics, &p.path);
1540 syn::Type::Reference(r) => {
1541 write!(w, "&").unwrap();
1542 if let Some(lft) = &r.lifetime {
1543 write!(w, "'{} ", lft.ident).unwrap();
1545 if r.mutability.is_some() {
1546 write!(w, "mut ").unwrap();
1548 self.write_rust_type(w, generics, &*r.elem);
1550 syn::Type::Array(a) => {
1551 write!(w, "[").unwrap();
1552 self.write_rust_type(w, generics, &a.elem);
1553 if let syn::Expr::Lit(l) = &a.len {
1554 if let syn::Lit::Int(i) = &l.lit {
1555 write!(w, "; {}]", i).unwrap();
1556 } else { unimplemented!(); }
1557 } else { unimplemented!(); }
1559 syn::Type::Slice(s) => {
1560 write!(w, "[").unwrap();
1561 self.write_rust_type(w, generics, &s.elem);
1562 write!(w, "]").unwrap();
1564 syn::Type::Tuple(s) => {
1565 write!(w, "(").unwrap();
1566 for (idx, t) in s.elems.iter().enumerate() {
1567 if idx != 0 { write!(w, ", ").unwrap(); }
1568 self.write_rust_type(w, generics, &t);
1570 write!(w, ")").unwrap();
1572 _ => unimplemented!(),
1576 /// Prints a constructor for something which is "uninitialized" (but obviously not actually
1577 /// unint'd memory).
1578 pub fn write_empty_rust_val<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) {
1580 syn::Type::Reference(r) => {
1581 self.write_empty_rust_val(generics, w, &*r.elem)
1583 syn::Type::Path(p) => {
1584 let resolved = self.resolve_path(&p.path, generics);
1585 if self.crate_types.opaques.get(&resolved).is_some() {
1586 write!(w, "crate::{} {{ inner: std::ptr::null_mut(), is_owned: true }}", resolved).unwrap();
1588 // Assume its a manually-mapped C type, where we can just define an null() fn
1589 write!(w, "{}::null()", self.c_type_from_path(&resolved, false, false).unwrap()).unwrap();
1592 syn::Type::Array(a) => {
1593 if let syn::Expr::Lit(l) = &a.len {
1594 if let syn::Lit::Int(i) = &l.lit {
1595 if i.base10_digits().parse::<usize>().unwrap() < 32 {
1596 // Blindly assume that if we're trying to create an empty value for an
1597 // array < 32 entries that all-0s may be a valid state.
1600 let arrty = format!("[u8; {}]", i.base10_digits());
1601 write!(w, "{}", self.to_c_conversion_inline_prefix_from_path(&arrty, false, false).unwrap()).unwrap();
1602 write!(w, "[0; {}]", i.base10_digits()).unwrap();
1603 write!(w, "{}", self.to_c_conversion_inline_suffix_from_path(&arrty, false, false).unwrap()).unwrap();
1604 } else { unimplemented!(); }
1605 } else { unimplemented!(); }
1607 _ => unimplemented!(),
1611 fn is_real_type_array(&self, resolved_type: &str) -> Option<syn::Type> {
1612 if let Some(real_ty) = self.c_type_from_path(&resolved_type, true, false) {
1613 if real_ty.ends_with("]") && real_ty.starts_with("*const [u8; ") {
1614 let mut split = real_ty.split("; ");
1615 split.next().unwrap();
1616 let tail_str = split.next().unwrap();
1617 assert!(split.next().is_none());
1618 let len = usize::from_str_radix(&tail_str[..tail_str.len() - 1], 10).unwrap();
1619 Some(parse_quote!([u8; #len]))
1624 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1625 /// See EmptyValExpectedTy for information on return types.
1626 fn write_empty_rust_val_check_suffix<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) -> EmptyValExpectedTy {
1628 syn::Type::Reference(r) => {
1629 return self.write_empty_rust_val_check_suffix(generics, w, &*r.elem);
1631 syn::Type::Path(p) => {
1632 let resolved = self.resolve_path(&p.path, generics);
1633 if let Some(arr_ty) = self.is_real_type_array(&resolved) {
1634 write!(w, ".data").unwrap();
1635 return self.write_empty_rust_val_check_suffix(generics, w, &arr_ty);
1637 if self.crate_types.opaques.get(&resolved).is_some() {
1638 write!(w, ".inner.is_null()").unwrap();
1639 EmptyValExpectedTy::NonPointer
1641 if let Some(suffix) = self.empty_val_check_suffix_from_path(&resolved) {
1642 write!(w, "{}", suffix).unwrap();
1643 // We may eventually need to allow empty_val_check_suffix_from_path to specify if we need a deref or not
1644 EmptyValExpectedTy::NonPointer
1646 write!(w, " == std::ptr::null_mut()").unwrap();
1647 EmptyValExpectedTy::OwnedPointer
1651 syn::Type::Array(a) => {
1652 if let syn::Expr::Lit(l) = &a.len {
1653 if let syn::Lit::Int(i) = &l.lit {
1654 write!(w, " == [0; {}]", i.base10_digits()).unwrap();
1655 EmptyValExpectedTy::NonPointer
1656 } else { unimplemented!(); }
1657 } else { unimplemented!(); }
1659 syn::Type::Slice(_) => {
1660 // Option<[]> always implies that we want to treat len() == 0 differently from
1661 // None, so we always map an Option<[]> into a pointer.
1662 write!(w, " == std::ptr::null_mut()").unwrap();
1663 EmptyValExpectedTy::ReferenceAsPointer
1665 _ => unimplemented!(),
1669 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1670 pub fn write_empty_rust_val_check<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type, var_access: &str) {
1672 syn::Type::Reference(r) => {
1673 self.write_empty_rust_val_check(generics, w, &*r.elem, var_access);
1675 syn::Type::Path(_) => {
1676 write!(w, "{}", var_access).unwrap();
1677 self.write_empty_rust_val_check_suffix(generics, w, t);
1679 syn::Type::Array(a) => {
1680 if let syn::Expr::Lit(l) = &a.len {
1681 if let syn::Lit::Int(i) = &l.lit {
1682 let arrty = format!("[u8; {}]", i.base10_digits());
1683 // We don't (yet) support a new-var conversion here.
1684 assert!(self.from_c_conversion_new_var_from_path(&arrty, false).is_none());
1686 self.from_c_conversion_prefix_from_path(&arrty, false).unwrap(),
1688 self.from_c_conversion_suffix_from_path(&arrty, false).unwrap()).unwrap();
1689 self.write_empty_rust_val_check_suffix(generics, w, t);
1690 } else { unimplemented!(); }
1691 } else { unimplemented!(); }
1693 _ => unimplemented!(),
1697 // ********************************
1698 // *** Type conversion printing ***
1699 // ********************************
1701 /// Returns true we if can just skip passing this to C entirely
1702 pub fn skip_arg(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
1704 syn::Type::Path(p) => {
1705 if p.qself.is_some() { unimplemented!(); }
1706 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1707 self.skip_path(&full_path)
1710 syn::Type::Reference(r) => {
1711 self.skip_arg(&*r.elem, generics)
1716 pub fn no_arg_to_rust<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1718 syn::Type::Path(p) => {
1719 if p.qself.is_some() { unimplemented!(); }
1720 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1721 write!(w, "{}", self.no_arg_path_to_rust(&full_path)).unwrap();
1724 syn::Type::Reference(r) => {
1725 self.no_arg_to_rust(w, &*r.elem, generics);
1731 fn write_conversion_inline_intern<W: std::io::Write,
1732 LP: Fn(&str, bool, bool) -> Option<String>, DL: Fn(&mut W, &DeclType, &str, bool, bool), SC: Fn(bool, Option<&str>) -> String>
1733 (&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool,
1734 tupleconv: &str, prefix: bool, sliceconv: SC, path_lookup: LP, decl_lookup: DL) {
1735 match generics.resolve_type(t) {
1736 syn::Type::Reference(r) => {
1737 self.write_conversion_inline_intern(w, &*r.elem, generics, true, r.mutability.is_some(),
1738 ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1740 syn::Type::Path(p) => {
1741 if p.qself.is_some() {
1745 let resolved_path = self.resolve_path(&p.path, generics);
1746 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1747 return self.write_conversion_inline_intern(w, aliased_type, None, is_ref, is_mut, ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1748 } else if self.is_primitive(&resolved_path) {
1749 if is_ref && prefix {
1750 write!(w, "*").unwrap();
1752 } else if let Some(c_type) = path_lookup(&resolved_path, is_ref, ptr_for_ref) {
1753 write!(w, "{}", c_type).unwrap();
1754 } else if self.crate_types.opaques.get(&resolved_path).is_some() {
1755 decl_lookup(w, &DeclType::StructImported, &resolved_path, is_ref, is_mut);
1756 } else if self.crate_types.mirrored_enums.get(&resolved_path).is_some() {
1757 decl_lookup(w, &DeclType::MirroredEnum, &resolved_path, is_ref, is_mut);
1758 } else if let Some(t) = self.crate_types.traits.get(&resolved_path) {
1759 decl_lookup(w, &DeclType::Trait(t), &resolved_path, is_ref, is_mut);
1760 } else if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
1761 if let Some(decl_type) = self.types.maybe_resolve_declared(ident) {
1762 decl_lookup(w, decl_type, &self.maybe_resolve_ident(ident).unwrap(), is_ref, is_mut);
1763 } else { unimplemented!(); }
1764 } else { unimplemented!(); }
1766 syn::Type::Array(a) => {
1767 // We assume all arrays contain only [int_literal; X]s.
1768 // This may result in some outputs not compiling.
1769 if let syn::Expr::Lit(l) = &a.len {
1770 if let syn::Lit::Int(i) = &l.lit {
1771 write!(w, "{}", path_lookup(&format!("[u8; {}]", i.base10_digits()), is_ref, ptr_for_ref).unwrap()).unwrap();
1772 } else { unimplemented!(); }
1773 } else { unimplemented!(); }
1775 syn::Type::Slice(s) => {
1776 // We assume all slices contain only literals or references.
1777 // This may result in some outputs not compiling.
1778 if let syn::Type::Path(p) = &*s.elem {
1779 let resolved = self.resolve_path(&p.path, generics);
1780 assert!(self.is_primitive(&resolved));
1781 write!(w, "{}", path_lookup("[u8]", is_ref, ptr_for_ref).unwrap()).unwrap();
1782 } else if let syn::Type::Reference(r) = &*s.elem {
1783 if let syn::Type::Path(p) = &*r.elem {
1784 write!(w, "{}", sliceconv(self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)), None)).unwrap();
1785 } else { unimplemented!(); }
1786 } else if let syn::Type::Tuple(t) = &*s.elem {
1787 assert!(!t.elems.is_empty());
1789 write!(w, "{}", sliceconv(false, None)).unwrap();
1791 let mut needs_map = false;
1792 for e in t.elems.iter() {
1793 if let syn::Type::Reference(_) = e {
1798 let mut map_str = Vec::new();
1799 write!(&mut map_str, ".map(|(").unwrap();
1800 for i in 0..t.elems.len() {
1801 write!(&mut map_str, "{}{}", if i != 0 { ", " } else { "" }, ('a' as u8 + i as u8) as char).unwrap();
1803 write!(&mut map_str, ")| (").unwrap();
1804 for (idx, e) in t.elems.iter().enumerate() {
1805 if let syn::Type::Reference(_) = e {
1806 write!(&mut map_str, "{}{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1807 } else if let syn::Type::Path(_) = e {
1808 write!(&mut map_str, "{}*{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1809 } else { unimplemented!(); }
1811 write!(&mut map_str, "))").unwrap();
1812 write!(w, "{}", sliceconv(false, Some(&String::from_utf8(map_str).unwrap()))).unwrap();
1814 write!(w, "{}", sliceconv(false, None)).unwrap();
1817 } else { unimplemented!(); }
1819 syn::Type::Tuple(t) => {
1820 if t.elems.is_empty() {
1821 // cbindgen has poor support for (), see, eg https://github.com/eqrion/cbindgen/issues/527
1822 // so work around it by just pretending its a 0u8
1823 write!(w, "{}", tupleconv).unwrap();
1825 if prefix { write!(w, "local_").unwrap(); }
1828 _ => unimplemented!(),
1832 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) {
1833 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "() /*", true, |_, _| "local_".to_owned(),
1834 |a, b, c| self.to_c_conversion_inline_prefix_from_path(a, b, c),
1835 |w, decl_type, decl_path, is_ref, _is_mut| {
1837 DeclType::MirroredEnum if is_ref && ptr_for_ref => write!(w, "crate::{}::from_native(", decl_path).unwrap(),
1838 DeclType::MirroredEnum if is_ref => write!(w, "&crate::{}::from_native(", decl_path).unwrap(),
1839 DeclType::MirroredEnum => write!(w, "crate::{}::native_into(", decl_path).unwrap(),
1840 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1841 write!(w, "crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1842 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1843 write!(w, "crate::{} {{ inner: unsafe {{ ( (&(*", decl_path).unwrap(),
1844 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1845 write!(w, "&crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1846 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1847 write!(w, "crate::{} {{ inner: ", decl_path).unwrap(),
1848 DeclType::EnumIgnored|DeclType::StructImported if !is_ref =>
1849 write!(w, "crate::{} {{ inner: Box::into_raw(Box::new(", decl_path).unwrap(),
1850 DeclType::Trait(_) if is_ref => write!(w, "").unwrap(),
1851 DeclType::Trait(_) if !is_ref => {},
1852 _ => panic!("{:?}", decl_path),
1856 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) {
1857 self.write_to_c_conversion_inline_prefix_inner(w, t, generics, false, ptr_for_ref, false);
1859 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) {
1860 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "*/", false, |_, _| ".into()".to_owned(),
1861 |a, b, c| self.to_c_conversion_inline_suffix_from_path(a, b, c),
1862 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1863 DeclType::MirroredEnum => write!(w, ")").unwrap(),
1864 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1865 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1866 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1867 write!(w, ") as *const _) as *mut _) }}, is_owned: false }}").unwrap(),
1868 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1869 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1870 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1871 write!(w, ", is_owned: true }}").unwrap(),
1872 DeclType::EnumIgnored|DeclType::StructImported if !is_ref => write!(w, ")), is_owned: true }}").unwrap(),
1873 DeclType::Trait(_) if is_ref => {},
1874 DeclType::Trait(_) => {
1875 // This is used when we're converting a concrete Rust type into a C trait
1876 // for use when a Rust trait method returns an associated type.
1877 // Because all of our C traits implement From<RustTypesImplementingTraits>
1878 // we can just call .into() here and be done.
1879 write!(w, ".into()").unwrap()
1881 _ => unimplemented!(),
1884 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) {
1885 self.write_to_c_conversion_inline_suffix_inner(w, t, generics, false, ptr_for_ref, false);
1888 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) {
1889 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "() /*", true, |_, _| "&local_".to_owned(),
1890 |a, b, _c| self.from_c_conversion_prefix_from_path(a, b),
1891 |w, decl_type, _full_path, is_ref, is_mut| match decl_type {
1892 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, "unsafe {{ &*(*").unwrap(),
1893 DeclType::StructImported if is_mut && is_ref => write!(w, "unsafe {{ &mut *").unwrap(),
1894 DeclType::StructImported if is_ref => write!(w, "unsafe {{ &*").unwrap(),
1895 DeclType::StructImported if !is_ref => write!(w, "*unsafe {{ Box::from_raw(").unwrap(),
1896 DeclType::MirroredEnum if is_ref => write!(w, "&").unwrap(),
1897 DeclType::MirroredEnum => {},
1898 DeclType::Trait(_) => {},
1899 _ => unimplemented!(),
1902 pub fn write_from_c_conversion_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1903 self.write_from_c_conversion_prefix_inner(w, t, generics, false, false);
1905 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) {
1906 self.write_conversion_inline_intern(w, t, generics, is_ref, 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 && ptr_for_ref => write!(w, ").inner }}").unwrap(),
1916 DeclType::StructImported if is_ref => write!(w, ".inner }}").unwrap(),
1917 DeclType::StructImported if !is_ref => write!(w, ".take_inner()) }}").unwrap(),
1918 DeclType::MirroredEnum if is_ref => write!(w, ".to_native()").unwrap(),
1919 DeclType::MirroredEnum => write!(w, ".into_native()").unwrap(),
1920 DeclType::Trait(_) => {},
1921 _ => unimplemented!(),
1924 pub fn write_from_c_conversion_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1925 self.write_from_c_conversion_suffix_inner(w, t, generics, false, false);
1927 // Note that compared to the above conversion functions, the following two are generally
1928 // significantly undertested:
1929 pub fn write_from_c_conversion_to_ref_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1930 self.write_conversion_inline_intern(w, t, generics, false, false, false, "() /*", true, |_, _| "&local_".to_owned(),
1932 if let Some(conv) = self.from_c_conversion_prefix_from_path(a, b) {
1933 Some(format!("&{}", conv))
1936 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1937 DeclType::StructImported if !is_ref => write!(w, "unsafe {{ &*").unwrap(),
1938 _ => unimplemented!(),
1941 pub fn write_from_c_conversion_to_ref_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1942 self.write_conversion_inline_intern(w, t, generics, false, false, false, "*/", false,
1943 |has_inner, map_str_opt| match (has_inner, map_str_opt) {
1944 (false, Some(map_str)) => format!(".iter(){}.collect::<Vec<_>>()[..]", map_str),
1945 (false, None) => ".iter().collect::<Vec<_>>()[..]".to_owned(),
1946 (true, None) => "[..]".to_owned(),
1947 (true, Some(_)) => unreachable!(),
1949 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1950 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1951 DeclType::StructImported if !is_ref => write!(w, ".inner }}").unwrap(),
1952 _ => unimplemented!(),
1956 fn write_conversion_new_var_intern<'b, W: std::io::Write,
1957 LP: Fn(&str, bool) -> Option<(&str, &str)>,
1958 LC: Fn(&str, bool, Option<&syn::Type>, &syn::Ident, &str) -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)>,
1959 VP: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool),
1960 VS: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool)>
1961 (&self, w: &mut W, ident: &syn::Ident, var: &str, t: &syn::Type, generics: Option<&GenericTypes>,
1962 mut is_ref: bool, mut ptr_for_ref: bool, to_c: bool,
1963 path_lookup: &LP, container_lookup: &LC, var_prefix: &VP, var_suffix: &VS) -> bool {
1965 macro_rules! convert_container {
1966 ($container_type: expr, $args_len: expr, $args_iter: expr) => { {
1967 // For slices (and Options), we refuse to directly map them as is_ref when they
1968 // aren't opaque types containing an inner pointer. This is due to the fact that,
1969 // in both cases, the actual higher-level type is non-is_ref.
1970 let ty_has_inner = if $args_len == 1 {
1971 let ty = $args_iter().next().unwrap();
1972 if $container_type == "Slice" && to_c {
1973 // "To C ptr_for_ref" means "return the regular object with is_owned
1974 // set to false", which is totally what we want in a slice if we're about to
1975 // set ty_has_inner.
1978 if let syn::Type::Reference(t) = ty {
1979 if let syn::Type::Path(p) = &*t.elem {
1980 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1982 } else if let syn::Type::Path(p) = ty {
1983 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1987 // Options get a bunch of special handling, since in general we map Option<>al
1988 // types into the same C type as non-Option-wrapped types. This ends up being
1989 // pretty manual here and most of the below special-cases are for Options.
1990 let mut needs_ref_map = false;
1991 let mut only_contained_type = None;
1992 let mut only_contained_type_nonref = None;
1993 let mut only_contained_has_inner = false;
1994 let mut contains_slice = false;
1996 only_contained_has_inner = ty_has_inner;
1997 let arg = $args_iter().next().unwrap();
1998 if let syn::Type::Reference(t) = arg {
1999 only_contained_type = Some(arg);
2000 only_contained_type_nonref = Some(&*t.elem);
2001 if let syn::Type::Path(_) = &*t.elem {
2003 } else if let syn::Type::Slice(_) = &*t.elem {
2004 contains_slice = true;
2005 } else { return false; }
2006 // If the inner element contains an inner pointer, we will just use that,
2007 // avoiding the need to map elements to references. Otherwise we'll need to
2008 // do an extra mapping step.
2009 needs_ref_map = !only_contained_has_inner;
2011 only_contained_type = Some(arg);
2012 only_contained_type_nonref = Some(arg);
2016 if let Some((prefix, conversions, suffix, prefix_location)) = container_lookup(&$container_type, is_ref && ty_has_inner, only_contained_type, ident, var) {
2017 assert_eq!(conversions.len(), $args_len);
2018 write!(w, "let mut local_{}{} = ", ident, if !to_c && needs_ref_map {"_base"} else { "" }).unwrap();
2019 if prefix_location == ContainerPrefixLocation::OutsideConv {
2020 var_prefix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
2022 write!(w, "{}{}", prefix, var).unwrap();
2024 for ((pfx, var_name), (idx, ty)) in conversions.iter().zip($args_iter().enumerate()) {
2025 let mut var = std::io::Cursor::new(Vec::new());
2026 write!(&mut var, "{}", var_name).unwrap();
2027 let var_access = String::from_utf8(var.into_inner()).unwrap();
2029 let conv_ty = if needs_ref_map { only_contained_type_nonref.as_ref().unwrap() } else { ty };
2031 write!(w, "{} {{ ", pfx).unwrap();
2032 let new_var_name = format!("{}_{}", ident, idx);
2033 let new_var = self.write_conversion_new_var_intern(w, &format_ident!("{}", new_var_name),
2034 &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);
2035 if new_var { write!(w, " ").unwrap(); }
2037 if prefix_location == ContainerPrefixLocation::PerConv {
2038 var_prefix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2039 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
2040 write!(w, "Box::into_raw(Box::new(").unwrap();
2043 write!(w, "{}{}", if contains_slice { "local_" } else { "" }, if new_var { new_var_name } else { var_access }).unwrap();
2044 if prefix_location == ContainerPrefixLocation::PerConv {
2045 var_suffix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2046 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
2047 write!(w, "))").unwrap();
2049 write!(w, " }}").unwrap();
2051 write!(w, "{}", suffix).unwrap();
2052 if prefix_location == ContainerPrefixLocation::OutsideConv {
2053 var_suffix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
2055 write!(w, ";").unwrap();
2056 if !to_c && needs_ref_map {
2057 write!(w, " let mut local_{} = local_{}_base.as_ref()", ident, ident).unwrap();
2059 write!(w, ".map(|a| &a[..])").unwrap();
2061 write!(w, ";").unwrap();
2068 match generics.resolve_type(t) {
2069 syn::Type::Reference(r) => {
2070 if let syn::Type::Slice(_) = &*r.elem {
2071 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)
2073 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)
2076 syn::Type::Path(p) => {
2077 if p.qself.is_some() {
2080 let resolved_path = self.resolve_path(&p.path, generics);
2081 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
2082 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);
2084 if self.is_known_container(&resolved_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
2085 if let syn::PathArguments::AngleBracketed(args) = &p.path.segments.iter().next().unwrap().arguments {
2086 convert_container!(resolved_path, args.args.len(), || args.args.iter().map(|arg| {
2087 if let syn::GenericArgument::Type(ty) = arg {
2089 } else { unimplemented!(); }
2091 } else { unimplemented!(); }
2093 if self.is_primitive(&resolved_path) {
2095 } else if let Some(ty_ident) = single_ident_generic_path_to_ident(&p.path) {
2096 if let Some((prefix, suffix)) = path_lookup(&resolved_path, is_ref) {
2097 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
2099 } else if self.types.maybe_resolve_declared(ty_ident).is_some() {
2104 syn::Type::Array(_) => {
2105 // We assume all arrays contain only primitive types.
2106 // This may result in some outputs not compiling.
2109 syn::Type::Slice(s) => {
2110 if let syn::Type::Path(p) = &*s.elem {
2111 let resolved = self.resolve_path(&p.path, generics);
2112 assert!(self.is_primitive(&resolved));
2113 let slice_path = format!("[{}]", resolved);
2114 if let Some((prefix, suffix)) = path_lookup(&slice_path, true) {
2115 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
2118 } else if let syn::Type::Reference(ty) = &*s.elem {
2119 let tyref = [&*ty.elem];
2121 convert_container!("Slice", 1, || tyref.iter().map(|t| *t));
2122 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
2123 } else if let syn::Type::Tuple(t) = &*s.elem {
2124 // When mapping into a temporary new var, we need to own all the underlying objects.
2125 // Thus, we drop any references inside the tuple and convert with non-reference types.
2126 let mut elems = syn::punctuated::Punctuated::new();
2127 for elem in t.elems.iter() {
2128 if let syn::Type::Reference(r) = elem {
2129 elems.push((*r.elem).clone());
2131 elems.push(elem.clone());
2134 let ty = [syn::Type::Tuple(syn::TypeTuple {
2135 paren_token: t.paren_token, elems
2139 convert_container!("Slice", 1, || ty.iter());
2140 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
2141 } else { unimplemented!() }
2143 syn::Type::Tuple(t) => {
2144 if !t.elems.is_empty() {
2145 // We don't (yet) support tuple elements which cannot be converted inline
2146 write!(w, "let (").unwrap();
2147 for idx in 0..t.elems.len() {
2148 if idx != 0 { write!(w, ", ").unwrap(); }
2149 write!(w, "{} orig_{}_{}", if is_ref { "ref" } else { "mut" }, ident, idx).unwrap();
2151 write!(w, ") = {}{}; ", var, if !to_c { ".to_rust()" } else { "" }).unwrap();
2152 // Like other template types, tuples are always mapped as their non-ref
2153 // versions for types which have different ref mappings. Thus, we convert to
2154 // non-ref versions and handle opaque types with inner pointers manually.
2155 for (idx, elem) in t.elems.iter().enumerate() {
2156 if let syn::Type::Path(p) = elem {
2157 let v_name = format!("orig_{}_{}", ident, idx);
2158 let tuple_elem_ident = format_ident!("{}", &v_name);
2159 if self.write_conversion_new_var_intern(w, &tuple_elem_ident, &v_name, elem, generics,
2160 false, ptr_for_ref, to_c,
2161 path_lookup, container_lookup, var_prefix, var_suffix) {
2162 write!(w, " ").unwrap();
2163 // Opaque types with inner pointers shouldn't ever create new stack
2164 // variables, so we don't handle it and just assert that it doesn't
2166 assert!(!self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)));
2170 write!(w, "let mut local_{} = (", ident).unwrap();
2171 for (idx, elem) in t.elems.iter().enumerate() {
2172 let ty_has_inner = {
2174 // "To C ptr_for_ref" means "return the regular object with
2175 // is_owned set to false", which is totally what we want
2176 // if we're about to set ty_has_inner.
2179 if let syn::Type::Reference(t) = elem {
2180 if let syn::Type::Path(p) = &*t.elem {
2181 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2183 } else if let syn::Type::Path(p) = elem {
2184 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2187 if idx != 0 { write!(w, ", ").unwrap(); }
2188 var_prefix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2189 if is_ref && ty_has_inner {
2190 // For ty_has_inner, the regular var_prefix mapping will take a
2191 // reference, so deref once here to make sure we keep the original ref.
2192 write!(w, "*").unwrap();
2194 write!(w, "orig_{}_{}", ident, idx).unwrap();
2195 if is_ref && !ty_has_inner {
2196 // If we don't have an inner variable's reference to maintain, just
2197 // hope the type is Clonable and use that.
2198 write!(w, ".clone()").unwrap();
2200 var_suffix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2202 write!(w, "){};", if to_c { ".into()" } else { "" }).unwrap();
2206 _ => unimplemented!(),
2210 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 {
2211 self.write_conversion_new_var_intern(w, ident, var_access, t, generics, false, ptr_for_ref, true,
2212 &|a, b| self.to_c_conversion_new_var_from_path(a, b),
2213 &|a, b, c, d, e| self.to_c_conversion_container_new_var(generics, a, b, c, d, e),
2214 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
2215 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_prefix_inner(a, b, c, d, e, f),
2216 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_suffix_inner(a, b, c, d, e, f))
2218 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 {
2219 self.write_to_c_conversion_new_var_inner(w, ident, &format!("{}", ident), t, generics, ptr_for_ref)
2221 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 {
2222 self.write_conversion_new_var_intern(w, ident, &format!("{}", ident), t, generics, false, false, false,
2223 &|a, b| self.from_c_conversion_new_var_from_path(a, b),
2224 &|a, b, c, d, e| self.from_c_conversion_container_new_var(generics, a, b, c, d, e),
2225 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
2226 &|a, b, c, d, e, _f| self.write_from_c_conversion_prefix_inner(a, b, c, d, e),
2227 &|a, b, c, d, e, _f| self.write_from_c_conversion_suffix_inner(a, b, c, d, e))
2230 // ******************************************************
2231 // *** C Container Type Equivalent and alias Printing ***
2232 // ******************************************************
2234 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 {
2235 for (idx, t) in args.enumerate() {
2237 write!(w, ", ").unwrap();
2239 if let syn::Type::Reference(r_arg) = t {
2240 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2242 if !self.write_c_type_intern(w, &*r_arg.elem, generics, false, false, false) { return false; }
2244 // While write_c_type_intern, above is correct, we don't want to blindly convert a
2245 // reference to something stupid, so check that the container is either opaque or a
2246 // predefined type (currently only Transaction).
2247 if let syn::Type::Path(p_arg) = &*r_arg.elem {
2248 let resolved = self.resolve_path(&p_arg.path, generics);
2249 assert!(self.crate_types.opaques.get(&resolved).is_some() ||
2250 self.c_type_from_path(&resolved, true, true).is_some(), "Template generics should be opaque or have a predefined mapping");
2251 } else { unimplemented!(); }
2252 } else if let syn::Type::Path(p_arg) = t {
2253 if let Some(resolved) = self.maybe_resolve_path(&p_arg.path, generics) {
2254 if !self.is_primitive(&resolved) {
2255 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2258 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2260 if !self.write_c_type_intern(w, t, generics, false, false, false) { return false; }
2262 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2263 if !self.write_c_type_intern(w, t, generics, false, false, false) { return false; }
2268 fn check_create_container(&self, mangled_container: String, container_type: &str, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
2269 if !self.crate_types.templates_defined.borrow().get(&mangled_container).is_some() {
2270 let mut created_container: Vec<u8> = Vec::new();
2272 if container_type == "Result" {
2273 let mut a_ty: Vec<u8> = Vec::new();
2274 if let syn::Type::Tuple(tup) = args.iter().next().unwrap() {
2275 if tup.elems.is_empty() {
2276 write!(&mut a_ty, "()").unwrap();
2278 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
2281 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
2284 let mut b_ty: Vec<u8> = Vec::new();
2285 if let syn::Type::Tuple(tup) = args.iter().skip(1).next().unwrap() {
2286 if tup.elems.is_empty() {
2287 write!(&mut b_ty, "()").unwrap();
2289 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
2292 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
2295 let ok_str = String::from_utf8(a_ty).unwrap();
2296 let err_str = String::from_utf8(b_ty).unwrap();
2297 let is_clonable = self.is_clonable(&ok_str) && self.is_clonable(&err_str);
2298 write_result_block(&mut created_container, &mangled_container, &ok_str, &err_str, is_clonable);
2300 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2302 } else if container_type == "Vec" {
2303 let mut a_ty: Vec<u8> = Vec::new();
2304 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2305 let ty = String::from_utf8(a_ty).unwrap();
2306 let is_clonable = self.is_clonable(&ty);
2307 write_vec_block(&mut created_container, &mangled_container, &ty, is_clonable);
2309 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2311 } else if container_type.ends_with("Tuple") {
2312 let mut tuple_args = Vec::new();
2313 let mut is_clonable = true;
2314 for arg in args.iter() {
2315 let mut ty: Vec<u8> = Vec::new();
2316 if !self.write_template_generics(&mut ty, &mut [arg].iter().map(|t| **t), generics, is_ref) { return false; }
2317 let ty_str = String::from_utf8(ty).unwrap();
2318 if !self.is_clonable(&ty_str) {
2319 is_clonable = false;
2321 tuple_args.push(ty_str);
2323 write_tuple_block(&mut created_container, &mangled_container, &tuple_args, is_clonable);
2325 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2327 } else if container_type == "Option" {
2328 let mut a_ty: Vec<u8> = Vec::new();
2329 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2330 let ty = String::from_utf8(a_ty).unwrap();
2331 let is_clonable = self.is_clonable(&ty);
2332 write_option_block(&mut created_container, &mangled_container, &ty, is_clonable);
2334 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2339 self.crate_types.write_new_template(mangled_container.clone(), true, &created_container);
2343 fn path_to_generic_args(path: &syn::Path) -> Vec<&syn::Type> {
2344 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().next().unwrap().arguments {
2345 args.args.iter().map(|gen| if let syn::GenericArgument::Type(t) = gen { t } else { unimplemented!() }).collect()
2346 } else { unimplemented!(); }
2348 fn write_c_mangled_container_path_intern<W: std::io::Write>
2349 (&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 {
2350 let mut mangled_type: Vec<u8> = Vec::new();
2351 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2352 write!(w, "C{}_", ident).unwrap();
2353 write!(mangled_type, "C{}_", ident).unwrap();
2354 } else { assert_eq!(args.len(), 1); }
2355 for arg in args.iter() {
2356 macro_rules! write_path {
2357 ($p_arg: expr, $extra_write: expr) => {
2358 if let Some(subtype) = self.maybe_resolve_path(&$p_arg.path, generics) {
2359 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2361 if self.c_type_has_inner_from_path(&subtype) {
2362 if !self.write_c_path_intern(w, &$p_arg.path, generics, is_ref, is_mut, ptr_for_ref) { return false; }
2364 if let Some(arr_ty) = self.is_real_type_array(&subtype) {
2365 if !self.write_c_type_intern(w, &arr_ty, generics, false, true, false) { return false; }
2367 // Option<T> needs to be converted to a *mut T, ie mut ptr-for-ref
2368 if !self.write_c_path_intern(w, &$p_arg.path, generics, true, true, true) { return false; }
2372 write!(w, "{}", $p_arg.path.segments.last().unwrap().ident).unwrap();
2374 } else if self.is_known_container(&subtype, is_ref) || self.is_path_transparent_container(&$p_arg.path, generics, is_ref) {
2375 if !self.write_c_mangled_container_path_intern(w, Self::path_to_generic_args(&$p_arg.path), generics,
2376 &subtype, is_ref, is_mut, ptr_for_ref, true) {
2379 self.write_c_mangled_container_path_intern(&mut mangled_type, Self::path_to_generic_args(&$p_arg.path),
2380 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2381 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2382 self.write_c_mangled_container_path_intern(w2, Self::path_to_generic_args(&$p_arg.path),
2383 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2386 let id = subtype.rsplitn(2, ':').next().unwrap(); // Get the "Base" name of the resolved type
2387 write!(w, "{}", id).unwrap();
2388 write!(mangled_type, "{}", id).unwrap();
2389 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2390 write!(w2, "{}", id).unwrap();
2393 } else { return false; }
2396 if let syn::Type::Tuple(tuple) = arg {
2397 if tuple.elems.len() == 0 {
2398 write!(w, "None").unwrap();
2399 write!(mangled_type, "None").unwrap();
2401 let mut mangled_tuple_type: Vec<u8> = Vec::new();
2403 // Figure out what the mangled type should look like. To disambiguate
2404 // ((A, B), C) and (A, B, C) we prefix the generic args with a _ and suffix
2405 // them with a Z. Ideally we wouldn't use Z, but not many special chars are
2406 // available for use in type names.
2407 write!(w, "C{}Tuple_", tuple.elems.len()).unwrap();
2408 write!(mangled_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2409 write!(mangled_tuple_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2410 for elem in tuple.elems.iter() {
2411 if let syn::Type::Path(p) = elem {
2412 write_path!(p, Some(&mut mangled_tuple_type));
2413 } else if let syn::Type::Reference(refelem) = elem {
2414 if let syn::Type::Path(p) = &*refelem.elem {
2415 write_path!(p, Some(&mut mangled_tuple_type));
2416 } else { return false; }
2417 } else { return false; }
2419 write!(w, "Z").unwrap();
2420 write!(mangled_type, "Z").unwrap();
2421 write!(mangled_tuple_type, "Z").unwrap();
2422 if !self.check_create_container(String::from_utf8(mangled_tuple_type).unwrap(),
2423 &format!("{}Tuple", tuple.elems.len()), tuple.elems.iter().collect(), generics, is_ref) {
2427 } else if let syn::Type::Path(p_arg) = arg {
2428 write_path!(p_arg, None);
2429 } else if let syn::Type::Reference(refty) = arg {
2430 if let syn::Type::Path(p_arg) = &*refty.elem {
2431 write_path!(p_arg, None);
2432 } else if let syn::Type::Slice(_) = &*refty.elem {
2433 // write_c_type will actually do exactly what we want here, we just need to
2434 // make it a pointer so that its an option. Note that we cannot always convert
2435 // the Vec-as-slice (ie non-ref types) containers, so sometimes need to be able
2436 // to edit it, hence we use *mut here instead of *const.
2437 if args.len() != 1 { return false; }
2438 write!(w, "*mut ").unwrap();
2439 self.write_c_type(w, arg, None, true);
2440 } else { return false; }
2441 } else if let syn::Type::Array(a) = arg {
2442 if let syn::Type::Path(p_arg) = &*a.elem {
2443 let resolved = self.resolve_path(&p_arg.path, generics);
2444 if !self.is_primitive(&resolved) { return false; }
2445 if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(len), .. }) = &a.len {
2446 if self.c_type_from_path(&format!("[{}; {}]", resolved, len.base10_digits()), is_ref, ptr_for_ref).is_none() { return false; }
2447 write!(w, "_{}{}", resolved, len.base10_digits()).unwrap();
2448 write!(mangled_type, "_{}{}", resolved, len.base10_digits()).unwrap();
2449 } else { return false; }
2450 } else { return false; }
2451 } else { return false; }
2453 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) { return true; }
2454 // Push the "end of type" Z
2455 write!(w, "Z").unwrap();
2456 write!(mangled_type, "Z").unwrap();
2458 // Make sure the type is actually defined:
2459 self.check_create_container(String::from_utf8(mangled_type).unwrap(), ident, args, generics, is_ref)
2461 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 {
2462 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2463 write!(w, "{}::", Self::generated_container_path()).unwrap();
2465 self.write_c_mangled_container_path_intern(w, args, generics, ident, is_ref, is_mut, ptr_for_ref, false)
2467 pub fn get_c_mangled_container_type(&self, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, template_name: &str) -> Option<String> {
2468 let mut out = Vec::new();
2469 if !self.write_c_mangled_container_path(&mut out, args, generics, template_name, false, false, false) {
2472 Some(String::from_utf8(out).unwrap())
2475 // **********************************
2476 // *** C Type Equivalent Printing ***
2477 // **********************************
2479 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 {
2480 let full_path = match self.maybe_resolve_path(&path, generics) {
2481 Some(path) => path, None => return false };
2482 if let Some(c_type) = self.c_type_from_path(&full_path, is_ref, ptr_for_ref) {
2483 write!(w, "{}", c_type).unwrap();
2485 } else if self.crate_types.traits.get(&full_path).is_some() {
2486 if is_ref && ptr_for_ref {
2487 write!(w, "*{} crate::{}", if is_mut { "mut" } else { "const" }, full_path).unwrap();
2489 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2491 write!(w, "crate::{}", full_path).unwrap();
2494 } else if self.crate_types.opaques.get(&full_path).is_some() || self.crate_types.mirrored_enums.get(&full_path).is_some() {
2495 if is_ref && ptr_for_ref {
2496 // ptr_for_ref implies we're returning the object, which we can't really do for
2497 // opaque or mirrored types without box'ing them, which is quite a waste, so return
2498 // the actual object itself (for opaque types we'll set the pointer to the actual
2499 // type and note that its a reference).
2500 write!(w, "crate::{}", full_path).unwrap();
2502 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2504 write!(w, "crate::{}", full_path).unwrap();
2511 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 {
2512 match generics.resolve_type(t) {
2513 syn::Type::Path(p) => {
2514 if p.qself.is_some() {
2517 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
2518 if self.is_known_container(&full_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
2519 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);
2521 if let Some(aliased_type) = self.crate_types.type_aliases.get(&full_path).cloned() {
2522 return self.write_c_type_intern(w, &aliased_type, None, is_ref, is_mut, ptr_for_ref);
2525 self.write_c_path_intern(w, &p.path, generics, is_ref, is_mut, ptr_for_ref)
2527 syn::Type::Reference(r) => {
2528 self.write_c_type_intern(w, &*r.elem, generics, true, r.mutability.is_some(), ptr_for_ref)
2530 syn::Type::Array(a) => {
2531 if is_ref && is_mut {
2532 write!(w, "*mut [").unwrap();
2533 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2535 write!(w, "*const [").unwrap();
2536 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2538 let mut typecheck = Vec::new();
2539 if !self.write_c_type_intern(&mut typecheck, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2540 if typecheck[..] != ['u' as u8, '8' as u8] { return false; }
2542 if let syn::Expr::Lit(l) = &a.len {
2543 if let syn::Lit::Int(i) = &l.lit {
2545 if let Some(ty) = self.c_type_from_path(&format!("[u8; {}]", i.base10_digits()), false, ptr_for_ref) {
2546 write!(w, "{}", ty).unwrap();
2550 write!(w, "; {}]", i).unwrap();
2556 syn::Type::Slice(s) => {
2557 if !is_ref || is_mut { return false; }
2558 if let syn::Type::Path(p) = &*s.elem {
2559 let resolved = self.resolve_path(&p.path, generics);
2560 if self.is_primitive(&resolved) {
2561 write!(w, "{}::{}slice", Self::container_templ_path(), resolved).unwrap();
2564 } else if let syn::Type::Reference(r) = &*s.elem {
2565 if let syn::Type::Path(p) = &*r.elem {
2566 // Slices with "real types" inside are mapped as the equivalent non-ref Vec
2567 let resolved = self.resolve_path(&p.path, generics);
2568 let mangled_container = if let Some(ident) = self.crate_types.opaques.get(&resolved) {
2569 format!("CVec_{}Z", ident)
2570 } else if let Some(en) = self.crate_types.mirrored_enums.get(&resolved) {
2571 format!("CVec_{}Z", en.ident)
2572 } else if let Some(id) = p.path.get_ident() {
2573 format!("CVec_{}Z", id)
2574 } else { return false; };
2575 write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
2576 self.check_create_container(mangled_container, "Vec", vec![&*r.elem], generics, false)
2578 } else if let syn::Type::Tuple(_) = &*s.elem {
2579 let mut args = syn::punctuated::Punctuated::<_, syn::token::Comma>::new();
2580 args.push(syn::GenericArgument::Type((*s.elem).clone()));
2581 let mut segments = syn::punctuated::Punctuated::new();
2582 segments.push(parse_quote!(Vec<#args>));
2583 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)
2586 syn::Type::Tuple(t) => {
2587 if t.elems.len() == 0 {
2590 self.write_c_mangled_container_path(w, t.elems.iter().collect(), generics,
2591 &format!("{}Tuple", t.elems.len()), is_ref, is_mut, ptr_for_ref)
2597 pub fn write_c_type<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) {
2598 assert!(self.write_c_type_intern(w, t, generics, false, false, ptr_for_ref));
2600 pub fn understood_c_path(&self, p: &syn::Path) -> bool {
2601 if p.leading_colon.is_some() { return false; }
2602 self.write_c_path_intern(&mut std::io::sink(), p, None, false, false, false)
2604 pub fn understood_c_type(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
2605 self.write_c_type_intern(&mut std::io::sink(), t, generics, false, false, false)