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 first_seg_is_stdlib(first_seg_str: &str) -> bool {
50 first_seg_str == "std" || first_seg_str == "core" || first_seg_str == "alloc"
53 pub fn single_ident_generic_path_to_ident(p: &syn::Path) -> Option<&syn::Ident> {
54 if p.segments.len() == 1 {
55 Some(&p.segments.iter().next().unwrap().ident)
59 pub fn path_matches_nongeneric(p: &syn::Path, exp: &[&str]) -> bool {
60 if p.segments.len() != exp.len() { return false; }
61 for (seg, e) in p.segments.iter().zip(exp.iter()) {
62 if seg.arguments != syn::PathArguments::None { return false; }
63 if &format!("{}", seg.ident) != *e { return false; }
68 #[derive(Debug, PartialEq)]
69 pub enum ExportStatus {
73 /// This is used only for traits to indicate that users should not be able to implement their
74 /// own version of a trait, but we should export Rust implementations of the trait (and the
76 /// Concretly, this means that we do not implement the Rust trait for the C trait struct.
79 /// Gets the ExportStatus of an object (struct, fn, etc) given its attributes.
80 pub fn export_status(attrs: &[syn::Attribute]) -> ExportStatus {
81 for attr in attrs.iter() {
82 let tokens_clone = attr.tokens.clone();
83 let mut token_iter = tokens_clone.into_iter();
84 if let Some(token) = token_iter.next() {
86 TokenTree::Punct(c) if c.as_char() == '=' => {
87 // Really not sure where syn gets '=' from here -
88 // it somehow represents '///' or '//!'
90 TokenTree::Group(g) => {
91 if format!("{}", single_ident_generic_path_to_ident(&attr.path).unwrap()) == "cfg" {
92 let mut iter = g.stream().into_iter();
93 if let TokenTree::Ident(i) = iter.next().unwrap() {
95 // #[cfg(any(test, feature = ""))]
96 if let TokenTree::Group(g) = iter.next().unwrap() {
97 let mut all_test = true;
98 for token in g.stream().into_iter() {
99 if let TokenTree::Ident(i) = token {
100 match format!("{}", i).as_str() {
103 _ => all_test = false,
105 } else if let TokenTree::Literal(lit) = token {
106 if format!("{}", lit) != "fuzztarget" {
111 if all_test { return ExportStatus::TestOnly; }
113 } else if i == "test" || i == "feature" {
114 // If its cfg(feature(...)) we assume its test-only
115 return ExportStatus::TestOnly;
119 continue; // eg #[derive()]
121 _ => unimplemented!(),
124 match token_iter.next().unwrap() {
125 TokenTree::Literal(lit) => {
126 let line = format!("{}", lit);
127 if line.contains("(C-not exported)") {
128 return ExportStatus::NoExport;
129 } else if line.contains("(C-not implementable)") {
130 return ExportStatus::NotImplementable;
133 _ => unimplemented!(),
139 pub fn assert_simple_bound(bound: &syn::TraitBound) {
140 if bound.paren_token.is_some() || bound.lifetimes.is_some() { unimplemented!(); }
141 if let syn::TraitBoundModifier::Maybe(_) = bound.modifier { unimplemented!(); }
144 /// Returns true if the enum will be mapped as an opaue (ie struct with a pointer to the underlying
145 /// type), otherwise it is mapped into a transparent, C-compatible version of itself.
146 pub fn is_enum_opaque(e: &syn::ItemEnum) -> bool {
147 for var in e.variants.iter() {
148 if let syn::Fields::Named(fields) = &var.fields {
149 for field in fields.named.iter() {
150 match export_status(&field.attrs) {
151 ExportStatus::Export|ExportStatus::TestOnly => {},
152 ExportStatus::NotImplementable => panic!("(C-not implementable) should only appear on traits!"),
153 ExportStatus::NoExport => return true,
156 } else if let syn::Fields::Unnamed(fields) = &var.fields {
157 for field in fields.unnamed.iter() {
158 match export_status(&field.attrs) {
159 ExportStatus::Export|ExportStatus::TestOnly => {},
160 ExportStatus::NotImplementable => panic!("(C-not implementable) should only appear on traits!"),
161 ExportStatus::NoExport => return true,
169 /// A stack of sets of generic resolutions.
171 /// This tracks the template parameters for a function, struct, or trait, allowing resolution into
172 /// a concrete type. By pushing a new context onto the stack, this can track a function's template
173 /// parameters inside of a generic struct or trait.
175 /// It maps both direct types as well as Deref<Target = X>, mapping them via the provided
176 /// TypeResolver's resolve_path function (ie traits map to the concrete jump table, structs to the
177 /// concrete C container struct, etc).
179 pub struct GenericTypes<'a, 'b> {
180 self_ty: Option<String>,
181 parent: Option<&'b GenericTypes<'b, 'b>>,
182 typed_generics: HashMap<&'a syn::Ident, String>,
183 default_generics: HashMap<&'a syn::Ident, (syn::Type, syn::Type)>,
185 impl<'a, 'p: 'a> GenericTypes<'a, 'p> {
186 pub fn new(self_ty: Option<String>) -> Self {
187 Self { self_ty, parent: None, typed_generics: HashMap::new(), default_generics: HashMap::new(), }
190 /// push a new context onto the stack, allowing for a new set of generics to be learned which
191 /// will override any lower contexts, but which will still fall back to resoltion via lower
193 pub fn push_ctx<'c>(&'c self) -> GenericTypes<'a, 'c> {
194 GenericTypes { self_ty: None, parent: Some(self), typed_generics: HashMap::new(), default_generics: HashMap::new(), }
197 /// Learn the generics in generics in the current context, given a TypeResolver.
198 pub fn learn_generics<'b, 'c>(&mut self, generics: &'a syn::Generics, types: &'b TypeResolver<'a, 'c>) -> bool {
199 let mut new_typed_generics = HashMap::new();
200 // First learn simple generics...
201 for generic in generics.params.iter() {
203 syn::GenericParam::Type(type_param) => {
204 let mut non_lifetimes_processed = false;
205 'bound_loop: for bound in type_param.bounds.iter() {
206 if let syn::TypeParamBound::Trait(trait_bound) = bound {
207 if let Some(ident) = single_ident_generic_path_to_ident(&trait_bound.path) {
208 match &format!("{}", ident) as &str { "Send" => continue, "Sync" => continue, _ => {} }
210 if path_matches_nongeneric(&trait_bound.path, &["core", "clone", "Clone"]) { continue; }
212 assert_simple_bound(&trait_bound);
213 if let Some(path) = types.maybe_resolve_path(&trait_bound.path, None) {
214 if types.skip_path(&path) { continue; }
215 if path == "Sized" { continue; }
216 if non_lifetimes_processed { return false; }
217 non_lifetimes_processed = true;
218 if path != "std::ops::Deref" && path != "core::ops::Deref" {
219 new_typed_generics.insert(&type_param.ident, Some(path));
220 } else if trait_bound.path.segments.len() == 1 {
221 // If we're templated on Deref<Target = ConcreteThing>, store
222 // the reference type in `default_generics` which handles full
223 // types and not just paths.
224 if let syn::PathArguments::AngleBracketed(ref args) =
225 trait_bound.path.segments[0].arguments {
226 for subargument in args.args.iter() {
228 syn::GenericArgument::Lifetime(_) => {},
229 syn::GenericArgument::Binding(ref b) => {
230 if &format!("{}", b.ident) != "Target" { return false; }
232 self.default_generics.insert(&type_param.ident, (parse_quote!(&#default), parse_quote!(&#default)));
235 _ => unimplemented!(),
239 new_typed_generics.insert(&type_param.ident, None);
245 if let Some(default) = type_param.default.as_ref() {
246 assert!(type_param.bounds.is_empty());
247 self.default_generics.insert(&type_param.ident, (default.clone(), parse_quote!(&#default)));
253 // Then find generics where we are required to pass a Deref<Target=X> and pretend its just X.
254 if let Some(wh) = &generics.where_clause {
255 for pred in wh.predicates.iter() {
256 if let syn::WherePredicate::Type(t) = pred {
257 if let syn::Type::Path(p) = &t.bounded_ty {
258 if p.qself.is_some() { return false; }
259 if p.path.leading_colon.is_some() { return false; }
260 let mut p_iter = p.path.segments.iter();
261 if let Some(gen) = new_typed_generics.get_mut(&p_iter.next().unwrap().ident) {
262 if gen.is_some() { return false; }
263 if &format!("{}", p_iter.next().unwrap().ident) != "Target" {return false; }
265 let mut non_lifetimes_processed = false;
266 for bound in t.bounds.iter() {
267 if let syn::TypeParamBound::Trait(trait_bound) = bound {
268 if let Some(id) = trait_bound.path.get_ident() {
269 if format!("{}", id) == "Sized" { continue; }
271 if non_lifetimes_processed { return false; }
272 non_lifetimes_processed = true;
273 assert_simple_bound(&trait_bound);
274 *gen = Some(types.resolve_path(&trait_bound.path, None));
277 } else { return false; }
278 } else { return false; }
282 for (key, value) in new_typed_generics.drain() {
283 if let Some(v) = value {
284 assert!(self.typed_generics.insert(key, v).is_none());
285 } else { return false; }
290 /// Learn the associated types from the trait in the current context.
291 pub fn learn_associated_types<'b, 'c>(&mut self, t: &'a syn::ItemTrait, types: &'b TypeResolver<'a, 'c>) {
292 for item in t.items.iter() {
294 &syn::TraitItem::Type(ref t) => {
295 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
296 let mut bounds_iter = t.bounds.iter();
297 match bounds_iter.next().unwrap() {
298 syn::TypeParamBound::Trait(tr) => {
299 assert_simple_bound(&tr);
300 if let Some(path) = types.maybe_resolve_path(&tr.path, None) {
301 if types.skip_path(&path) { continue; }
302 // In general we handle Deref<Target=X> as if it were just X (and
303 // implement Deref<Target=Self> for relevant types). We don't
304 // bother to implement it for associated types, however, so we just
305 // ignore such bounds.
306 if path != "std::ops::Deref" && path != "core::ops::Deref" {
307 self.typed_generics.insert(&t.ident, path);
309 } else { unimplemented!(); }
311 _ => unimplemented!(),
313 if bounds_iter.next().is_some() { unimplemented!(); }
320 /// Attempt to resolve a Path as a generic parameter and return the full path. as both a string
322 pub fn maybe_resolve_path<'b>(&'b self, path: &syn::Path) -> Option<&'b String> {
323 if let Some(ident) = path.get_ident() {
324 if let Some(ty) = &self.self_ty {
325 if format!("{}", ident) == "Self" {
329 if let Some(res) = self.typed_generics.get(ident) {
333 // Associated types are usually specified as "Self::Generic", so we check for that
335 let mut it = path.segments.iter();
336 if path.segments.len() == 2 && format!("{}", it.next().unwrap().ident) == "Self" {
337 let ident = &it.next().unwrap().ident;
338 if let Some(res) = self.typed_generics.get(ident) {
343 if let Some(parent) = self.parent {
344 parent.maybe_resolve_path(path)
351 trait ResolveType<'a> { fn resolve_type(&'a self, ty: &'a syn::Type) -> &'a syn::Type; }
352 impl<'a, 'b, 'c: 'a + 'b> ResolveType<'c> for Option<&GenericTypes<'a, 'b>> {
353 fn resolve_type(&'c self, ty: &'c syn::Type) -> &'c syn::Type {
354 if let Some(us) = self {
356 syn::Type::Path(p) => {
357 if let Some(ident) = p.path.get_ident() {
358 if let Some((ty, _)) = us.default_generics.get(ident) {
363 syn::Type::Reference(syn::TypeReference { elem, .. }) => {
364 if let syn::Type::Path(p) = &**elem {
365 if let Some(ident) = p.path.get_ident() {
366 if let Some((_, refty)) = us.default_generics.get(ident) {
374 us.parent.resolve_type(ty)
379 #[derive(Clone, PartialEq)]
380 // The type of declaration and the object itself
381 pub enum DeclType<'a> {
383 Trait(&'a syn::ItemTrait),
389 pub struct ImportResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
390 crate_name: &'mod_lifetime str,
391 dependencies: &'mod_lifetime HashSet<syn::Ident>,
392 module_path: &'mod_lifetime str,
393 imports: HashMap<syn::Ident, (String, syn::Path)>,
394 declared: HashMap<syn::Ident, DeclType<'crate_lft>>,
395 priv_modules: HashSet<syn::Ident>,
397 impl<'mod_lifetime, 'crate_lft: 'mod_lifetime> ImportResolver<'mod_lifetime, 'crate_lft> {
398 fn process_use_intern(crate_name: &str, module_path: &str, dependencies: &HashSet<syn::Ident>, imports: &mut HashMap<syn::Ident, (String, syn::Path)>,
399 u: &syn::UseTree, partial_path: &str, mut path: syn::punctuated::Punctuated<syn::PathSegment, syn::token::Colon2>) {
402 macro_rules! push_path {
403 ($ident: expr, $path_suffix: expr) => {
404 if partial_path == "" && format!("{}", $ident) == "super" {
405 let mut mod_iter = module_path.rsplitn(2, "::");
406 mod_iter.next().unwrap();
407 let super_mod = mod_iter.next().unwrap();
408 new_path = format!("{}{}", super_mod, $path_suffix);
409 assert_eq!(path.len(), 0);
410 for module in super_mod.split("::") {
411 path.push(syn::PathSegment { ident: syn::Ident::new(module, Span::call_site()), arguments: syn::PathArguments::None });
413 } else if partial_path == "" && !dependencies.contains(&$ident) {
414 new_path = format!("{}::{}{}", crate_name, $ident, $path_suffix);
415 let crate_name_ident = format_ident!("{}", crate_name);
416 path.push(parse_quote!(#crate_name_ident));
418 new_path = format!("{}{}{}", partial_path, $ident, $path_suffix);
421 path.push(parse_quote!(#ident));
425 syn::UseTree::Path(p) => {
426 push_path!(p.ident, "::");
427 Self::process_use_intern(crate_name, module_path, dependencies, imports, &p.tree, &new_path, path);
429 syn::UseTree::Name(n) => {
430 push_path!(n.ident, "");
431 imports.insert(n.ident.clone(), (new_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
433 syn::UseTree::Group(g) => {
434 for i in g.items.iter() {
435 Self::process_use_intern(crate_name, module_path, dependencies, imports, i, partial_path, path.clone());
438 syn::UseTree::Rename(r) => {
439 push_path!(r.ident, "");
440 imports.insert(r.rename.clone(), (new_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
442 syn::UseTree::Glob(_) => {
443 eprintln!("Ignoring * use for {} - this may result in resolution failures", partial_path);
448 fn process_use(crate_name: &str, module_path: &str, dependencies: &HashSet<syn::Ident>, imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::ItemUse) {
449 if let syn::Visibility::Public(_) = u.vis {
450 // We actually only use these for #[cfg(fuzztarget)]
451 eprintln!("Ignoring pub(use) tree!");
454 if u.leading_colon.is_some() { eprintln!("Ignoring leading-colon use!"); return; }
455 Self::process_use_intern(crate_name, module_path, dependencies, imports, &u.tree, "", syn::punctuated::Punctuated::new());
458 fn insert_primitive(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, id: &str) {
459 let ident = format_ident!("{}", id);
460 let path = parse_quote!(#ident);
461 imports.insert(ident, (id.to_owned(), path));
464 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 {
465 Self::from_borrowed_items(crate_name, dependencies, module_path, &contents.iter().map(|a| a).collect::<Vec<_>>())
467 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 {
468 let mut imports = HashMap::new();
469 // Add primitives to the "imports" list:
470 Self::insert_primitive(&mut imports, "bool");
471 Self::insert_primitive(&mut imports, "u64");
472 Self::insert_primitive(&mut imports, "u32");
473 Self::insert_primitive(&mut imports, "u16");
474 Self::insert_primitive(&mut imports, "u8");
475 Self::insert_primitive(&mut imports, "usize");
476 Self::insert_primitive(&mut imports, "str");
477 Self::insert_primitive(&mut imports, "String");
479 // These are here to allow us to print native Rust types in trait fn impls even if we don't
481 Self::insert_primitive(&mut imports, "Result");
482 Self::insert_primitive(&mut imports, "Vec");
483 Self::insert_primitive(&mut imports, "Option");
485 let mut declared = HashMap::new();
486 let mut priv_modules = HashSet::new();
488 for item in contents.iter() {
490 syn::Item::Use(u) => Self::process_use(crate_name, module_path, dependencies, &mut imports, &u),
491 syn::Item::Struct(s) => {
492 if let syn::Visibility::Public(_) = s.vis {
493 match export_status(&s.attrs) {
494 ExportStatus::Export => { declared.insert(s.ident.clone(), DeclType::StructImported); },
495 ExportStatus::NoExport => { declared.insert(s.ident.clone(), DeclType::StructIgnored); },
496 ExportStatus::TestOnly => continue,
497 ExportStatus::NotImplementable => panic!("(C-not implementable) should only appear on traits!"),
501 syn::Item::Type(t) if export_status(&t.attrs) == ExportStatus::Export => {
502 if let syn::Visibility::Public(_) = t.vis {
503 let mut process_alias = true;
504 for tok in t.generics.params.iter() {
505 if let syn::GenericParam::Lifetime(_) = tok {}
506 else { process_alias = false; }
509 declared.insert(t.ident.clone(), DeclType::StructImported);
513 syn::Item::Enum(e) => {
514 if let syn::Visibility::Public(_) = e.vis {
515 match export_status(&e.attrs) {
516 ExportStatus::Export if is_enum_opaque(e) => { declared.insert(e.ident.clone(), DeclType::EnumIgnored); },
517 ExportStatus::Export => { declared.insert(e.ident.clone(), DeclType::MirroredEnum); },
518 ExportStatus::NotImplementable => panic!("(C-not implementable) should only appear on traits!"),
523 syn::Item::Trait(t) => {
524 match export_status(&t.attrs) {
525 ExportStatus::Export|ExportStatus::NotImplementable => {
526 if let syn::Visibility::Public(_) = t.vis {
527 declared.insert(t.ident.clone(), DeclType::Trait(t));
533 syn::Item::Mod(m) => {
534 priv_modules.insert(m.ident.clone());
540 Self { crate_name, dependencies, module_path, imports, declared, priv_modules }
543 pub fn get_declared_type(&self, ident: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
544 self.declared.get(ident)
547 pub fn maybe_resolve_declared(&self, id: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
548 self.declared.get(id)
551 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
552 if let Some((imp, _)) = self.imports.get(id) {
554 } else if self.declared.get(id).is_some() {
555 Some(self.module_path.to_string() + "::" + &format!("{}", id))
559 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
560 if let Some((imp, _)) = self.imports.get(id) {
562 } else if let Some(decl_type) = self.declared.get(id) {
564 DeclType::StructIgnored => None,
565 _ => Some(self.module_path.to_string() + "::" + &format!("{}", id)),
570 pub fn maybe_resolve_path(&self, p: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
571 if let Some(gen_types) = generics {
572 if let Some(resp) = gen_types.maybe_resolve_path(p) {
573 return Some(resp.clone());
577 if p.leading_colon.is_some() {
578 let mut res: String = p.segments.iter().enumerate().map(|(idx, seg)| {
579 format!("{}{}", if idx == 0 { "" } else { "::" }, seg.ident)
581 let firstseg = p.segments.iter().next().unwrap();
582 if !self.dependencies.contains(&firstseg.ident) {
583 res = self.crate_name.to_owned() + "::" + &res;
586 } else if let Some(id) = p.get_ident() {
587 self.maybe_resolve_ident(id)
589 if p.segments.len() == 1 {
590 let seg = p.segments.iter().next().unwrap();
591 return self.maybe_resolve_ident(&seg.ident);
593 let mut seg_iter = p.segments.iter();
594 let first_seg = seg_iter.next().unwrap();
595 let remaining: String = seg_iter.map(|seg| {
596 format!("::{}", seg.ident)
598 let first_seg_str = format!("{}", first_seg.ident);
599 if let Some((imp, _)) = self.imports.get(&first_seg.ident) {
601 Some(imp.clone() + &remaining)
605 } else if let Some(_) = self.priv_modules.get(&first_seg.ident) {
606 Some(format!("{}::{}{}", self.module_path, first_seg.ident, remaining))
607 } else if first_seg_is_stdlib(&first_seg_str) || self.dependencies.contains(&first_seg.ident) {
608 Some(first_seg_str + &remaining)
613 /// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern)
614 pub fn resolve_imported_refs(&self, mut ty: syn::Type) -> syn::Type {
616 syn::Type::Path(p) => {
617 if p.path.segments.len() != 1 { unimplemented!(); }
618 let mut args = p.path.segments[0].arguments.clone();
619 if let syn::PathArguments::AngleBracketed(ref mut generics) = &mut args {
620 for arg in generics.args.iter_mut() {
621 if let syn::GenericArgument::Type(ref mut t) = arg {
622 *t = self.resolve_imported_refs(t.clone());
626 if let Some((_, newpath)) = self.imports.get(single_ident_generic_path_to_ident(&p.path).unwrap()) {
627 p.path = newpath.clone();
629 p.path.segments[0].arguments = args;
631 syn::Type::Reference(r) => {
632 r.elem = Box::new(self.resolve_imported_refs((*r.elem).clone()));
634 syn::Type::Slice(s) => {
635 s.elem = Box::new(self.resolve_imported_refs((*s.elem).clone()));
637 syn::Type::Tuple(t) => {
638 for e in t.elems.iter_mut() {
639 *e = self.resolve_imported_refs(e.clone());
642 _ => unimplemented!(),
648 // templates_defined is walked to write the C++ header, so if we use the default hashing it get
649 // reordered on each genbindings run. Instead, we use SipHasher (which defaults to 0-keys) so that
650 // the sorting is stable across runs. It is deprecated, but the "replacement" doesn't actually
651 // accomplish the same goals, so we just ignore it.
653 pub type NonRandomHash = hash::BuildHasherDefault<hash::SipHasher>;
656 pub struct ASTModule {
657 pub attrs: Vec<syn::Attribute>,
658 pub items: Vec<syn::Item>,
659 pub submods: Vec<String>,
661 /// A struct containing the syn::File AST for each file in the crate.
662 pub struct FullLibraryAST {
663 pub modules: HashMap<String, ASTModule, NonRandomHash>,
664 pub dependencies: HashSet<syn::Ident>,
666 impl FullLibraryAST {
667 fn load_module(&mut self, module: String, attrs: Vec<syn::Attribute>, mut items: Vec<syn::Item>) {
668 let mut non_mod_items = Vec::with_capacity(items.len());
669 let mut submods = Vec::with_capacity(items.len());
670 for item in items.drain(..) {
672 syn::Item::Mod(m) if m.content.is_some() => {
673 if export_status(&m.attrs) == ExportStatus::Export {
674 if let syn::Visibility::Public(_) = m.vis {
675 let modident = format!("{}", m.ident);
676 let modname = if module != "" {
677 module.clone() + "::" + &modident
681 self.load_module(modname, m.attrs, m.content.unwrap().1);
682 submods.push(modident);
684 non_mod_items.push(syn::Item::Mod(m));
688 syn::Item::Mod(_) => panic!("--pretty=expanded output should never have non-body modules"),
689 syn::Item::ExternCrate(c) => {
690 if export_status(&c.attrs) == ExportStatus::Export {
691 self.dependencies.insert(c.ident);
694 _ => { non_mod_items.push(item); }
697 self.modules.insert(module, ASTModule { attrs, items: non_mod_items, submods });
700 pub fn load_lib(lib: syn::File) -> Self {
701 assert_eq!(export_status(&lib.attrs), ExportStatus::Export);
702 let mut res = Self { modules: HashMap::default(), dependencies: HashSet::new() };
703 res.load_module("".to_owned(), lib.attrs, lib.items);
708 /// List of manually-generated types which are clonable
709 fn initial_clonable_types() -> HashSet<String> {
710 let mut res = HashSet::new();
711 res.insert("crate::c_types::u5".to_owned());
712 res.insert("crate::c_types::ThirtyTwoBytes".to_owned());
713 res.insert("crate::c_types::PublicKey".to_owned());
714 res.insert("crate::c_types::Transaction".to_owned());
715 res.insert("crate::c_types::TxOut".to_owned());
716 res.insert("crate::c_types::Signature".to_owned());
717 res.insert("crate::c_types::RecoverableSignature".to_owned());
718 res.insert("crate::c_types::Secp256k1Error".to_owned());
719 res.insert("crate::c_types::IOError".to_owned());
723 /// Top-level struct tracking everything which has been defined while walking the crate.
724 pub struct CrateTypes<'a> {
725 /// This may contain structs or enums, but only when either is mapped as
726 /// struct X { inner: *mut originalX, .. }
727 pub opaques: HashMap<String, &'a syn::Ident>,
728 /// Enums which are mapped as C enums with conversion functions
729 pub mirrored_enums: HashMap<String, &'a syn::ItemEnum>,
730 /// Traits which are mapped as a pointer + jump table
731 pub traits: HashMap<String, &'a syn::ItemTrait>,
732 /// Aliases from paths to some other Type
733 pub type_aliases: HashMap<String, syn::Type>,
734 /// Value is an alias to Key (maybe with some generics)
735 pub reverse_alias_map: HashMap<String, Vec<(syn::Path, syn::PathArguments)>>,
736 /// Template continer types defined, map from mangled type name -> whether a destructor fn
739 /// This is used at the end of processing to make C++ wrapper classes
740 pub templates_defined: RefCell<HashMap<String, bool, NonRandomHash>>,
741 /// The output file for any created template container types, written to as we find new
742 /// template containers which need to be defined.
743 template_file: RefCell<&'a mut File>,
744 /// Set of containers which are clonable
745 clonable_types: RefCell<HashSet<String>>,
747 pub trait_impls: HashMap<String, Vec<String>>,
748 /// The full set of modules in the crate(s)
749 pub lib_ast: &'a FullLibraryAST,
752 impl<'a> CrateTypes<'a> {
753 pub fn new(template_file: &'a mut File, libast: &'a FullLibraryAST) -> Self {
755 opaques: HashMap::new(), mirrored_enums: HashMap::new(), traits: HashMap::new(),
756 type_aliases: HashMap::new(), reverse_alias_map: HashMap::new(),
757 templates_defined: RefCell::new(HashMap::default()),
758 clonable_types: RefCell::new(initial_clonable_types()), trait_impls: HashMap::new(),
759 template_file: RefCell::new(template_file), lib_ast: &libast,
762 pub fn set_clonable(&self, object: String) {
763 self.clonable_types.borrow_mut().insert(object);
765 pub fn is_clonable(&self, object: &str) -> bool {
766 self.clonable_types.borrow().contains(object)
768 pub fn write_new_template(&self, mangled_container: String, has_destructor: bool, created_container: &[u8]) {
769 self.template_file.borrow_mut().write(created_container).unwrap();
770 self.templates_defined.borrow_mut().insert(mangled_container, has_destructor);
774 /// A struct which tracks resolving rust types into C-mapped equivalents, exists for one specific
775 /// module but contains a reference to the overall CrateTypes tracking.
776 pub struct TypeResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
777 pub module_path: &'mod_lifetime str,
778 pub crate_types: &'mod_lifetime CrateTypes<'crate_lft>,
779 types: ImportResolver<'mod_lifetime, 'crate_lft>,
782 /// Returned by write_empty_rust_val_check_suffix to indicate what type of dereferencing needs to
783 /// happen to get the inner value of a generic.
784 enum EmptyValExpectedTy {
785 /// A type which has a flag for being empty (eg an array where we treat all-0s as empty).
787 /// A Option mapped as a COption_*Z
789 /// A pointer which we want to convert to a reference.
794 /// Describes the appropriate place to print a general type-conversion string when converting a
796 enum ContainerPrefixLocation {
797 /// Prints a general type-conversion string prefix and suffix outside of the
798 /// container-conversion strings.
800 /// Prints a general type-conversion string prefix and suffix inside of the
801 /// container-conversion strings.
803 /// Does not print the usual type-conversion string prefix and suffix.
807 impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
808 pub fn new(module_path: &'a str, types: ImportResolver<'a, 'c>, crate_types: &'a CrateTypes<'c>) -> Self {
809 Self { module_path, types, crate_types }
812 // *************************************************
813 // *** Well know type and conversion definitions ***
814 // *************************************************
816 /// Returns true we if can just skip passing this to C entirely
817 fn skip_path(&self, full_path: &str) -> bool {
818 full_path == "bitcoin::secp256k1::Secp256k1" ||
819 full_path == "bitcoin::secp256k1::Signing" ||
820 full_path == "bitcoin::secp256k1::Verification"
822 /// Returns true we if can just skip passing this to C entirely
823 fn no_arg_path_to_rust(&self, full_path: &str) -> &str {
824 if full_path == "bitcoin::secp256k1::Secp256k1" {
825 "secp256k1::SECP256K1"
826 } else { unimplemented!(); }
829 /// Returns true if the object is a primitive and is mapped as-is with no conversion
831 pub fn is_primitive(&self, full_path: &str) -> bool {
842 pub fn is_clonable(&self, ty: &str) -> bool {
843 if self.crate_types.is_clonable(ty) { return true; }
844 if self.is_primitive(ty) { return true; }
850 /// Gets the C-mapped type for types which are outside of the crate, or which are manually
851 /// ignored by for some reason need mapping anyway.
852 fn c_type_from_path<'b>(&self, full_path: &'b str, is_ref: bool, _ptr_for_ref: bool) -> Option<&'b str> {
853 if self.is_primitive(full_path) {
854 return Some(full_path);
857 // Note that no !is_ref types can map to an array because Rust and C's call semantics
858 // for arrays are different (https://github.com/eqrion/cbindgen/issues/528)
860 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
861 "[u8; 20]" if !is_ref => Some("crate::c_types::TwentyBytes"),
862 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes"),
863 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes"),
864 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes"),
865 "[u8; 3]" if !is_ref => Some("crate::c_types::ThreeBytes"), // Used for RGB values
867 "str" if is_ref => Some("crate::c_types::Str"),
868 "alloc::string::String"|"String" => Some("crate::c_types::Str"),
870 "std::time::Duration"|"core::time::Duration" => Some("u64"),
871 "std::time::SystemTime" => Some("u64"),
872 "std::io::Error" => Some("crate::c_types::IOError"),
874 "core::convert::Infallible" => Some("crate::c_types::NotConstructable"),
876 "bech32::u5" => Some("crate::c_types::u5"),
877 "core::num::NonZeroU8" => Some("u8"),
879 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
880 => Some("crate::c_types::PublicKey"),
881 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature"),
882 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some("crate::c_types::RecoverableSignature"),
883 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
884 if is_ref => Some("*const [u8; 32]"),
885 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
886 if !is_ref => Some("crate::c_types::SecretKey"),
887 "bitcoin::secp256k1::Error"|"secp256k1::Error"
888 if !is_ref => Some("crate::c_types::Secp256k1Error"),
889 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice"),
890 "bitcoin::blockdata::script::Script" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
891 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::lightning::chain::transaction::OutPoint"),
892 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" => Some("crate::c_types::Transaction"),
893 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut"),
894 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network"),
895 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("*const [u8; 80]"),
896 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice"),
898 "bitcoin::hash_types::PubkeyHash"|"bitcoin::hash_types::WPubkeyHash"|"bitcoin::hash_types::ScriptHash"
899 if is_ref => Some("*const [u8; 20]"),
900 "bitcoin::hash_types::WScriptHash"
901 if is_ref => Some("*const [u8; 32]"),
903 // Newtypes that we just expose in their original form.
904 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
905 if is_ref => Some("*const [u8; 32]"),
906 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
907 if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
908 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
909 "lightning::ln::PaymentHash" if is_ref => Some("*const [u8; 32]"),
910 "lightning::ln::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
911 "lightning::ln::PaymentPreimage" if is_ref => Some("*const [u8; 32]"),
912 "lightning::ln::PaymentPreimage" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
913 "lightning::ln::PaymentSecret" => Some("crate::c_types::ThirtyTwoBytes"),
915 // Override the default since Records contain an fmt with a lifetime:
916 "lightning::util::logger::Record" => Some("*const std::os::raw::c_char"),
918 "lightning::io::Read" => Some("crate::c_types::u8slice"),
924 fn from_c_conversion_new_var_from_path<'b>(&self, _full_path: &str, _is_ref: bool) -> Option<(&'b str, &'b str)> {
927 fn from_c_conversion_prefix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
928 if self.is_primitive(full_path) {
929 return Some("".to_owned());
932 "Vec" if !is_ref => Some("local_"),
933 "Result" if !is_ref => Some("local_"),
934 "Option" if is_ref => Some("&local_"),
935 "Option" => Some("local_"),
937 "[u8; 32]" if is_ref => Some("unsafe { &*"),
938 "[u8; 32]" if !is_ref => Some(""),
939 "[u8; 20]" if !is_ref => Some(""),
940 "[u8; 16]" if !is_ref => Some(""),
941 "[u8; 10]" if !is_ref => Some(""),
942 "[u8; 4]" if !is_ref => Some(""),
943 "[u8; 3]" if !is_ref => Some(""),
945 "[u8]" if is_ref => Some(""),
946 "[usize]" if is_ref => Some(""),
948 "str" if is_ref => Some(""),
949 "alloc::string::String"|"String" => Some(""),
950 "std::io::Error" if !is_ref => Some(""),
951 // Note that we'll panic for String if is_ref, as we only have non-owned memory, we
952 // cannot create a &String.
954 "core::convert::Infallible" => Some("panic!(\"You must never construct a NotConstructable! : "),
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(""),
960 "core::num::NonZeroU8" => Some("core::num::NonZeroU8::new("),
962 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
963 if is_ref => Some("&"),
964 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
966 "bitcoin::secp256k1::Signature" if is_ref => Some("&"),
967 "bitcoin::secp256k1::Signature" => Some(""),
968 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(""),
969 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
970 if is_ref => Some("&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *"),
971 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
972 if !is_ref => Some(""),
973 "bitcoin::blockdata::script::Script" if is_ref => Some("&::bitcoin::blockdata::script::Script::from(Vec::from("),
974 "bitcoin::blockdata::script::Script" if !is_ref => Some("::bitcoin::blockdata::script::Script::from("),
975 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" if is_ref => Some("&"),
976 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" => Some(""),
977 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::c_types::C_to_bitcoin_outpoint("),
978 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(""),
979 "bitcoin::network::constants::Network" => Some(""),
980 "bitcoin::blockdata::block::BlockHeader" => Some("&::bitcoin::consensus::encode::deserialize(unsafe { &*"),
981 "bitcoin::blockdata::block::Block" if is_ref => Some("&::bitcoin::consensus::encode::deserialize("),
983 "bitcoin::hash_types::PubkeyHash" if is_ref =>
984 Some("&bitcoin::hash_types::PubkeyHash::from_hash(bitcoin::hashes::Hash::from_inner(unsafe { *"),
985 "bitcoin::hash_types::WPubkeyHash" if is_ref =>
986 Some("&bitcoin::hash_types::WPubkeyHash::from_hash(bitcoin::hashes::Hash::from_inner(unsafe { *"),
987 "bitcoin::hash_types::ScriptHash" if is_ref =>
988 Some("&bitcoin::hash_types::ScriptHash::from_hash(bitcoin::hashes::Hash::from_inner(unsafe { *"),
989 "bitcoin::hash_types::WScriptHash" if is_ref =>
990 Some("&bitcoin::hash_types::WScriptHash::from_hash(bitcoin::hashes::Hash::from_inner(unsafe { *"),
992 // Newtypes that we just expose in their original form.
993 "bitcoin::hash_types::Txid" if is_ref => Some("&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*"),
994 "bitcoin::hash_types::Txid" if !is_ref => Some("::bitcoin::hash_types::Txid::from_slice(&"),
995 "bitcoin::hash_types::BlockHash" => Some("::bitcoin::hash_types::BlockHash::from_slice(&"),
996 "lightning::ln::PaymentHash" if !is_ref => Some("::lightning::ln::PaymentHash("),
997 "lightning::ln::PaymentHash" if is_ref => Some("&::lightning::ln::PaymentHash(unsafe { *"),
998 "lightning::ln::PaymentPreimage" if !is_ref => Some("::lightning::ln::PaymentPreimage("),
999 "lightning::ln::PaymentPreimage" if is_ref => Some("&::lightning::ln::PaymentPreimage(unsafe { *"),
1000 "lightning::ln::PaymentSecret" => Some("::lightning::ln::PaymentSecret("),
1002 // List of traits we map (possibly during processing of other files):
1003 "crate::util::logger::Logger" => Some(""),
1005 "lightning::io::Read" => Some("&mut "),
1008 }.map(|s| s.to_owned())
1010 fn from_c_conversion_suffix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
1011 if self.is_primitive(full_path) {
1012 return Some("".to_owned());
1015 "Vec" if !is_ref => Some(""),
1016 "Option" => Some(""),
1017 "Result" if !is_ref => Some(""),
1019 "[u8; 32]" if is_ref => Some("}"),
1020 "[u8; 32]" if !is_ref => Some(".data"),
1021 "[u8; 20]" if !is_ref => Some(".data"),
1022 "[u8; 16]" if !is_ref => Some(".data"),
1023 "[u8; 10]" if !is_ref => Some(".data"),
1024 "[u8; 4]" if !is_ref => Some(".data"),
1025 "[u8; 3]" if !is_ref => Some(".data"),
1027 "[u8]" if is_ref => Some(".to_slice()"),
1028 "[usize]" if is_ref => Some(".to_slice()"),
1030 "str" if is_ref => Some(".into_str()"),
1031 "alloc::string::String"|"String" => Some(".into_string()"),
1032 "std::io::Error" if !is_ref => Some(".to_rust()"),
1034 "core::convert::Infallible" => Some("\")"),
1036 "std::time::Duration"|"core::time::Duration" => Some(")"),
1037 "std::time::SystemTime" => Some("))"),
1039 "bech32::u5" => Some(".into()"),
1040 "core::num::NonZeroU8" => Some(").expect(\"Value must be non-zero\")"),
1042 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1043 => Some(".into_rust()"),
1044 "bitcoin::secp256k1::Signature" => Some(".into_rust()"),
1045 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(".into_rust()"),
1046 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1047 if !is_ref => Some(".into_rust()"),
1048 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1049 if is_ref => Some("}[..]).unwrap()"),
1050 "bitcoin::blockdata::script::Script" if is_ref => Some(".to_slice()))"),
1051 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_rust())"),
1052 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" => Some(".into_bitcoin()"),
1053 "bitcoin::blockdata::transaction::OutPoint" => Some(")"),
1054 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(".into_rust()"),
1055 "bitcoin::network::constants::Network" => Some(".into_bitcoin()"),
1056 "bitcoin::blockdata::block::BlockHeader" => Some(" }).unwrap()"),
1057 "bitcoin::blockdata::block::Block" => Some(".to_slice()).unwrap()"),
1059 "bitcoin::hash_types::PubkeyHash"|"bitcoin::hash_types::WPubkeyHash"|
1060 "bitcoin::hash_types::ScriptHash"|"bitcoin::hash_types::WScriptHash"
1061 if is_ref => Some(" }.clone()))"),
1063 // Newtypes that we just expose in their original form.
1064 "bitcoin::hash_types::Txid" if is_ref => Some(" }[..]).unwrap()"),
1065 "bitcoin::hash_types::Txid" => Some(".data[..]).unwrap()"),
1066 "bitcoin::hash_types::BlockHash" if !is_ref => Some(".data[..]).unwrap()"),
1067 "lightning::ln::PaymentHash" if !is_ref => Some(".data)"),
1068 "lightning::ln::PaymentHash" if is_ref => Some(" })"),
1069 "lightning::ln::PaymentPreimage" if !is_ref => Some(".data)"),
1070 "lightning::ln::PaymentPreimage" if is_ref => Some(" })"),
1071 "lightning::ln::PaymentSecret" => Some(".data)"),
1073 // List of traits we map (possibly during processing of other files):
1074 "crate::util::logger::Logger" => Some(""),
1076 "lightning::io::Read" => Some(".to_reader()"),
1079 }.map(|s| s.to_owned())
1082 fn to_c_conversion_new_var_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<(&'b str, &'b str)> {
1083 if self.is_primitive(full_path) {
1087 "[u8]" if is_ref => Some(("crate::c_types::u8slice::from_slice(", ")")),
1088 "[usize]" if is_ref => Some(("crate::c_types::usizeslice::from_slice(", ")")),
1090 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(("{ let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(", ")); s }")),
1091 "bitcoin::blockdata::block::Block" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
1092 "bitcoin::hash_types::Txid" => None,
1094 // Override the default since Records contain an fmt with a lifetime:
1095 // TODO: We should include the other record fields
1096 "lightning::util::logger::Record" => Some(("std::ffi::CString::new(format!(\"{}\", ", ".args)).unwrap()")),
1098 }.map(|s| s.to_owned())
1100 fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
1101 if self.is_primitive(full_path) {
1102 return Some("".to_owned());
1105 "Result" if !is_ref => Some("local_"),
1106 "Vec" if !is_ref => Some("local_"),
1107 "Option" => Some("local_"),
1109 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1110 "[u8; 32]" if is_ref => Some(""),
1111 "[u8; 20]" if !is_ref => Some("crate::c_types::TwentyBytes { data: "),
1112 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes { data: "),
1113 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes { data: "),
1114 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes { data: "),
1115 "[u8; 3]" if is_ref => Some(""),
1117 "[u8]" if is_ref => Some("local_"),
1118 "[usize]" if is_ref => Some("local_"),
1120 "str" if is_ref => Some(""),
1121 "alloc::string::String"|"String" => Some(""),
1123 "std::time::Duration"|"core::time::Duration" => Some(""),
1124 "std::time::SystemTime" => Some(""),
1125 "std::io::Error" if !is_ref => Some("crate::c_types::IOError::from_rust("),
1127 "core::convert::Infallible" => Some("panic!(\"Cannot construct an Infallible: "),
1129 "bech32::u5" => Some(""),
1131 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1132 => Some("crate::c_types::PublicKey::from_rust(&"),
1133 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature::from_rust(&"),
1134 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some("crate::c_types::RecoverableSignature::from_rust(&"),
1135 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1136 if is_ref => Some(""),
1137 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1138 if !is_ref => Some("crate::c_types::SecretKey::from_rust("),
1139 "bitcoin::secp256k1::Error"|"secp256k1::Error"
1140 if !is_ref => Some("crate::c_types::Secp256k1Error::from_rust("),
1141 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice::from_slice(&"),
1142 "bitcoin::blockdata::script::Script" if !is_ref => Some(""),
1143 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" if is_ref => Some("crate::c_types::Transaction::from_bitcoin("),
1144 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" => Some("crate::c_types::Transaction::from_bitcoin(&"),
1145 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::c_types::bitcoin_to_C_outpoint("),
1146 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut::from_rust("),
1147 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network::from_bitcoin("),
1148 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("&local_"),
1149 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice::from_slice(&local_"),
1151 "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1153 // Newtypes that we just expose in their original form.
1154 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1155 if is_ref => Some(""),
1156 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1157 if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1158 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1159 "lightning::ln::PaymentHash" if is_ref => Some("&"),
1160 "lightning::ln::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1161 "lightning::ln::PaymentPreimage" if is_ref => Some("&"),
1162 "lightning::ln::PaymentPreimage" => Some("crate::c_types::ThirtyTwoBytes { data: "),
1163 "lightning::ln::PaymentSecret" => Some("crate::c_types::ThirtyTwoBytes { data: "),
1165 // Override the default since Records contain an fmt with a lifetime:
1166 "lightning::util::logger::Record" => Some("local_"),
1168 "lightning::io::Read" => Some("crate::c_types::u8slice::from_vec(&crate::c_types::reader_to_vec("),
1171 }.map(|s| s.to_owned())
1173 fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
1174 if self.is_primitive(full_path) {
1175 return Some("".to_owned());
1178 "Result" if !is_ref => Some(""),
1179 "Vec" if !is_ref => Some(".into()"),
1180 "Option" => Some(""),
1182 "[u8; 32]" if !is_ref => Some(" }"),
1183 "[u8; 32]" if is_ref => Some(""),
1184 "[u8; 20]" if !is_ref => Some(" }"),
1185 "[u8; 16]" if !is_ref => Some(" }"),
1186 "[u8; 10]" if !is_ref => Some(" }"),
1187 "[u8; 4]" if !is_ref => Some(" }"),
1188 "[u8; 3]" if is_ref => Some(""),
1190 "[u8]" if is_ref => Some(""),
1191 "[usize]" if is_ref => Some(""),
1193 "str" if is_ref => Some(".into()"),
1194 "alloc::string::String"|"String" if is_ref => Some(".as_str().into()"),
1195 "alloc::string::String"|"String" => Some(".into()"),
1197 "std::time::Duration"|"core::time::Duration" => Some(".as_secs()"),
1198 "std::time::SystemTime" => Some(".duration_since(::std::time::SystemTime::UNIX_EPOCH).expect(\"Times must be post-1970\").as_secs()"),
1199 "std::io::Error" if !is_ref => Some(")"),
1201 "core::convert::Infallible" => Some("\")"),
1203 "bech32::u5" => Some(".into()"),
1205 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1207 "bitcoin::secp256k1::Signature" => Some(")"),
1208 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(")"),
1209 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1210 if !is_ref => Some(")"),
1211 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1212 if is_ref => Some(".as_ref()"),
1213 "bitcoin::secp256k1::Error"|"secp256k1::Error"
1214 if !is_ref => Some(")"),
1215 "bitcoin::blockdata::script::Script" if is_ref => Some("[..])"),
1216 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_bytes().into()"),
1217 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" => Some(")"),
1218 "bitcoin::blockdata::transaction::OutPoint" => Some(")"),
1219 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(")"),
1220 "bitcoin::network::constants::Network" => Some(")"),
1221 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(""),
1222 "bitcoin::blockdata::block::Block" if is_ref => Some(")"),
1224 "bitcoin::hash_types::Txid" if !is_ref => Some(".into_inner() }"),
1226 // Newtypes that we just expose in their original form.
1227 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1228 if is_ref => Some(".as_inner()"),
1229 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1230 if !is_ref => Some(".into_inner() }"),
1231 "bitcoin::secp256k1::Message" if !is_ref => Some(".as_ref().clone() }"),
1232 "lightning::ln::PaymentHash" if is_ref => Some(".0"),
1233 "lightning::ln::PaymentHash" => Some(".0 }"),
1234 "lightning::ln::PaymentPreimage" if is_ref => Some(".0"),
1235 "lightning::ln::PaymentPreimage" => Some(".0 }"),
1236 "lightning::ln::PaymentSecret" => Some(".0 }"),
1238 // Override the default since Records contain an fmt with a lifetime:
1239 "lightning::util::logger::Record" => Some(".as_ptr()"),
1241 "lightning::io::Read" => Some("))"),
1244 }.map(|s| s.to_owned())
1247 fn empty_val_check_suffix_from_path(&self, full_path: &str) -> Option<&str> {
1249 "lightning::ln::PaymentSecret" => Some(".data == [0; 32]"),
1250 "secp256k1::key::PublicKey"|"bitcoin::secp256k1::key::PublicKey" => Some(".is_null()"),
1251 "bitcoin::secp256k1::Signature" => Some(".is_null()"),
1256 /// When printing a reference to the source crate's rust type, if we need to map it to a
1257 /// different "real" type, it can be done so here.
1258 /// This is useful to work around limitations in the binding type resolver, where we reference
1259 /// a non-public `use` alias.
1260 /// TODO: We should never need to use this!
1261 fn real_rust_type_mapping<'equiv>(&self, thing: &'equiv str) -> &'equiv str {
1263 "lightning::io::Read" => "std::io::Read",
1268 // ****************************
1269 // *** Container Processing ***
1270 // ****************************
1272 /// Returns the module path in the generated mapping crate to the containers which we generate
1273 /// when writing to CrateTypes::template_file.
1274 pub fn generated_container_path() -> &'static str {
1275 "crate::c_types::derived"
1277 /// Returns the module path in the generated mapping crate to the container templates, which
1278 /// are then concretized and put in the generated container path/template_file.
1279 fn container_templ_path() -> &'static str {
1283 /// Returns true if the path containing the given args is a "transparent" container, ie an
1284 /// Option or a container which does not require a generated continer class.
1285 fn is_transparent_container<'i, I: Iterator<Item=&'i syn::Type>>(&self, full_path: &str, _is_ref: bool, mut args: I, generics: Option<&GenericTypes>) -> bool {
1286 if full_path == "Option" {
1287 let inner = args.next().unwrap();
1288 assert!(args.next().is_none());
1290 syn::Type::Reference(_) => true,
1291 syn::Type::Path(p) => {
1292 if let Some(resolved) = self.maybe_resolve_path(&p.path, generics) {
1293 if self.c_type_has_inner_from_path(&resolved) { return true; }
1294 if self.is_primitive(&resolved) { return false; }
1295 if self.c_type_from_path(&resolved, false, false).is_some() { true } else { false }
1298 syn::Type::Tuple(_) => false,
1299 _ => unimplemented!(),
1303 /// Returns true if the path is a "transparent" container, ie an Option or a container which does
1304 /// not require a generated continer class.
1305 pub fn is_path_transparent_container(&self, full_path: &syn::Path, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
1306 let inner_iter = match &full_path.segments.last().unwrap().arguments {
1307 syn::PathArguments::None => return false,
1308 syn::PathArguments::AngleBracketed(args) => args.args.iter().map(|arg| {
1309 if let syn::GenericArgument::Type(ref ty) = arg {
1311 } else { unimplemented!() }
1313 syn::PathArguments::Parenthesized(_) => unimplemented!(),
1315 self.is_transparent_container(&self.resolve_path(full_path, generics), is_ref, inner_iter, generics)
1317 /// Returns true if this is a known, supported, non-transparent container.
1318 fn is_known_container(&self, full_path: &str, is_ref: bool) -> bool {
1319 (full_path == "Result" && !is_ref) || (full_path == "Vec" && !is_ref) || full_path.ends_with("Tuple") || full_path == "Option"
1321 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)
1322 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1323 // expecting one element in the vec per generic type, each of which is inline-converted
1324 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1326 "Result" if !is_ref => {
1328 vec![(" { Ok(mut o) => crate::c_types::CResultTempl::ok(".to_string(), "o".to_string()),
1329 (").into(), Err(mut e) => crate::c_types::CResultTempl::err(".to_string(), "e".to_string())],
1330 ").into() }", ContainerPrefixLocation::PerConv))
1334 // We should only get here if the single contained has an inner
1335 assert!(self.c_type_has_inner(single_contained.unwrap()));
1337 Some(("Vec::new(); for mut item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1340 Some(("Vec::new(); for item in ", vec![(format!(".iter() {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1343 let contained_struct = if let Some(syn::Type::Path(p)) = single_contained {
1344 Some(self.resolve_path(&p.path, generics))
1345 } else if let Some(syn::Type::Reference(r)) = single_contained {
1346 if let syn::Type::Path(p) = &*r.elem {
1347 Some(self.resolve_path(&p.path, generics))
1350 if let Some(inner_path) = contained_struct {
1351 if self.c_type_has_inner_from_path(&inner_path) {
1352 let is_inner_ref = if let Some(syn::Type::Reference(_)) = single_contained { true } else { false };
1354 return Some(("if ", vec![
1355 (".is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner(".to_owned(),
1356 format!("({}{}.unwrap())", var_access, if is_inner_ref { "" } else { ".as_ref()" }))
1357 ], ") }", ContainerPrefixLocation::OutsideConv));
1359 return Some(("if ", vec![
1360 (".is_none() { std::ptr::null_mut() } else { ".to_owned(), format!("({}.unwrap())", var_access))
1361 ], " }", ContainerPrefixLocation::OutsideConv));
1363 } else if self.is_primitive(&inner_path) || self.c_type_from_path(&inner_path, false, false).is_none() {
1364 let inner_name = self.get_c_mangled_container_type(vec![single_contained.unwrap()], generics, "Option").unwrap();
1365 return Some(("if ", vec![
1366 (format!(".is_none() {{ {}::None }} else {{ {}::Some(",
1367 inner_name, inner_name),
1368 format!("{}.unwrap()", var_access))
1369 ], ") }", ContainerPrefixLocation::PerConv));
1371 // If c_type_from_path is some (ie there's a manual mapping for the inner
1372 // type), lean on write_empty_rust_val, below.
1375 if let Some(t) = single_contained {
1376 if let syn::Type::Reference(syn::TypeReference { elem, .. }) = t {
1377 if let syn::Type::Slice(_) = &**elem {
1378 return Some(("if ", vec![
1379 (".is_none() { SmartPtr::null() } else { SmartPtr::from_obj(".to_string(),
1380 format!("({}.unwrap())", var_access))
1381 ], ") }", ContainerPrefixLocation::PerConv));
1384 let mut v = Vec::new();
1385 self.write_empty_rust_val(generics, &mut v, t);
1386 let s = String::from_utf8(v).unwrap();
1387 return Some(("if ", vec![
1388 (format!(".is_none() {{ {} }} else {{ ", s), format!("({}.unwrap())", var_access))
1389 ], " }", ContainerPrefixLocation::PerConv));
1390 } else { unreachable!(); }
1396 /// only_contained_has_inner implies that there is only one contained element in the container
1397 /// and it has an inner field (ie is an "opaque" type we've defined).
1398 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)
1399 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1400 // expecting one element in the vec per generic type, each of which is inline-converted
1401 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1403 "Result" if !is_ref => {
1405 vec![(".result_ok { true => Ok(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.result)) }})", var_access)),
1406 ("), false => Err(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.err)) }})", var_access))],
1407 ")}", ContainerPrefixLocation::PerConv))
1409 "Slice" if is_ref => {
1410 Some(("Vec::new(); for mut item in ", vec![(format!(".as_slice().iter() {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1413 Some(("Vec::new(); for mut item in ", vec![(format!(".into_rust().drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1416 if let Some(syn::Type::Path(p)) = single_contained {
1417 let inner_path = self.resolve_path(&p.path, generics);
1418 if self.is_primitive(&inner_path) {
1419 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::NoPrefix))
1420 } else if self.c_type_has_inner_from_path(&inner_path) {
1422 return Some(("if ", vec![(".inner.is_null() { None } else { Some((*".to_string(), format!("{}", var_access))], ").clone()) }", ContainerPrefixLocation::PerConv))
1424 return Some(("if ", vec![(".inner.is_null() { None } else { Some(".to_string(), format!("{}", var_access))], ") }", ContainerPrefixLocation::PerConv));
1429 if let Some(t) = single_contained {
1431 syn::Type::Reference(_)|syn::Type::Path(_)|syn::Type::Slice(_) => {
1432 let mut v = Vec::new();
1433 let ret_ref = self.write_empty_rust_val_check_suffix(generics, &mut v, t);
1434 let s = String::from_utf8(v).unwrap();
1436 EmptyValExpectedTy::ReferenceAsPointer =>
1437 return Some(("if ", vec![
1438 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ &mut *{} }}", var_access))
1439 ], ") }", ContainerPrefixLocation::NoPrefix)),
1440 EmptyValExpectedTy::OptionType =>
1441 return Some(("{ /* ", vec![
1442 (format!("*/ let {}_opt = {};", var_name, var_access),
1443 format!("}} if {}_opt{} {{ None }} else {{ Some({{ {}_opt.take()", var_name, s, var_name))
1444 ], ") } }", ContainerPrefixLocation::PerConv)),
1445 EmptyValExpectedTy::NonPointer =>
1446 return Some(("if ", vec![
1447 (format!("{} {{ None }} else {{ Some(", s), format!("{}", var_access))
1448 ], ") }", ContainerPrefixLocation::PerConv)),
1451 syn::Type::Tuple(_) => {
1452 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::PerConv))
1454 _ => unimplemented!(),
1456 } else { unreachable!(); }
1462 /// Constructs a reference to the given type, possibly tweaking the type if relevant to make it
1463 /// convertable to C.
1464 pub fn create_ownable_reference(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> Option<syn::Type> {
1465 let default_value = Some(syn::Type::Reference(syn::TypeReference {
1466 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
1467 elem: Box::new(t.clone()) }));
1468 match generics.resolve_type(t) {
1469 syn::Type::Path(p) => {
1470 if let Some(resolved_path) = self.maybe_resolve_path(&p.path, generics) {
1471 if resolved_path != "Vec" { return default_value; }
1472 if p.path.segments.len() != 1 { unimplemented!(); }
1473 let only_seg = p.path.segments.iter().next().unwrap();
1474 if let syn::PathArguments::AngleBracketed(args) = &only_seg.arguments {
1475 if args.args.len() != 1 { unimplemented!(); }
1476 let inner_arg = args.args.iter().next().unwrap();
1477 if let syn::GenericArgument::Type(ty) = &inner_arg {
1478 let mut can_create = self.c_type_has_inner(&ty);
1479 if let syn::Type::Path(inner) = ty {
1480 if inner.path.segments.len() == 1 &&
1481 format!("{}", inner.path.segments[0].ident) == "Vec" {
1485 if !can_create { return default_value; }
1486 if let Some(inner_ty) = self.create_ownable_reference(&ty, generics) {
1487 return Some(syn::Type::Reference(syn::TypeReference {
1488 and_token: syn::Token![&](Span::call_site()),
1491 elem: Box::new(syn::Type::Slice(syn::TypeSlice {
1492 bracket_token: syn::token::Bracket { span: Span::call_site() },
1493 elem: Box::new(inner_ty)
1496 } else { return default_value; }
1497 } else { unimplemented!(); }
1498 } else { unimplemented!(); }
1499 } else { return None; }
1505 // *************************************************
1506 // *** Type definition during main.rs processing ***
1507 // *************************************************
1509 pub fn get_declared_type(&'a self, ident: &syn::Ident) -> Option<&'a DeclType<'c>> {
1510 self.types.get_declared_type(ident)
1512 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1513 pub fn c_type_has_inner_from_path(&self, full_path: &str) -> bool {
1514 self.crate_types.opaques.get(full_path).is_some()
1517 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1518 pub fn c_type_has_inner(&self, ty: &syn::Type) -> bool {
1520 syn::Type::Path(p) => {
1521 if let Some(full_path) = self.maybe_resolve_path(&p.path, None) {
1522 self.c_type_has_inner_from_path(&full_path)
1525 syn::Type::Reference(r) => {
1526 self.c_type_has_inner(&*r.elem)
1532 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
1533 self.types.maybe_resolve_ident(id)
1536 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
1537 self.types.maybe_resolve_non_ignored_ident(id)
1540 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
1541 self.types.maybe_resolve_path(p_arg, generics)
1543 pub fn resolve_path(&self, p: &syn::Path, generics: Option<&GenericTypes>) -> String {
1544 self.maybe_resolve_path(p, generics).unwrap()
1547 // ***********************************
1548 // *** Original Rust Type Printing ***
1549 // ***********************************
1551 fn in_rust_prelude(resolved_path: &str) -> bool {
1552 match resolved_path {
1560 fn write_rust_path<W: std::io::Write>(&self, w: &mut W, generics_resolver: Option<&GenericTypes>, path: &syn::Path) {
1561 if let Some(resolved) = self.maybe_resolve_path(&path, generics_resolver) {
1562 if self.is_primitive(&resolved) {
1563 write!(w, "{}", path.get_ident().unwrap()).unwrap();
1565 // TODO: We should have a generic "is from a dependency" check here instead of
1566 // checking for "bitcoin" explicitly.
1567 if resolved.starts_with("bitcoin::") || Self::in_rust_prelude(&resolved) {
1568 write!(w, "{}", resolved).unwrap();
1569 // If we're printing a generic argument, it needs to reference the crate, otherwise
1570 // the original crate:
1571 } else if self.maybe_resolve_path(&path, None).as_ref() == Some(&resolved) {
1572 write!(w, "{}", self.real_rust_type_mapping(&resolved)).unwrap();
1574 write!(w, "crate::{}", resolved).unwrap();
1577 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().last().unwrap().arguments {
1578 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1581 if path.leading_colon.is_some() {
1582 write!(w, "::").unwrap();
1584 for (idx, seg) in path.segments.iter().enumerate() {
1585 if idx != 0 { write!(w, "::").unwrap(); }
1586 write!(w, "{}", seg.ident).unwrap();
1587 if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
1588 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1593 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>) {
1594 let mut had_params = false;
1595 for (idx, arg) in generics.enumerate() {
1596 if idx != 0 { write!(w, ", ").unwrap(); } else { write!(w, "<").unwrap(); }
1599 syn::GenericParam::Lifetime(lt) => write!(w, "'{}", lt.lifetime.ident).unwrap(),
1600 syn::GenericParam::Type(t) => {
1601 write!(w, "{}", t.ident).unwrap();
1602 if t.colon_token.is_some() { write!(w, ":").unwrap(); }
1603 for (idx, bound) in t.bounds.iter().enumerate() {
1604 if idx != 0 { write!(w, " + ").unwrap(); }
1606 syn::TypeParamBound::Trait(tb) => {
1607 if tb.paren_token.is_some() || tb.lifetimes.is_some() { unimplemented!(); }
1608 self.write_rust_path(w, generics_resolver, &tb.path);
1610 _ => unimplemented!(),
1613 if t.eq_token.is_some() || t.default.is_some() { unimplemented!(); }
1615 _ => unimplemented!(),
1618 if had_params { write!(w, ">").unwrap(); }
1621 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>) {
1622 write!(w, "<").unwrap();
1623 for (idx, arg) in generics.enumerate() {
1624 if idx != 0 { write!(w, ", ").unwrap(); }
1626 syn::GenericArgument::Type(t) => self.write_rust_type(w, generics_resolver, t),
1627 _ => unimplemented!(),
1630 write!(w, ">").unwrap();
1632 pub fn write_rust_type<W: std::io::Write>(&self, w: &mut W, generics: Option<&GenericTypes>, t: &syn::Type) {
1634 syn::Type::Path(p) => {
1635 if p.qself.is_some() {
1638 self.write_rust_path(w, generics, &p.path);
1640 syn::Type::Reference(r) => {
1641 write!(w, "&").unwrap();
1642 if let Some(lft) = &r.lifetime {
1643 write!(w, "'{} ", lft.ident).unwrap();
1645 if r.mutability.is_some() {
1646 write!(w, "mut ").unwrap();
1648 self.write_rust_type(w, generics, &*r.elem);
1650 syn::Type::Array(a) => {
1651 write!(w, "[").unwrap();
1652 self.write_rust_type(w, generics, &a.elem);
1653 if let syn::Expr::Lit(l) = &a.len {
1654 if let syn::Lit::Int(i) = &l.lit {
1655 write!(w, "; {}]", i).unwrap();
1656 } else { unimplemented!(); }
1657 } else { unimplemented!(); }
1659 syn::Type::Slice(s) => {
1660 write!(w, "[").unwrap();
1661 self.write_rust_type(w, generics, &s.elem);
1662 write!(w, "]").unwrap();
1664 syn::Type::Tuple(s) => {
1665 write!(w, "(").unwrap();
1666 for (idx, t) in s.elems.iter().enumerate() {
1667 if idx != 0 { write!(w, ", ").unwrap(); }
1668 self.write_rust_type(w, generics, &t);
1670 write!(w, ")").unwrap();
1672 _ => unimplemented!(),
1676 /// Prints a constructor for something which is "uninitialized" (but obviously not actually
1677 /// unint'd memory).
1678 pub fn write_empty_rust_val<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) {
1680 syn::Type::Reference(r) => {
1681 self.write_empty_rust_val(generics, w, &*r.elem)
1683 syn::Type::Path(p) => {
1684 let resolved = self.resolve_path(&p.path, generics);
1685 if self.crate_types.opaques.get(&resolved).is_some() {
1686 write!(w, "crate::{} {{ inner: std::ptr::null_mut(), is_owned: true }}", resolved).unwrap();
1688 // Assume its a manually-mapped C type, where we can just define an null() fn
1689 write!(w, "{}::null()", self.c_type_from_path(&resolved, false, false).unwrap()).unwrap();
1692 syn::Type::Array(a) => {
1693 if let syn::Expr::Lit(l) = &a.len {
1694 if let syn::Lit::Int(i) = &l.lit {
1695 if i.base10_digits().parse::<usize>().unwrap() < 32 {
1696 // Blindly assume that if we're trying to create an empty value for an
1697 // array < 32 entries that all-0s may be a valid state.
1700 let arrty = format!("[u8; {}]", i.base10_digits());
1701 write!(w, "{}", self.to_c_conversion_inline_prefix_from_path(&arrty, false, false).unwrap()).unwrap();
1702 write!(w, "[0; {}]", i.base10_digits()).unwrap();
1703 write!(w, "{}", self.to_c_conversion_inline_suffix_from_path(&arrty, false, false).unwrap()).unwrap();
1704 } else { unimplemented!(); }
1705 } else { unimplemented!(); }
1707 _ => unimplemented!(),
1711 fn is_real_type_array(&self, resolved_type: &str) -> Option<syn::Type> {
1712 if let Some(real_ty) = self.c_type_from_path(&resolved_type, true, false) {
1713 if real_ty.ends_with("]") && real_ty.starts_with("*const [u8; ") {
1714 let mut split = real_ty.split("; ");
1715 split.next().unwrap();
1716 let tail_str = split.next().unwrap();
1717 assert!(split.next().is_none());
1718 let len = usize::from_str_radix(&tail_str[..tail_str.len() - 1], 10).unwrap();
1719 Some(parse_quote!([u8; #len]))
1724 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1725 /// See EmptyValExpectedTy for information on return types.
1726 fn write_empty_rust_val_check_suffix<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) -> EmptyValExpectedTy {
1728 syn::Type::Reference(r) => {
1729 return self.write_empty_rust_val_check_suffix(generics, w, &*r.elem);
1731 syn::Type::Path(p) => {
1732 let resolved = self.resolve_path(&p.path, generics);
1733 if let Some(arr_ty) = self.is_real_type_array(&resolved) {
1734 write!(w, ".data").unwrap();
1735 return self.write_empty_rust_val_check_suffix(generics, w, &arr_ty);
1737 if self.crate_types.opaques.get(&resolved).is_some() {
1738 write!(w, ".inner.is_null()").unwrap();
1739 EmptyValExpectedTy::NonPointer
1741 if let Some(suffix) = self.empty_val_check_suffix_from_path(&resolved) {
1742 write!(w, "{}", suffix).unwrap();
1743 // We may eventually need to allow empty_val_check_suffix_from_path to specify if we need a deref or not
1744 EmptyValExpectedTy::NonPointer
1746 write!(w, ".is_none()").unwrap();
1747 EmptyValExpectedTy::OptionType
1751 syn::Type::Array(a) => {
1752 if let syn::Expr::Lit(l) = &a.len {
1753 if let syn::Lit::Int(i) = &l.lit {
1754 write!(w, " == [0; {}]", i.base10_digits()).unwrap();
1755 EmptyValExpectedTy::NonPointer
1756 } else { unimplemented!(); }
1757 } else { unimplemented!(); }
1759 syn::Type::Slice(_) => {
1760 // Option<[]> always implies that we want to treat len() == 0 differently from
1761 // None, so we always map an Option<[]> into a pointer.
1762 write!(w, " == std::ptr::null_mut()").unwrap();
1763 EmptyValExpectedTy::ReferenceAsPointer
1765 _ => unimplemented!(),
1769 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1770 pub fn write_empty_rust_val_check<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type, var_access: &str) {
1772 syn::Type::Reference(r) => {
1773 self.write_empty_rust_val_check(generics, w, &*r.elem, var_access);
1775 syn::Type::Path(_) => {
1776 write!(w, "{}", var_access).unwrap();
1777 self.write_empty_rust_val_check_suffix(generics, w, t);
1779 syn::Type::Array(a) => {
1780 if let syn::Expr::Lit(l) = &a.len {
1781 if let syn::Lit::Int(i) = &l.lit {
1782 let arrty = format!("[u8; {}]", i.base10_digits());
1783 // We don't (yet) support a new-var conversion here.
1784 assert!(self.from_c_conversion_new_var_from_path(&arrty, false).is_none());
1786 self.from_c_conversion_prefix_from_path(&arrty, false).unwrap(),
1788 self.from_c_conversion_suffix_from_path(&arrty, false).unwrap()).unwrap();
1789 self.write_empty_rust_val_check_suffix(generics, w, t);
1790 } else { unimplemented!(); }
1791 } else { unimplemented!(); }
1793 _ => unimplemented!(),
1797 // ********************************
1798 // *** Type conversion printing ***
1799 // ********************************
1801 /// Returns true we if can just skip passing this to C entirely
1802 pub fn skip_arg(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
1804 syn::Type::Path(p) => {
1805 if p.qself.is_some() { unimplemented!(); }
1806 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1807 self.skip_path(&full_path)
1810 syn::Type::Reference(r) => {
1811 self.skip_arg(&*r.elem, generics)
1816 pub fn no_arg_to_rust<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1818 syn::Type::Path(p) => {
1819 if p.qself.is_some() { unimplemented!(); }
1820 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1821 write!(w, "{}", self.no_arg_path_to_rust(&full_path)).unwrap();
1824 syn::Type::Reference(r) => {
1825 self.no_arg_to_rust(w, &*r.elem, generics);
1831 fn write_conversion_inline_intern<W: std::io::Write,
1832 LP: Fn(&str, bool, bool) -> Option<String>, DL: Fn(&mut W, &DeclType, &str, bool, bool), SC: Fn(bool, Option<&str>) -> String>
1833 (&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool,
1834 tupleconv: &str, prefix: bool, sliceconv: SC, path_lookup: LP, decl_lookup: DL) {
1835 match generics.resolve_type(t) {
1836 syn::Type::Reference(r) => {
1837 self.write_conversion_inline_intern(w, &*r.elem, generics, true, r.mutability.is_some(),
1838 ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1840 syn::Type::Path(p) => {
1841 if p.qself.is_some() {
1845 let resolved_path = self.resolve_path(&p.path, generics);
1846 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1847 return self.write_conversion_inline_intern(w, aliased_type, None, is_ref, is_mut, ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1848 } else if self.is_primitive(&resolved_path) {
1849 if is_ref && prefix {
1850 write!(w, "*").unwrap();
1852 } else if let Some(c_type) = path_lookup(&resolved_path, is_ref, ptr_for_ref) {
1853 write!(w, "{}", c_type).unwrap();
1854 } else if self.crate_types.opaques.get(&resolved_path).is_some() {
1855 decl_lookup(w, &DeclType::StructImported, &resolved_path, is_ref, is_mut);
1856 } else if self.crate_types.mirrored_enums.get(&resolved_path).is_some() {
1857 decl_lookup(w, &DeclType::MirroredEnum, &resolved_path, is_ref, is_mut);
1858 } else if let Some(t) = self.crate_types.traits.get(&resolved_path) {
1859 decl_lookup(w, &DeclType::Trait(t), &resolved_path, is_ref, is_mut);
1860 } else if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
1861 if let Some(decl_type) = self.types.maybe_resolve_declared(ident) {
1862 decl_lookup(w, decl_type, &self.maybe_resolve_ident(ident).unwrap(), is_ref, is_mut);
1863 } else { unimplemented!(); }
1864 } else { unimplemented!(); }
1866 syn::Type::Array(a) => {
1867 // We assume all arrays contain only [int_literal; X]s.
1868 // This may result in some outputs not compiling.
1869 if let syn::Expr::Lit(l) = &a.len {
1870 if let syn::Lit::Int(i) = &l.lit {
1871 write!(w, "{}", path_lookup(&format!("[u8; {}]", i.base10_digits()), is_ref, ptr_for_ref).unwrap()).unwrap();
1872 } else { unimplemented!(); }
1873 } else { unimplemented!(); }
1875 syn::Type::Slice(s) => {
1876 // We assume all slices contain only literals or references.
1877 // This may result in some outputs not compiling.
1878 if let syn::Type::Path(p) = &*s.elem {
1879 let resolved = self.resolve_path(&p.path, generics);
1880 assert!(self.is_primitive(&resolved));
1881 write!(w, "{}", path_lookup("[u8]", is_ref, ptr_for_ref).unwrap()).unwrap();
1882 } else if let syn::Type::Reference(r) = &*s.elem {
1883 if let syn::Type::Path(p) = &*r.elem {
1884 write!(w, "{}", sliceconv(self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)), None)).unwrap();
1885 } else if let syn::Type::Slice(_) = &*r.elem {
1886 write!(w, "{}", sliceconv(false, None)).unwrap();
1887 } else { unimplemented!(); }
1888 } else if let syn::Type::Tuple(t) = &*s.elem {
1889 assert!(!t.elems.is_empty());
1891 write!(w, "{}", sliceconv(false, None)).unwrap();
1893 let mut needs_map = false;
1894 for e in t.elems.iter() {
1895 if let syn::Type::Reference(_) = e {
1900 let mut map_str = Vec::new();
1901 write!(&mut map_str, ".map(|(").unwrap();
1902 for i in 0..t.elems.len() {
1903 write!(&mut map_str, "{}{}", if i != 0 { ", " } else { "" }, ('a' as u8 + i as u8) as char).unwrap();
1905 write!(&mut map_str, ")| (").unwrap();
1906 for (idx, e) in t.elems.iter().enumerate() {
1907 if let syn::Type::Reference(_) = e {
1908 write!(&mut map_str, "{}{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1909 } else if let syn::Type::Path(_) = e {
1910 write!(&mut map_str, "{}*{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1911 } else { unimplemented!(); }
1913 write!(&mut map_str, "))").unwrap();
1914 write!(w, "{}", sliceconv(false, Some(&String::from_utf8(map_str).unwrap()))).unwrap();
1916 write!(w, "{}", sliceconv(false, None)).unwrap();
1919 } else { unimplemented!(); }
1921 syn::Type::Tuple(t) => {
1922 if t.elems.is_empty() {
1923 // cbindgen has poor support for (), see, eg https://github.com/eqrion/cbindgen/issues/527
1924 // so work around it by just pretending its a 0u8
1925 write!(w, "{}", tupleconv).unwrap();
1927 if prefix { write!(w, "local_").unwrap(); }
1930 _ => unimplemented!(),
1934 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) {
1935 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "() /*", true, |_, _| "local_".to_owned(),
1936 |a, b, c| self.to_c_conversion_inline_prefix_from_path(a, b, c),
1937 |w, decl_type, decl_path, is_ref, _is_mut| {
1939 DeclType::MirroredEnum if is_ref && ptr_for_ref => write!(w, "crate::{}::from_native(", decl_path).unwrap(),
1940 DeclType::MirroredEnum if is_ref => write!(w, "&crate::{}::from_native(", decl_path).unwrap(),
1941 DeclType::MirroredEnum => write!(w, "crate::{}::native_into(", decl_path).unwrap(),
1942 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1943 write!(w, "crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1944 DeclType::EnumIgnored|DeclType::StructImported if is_ref => {
1945 if !ptr_for_ref { write!(w, "&").unwrap(); }
1946 write!(w, "crate::{} {{ inner: unsafe {{ ObjOps::nonnull_ptr_to_inner((", decl_path).unwrap()
1948 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1949 write!(w, "crate::{} {{ inner: ", decl_path).unwrap(),
1950 DeclType::EnumIgnored|DeclType::StructImported if !is_ref =>
1951 write!(w, "crate::{} {{ inner: ObjOps::heap_alloc(", decl_path).unwrap(),
1952 DeclType::Trait(_) if is_ref => write!(w, "").unwrap(),
1953 DeclType::Trait(_) if !is_ref => write!(w, "Into::into(").unwrap(),
1954 _ => panic!("{:?}", decl_path),
1958 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) {
1959 self.write_to_c_conversion_inline_prefix_inner(w, t, generics, false, ptr_for_ref, false);
1961 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) {
1962 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "*/", false, |_, _| ".into()".to_owned(),
1963 |a, b, c| self.to_c_conversion_inline_suffix_from_path(a, b, c),
1964 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1965 DeclType::MirroredEnum => write!(w, ")").unwrap(),
1966 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1967 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1968 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1969 write!(w, " as *const _) as *mut _) }}, is_owned: false }}").unwrap(),
1970 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1971 write!(w, ", is_owned: true }}").unwrap(),
1972 DeclType::EnumIgnored|DeclType::StructImported if !is_ref => write!(w, "), is_owned: true }}").unwrap(),
1973 DeclType::Trait(_) if is_ref => {},
1974 DeclType::Trait(_) => {
1975 // This is used when we're converting a concrete Rust type into a C trait
1976 // for use when a Rust trait method returns an associated type.
1977 // Because all of our C traits implement From<RustTypesImplementingTraits>
1978 // we can just call .into() here and be done.
1979 write!(w, ")").unwrap()
1981 _ => unimplemented!(),
1984 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) {
1985 self.write_to_c_conversion_inline_suffix_inner(w, t, generics, false, ptr_for_ref, false);
1988 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) {
1989 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "() /*", true, |_, _| "&local_".to_owned(),
1990 |a, b, _c| self.from_c_conversion_prefix_from_path(a, b),
1991 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1992 DeclType::StructImported if is_ref => write!(w, "").unwrap(),
1993 DeclType::StructImported if !is_ref => write!(w, "*unsafe {{ Box::from_raw(").unwrap(),
1994 DeclType::MirroredEnum if is_ref => write!(w, "&").unwrap(),
1995 DeclType::MirroredEnum => {},
1996 DeclType::Trait(_) => {},
1997 _ => unimplemented!(),
2000 pub fn write_from_c_conversion_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
2001 self.write_from_c_conversion_prefix_inner(w, t, generics, false, false);
2003 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) {
2004 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "*/", false,
2005 |has_inner, map_str_opt| match (has_inner, map_str_opt) {
2006 (false, Some(map_str)) => format!(".iter(){}.collect::<Vec<_>>()[..]", map_str),
2007 (false, None) => ".iter().collect::<Vec<_>>()[..]".to_owned(),
2008 (true, None) => "[..]".to_owned(),
2009 (true, Some(_)) => unreachable!(),
2011 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
2012 |w, decl_type, _full_path, is_ref, is_mut| match decl_type {
2013 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, "XXX unimplemented").unwrap(),
2014 DeclType::StructImported if is_mut && is_ref => write!(w, ".get_native_mut_ref()").unwrap(),
2015 DeclType::StructImported if is_ref => write!(w, ".get_native_ref()").unwrap(),
2016 DeclType::StructImported if !is_ref => write!(w, ".take_inner()) }}").unwrap(),
2017 DeclType::MirroredEnum if is_ref => write!(w, ".to_native()").unwrap(),
2018 DeclType::MirroredEnum => write!(w, ".into_native()").unwrap(),
2019 DeclType::Trait(_) => {},
2020 _ => unimplemented!(),
2023 pub fn write_from_c_conversion_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
2024 self.write_from_c_conversion_suffix_inner(w, t, generics, false, false);
2026 // Note that compared to the above conversion functions, the following two are generally
2027 // significantly undertested:
2028 pub fn write_from_c_conversion_to_ref_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
2029 self.write_conversion_inline_intern(w, t, generics, false, false, false, "() /*", true, |_, _| "&local_".to_owned(),
2031 if let Some(conv) = self.from_c_conversion_prefix_from_path(a, b) {
2032 Some(format!("&{}", conv))
2035 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
2036 DeclType::StructImported if !is_ref => write!(w, "").unwrap(),
2037 _ => unimplemented!(),
2040 pub fn write_from_c_conversion_to_ref_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
2041 self.write_conversion_inline_intern(w, t, generics, false, false, false, "*/", false,
2042 |has_inner, map_str_opt| match (has_inner, map_str_opt) {
2043 (false, Some(map_str)) => format!(".iter(){}.collect::<Vec<_>>()[..]", map_str),
2044 (false, None) => ".iter().collect::<Vec<_>>()[..]".to_owned(),
2045 (true, None) => "[..]".to_owned(),
2046 (true, Some(_)) => unreachable!(),
2048 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
2049 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
2050 DeclType::StructImported if !is_ref => write!(w, ".get_native_ref()").unwrap(),
2051 _ => unimplemented!(),
2055 fn write_conversion_new_var_intern<'b, W: std::io::Write,
2056 LP: Fn(&str, bool) -> Option<(&str, &str)>,
2057 LC: Fn(&str, bool, Option<&syn::Type>, &syn::Ident, &str) -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)>,
2058 VP: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool),
2059 VS: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool)>
2060 (&self, w: &mut W, ident: &syn::Ident, var: &str, t: &syn::Type, generics: Option<&GenericTypes>,
2061 mut is_ref: bool, mut ptr_for_ref: bool, to_c: bool,
2062 path_lookup: &LP, container_lookup: &LC, var_prefix: &VP, var_suffix: &VS) -> bool {
2064 macro_rules! convert_container {
2065 ($container_type: expr, $args_len: expr, $args_iter: expr) => { {
2066 // For slices (and Options), we refuse to directly map them as is_ref when they
2067 // aren't opaque types containing an inner pointer. This is due to the fact that,
2068 // in both cases, the actual higher-level type is non-is_ref.
2069 let ty_has_inner = if $args_len == 1 {
2070 let ty = $args_iter().next().unwrap();
2071 if $container_type == "Slice" && to_c {
2072 // "To C ptr_for_ref" means "return the regular object with is_owned
2073 // set to false", which is totally what we want in a slice if we're about to
2074 // set ty_has_inner.
2077 if let syn::Type::Reference(t) = ty {
2078 if let syn::Type::Path(p) = &*t.elem {
2079 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2081 } else if let syn::Type::Path(p) = ty {
2082 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2086 // Options get a bunch of special handling, since in general we map Option<>al
2087 // types into the same C type as non-Option-wrapped types. This ends up being
2088 // pretty manual here and most of the below special-cases are for Options.
2089 let mut needs_ref_map = false;
2090 let mut only_contained_type = None;
2091 let mut only_contained_type_nonref = None;
2092 let mut only_contained_has_inner = false;
2093 let mut contains_slice = false;
2095 only_contained_has_inner = ty_has_inner;
2096 let arg = $args_iter().next().unwrap();
2097 if let syn::Type::Reference(t) = arg {
2098 only_contained_type = Some(arg);
2099 only_contained_type_nonref = Some(&*t.elem);
2100 if let syn::Type::Path(_) = &*t.elem {
2102 } else if let syn::Type::Slice(_) = &*t.elem {
2103 contains_slice = true;
2104 } else { return false; }
2105 // If the inner element contains an inner pointer, we will just use that,
2106 // avoiding the need to map elements to references. Otherwise we'll need to
2107 // do an extra mapping step.
2108 needs_ref_map = !only_contained_has_inner;
2110 only_contained_type = Some(arg);
2111 only_contained_type_nonref = Some(arg);
2115 if let Some((prefix, conversions, suffix, prefix_location)) = container_lookup(&$container_type, is_ref && ty_has_inner, only_contained_type, ident, var) {
2116 assert_eq!(conversions.len(), $args_len);
2117 write!(w, "let mut local_{}{} = ", ident,
2118 if (!to_c && needs_ref_map) || (to_c && $container_type == "Option" && contains_slice) {"_base"} else { "" }).unwrap();
2119 if prefix_location == ContainerPrefixLocation::OutsideConv {
2120 var_prefix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
2122 write!(w, "{}{}", prefix, var).unwrap();
2124 for ((pfx, var_name), (idx, ty)) in conversions.iter().zip($args_iter().enumerate()) {
2125 let mut var = std::io::Cursor::new(Vec::new());
2126 write!(&mut var, "{}", var_name).unwrap();
2127 let var_access = String::from_utf8(var.into_inner()).unwrap();
2129 let conv_ty = if needs_ref_map { only_contained_type_nonref.as_ref().unwrap() } else { ty };
2131 write!(w, "{} {{ ", pfx).unwrap();
2132 let new_var_name = format!("{}_{}", ident, idx);
2133 let new_var = self.write_conversion_new_var_intern(w, &format_ident!("{}", new_var_name),
2134 &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);
2135 if new_var { write!(w, " ").unwrap(); }
2137 if prefix_location == ContainerPrefixLocation::PerConv {
2138 var_prefix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2139 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
2140 write!(w, "ObjOps::heap_alloc(").unwrap();
2143 write!(w, "{}{}", if contains_slice && !to_c { "local_" } else { "" }, if new_var { new_var_name } else { var_access }).unwrap();
2144 if prefix_location == ContainerPrefixLocation::PerConv {
2145 var_suffix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2146 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
2147 write!(w, ")").unwrap();
2149 write!(w, " }}").unwrap();
2151 write!(w, "{}", suffix).unwrap();
2152 if prefix_location == ContainerPrefixLocation::OutsideConv {
2153 var_suffix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
2155 write!(w, ";").unwrap();
2156 if !to_c && needs_ref_map {
2157 write!(w, " let mut local_{} = local_{}_base.as_ref()", ident, ident).unwrap();
2159 write!(w, ".map(|a| &a[..])").unwrap();
2161 write!(w, ";").unwrap();
2162 } else if to_c && $container_type == "Option" && contains_slice {
2163 write!(w, " let mut local_{} = *local_{}_base;", ident, ident).unwrap();
2170 match generics.resolve_type(t) {
2171 syn::Type::Reference(r) => {
2172 if let syn::Type::Slice(_) = &*r.elem {
2173 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)
2175 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)
2178 syn::Type::Path(p) => {
2179 if p.qself.is_some() {
2182 let resolved_path = self.resolve_path(&p.path, generics);
2183 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
2184 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);
2186 if self.is_known_container(&resolved_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
2187 if let syn::PathArguments::AngleBracketed(args) = &p.path.segments.iter().next().unwrap().arguments {
2188 convert_container!(resolved_path, args.args.len(), || args.args.iter().map(|arg| {
2189 if let syn::GenericArgument::Type(ty) = arg {
2190 generics.resolve_type(ty)
2191 } else { unimplemented!(); }
2193 } else { unimplemented!(); }
2195 if self.is_primitive(&resolved_path) {
2197 } else if let Some(ty_ident) = single_ident_generic_path_to_ident(&p.path) {
2198 if let Some((prefix, suffix)) = path_lookup(&resolved_path, is_ref) {
2199 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
2201 } else if self.types.maybe_resolve_declared(ty_ident).is_some() {
2206 syn::Type::Array(_) => {
2207 // We assume all arrays contain only primitive types.
2208 // This may result in some outputs not compiling.
2211 syn::Type::Slice(s) => {
2212 if let syn::Type::Path(p) = &*s.elem {
2213 let resolved = self.resolve_path(&p.path, generics);
2214 assert!(self.is_primitive(&resolved));
2215 let slice_path = format!("[{}]", resolved);
2216 if let Some((prefix, suffix)) = path_lookup(&slice_path, true) {
2217 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
2220 } else if let syn::Type::Reference(ty) = &*s.elem {
2221 let tyref = [&*ty.elem];
2223 convert_container!("Slice", 1, || tyref.iter().map(|t| generics.resolve_type(*t)));
2224 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
2225 } else if let syn::Type::Tuple(t) = &*s.elem {
2226 // When mapping into a temporary new var, we need to own all the underlying objects.
2227 // Thus, we drop any references inside the tuple and convert with non-reference types.
2228 let mut elems = syn::punctuated::Punctuated::new();
2229 for elem in t.elems.iter() {
2230 if let syn::Type::Reference(r) = elem {
2231 elems.push((*r.elem).clone());
2233 elems.push(elem.clone());
2236 let ty = [syn::Type::Tuple(syn::TypeTuple {
2237 paren_token: t.paren_token, elems
2241 convert_container!("Slice", 1, || ty.iter());
2242 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
2243 } else { unimplemented!() }
2245 syn::Type::Tuple(t) => {
2246 if !t.elems.is_empty() {
2247 // We don't (yet) support tuple elements which cannot be converted inline
2248 write!(w, "let (").unwrap();
2249 for idx in 0..t.elems.len() {
2250 if idx != 0 { write!(w, ", ").unwrap(); }
2251 write!(w, "{} orig_{}_{}", if is_ref { "ref" } else { "mut" }, ident, idx).unwrap();
2253 write!(w, ") = {}{}; ", var, if !to_c { ".to_rust()" } else { "" }).unwrap();
2254 // Like other template types, tuples are always mapped as their non-ref
2255 // versions for types which have different ref mappings. Thus, we convert to
2256 // non-ref versions and handle opaque types with inner pointers manually.
2257 for (idx, elem) in t.elems.iter().enumerate() {
2258 if let syn::Type::Path(p) = elem {
2259 let v_name = format!("orig_{}_{}", ident, idx);
2260 let tuple_elem_ident = format_ident!("{}", &v_name);
2261 if self.write_conversion_new_var_intern(w, &tuple_elem_ident, &v_name, elem, generics,
2262 false, ptr_for_ref, to_c,
2263 path_lookup, container_lookup, var_prefix, var_suffix) {
2264 write!(w, " ").unwrap();
2265 // Opaque types with inner pointers shouldn't ever create new stack
2266 // variables, so we don't handle it and just assert that it doesn't
2268 assert!(!self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)));
2272 write!(w, "let mut local_{} = (", ident).unwrap();
2273 for (idx, elem) in t.elems.iter().enumerate() {
2274 let ty_has_inner = {
2276 // "To C ptr_for_ref" means "return the regular object with
2277 // is_owned set to false", which is totally what we want
2278 // if we're about to set ty_has_inner.
2281 if let syn::Type::Reference(t) = elem {
2282 if let syn::Type::Path(p) = &*t.elem {
2283 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2285 } else if let syn::Type::Path(p) = elem {
2286 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2289 if idx != 0 { write!(w, ", ").unwrap(); }
2290 var_prefix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2291 if is_ref && ty_has_inner {
2292 // For ty_has_inner, the regular var_prefix mapping will take a
2293 // reference, so deref once here to make sure we keep the original ref.
2294 write!(w, "*").unwrap();
2296 write!(w, "orig_{}_{}", ident, idx).unwrap();
2297 if is_ref && !ty_has_inner {
2298 // If we don't have an inner variable's reference to maintain, just
2299 // hope the type is Clonable and use that.
2300 write!(w, ".clone()").unwrap();
2302 var_suffix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2304 write!(w, "){};", if to_c { ".into()" } else { "" }).unwrap();
2308 _ => unimplemented!(),
2312 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 {
2313 self.write_conversion_new_var_intern(w, ident, var_access, t, generics, false, ptr_for_ref, true,
2314 &|a, b| self.to_c_conversion_new_var_from_path(a, b),
2315 &|a, b, c, d, e| self.to_c_conversion_container_new_var(generics, a, b, c, d, e),
2316 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
2317 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_prefix_inner(a, b, c, d, e, f),
2318 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_suffix_inner(a, b, c, d, e, f))
2320 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 {
2321 self.write_to_c_conversion_new_var_inner(w, ident, &format!("{}", ident), t, generics, ptr_for_ref)
2323 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 {
2324 self.write_conversion_new_var_intern(w, ident, &format!("{}", ident), t, generics, false, false, false,
2325 &|a, b| self.from_c_conversion_new_var_from_path(a, b),
2326 &|a, b, c, d, e| self.from_c_conversion_container_new_var(generics, a, b, c, d, e),
2327 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
2328 &|a, b, c, d, e, _f| self.write_from_c_conversion_prefix_inner(a, b, c, d, e),
2329 &|a, b, c, d, e, _f| self.write_from_c_conversion_suffix_inner(a, b, c, d, e))
2332 // ******************************************************
2333 // *** C Container Type Equivalent and alias Printing ***
2334 // ******************************************************
2336 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 {
2337 for (idx, t) in args.enumerate() {
2339 write!(w, ", ").unwrap();
2341 if let syn::Type::Reference(r_arg) = t {
2342 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2344 if !self.write_c_type_intern(w, &*r_arg.elem, generics, false, false, false, false) { return false; }
2346 // While write_c_type_intern, above is correct, we don't want to blindly convert a
2347 // reference to something stupid, so check that the container is either opaque or a
2348 // predefined type (currently only Transaction).
2349 if let syn::Type::Path(p_arg) = &*r_arg.elem {
2350 let resolved = self.resolve_path(&p_arg.path, generics);
2351 assert!(self.crate_types.opaques.get(&resolved).is_some() ||
2352 self.c_type_from_path(&resolved, true, true).is_some(), "Template generics should be opaque or have a predefined mapping");
2353 } else { unimplemented!(); }
2354 } else if let syn::Type::Path(p_arg) = t {
2355 if let Some(resolved) = self.maybe_resolve_path(&p_arg.path, generics) {
2356 if !self.is_primitive(&resolved) {
2357 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2360 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2362 if !self.write_c_type_intern(w, t, generics, false, false, false, false) { return false; }
2364 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2365 if !self.write_c_type_intern(w, t, generics, false, false, false, false) { return false; }
2370 fn check_create_container(&self, mangled_container: String, container_type: &str, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
2371 if !self.crate_types.templates_defined.borrow().get(&mangled_container).is_some() {
2372 let mut created_container: Vec<u8> = Vec::new();
2374 if container_type == "Result" {
2375 let mut a_ty: Vec<u8> = Vec::new();
2376 if let syn::Type::Tuple(tup) = args.iter().next().unwrap() {
2377 if tup.elems.is_empty() {
2378 write!(&mut a_ty, "()").unwrap();
2380 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
2383 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
2386 let mut b_ty: Vec<u8> = Vec::new();
2387 if let syn::Type::Tuple(tup) = args.iter().skip(1).next().unwrap() {
2388 if tup.elems.is_empty() {
2389 write!(&mut b_ty, "()").unwrap();
2391 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
2394 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
2397 let ok_str = String::from_utf8(a_ty).unwrap();
2398 let err_str = String::from_utf8(b_ty).unwrap();
2399 let is_clonable = self.is_clonable(&ok_str) && self.is_clonable(&err_str);
2400 write_result_block(&mut created_container, &mangled_container, &ok_str, &err_str, is_clonable);
2402 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2404 } else if container_type == "Vec" {
2405 let mut a_ty: Vec<u8> = Vec::new();
2406 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2407 let ty = String::from_utf8(a_ty).unwrap();
2408 let is_clonable = self.is_clonable(&ty);
2409 write_vec_block(&mut created_container, &mangled_container, &ty, is_clonable);
2411 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2413 } else if container_type.ends_with("Tuple") {
2414 let mut tuple_args = Vec::new();
2415 let mut is_clonable = true;
2416 for arg in args.iter() {
2417 let mut ty: Vec<u8> = Vec::new();
2418 if !self.write_template_generics(&mut ty, &mut [arg].iter().map(|t| **t), generics, is_ref) { return false; }
2419 let ty_str = String::from_utf8(ty).unwrap();
2420 if !self.is_clonable(&ty_str) {
2421 is_clonable = false;
2423 tuple_args.push(ty_str);
2425 write_tuple_block(&mut created_container, &mangled_container, &tuple_args, is_clonable);
2427 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2429 } else if container_type == "Option" {
2430 let mut a_ty: Vec<u8> = Vec::new();
2431 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2432 let ty = String::from_utf8(a_ty).unwrap();
2433 let is_clonable = self.is_clonable(&ty);
2434 write_option_block(&mut created_container, &mangled_container, &ty, is_clonable);
2436 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2441 self.crate_types.write_new_template(mangled_container.clone(), true, &created_container);
2445 fn path_to_generic_args(path: &syn::Path) -> Vec<&syn::Type> {
2446 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().next().unwrap().arguments {
2447 args.args.iter().map(|gen| if let syn::GenericArgument::Type(t) = gen { t } else { unimplemented!() }).collect()
2448 } else { unimplemented!(); }
2450 fn write_c_mangled_container_path_intern<W: std::io::Write>
2451 (&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 {
2452 let mut mangled_type: Vec<u8> = Vec::new();
2453 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a), generics) {
2454 write!(w, "C{}_", ident).unwrap();
2455 write!(mangled_type, "C{}_", ident).unwrap();
2456 } else { assert_eq!(args.len(), 1); }
2457 for arg in args.iter() {
2458 macro_rules! write_path {
2459 ($p_arg: expr, $extra_write: expr) => {
2460 if let Some(subtype) = self.maybe_resolve_path(&$p_arg.path, generics) {
2461 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a), generics) {
2463 if self.c_type_has_inner_from_path(&subtype) {
2464 if !self.write_c_path_intern(w, &$p_arg.path, generics, is_ref, is_mut, ptr_for_ref, false) { return false; }
2466 if let Some(arr_ty) = self.is_real_type_array(&subtype) {
2467 if !self.write_c_type_intern(w, &arr_ty, generics, false, true, false, false) { return false; }
2469 // Option<T> needs to be converted to a *mut T, ie mut ptr-for-ref
2470 if !self.write_c_path_intern(w, &$p_arg.path, generics, true, true, true, false) { return false; }
2474 write!(w, "{}", $p_arg.path.segments.last().unwrap().ident).unwrap();
2476 } else if self.is_known_container(&subtype, is_ref) || self.is_path_transparent_container(&$p_arg.path, generics, is_ref) {
2477 if !self.write_c_mangled_container_path_intern(w, Self::path_to_generic_args(&$p_arg.path), generics,
2478 &subtype, is_ref, is_mut, ptr_for_ref, true) {
2481 self.write_c_mangled_container_path_intern(&mut mangled_type, Self::path_to_generic_args(&$p_arg.path),
2482 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2483 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2484 self.write_c_mangled_container_path_intern(w2, Self::path_to_generic_args(&$p_arg.path),
2485 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2488 let id = subtype.rsplitn(2, ':').next().unwrap(); // Get the "Base" name of the resolved type
2489 write!(w, "{}", id).unwrap();
2490 write!(mangled_type, "{}", id).unwrap();
2491 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2492 write!(w2, "{}", id).unwrap();
2495 } else { return false; }
2498 match generics.resolve_type(arg) {
2499 syn::Type::Tuple(tuple) => {
2500 if tuple.elems.len() == 0 {
2501 write!(w, "None").unwrap();
2502 write!(mangled_type, "None").unwrap();
2504 let mut mangled_tuple_type: Vec<u8> = Vec::new();
2506 // Figure out what the mangled type should look like. To disambiguate
2507 // ((A, B), C) and (A, B, C) we prefix the generic args with a _ and suffix
2508 // them with a Z. Ideally we wouldn't use Z, but not many special chars are
2509 // available for use in type names.
2510 write!(w, "C{}Tuple_", tuple.elems.len()).unwrap();
2511 write!(mangled_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2512 write!(mangled_tuple_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2513 for elem in tuple.elems.iter() {
2514 if let syn::Type::Path(p) = elem {
2515 write_path!(p, Some(&mut mangled_tuple_type));
2516 } else if let syn::Type::Reference(refelem) = elem {
2517 if let syn::Type::Path(p) = &*refelem.elem {
2518 write_path!(p, Some(&mut mangled_tuple_type));
2519 } else { return false; }
2520 } else { return false; }
2522 write!(w, "Z").unwrap();
2523 write!(mangled_type, "Z").unwrap();
2524 write!(mangled_tuple_type, "Z").unwrap();
2525 if !self.check_create_container(String::from_utf8(mangled_tuple_type).unwrap(),
2526 &format!("{}Tuple", tuple.elems.len()), tuple.elems.iter().collect(), generics, is_ref) {
2531 syn::Type::Path(p_arg) => {
2532 write_path!(p_arg, None);
2534 syn::Type::Reference(refty) => {
2535 if let syn::Type::Path(p_arg) = &*refty.elem {
2536 write_path!(p_arg, None);
2537 } else if let syn::Type::Slice(_) = &*refty.elem {
2538 // write_c_type will actually do exactly what we want here, we just need to
2539 // make it a pointer so that its an option. Note that we cannot always convert
2540 // the Vec-as-slice (ie non-ref types) containers, so sometimes need to be able
2541 // to edit it, hence we use *mut here instead of *const.
2542 if args.len() != 1 { return false; }
2543 write!(w, "*mut ").unwrap();
2544 self.write_c_type(w, arg, None, true);
2545 } else { return false; }
2547 syn::Type::Array(a) => {
2548 if let syn::Type::Path(p_arg) = &*a.elem {
2549 let resolved = self.resolve_path(&p_arg.path, generics);
2550 if !self.is_primitive(&resolved) { return false; }
2551 if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(len), .. }) = &a.len {
2552 if self.c_type_from_path(&format!("[{}; {}]", resolved, len.base10_digits()), is_ref, ptr_for_ref).is_none() { return false; }
2553 write!(w, "_{}{}", resolved, len.base10_digits()).unwrap();
2554 write!(mangled_type, "_{}{}", resolved, len.base10_digits()).unwrap();
2555 } else { return false; }
2556 } else { return false; }
2558 _ => { return false; },
2561 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a), generics) { return true; }
2562 // Push the "end of type" Z
2563 write!(w, "Z").unwrap();
2564 write!(mangled_type, "Z").unwrap();
2566 // Make sure the type is actually defined:
2567 self.check_create_container(String::from_utf8(mangled_type).unwrap(), ident, args, generics, is_ref)
2569 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 {
2570 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a), generics) {
2571 write!(w, "{}::", Self::generated_container_path()).unwrap();
2573 self.write_c_mangled_container_path_intern(w, args, generics, ident, is_ref, is_mut, ptr_for_ref, false)
2575 pub fn get_c_mangled_container_type(&self, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, template_name: &str) -> Option<String> {
2576 let mut out = Vec::new();
2577 if !self.write_c_mangled_container_path(&mut out, args, generics, template_name, false, false, false) {
2580 Some(String::from_utf8(out).unwrap())
2583 // **********************************
2584 // *** C Type Equivalent Printing ***
2585 // **********************************
2587 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, with_ref_lifetime: bool) -> bool {
2588 let full_path = match self.maybe_resolve_path(&path, generics) {
2589 Some(path) => path, None => return false };
2590 if let Some(c_type) = self.c_type_from_path(&full_path, is_ref, ptr_for_ref) {
2591 write!(w, "{}", c_type).unwrap();
2593 } else if self.crate_types.traits.get(&full_path).is_some() {
2594 if is_ref && ptr_for_ref {
2595 write!(w, "*{} crate::{}", if is_mut { "mut" } else { "const" }, full_path).unwrap();
2597 if with_ref_lifetime { unimplemented!(); }
2598 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2600 write!(w, "crate::{}", full_path).unwrap();
2603 } else if self.crate_types.opaques.get(&full_path).is_some() || self.crate_types.mirrored_enums.get(&full_path).is_some() {
2604 if is_ref && ptr_for_ref {
2605 // ptr_for_ref implies we're returning the object, which we can't really do for
2606 // opaque or mirrored types without box'ing them, which is quite a waste, so return
2607 // the actual object itself (for opaque types we'll set the pointer to the actual
2608 // type and note that its a reference).
2609 write!(w, "crate::{}", full_path).unwrap();
2610 } else if is_ref && with_ref_lifetime {
2612 // If we're concretizing something with a lifetime parameter, we have to pick a
2613 // lifetime, of which the only real available choice is `static`, obviously.
2614 write!(w, "&'static ").unwrap();
2615 self.write_rust_path(w, generics, path);
2617 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2619 write!(w, "crate::{}", full_path).unwrap();
2626 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, with_ref_lifetime: bool) -> bool {
2627 match generics.resolve_type(t) {
2628 syn::Type::Path(p) => {
2629 if p.qself.is_some() {
2632 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
2633 if self.is_known_container(&full_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
2634 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);
2636 if let Some(aliased_type) = self.crate_types.type_aliases.get(&full_path).cloned() {
2637 return self.write_c_type_intern(w, &aliased_type, None, is_ref, is_mut, ptr_for_ref, with_ref_lifetime);
2640 self.write_c_path_intern(w, &p.path, generics, is_ref, is_mut, ptr_for_ref, with_ref_lifetime)
2642 syn::Type::Reference(r) => {
2643 self.write_c_type_intern(w, &*r.elem, generics, true, r.mutability.is_some(), ptr_for_ref, with_ref_lifetime)
2645 syn::Type::Array(a) => {
2646 if is_ref && is_mut {
2647 write!(w, "*mut [").unwrap();
2648 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref, with_ref_lifetime) { return false; }
2650 write!(w, "*const [").unwrap();
2651 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref, with_ref_lifetime) { return false; }
2653 let mut typecheck = Vec::new();
2654 if !self.write_c_type_intern(&mut typecheck, &a.elem, generics, false, false, ptr_for_ref, with_ref_lifetime) { return false; }
2655 if typecheck[..] != ['u' as u8, '8' as u8] { return false; }
2657 if let syn::Expr::Lit(l) = &a.len {
2658 if let syn::Lit::Int(i) = &l.lit {
2660 if let Some(ty) = self.c_type_from_path(&format!("[u8; {}]", i.base10_digits()), false, ptr_for_ref) {
2661 write!(w, "{}", ty).unwrap();
2665 write!(w, "; {}]", i).unwrap();
2671 syn::Type::Slice(s) => {
2672 if !is_ref || is_mut { return false; }
2673 if let syn::Type::Path(p) = &*s.elem {
2674 let resolved = self.resolve_path(&p.path, generics);
2675 if self.is_primitive(&resolved) {
2676 write!(w, "{}::{}slice", Self::container_templ_path(), resolved).unwrap();
2679 } else if let syn::Type::Reference(r) = &*s.elem {
2680 if let syn::Type::Path(p) = &*r.elem {
2681 // Slices with "real types" inside are mapped as the equivalent non-ref Vec
2682 let resolved = self.resolve_path(&p.path, generics);
2683 let mangled_container = if let Some(ident) = self.crate_types.opaques.get(&resolved) {
2684 format!("CVec_{}Z", ident)
2685 } else if let Some(en) = self.crate_types.mirrored_enums.get(&resolved) {
2686 format!("CVec_{}Z", en.ident)
2687 } else if let Some(id) = p.path.get_ident() {
2688 format!("CVec_{}Z", id)
2689 } else { return false; };
2690 write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
2691 self.check_create_container(mangled_container, "Vec", vec![&*r.elem], generics, false)
2692 } else if let syn::Type::Slice(sl2) = &*r.elem {
2693 if let syn::Type::Reference(r2) = &*sl2.elem {
2694 if let syn::Type::Path(p) = &*r2.elem {
2695 // Slices with slices with opaque types (with is_owned flags) are mapped as non-ref Vecs
2696 let resolved = self.resolve_path(&p.path, generics);
2697 let mangled_container = if let Some(ident) = self.crate_types.opaques.get(&resolved) {
2698 format!("CVec_CVec_{}ZZ", ident)
2699 } else { return false; };
2700 write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
2701 let inner = &r2.elem;
2702 let vec_ty: syn::Type = syn::parse_quote!(Vec<#inner>);
2703 self.check_create_container(mangled_container, "Vec", vec![&vec_ty], generics, false)
2707 } else if let syn::Type::Tuple(_) = &*s.elem {
2708 let mut args = syn::punctuated::Punctuated::<_, syn::token::Comma>::new();
2709 args.push(syn::GenericArgument::Type((*s.elem).clone()));
2710 let mut segments = syn::punctuated::Punctuated::new();
2711 segments.push(parse_quote!(Vec<#args>));
2712 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, with_ref_lifetime)
2715 syn::Type::Tuple(t) => {
2716 if t.elems.len() == 0 {
2719 self.write_c_mangled_container_path(w, t.elems.iter().collect(), generics,
2720 &format!("{}Tuple", t.elems.len()), is_ref, is_mut, ptr_for_ref)
2726 pub fn write_c_type<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) {
2727 assert!(self.write_c_type_intern(w, t, generics, false, false, ptr_for_ref, false));
2729 pub fn write_c_type_in_generic_param<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) {
2730 assert!(self.write_c_type_intern(w, t, generics, false, false, ptr_for_ref, true));
2732 pub fn understood_c_path(&self, p: &syn::Path) -> bool {
2733 if p.leading_colon.is_some() { return false; }
2734 self.write_c_path_intern(&mut std::io::sink(), p, None, false, false, false, false)
2736 pub fn understood_c_type(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
2737 self.write_c_type_intern(&mut std::io::sink(), t, generics, false, false, false, false)