1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE>
5 // or the MIT license <LICENSE-MIT>, at your option.
6 // You may not use this file except in accordance with one or both of these
9 use std::cell::RefCell;
10 use std::collections::{HashMap, HashSet};
17 use proc_macro2::{TokenTree, Span};
18 use quote::format_ident;
21 // The following utils are used purely to build our known types maps - they break down all the
22 // types we need to resolve to include the given object, and no more.
24 pub fn first_seg_self<'a>(t: &'a syn::Type) -> Option<impl Iterator<Item=&syn::PathSegment> + 'a> {
26 syn::Type::Path(p) => {
27 if p.qself.is_some() || p.path.leading_colon.is_some() {
30 let mut segs = p.path.segments.iter();
31 let ty = segs.next().unwrap();
32 if !ty.arguments.is_empty() { return None; }
33 if format!("{}", ty.ident) == "Self" {
41 pub fn get_single_remaining_path_seg<'a, I: Iterator<Item=&'a syn::PathSegment>>(segs: &mut I) -> Option<&'a syn::Ident> {
42 if let Some(ty) = segs.next() {
43 if !ty.arguments.is_empty() { unimplemented!(); }
44 if segs.next().is_some() { return None; }
49 pub fn single_ident_generic_path_to_ident(p: &syn::Path) -> Option<&syn::Ident> {
50 if p.segments.len() == 1 {
51 Some(&p.segments.iter().next().unwrap().ident)
55 pub fn path_matches_nongeneric(p: &syn::Path, exp: &[&str]) -> bool {
56 if p.segments.len() != exp.len() { return false; }
57 for (seg, e) in p.segments.iter().zip(exp.iter()) {
58 if seg.arguments != syn::PathArguments::None { return false; }
59 if &format!("{}", seg.ident) != *e { return false; }
64 #[derive(Debug, PartialEq)]
65 pub enum ExportStatus {
70 /// Gets the ExportStatus of an object (struct, fn, etc) given its attributes.
71 pub fn export_status(attrs: &[syn::Attribute]) -> ExportStatus {
72 for attr in attrs.iter() {
73 let tokens_clone = attr.tokens.clone();
74 let mut token_iter = tokens_clone.into_iter();
75 if let Some(token) = token_iter.next() {
77 TokenTree::Punct(c) if c.as_char() == '=' => {
78 // Really not sure where syn gets '=' from here -
79 // it somehow represents '///' or '//!'
81 TokenTree::Group(g) => {
82 if format!("{}", single_ident_generic_path_to_ident(&attr.path).unwrap()) == "cfg" {
83 let mut iter = g.stream().into_iter();
84 if let TokenTree::Ident(i) = iter.next().unwrap() {
86 // #[cfg(any(test, feature = ""))]
87 if let TokenTree::Group(g) = iter.next().unwrap() {
88 let mut all_test = true;
89 for token in g.stream().into_iter() {
90 if let TokenTree::Ident(i) = token {
91 match format!("{}", i).as_str() {
94 _ => all_test = false,
96 } else if let TokenTree::Literal(lit) = token {
97 if format!("{}", lit) != "fuzztarget" {
102 if all_test { return ExportStatus::TestOnly; }
104 } else if i == "test" || i == "feature" {
105 // If its cfg(feature(...)) we assume its test-only
106 return ExportStatus::TestOnly;
110 continue; // eg #[derive()]
112 _ => unimplemented!(),
115 match token_iter.next().unwrap() {
116 TokenTree::Literal(lit) => {
117 let line = format!("{}", lit);
118 if line.contains("(C-not exported)") {
119 return ExportStatus::NoExport;
122 _ => unimplemented!(),
128 pub fn assert_simple_bound(bound: &syn::TraitBound) {
129 if bound.paren_token.is_some() || bound.lifetimes.is_some() { unimplemented!(); }
130 if let syn::TraitBoundModifier::Maybe(_) = bound.modifier { unimplemented!(); }
133 /// Returns true if the enum will be mapped as an opaue (ie struct with a pointer to the underlying
134 /// type), otherwise it is mapped into a transparent, C-compatible version of itself.
135 pub fn is_enum_opaque(e: &syn::ItemEnum) -> bool {
136 for var in e.variants.iter() {
137 if let syn::Fields::Named(fields) = &var.fields {
138 for field in fields.named.iter() {
139 match export_status(&field.attrs) {
140 ExportStatus::Export|ExportStatus::TestOnly => {},
141 ExportStatus::NoExport => return true,
144 } else if let syn::Fields::Unnamed(fields) = &var.fields {
145 for field in fields.unnamed.iter() {
146 match export_status(&field.attrs) {
147 ExportStatus::Export|ExportStatus::TestOnly => {},
148 ExportStatus::NoExport => return true,
156 /// A stack of sets of generic resolutions.
158 /// This tracks the template parameters for a function, struct, or trait, allowing resolution into
159 /// a concrete type. By pushing a new context onto the stack, this can track a function's template
160 /// parameters inside of a generic struct or trait.
162 /// It maps both direct types as well as Deref<Target = X>, mapping them via the provided
163 /// TypeResolver's resolve_path function (ie traits map to the concrete jump table, structs to the
164 /// concrete C container struct, etc).
166 pub struct GenericTypes<'a, 'b> {
167 parent: Option<&'b GenericTypes<'b, 'b>>,
168 typed_generics: HashMap<&'a syn::Ident, (String, Option<&'a syn::Path>)>,
170 impl<'a, 'p: 'a> GenericTypes<'a, 'p> {
171 pub fn new() -> Self {
172 Self { parent: None, typed_generics: HashMap::new(), }
175 /// push a new context onto the stack, allowing for a new set of generics to be learned which
176 /// will override any lower contexts, but which will still fall back to resoltion via lower
178 pub fn push_ctx<'c>(&'c self) -> GenericTypes<'a, 'c> {
179 GenericTypes { parent: Some(self), typed_generics: HashMap::new(), }
182 /// Learn the generics in generics in the current context, given a TypeResolver.
183 pub fn learn_generics<'b, 'c>(&mut self, generics: &'a syn::Generics, types: &'b TypeResolver<'a, 'c>) -> bool {
184 // First learn simple generics...
185 for generic in generics.params.iter() {
187 syn::GenericParam::Type(type_param) => {
188 let mut non_lifetimes_processed = false;
189 for bound in type_param.bounds.iter() {
190 if let syn::TypeParamBound::Trait(trait_bound) = bound {
191 if let Some(ident) = single_ident_generic_path_to_ident(&trait_bound.path) {
192 match &format!("{}", ident) as &str { "Send" => continue, "Sync" => continue, _ => {} }
194 if path_matches_nongeneric(&trait_bound.path, &["core", "clone", "Clone"]) { continue; }
196 assert_simple_bound(&trait_bound);
197 if let Some(mut path) = types.maybe_resolve_path(&trait_bound.path, None) {
198 if types.skip_path(&path) { continue; }
199 if path == "Sized" { continue; }
200 if non_lifetimes_processed { return false; }
201 non_lifetimes_processed = true;
202 let new_ident = if path != "std::ops::Deref" {
203 path = "crate::".to_string() + &path;
204 Some(&trait_bound.path)
206 self.typed_generics.insert(&type_param.ident, (path, new_ident));
207 } else { return false; }
214 // Then find generics where we are required to pass a Deref<Target=X> and pretend its just X.
215 if let Some(wh) = &generics.where_clause {
216 for pred in wh.predicates.iter() {
217 if let syn::WherePredicate::Type(t) = pred {
218 if let syn::Type::Path(p) = &t.bounded_ty {
219 if p.qself.is_some() { return false; }
220 if p.path.leading_colon.is_some() { return false; }
221 let mut p_iter = p.path.segments.iter();
222 if let Some(gen) = self.typed_generics.get_mut(&p_iter.next().unwrap().ident) {
223 if gen.0 != "std::ops::Deref" { return false; }
224 if &format!("{}", p_iter.next().unwrap().ident) != "Target" { return false; }
226 let mut non_lifetimes_processed = false;
227 for bound in t.bounds.iter() {
228 if let syn::TypeParamBound::Trait(trait_bound) = bound {
229 if let Some(id) = trait_bound.path.get_ident() {
230 if format!("{}", id) == "Sized" { continue; }
232 if non_lifetimes_processed { return false; }
233 non_lifetimes_processed = true;
234 assert_simple_bound(&trait_bound);
235 *gen = ("crate::".to_string() + &types.resolve_path(&trait_bound.path, None),
236 Some(&trait_bound.path));
239 } else { return false; }
240 } else { return false; }
244 for (_, (_, ident)) in self.typed_generics.iter() {
245 if ident.is_none() { return false; }
250 /// Learn the associated types from the trait in the current context.
251 pub fn learn_associated_types<'b, 'c>(&mut self, t: &'a syn::ItemTrait, types: &'b TypeResolver<'a, 'c>) {
252 for item in t.items.iter() {
254 &syn::TraitItem::Type(ref t) => {
255 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
256 let mut bounds_iter = t.bounds.iter();
257 match bounds_iter.next().unwrap() {
258 syn::TypeParamBound::Trait(tr) => {
259 assert_simple_bound(&tr);
260 if let Some(mut path) = types.maybe_resolve_path(&tr.path, None) {
261 if types.skip_path(&path) { continue; }
262 // In general we handle Deref<Target=X> as if it were just X (and
263 // implement Deref<Target=Self> for relevant types). We don't
264 // bother to implement it for associated types, however, so we just
265 // ignore such bounds.
266 let new_ident = if path != "std::ops::Deref" {
267 path = "crate::".to_string() + &path;
270 self.typed_generics.insert(&t.ident, (path, new_ident));
271 } else { unimplemented!(); }
273 _ => unimplemented!(),
275 if bounds_iter.next().is_some() { unimplemented!(); }
282 /// Attempt to resolve an Ident as a generic parameter and return the full path.
283 pub fn maybe_resolve_ident<'b>(&'b self, ident: &syn::Ident) -> Option<&'b String> {
284 if let Some(res) = self.typed_generics.get(ident).map(|(a, _)| a) {
287 if let Some(parent) = self.parent {
288 parent.maybe_resolve_ident(ident)
293 /// Attempt to resolve a Path as a generic parameter and return the full path. as both a string
295 pub fn maybe_resolve_path<'b>(&'b self, path: &syn::Path) -> Option<(&'b String, &'a syn::Path)> {
296 if let Some(ident) = path.get_ident() {
297 if let Some(res) = self.typed_generics.get(ident).map(|(a, b)| (a, b.unwrap())) {
301 // Associated types are usually specified as "Self::Generic", so we check for that
303 let mut it = path.segments.iter();
304 if path.segments.len() == 2 && format!("{}", it.next().unwrap().ident) == "Self" {
305 let ident = &it.next().unwrap().ident;
306 if let Some(res) = self.typed_generics.get(ident).map(|(a, b)| (a, b.unwrap())) {
311 if let Some(parent) = self.parent {
312 parent.maybe_resolve_path(path)
319 #[derive(Clone, PartialEq)]
320 // The type of declaration and the object itself
321 pub enum DeclType<'a> {
323 Trait(&'a syn::ItemTrait),
329 pub struct ImportResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
330 crate_name: &'mod_lifetime str,
331 dependencies: &'mod_lifetime HashSet<syn::Ident>,
332 module_path: &'mod_lifetime str,
333 imports: HashMap<syn::Ident, (String, syn::Path)>,
334 declared: HashMap<syn::Ident, DeclType<'crate_lft>>,
335 priv_modules: HashSet<syn::Ident>,
337 impl<'mod_lifetime, 'crate_lft: 'mod_lifetime> ImportResolver<'mod_lifetime, 'crate_lft> {
338 fn process_use_intern(crate_name: &str, dependencies: &HashSet<syn::Ident>, imports: &mut HashMap<syn::Ident, (String, syn::Path)>,
339 u: &syn::UseTree, partial_path: &str, mut path: syn::punctuated::Punctuated<syn::PathSegment, syn::token::Colon2>) {
342 macro_rules! push_path {
343 ($ident: expr, $path_suffix: expr) => {
344 if partial_path == "" && !dependencies.contains(&$ident) {
345 new_path = format!("{}::{}{}", crate_name, $ident, $path_suffix);
346 let crate_name_ident = format_ident!("{}", crate_name);
347 path.push(parse_quote!(#crate_name_ident));
349 new_path = format!("{}{}{}", partial_path, $ident, $path_suffix);
352 path.push(parse_quote!(#ident));
356 syn::UseTree::Path(p) => {
357 push_path!(p.ident, "::");
358 Self::process_use_intern(crate_name, dependencies, imports, &p.tree, &new_path, path);
360 syn::UseTree::Name(n) => {
361 push_path!(n.ident, "");
362 imports.insert(n.ident.clone(), (new_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
364 syn::UseTree::Group(g) => {
365 for i in g.items.iter() {
366 Self::process_use_intern(crate_name, dependencies, imports, i, partial_path, path.clone());
369 syn::UseTree::Rename(r) => {
370 push_path!(r.ident, "");
371 imports.insert(r.rename.clone(), (new_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
373 syn::UseTree::Glob(_) => {
374 eprintln!("Ignoring * use for {} - this may result in resolution failures", partial_path);
379 fn process_use(crate_name: &str, dependencies: &HashSet<syn::Ident>, imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::ItemUse) {
380 if let syn::Visibility::Public(_) = u.vis {
381 // We actually only use these for #[cfg(fuzztarget)]
382 eprintln!("Ignoring pub(use) tree!");
385 if u.leading_colon.is_some() { eprintln!("Ignoring leading-colon use!"); return; }
386 Self::process_use_intern(crate_name, dependencies, imports, &u.tree, "", syn::punctuated::Punctuated::new());
389 fn insert_primitive(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, id: &str) {
390 let ident = format_ident!("{}", id);
391 let path = parse_quote!(#ident);
392 imports.insert(ident, (id.to_owned(), path));
395 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 {
396 let mut imports = HashMap::new();
397 // Add primitives to the "imports" list:
398 Self::insert_primitive(&mut imports, "bool");
399 Self::insert_primitive(&mut imports, "u64");
400 Self::insert_primitive(&mut imports, "u32");
401 Self::insert_primitive(&mut imports, "u16");
402 Self::insert_primitive(&mut imports, "u8");
403 Self::insert_primitive(&mut imports, "usize");
404 Self::insert_primitive(&mut imports, "str");
405 Self::insert_primitive(&mut imports, "String");
407 // These are here to allow us to print native Rust types in trait fn impls even if we don't
409 Self::insert_primitive(&mut imports, "Result");
410 Self::insert_primitive(&mut imports, "Vec");
411 Self::insert_primitive(&mut imports, "Option");
413 let mut declared = HashMap::new();
414 let mut priv_modules = HashSet::new();
416 for item in contents.iter() {
418 syn::Item::Use(u) => Self::process_use(crate_name, dependencies, &mut imports, &u),
419 syn::Item::Struct(s) => {
420 if let syn::Visibility::Public(_) = s.vis {
421 match export_status(&s.attrs) {
422 ExportStatus::Export => { declared.insert(s.ident.clone(), DeclType::StructImported); },
423 ExportStatus::NoExport => { declared.insert(s.ident.clone(), DeclType::StructIgnored); },
424 ExportStatus::TestOnly => continue,
428 syn::Item::Type(t) if export_status(&t.attrs) == ExportStatus::Export => {
429 if let syn::Visibility::Public(_) = t.vis {
430 let mut process_alias = true;
431 for tok in t.generics.params.iter() {
432 if let syn::GenericParam::Lifetime(_) = tok {}
433 else { process_alias = false; }
436 declared.insert(t.ident.clone(), DeclType::StructImported);
440 syn::Item::Enum(e) => {
441 if let syn::Visibility::Public(_) = e.vis {
442 match export_status(&e.attrs) {
443 ExportStatus::Export if is_enum_opaque(e) => { declared.insert(e.ident.clone(), DeclType::EnumIgnored); },
444 ExportStatus::Export => { declared.insert(e.ident.clone(), DeclType::MirroredEnum); },
449 syn::Item::Trait(t) if export_status(&t.attrs) == ExportStatus::Export => {
450 if let syn::Visibility::Public(_) = t.vis {
451 declared.insert(t.ident.clone(), DeclType::Trait(t));
454 syn::Item::Mod(m) => {
455 priv_modules.insert(m.ident.clone());
461 Self { crate_name, dependencies, module_path, imports, declared, priv_modules }
464 pub fn get_declared_type(&self, ident: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
465 self.declared.get(ident)
468 pub fn maybe_resolve_declared(&self, id: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
469 self.declared.get(id)
472 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
473 if let Some((imp, _)) = self.imports.get(id) {
475 } else if self.declared.get(id).is_some() {
476 Some(self.module_path.to_string() + "::" + &format!("{}", id))
480 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
481 if let Some((imp, _)) = self.imports.get(id) {
483 } else if let Some(decl_type) = self.declared.get(id) {
485 DeclType::StructIgnored => None,
486 _ => Some(self.module_path.to_string() + "::" + &format!("{}", id)),
491 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
492 let p = if let Some(gen_types) = generics {
493 if let Some((_, synpath)) = gen_types.maybe_resolve_path(p_arg) {
498 if p.leading_colon.is_some() {
499 let mut res: String = p.segments.iter().enumerate().map(|(idx, seg)| {
500 format!("{}{}", if idx == 0 { "" } else { "::" }, seg.ident)
502 let firstseg = p.segments.iter().next().unwrap();
503 if !self.dependencies.contains(&firstseg.ident) {
504 res = self.crate_name.to_owned() + "::" + &res;
507 } else if let Some(id) = p.get_ident() {
508 self.maybe_resolve_ident(id)
510 if p.segments.len() == 1 {
511 let seg = p.segments.iter().next().unwrap();
512 return self.maybe_resolve_ident(&seg.ident);
514 let mut seg_iter = p.segments.iter();
515 let first_seg = seg_iter.next().unwrap();
516 let remaining: String = seg_iter.map(|seg| {
517 format!("::{}", seg.ident)
519 let first_seg_str = format!("{}", first_seg.ident);
520 if let Some((imp, _)) = self.imports.get(&first_seg.ident) {
522 Some(imp.clone() + &remaining)
526 } else if let Some(_) = self.priv_modules.get(&first_seg.ident) {
527 Some(format!("{}::{}{}", self.module_path, first_seg.ident, remaining))
528 } else if first_seg_str == "std" || self.dependencies.contains(&first_seg.ident) {
529 Some(first_seg_str + &remaining)
534 /// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern)
535 pub fn resolve_imported_refs(&self, mut ty: syn::Type) -> syn::Type {
537 syn::Type::Path(p) => {
538 eprintln!("rir {:?}", p);
539 if p.path.segments.len() != 1 { unimplemented!(); }
540 let mut args = p.path.segments[0].arguments.clone();
541 if let syn::PathArguments::AngleBracketed(ref mut generics) = &mut args {
542 for arg in generics.args.iter_mut() {
543 if let syn::GenericArgument::Type(ref mut t) = arg {
544 *t = self.resolve_imported_refs(t.clone());
548 if let Some((_, newpath)) = self.imports.get(single_ident_generic_path_to_ident(&p.path).unwrap()) {
549 p.path = newpath.clone();
551 p.path.segments[0].arguments = args;
553 syn::Type::Reference(r) => {
554 r.elem = Box::new(self.resolve_imported_refs((*r.elem).clone()));
556 syn::Type::Slice(s) => {
557 s.elem = Box::new(self.resolve_imported_refs((*s.elem).clone()));
559 syn::Type::Tuple(t) => {
560 for e in t.elems.iter_mut() {
561 *e = self.resolve_imported_refs(e.clone());
564 _ => unimplemented!(),
570 // templates_defined is walked to write the C++ header, so if we use the default hashing it get
571 // reordered on each genbindings run. Instead, we use SipHasher (which defaults to 0-keys) so that
572 // the sorting is stable across runs. It is deprecated, but the "replacement" doesn't actually
573 // accomplish the same goals, so we just ignore it.
575 pub type NonRandomHash = hash::BuildHasherDefault<hash::SipHasher>;
578 pub struct ASTModule {
579 pub attrs: Vec<syn::Attribute>,
580 pub items: Vec<syn::Item>,
581 pub submods: Vec<String>,
583 /// A struct containing the syn::File AST for each file in the crate.
584 pub struct FullLibraryAST {
585 pub modules: HashMap<String, ASTModule, NonRandomHash>,
586 pub dependencies: HashSet<syn::Ident>,
588 impl FullLibraryAST {
589 fn load_module(&mut self, module: String, attrs: Vec<syn::Attribute>, mut items: Vec<syn::Item>) {
590 let mut non_mod_items = Vec::with_capacity(items.len());
591 let mut submods = Vec::with_capacity(items.len());
592 for item in items.drain(..) {
594 syn::Item::Mod(m) if m.content.is_some() => {
595 if export_status(&m.attrs) == ExportStatus::Export {
596 if let syn::Visibility::Public(_) = m.vis {
597 let modident = format!("{}", m.ident);
598 let modname = if module != "" {
599 module.clone() + "::" + &modident
603 self.load_module(modname, m.attrs, m.content.unwrap().1);
604 submods.push(modident);
606 non_mod_items.push(syn::Item::Mod(m));
610 syn::Item::Mod(_) => panic!("--pretty=expanded output should never have non-body modules"),
611 syn::Item::ExternCrate(c) => {
612 if export_status(&c.attrs) == ExportStatus::Export {
613 self.dependencies.insert(c.ident);
616 _ => { non_mod_items.push(item); }
619 self.modules.insert(module, ASTModule { attrs, items: non_mod_items, submods });
622 pub fn load_lib(lib: syn::File) -> Self {
623 assert_eq!(export_status(&lib.attrs), ExportStatus::Export);
624 let mut res = Self { modules: HashMap::default(), dependencies: HashSet::new() };
625 res.load_module("".to_owned(), lib.attrs, lib.items);
630 /// List of manually-generated types which are clonable
631 fn initial_clonable_types() -> HashSet<String> {
632 let mut res = HashSet::new();
633 res.insert("crate::c_types::u5".to_owned());
637 /// Top-level struct tracking everything which has been defined while walking the crate.
638 pub struct CrateTypes<'a> {
639 /// This may contain structs or enums, but only when either is mapped as
640 /// struct X { inner: *mut originalX, .. }
641 pub opaques: HashMap<String, &'a syn::Ident>,
642 /// Enums which are mapped as C enums with conversion functions
643 pub mirrored_enums: HashMap<String, &'a syn::ItemEnum>,
644 /// Traits which are mapped as a pointer + jump table
645 pub traits: HashMap<String, &'a syn::ItemTrait>,
646 /// Aliases from paths to some other Type
647 pub type_aliases: HashMap<String, syn::Type>,
648 /// Value is an alias to Key (maybe with some generics)
649 pub reverse_alias_map: HashMap<String, Vec<(syn::Path, syn::PathArguments)>>,
650 /// Template continer types defined, map from mangled type name -> whether a destructor fn
653 /// This is used at the end of processing to make C++ wrapper classes
654 pub templates_defined: RefCell<HashMap<String, bool, NonRandomHash>>,
655 /// The output file for any created template container types, written to as we find new
656 /// template containers which need to be defined.
657 template_file: RefCell<&'a mut File>,
658 /// Set of containers which are clonable
659 clonable_types: RefCell<HashSet<String>>,
661 pub trait_impls: HashMap<String, Vec<String>>,
662 /// The full set of modules in the crate(s)
663 pub lib_ast: &'a FullLibraryAST,
666 impl<'a> CrateTypes<'a> {
667 pub fn new(template_file: &'a mut File, libast: &'a FullLibraryAST) -> Self {
669 opaques: HashMap::new(), mirrored_enums: HashMap::new(), traits: HashMap::new(),
670 type_aliases: HashMap::new(), reverse_alias_map: HashMap::new(),
671 templates_defined: RefCell::new(HashMap::default()),
672 clonable_types: RefCell::new(initial_clonable_types()), trait_impls: HashMap::new(),
673 template_file: RefCell::new(template_file), lib_ast: &libast,
676 pub fn set_clonable(&self, object: String) {
677 self.clonable_types.borrow_mut().insert(object);
679 pub fn is_clonable(&self, object: &str) -> bool {
680 self.clonable_types.borrow().contains(object)
682 pub fn write_new_template(&self, mangled_container: String, has_destructor: bool, created_container: &[u8]) {
683 self.template_file.borrow_mut().write(created_container).unwrap();
684 self.templates_defined.borrow_mut().insert(mangled_container, has_destructor);
688 /// A struct which tracks resolving rust types into C-mapped equivalents, exists for one specific
689 /// module but contains a reference to the overall CrateTypes tracking.
690 pub struct TypeResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
691 pub module_path: &'mod_lifetime str,
692 pub crate_types: &'mod_lifetime CrateTypes<'crate_lft>,
693 types: ImportResolver<'mod_lifetime, 'crate_lft>,
696 /// Returned by write_empty_rust_val_check_suffix to indicate what type of dereferencing needs to
697 /// happen to get the inner value of a generic.
698 enum EmptyValExpectedTy {
699 /// A type which has a flag for being empty (eg an array where we treat all-0s as empty).
701 /// A pointer that we want to dereference and move out of.
703 /// A pointer which we want to convert to a reference.
708 /// Describes the appropriate place to print a general type-conversion string when converting a
710 enum ContainerPrefixLocation {
711 /// Prints a general type-conversion string prefix and suffix outside of the
712 /// container-conversion strings.
714 /// Prints a general type-conversion string prefix and suffix inside of the
715 /// container-conversion strings.
717 /// Does not print the usual type-conversion string prefix and suffix.
721 impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
722 pub fn new(module_path: &'a str, types: ImportResolver<'a, 'c>, crate_types: &'a CrateTypes<'c>) -> Self {
723 Self { module_path, types, crate_types }
726 // *************************************************
727 // *** Well know type and conversion definitions ***
728 // *************************************************
730 /// Returns true we if can just skip passing this to C entirely
731 fn skip_path(&self, full_path: &str) -> bool {
732 full_path == "bitcoin::secp256k1::Secp256k1" ||
733 full_path == "bitcoin::secp256k1::Signing" ||
734 full_path == "bitcoin::secp256k1::Verification"
736 /// Returns true we if can just skip passing this to C entirely
737 fn no_arg_path_to_rust(&self, full_path: &str) -> &str {
738 if full_path == "bitcoin::secp256k1::Secp256k1" {
739 "secp256k1::SECP256K1"
740 } else { unimplemented!(); }
743 /// Returns true if the object is a primitive and is mapped as-is with no conversion
745 pub fn is_primitive(&self, full_path: &str) -> bool {
756 pub fn is_clonable(&self, ty: &str) -> bool {
757 if self.crate_types.is_clonable(ty) { return true; }
758 if self.is_primitive(ty) { return true; }
761 "crate::c_types::Signature" => true,
762 "crate::c_types::TxOut" => true,
766 /// Gets the C-mapped type for types which are outside of the crate, or which are manually
767 /// ignored by for some reason need mapping anyway.
768 fn c_type_from_path<'b>(&self, full_path: &'b str, is_ref: bool, _ptr_for_ref: bool) -> Option<&'b str> {
769 if self.is_primitive(full_path) {
770 return Some(full_path);
773 "Result" => Some("crate::c_types::derived::CResult"),
774 "Vec" if !is_ref => Some("crate::c_types::derived::CVec"),
775 "Option" => Some(""),
777 // Note that no !is_ref types can map to an array because Rust and C's call semantics
778 // for arrays are different (https://github.com/eqrion/cbindgen/issues/528)
780 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
781 "[u8; 20]" if !is_ref => Some("crate::c_types::TwentyBytes"),
782 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes"),
783 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes"),
784 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes"),
785 "[u8; 3]" if !is_ref => Some("crate::c_types::ThreeBytes"), // Used for RGB values
787 "str" if is_ref => Some("crate::c_types::Str"),
788 "String" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
789 "String" if is_ref => Some("crate::c_types::Str"),
791 "std::time::Duration" => Some("u64"),
792 "std::io::Error" => Some("crate::c_types::IOError"),
794 "bech32::u5" => Some("crate::c_types::u5"),
796 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
797 => Some("crate::c_types::PublicKey"),
798 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature"),
799 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
800 if is_ref => Some("*const [u8; 32]"),
801 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
802 if !is_ref => Some("crate::c_types::SecretKey"),
803 "bitcoin::secp256k1::Error"|"secp256k1::Error"
804 if !is_ref => Some("crate::c_types::Secp256k1Error"),
805 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice"),
806 "bitcoin::blockdata::script::Script" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
807 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::lightning::chain::transaction::OutPoint"),
808 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction"),
809 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut"),
810 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network"),
811 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("*const [u8; 80]"),
812 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice"),
814 // Newtypes that we just expose in their original form.
815 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
816 if is_ref => Some("*const [u8; 32]"),
817 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
818 if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
819 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
820 "lightning::ln::channelmanager::PaymentHash" if is_ref => Some("*const [u8; 32]"),
821 "lightning::ln::channelmanager::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
822 "lightning::ln::channelmanager::PaymentPreimage" if is_ref => Some("*const [u8; 32]"),
823 "lightning::ln::channelmanager::PaymentPreimage" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
824 "lightning::ln::channelmanager::PaymentSecret" if is_ref => Some("crate::c_types::ThirtyTwoBytes"),
825 "lightning::ln::channelmanager::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
827 // Override the default since Records contain an fmt with a lifetime:
828 "lightning::util::logger::Record" => Some("*const std::os::raw::c_char"),
834 fn from_c_conversion_new_var_from_path<'b>(&self, _full_path: &str, _is_ref: bool) -> Option<(&'b str, &'b str)> {
837 fn from_c_conversion_prefix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
838 if self.is_primitive(full_path) {
839 return Some("".to_owned());
842 "Vec" if !is_ref => Some("local_"),
843 "Result" if !is_ref => Some("local_"),
844 "Option" if is_ref => Some("&local_"),
845 "Option" => Some("local_"),
847 "[u8; 32]" if is_ref => Some("unsafe { &*"),
848 "[u8; 32]" if !is_ref => Some(""),
849 "[u8; 20]" if !is_ref => Some(""),
850 "[u8; 16]" if !is_ref => Some(""),
851 "[u8; 10]" if !is_ref => Some(""),
852 "[u8; 4]" if !is_ref => Some(""),
853 "[u8; 3]" if !is_ref => Some(""),
855 "[u8]" if is_ref => Some(""),
856 "[usize]" if is_ref => Some(""),
858 "str" if is_ref => Some(""),
859 "String" if !is_ref => Some("String::from_utf8("),
860 // Note that we'll panic for String if is_ref, as we only have non-owned memory, we
861 // cannot create a &String.
863 "std::time::Duration" => Some("std::time::Duration::from_secs("),
865 "bech32::u5" => Some(""),
867 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
868 if is_ref => Some("&"),
869 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
871 "bitcoin::secp256k1::Signature" if is_ref => Some("&"),
872 "bitcoin::secp256k1::Signature" => Some(""),
873 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
874 if is_ref => Some("&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *"),
875 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
876 if !is_ref => Some(""),
877 "bitcoin::blockdata::script::Script" if is_ref => Some("&::bitcoin::blockdata::script::Script::from(Vec::from("),
878 "bitcoin::blockdata::script::Script" if !is_ref => Some("::bitcoin::blockdata::script::Script::from("),
879 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some("&"),
880 "bitcoin::blockdata::transaction::Transaction" => Some(""),
881 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(""),
882 "bitcoin::network::constants::Network" => Some(""),
883 "bitcoin::blockdata::block::BlockHeader" => Some("&::bitcoin::consensus::encode::deserialize(unsafe { &*"),
884 "bitcoin::blockdata::block::Block" if is_ref => Some("&::bitcoin::consensus::encode::deserialize("),
886 // Newtypes that we just expose in their original form.
887 "bitcoin::hash_types::Txid" if is_ref => Some("&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*"),
888 "bitcoin::hash_types::Txid" if !is_ref => Some("::bitcoin::hash_types::Txid::from_slice(&"),
889 "bitcoin::hash_types::BlockHash" => Some("::bitcoin::hash_types::BlockHash::from_slice(&"),
890 "lightning::ln::channelmanager::PaymentHash" if !is_ref => Some("::lightning::ln::channelmanager::PaymentHash("),
891 "lightning::ln::channelmanager::PaymentHash" if is_ref => Some("&::lightning::ln::channelmanager::PaymentHash(unsafe { *"),
892 "lightning::ln::channelmanager::PaymentPreimage" if !is_ref => Some("::lightning::ln::channelmanager::PaymentPreimage("),
893 "lightning::ln::channelmanager::PaymentPreimage" if is_ref => Some("&::lightning::ln::channelmanager::PaymentPreimage(unsafe { *"),
894 "lightning::ln::channelmanager::PaymentSecret" => Some("::lightning::ln::channelmanager::PaymentSecret("),
896 // List of traits we map (possibly during processing of other files):
897 "crate::util::logger::Logger" => Some(""),
900 }.map(|s| s.to_owned())
902 fn from_c_conversion_suffix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
903 if self.is_primitive(full_path) {
904 return Some("".to_owned());
907 "Vec" if !is_ref => Some(""),
908 "Option" => Some(""),
909 "Result" if !is_ref => Some(""),
911 "[u8; 32]" if is_ref => Some("}"),
912 "[u8; 32]" if !is_ref => Some(".data"),
913 "[u8; 20]" if !is_ref => Some(".data"),
914 "[u8; 16]" if !is_ref => Some(".data"),
915 "[u8; 10]" if !is_ref => Some(".data"),
916 "[u8; 4]" if !is_ref => Some(".data"),
917 "[u8; 3]" if !is_ref => Some(".data"),
919 "[u8]" if is_ref => Some(".to_slice()"),
920 "[usize]" if is_ref => Some(".to_slice()"),
922 "str" if is_ref => Some(".into()"),
923 "String" if !is_ref => Some(".into_rust()).unwrap()"),
925 "std::time::Duration" => Some(")"),
927 "bech32::u5" => Some(".into()"),
929 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
930 => Some(".into_rust()"),
931 "bitcoin::secp256k1::Signature" => Some(".into_rust()"),
932 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
933 if !is_ref => Some(".into_rust()"),
934 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
935 if is_ref => Some("}[..]).unwrap()"),
936 "bitcoin::blockdata::script::Script" if is_ref => Some(".to_slice()))"),
937 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_rust())"),
938 "bitcoin::blockdata::transaction::Transaction" => Some(".into_bitcoin()"),
939 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(".into_rust()"),
940 "bitcoin::network::constants::Network" => Some(".into_bitcoin()"),
941 "bitcoin::blockdata::block::BlockHeader" => Some(" }).unwrap()"),
942 "bitcoin::blockdata::block::Block" => Some(".to_slice()).unwrap()"),
944 // Newtypes that we just expose in their original form.
945 "bitcoin::hash_types::Txid" if is_ref => Some(" }[..]).unwrap()"),
946 "bitcoin::hash_types::Txid" => Some(".data[..]).unwrap()"),
947 "bitcoin::hash_types::BlockHash" if !is_ref => Some(".data[..]).unwrap()"),
948 "lightning::ln::channelmanager::PaymentHash" if !is_ref => Some(".data)"),
949 "lightning::ln::channelmanager::PaymentHash" if is_ref => Some(" })"),
950 "lightning::ln::channelmanager::PaymentPreimage" if !is_ref => Some(".data)"),
951 "lightning::ln::channelmanager::PaymentPreimage" if is_ref => Some(" })"),
952 "lightning::ln::channelmanager::PaymentSecret" => Some(".data)"),
954 // List of traits we map (possibly during processing of other files):
955 "crate::util::logger::Logger" => Some(""),
958 }.map(|s| s.to_owned())
961 fn to_c_conversion_new_var_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<(&'b str, &'b str)> {
962 if self.is_primitive(full_path) {
966 "[u8]" if is_ref => Some(("crate::c_types::u8slice::from_slice(", ")")),
967 "[usize]" if is_ref => Some(("crate::c_types::usizeslice::from_slice(", ")")),
969 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(("{ let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(", ")); s }")),
970 "bitcoin::blockdata::block::Block" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
971 "bitcoin::hash_types::Txid" => None,
973 // Override the default since Records contain an fmt with a lifetime:
974 // TODO: We should include the other record fields
975 "lightning::util::logger::Record" => Some(("std::ffi::CString::new(format!(\"{}\", ", ".args)).unwrap()")),
977 }.map(|s| s.to_owned())
979 fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
980 if self.is_primitive(full_path) {
981 return Some("".to_owned());
984 "Result" if !is_ref => Some("local_"),
985 "Vec" if !is_ref => Some("local_"),
986 "Option" => Some("local_"),
988 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
989 "[u8; 32]" if is_ref => Some(""),
990 "[u8; 20]" if !is_ref => Some("crate::c_types::TwentyBytes { data: "),
991 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes { data: "),
992 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes { data: "),
993 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes { data: "),
994 "[u8; 3]" if is_ref => Some(""),
996 "[u8]" if is_ref => Some("local_"),
997 "[usize]" if is_ref => Some("local_"),
999 "str" if is_ref => Some(""),
1000 "String" => Some(""),
1002 "std::time::Duration" => Some(""),
1003 "std::io::Error" if !is_ref => Some("crate::c_types::IOError::from_rust("),
1005 "bech32::u5" => Some(""),
1007 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1008 => Some("crate::c_types::PublicKey::from_rust(&"),
1009 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature::from_rust(&"),
1010 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1011 if is_ref => Some(""),
1012 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1013 if !is_ref => Some("crate::c_types::SecretKey::from_rust("),
1014 "bitcoin::secp256k1::Error"|"secp256k1::Error"
1015 if !is_ref => Some("crate::c_types::Secp256k1Error::from_rust("),
1016 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice::from_slice(&"),
1017 "bitcoin::blockdata::script::Script" if !is_ref => Some(""),
1018 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some("crate::c_types::Transaction::from_bitcoin("),
1019 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction::from_bitcoin(&"),
1020 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::c_types::bitcoin_to_C_outpoint("),
1021 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut::from_rust("),
1022 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network::from_bitcoin("),
1023 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("&local_"),
1024 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice::from_slice(&local_"),
1026 "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1028 // Newtypes that we just expose in their original form.
1029 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1030 if is_ref => Some(""),
1031 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1032 if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1033 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1034 "lightning::ln::channelmanager::PaymentHash" if is_ref => Some("&"),
1035 "lightning::ln::channelmanager::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1036 "lightning::ln::channelmanager::PaymentPreimage" if is_ref => Some("&"),
1037 "lightning::ln::channelmanager::PaymentPreimage" => Some("crate::c_types::ThirtyTwoBytes { data: "),
1038 "lightning::ln::channelmanager::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1040 // Override the default since Records contain an fmt with a lifetime:
1041 "lightning::util::logger::Record" => Some("local_"),
1044 }.map(|s| s.to_owned())
1046 fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
1047 if self.is_primitive(full_path) {
1048 return Some("".to_owned());
1051 "Result" if !is_ref => Some(""),
1052 "Vec" if !is_ref => Some(".into()"),
1053 "Option" => Some(""),
1055 "[u8; 32]" if !is_ref => Some(" }"),
1056 "[u8; 32]" if is_ref => Some(""),
1057 "[u8; 20]" if !is_ref => Some(" }"),
1058 "[u8; 16]" if !is_ref => Some(" }"),
1059 "[u8; 10]" if !is_ref => Some(" }"),
1060 "[u8; 4]" if !is_ref => Some(" }"),
1061 "[u8; 3]" if is_ref => Some(""),
1063 "[u8]" if is_ref => Some(""),
1064 "[usize]" if is_ref => Some(""),
1066 "str" if is_ref => Some(".into()"),
1067 "String" if !is_ref => Some(".into_bytes().into()"),
1068 "String" if is_ref => Some(".as_str().into()"),
1070 "std::time::Duration" => Some(".as_secs()"),
1071 "std::io::Error" if !is_ref => Some(")"),
1073 "bech32::u5" => Some(".into()"),
1075 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1077 "bitcoin::secp256k1::Signature" => Some(")"),
1078 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1079 if !is_ref => Some(")"),
1080 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1081 if is_ref => Some(".as_ref()"),
1082 "bitcoin::secp256k1::Error"|"secp256k1::Error"
1083 if !is_ref => Some(")"),
1084 "bitcoin::blockdata::script::Script" if is_ref => Some("[..])"),
1085 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_bytes().into()"),
1086 "bitcoin::blockdata::transaction::Transaction" => Some(")"),
1087 "bitcoin::blockdata::transaction::OutPoint" => Some(")"),
1088 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(")"),
1089 "bitcoin::network::constants::Network" => Some(")"),
1090 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(""),
1091 "bitcoin::blockdata::block::Block" if is_ref => Some(")"),
1093 "bitcoin::hash_types::Txid" if !is_ref => Some(".into_inner() }"),
1095 // Newtypes that we just expose in their original form.
1096 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1097 if is_ref => Some(".as_inner()"),
1098 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1099 if !is_ref => Some(".into_inner() }"),
1100 "bitcoin::secp256k1::Message" if !is_ref => Some(".as_ref().clone() }"),
1101 "lightning::ln::channelmanager::PaymentHash" if is_ref => Some(".0"),
1102 "lightning::ln::channelmanager::PaymentHash" => Some(".0 }"),
1103 "lightning::ln::channelmanager::PaymentPreimage" if is_ref => Some(".0"),
1104 "lightning::ln::channelmanager::PaymentPreimage" => Some(".0 }"),
1105 "lightning::ln::channelmanager::PaymentSecret" if !is_ref => Some(".0 }"),
1107 // Override the default since Records contain an fmt with a lifetime:
1108 "lightning::util::logger::Record" => Some(".as_ptr()"),
1111 }.map(|s| s.to_owned())
1114 fn empty_val_check_suffix_from_path(&self, full_path: &str) -> Option<&str> {
1116 "lightning::ln::channelmanager::PaymentSecret" => Some(".data == [0; 32]"),
1117 "secp256k1::key::PublicKey"|"bitcoin::secp256k1::key::PublicKey" => Some(".is_null()"),
1118 "bitcoin::secp256k1::Signature" => Some(".is_null()"),
1123 // ****************************
1124 // *** Container Processing ***
1125 // ****************************
1127 /// Returns the module path in the generated mapping crate to the containers which we generate
1128 /// when writing to CrateTypes::template_file.
1129 pub fn generated_container_path() -> &'static str {
1130 "crate::c_types::derived"
1132 /// Returns the module path in the generated mapping crate to the container templates, which
1133 /// are then concretized and put in the generated container path/template_file.
1134 fn container_templ_path() -> &'static str {
1138 /// Returns true if the path containing the given args is a "transparent" container, ie an
1139 /// Option or a container which does not require a generated continer class.
1140 fn is_transparent_container<'i, I: Iterator<Item=&'i syn::Type>>(&self, full_path: &str, _is_ref: bool, mut args: I) -> bool {
1141 if full_path == "Option" {
1142 let inner = args.next().unwrap();
1143 assert!(args.next().is_none());
1145 syn::Type::Reference(_) => true,
1146 syn::Type::Path(p) => {
1147 if let Some(resolved) = self.maybe_resolve_path(&p.path, None) {
1148 if self.is_primitive(&resolved) { false } else { true }
1151 syn::Type::Tuple(_) => false,
1152 _ => unimplemented!(),
1156 /// Returns true if the path is a "transparent" container, ie an Option or a container which does
1157 /// not require a generated continer class.
1158 fn is_path_transparent_container(&self, full_path: &syn::Path, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
1159 let inner_iter = match &full_path.segments.last().unwrap().arguments {
1160 syn::PathArguments::None => return false,
1161 syn::PathArguments::AngleBracketed(args) => args.args.iter().map(|arg| {
1162 if let syn::GenericArgument::Type(ref ty) = arg {
1164 } else { unimplemented!() }
1166 syn::PathArguments::Parenthesized(_) => unimplemented!(),
1168 self.is_transparent_container(&self.resolve_path(full_path, generics), is_ref, inner_iter)
1170 /// Returns true if this is a known, supported, non-transparent container.
1171 fn is_known_container(&self, full_path: &str, is_ref: bool) -> bool {
1172 (full_path == "Result" && !is_ref) || (full_path == "Vec" && !is_ref) || full_path.ends_with("Tuple") || full_path == "Option"
1174 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)
1175 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1176 // expecting one element in the vec per generic type, each of which is inline-converted
1177 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1179 "Result" if !is_ref => {
1181 vec![(" { Ok(mut o) => crate::c_types::CResultTempl::ok(".to_string(), "o".to_string()),
1182 (").into(), Err(mut e) => crate::c_types::CResultTempl::err(".to_string(), "e".to_string())],
1183 ").into() }", ContainerPrefixLocation::PerConv))
1185 "Vec" if !is_ref => {
1186 Some(("Vec::new(); for mut item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1189 // We should only get here if the single contained has an inner
1190 assert!(self.c_type_has_inner(single_contained.unwrap()));
1191 Some(("Vec::new(); for mut item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "*item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1194 Some(("Vec::new(); for item in ", vec![(format!(".iter() {{ local_{}.push(", var_name), "*item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1197 if let Some(syn::Type::Path(p)) = single_contained {
1198 let inner_path = self.resolve_path(&p.path, generics);
1199 if self.is_primitive(&inner_path) {
1200 return Some(("if ", vec![
1201 (format!(".is_none() {{ {}::COption_{}Z::None }} else {{ ", Self::generated_container_path(), inner_path),
1202 format!("{}::COption_{}Z::Some({}.unwrap())", Self::generated_container_path(), inner_path, var_access))
1203 ], " }", ContainerPrefixLocation::NoPrefix));
1204 } else if self.c_type_has_inner_from_path(&inner_path) {
1206 return Some(("if ", vec![
1207 (".is_none() { std::ptr::null() } else { ".to_owned(), format!("({}.as_ref().unwrap())", var_access))
1208 ], " }", ContainerPrefixLocation::OutsideConv));
1210 return Some(("if ", vec![
1211 (".is_none() { std::ptr::null_mut() } else { ".to_owned(), format!("({}.unwrap())", var_access))
1212 ], " }", ContainerPrefixLocation::OutsideConv));
1216 if let Some(t) = single_contained {
1217 let mut v = Vec::new();
1218 self.write_empty_rust_val(generics, &mut v, t);
1219 let s = String::from_utf8(v).unwrap();
1220 return Some(("if ", vec![
1221 (format!(".is_none() {{ {} }} else {{ ", s), format!("({}.unwrap())", var_access))
1222 ], " }", ContainerPrefixLocation::PerConv));
1223 } else { unreachable!(); }
1229 /// only_contained_has_inner implies that there is only one contained element in the container
1230 /// and it has an inner field (ie is an "opaque" type we've defined).
1231 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)
1232 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1233 // expecting one element in the vec per generic type, each of which is inline-converted
1234 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1236 "Result" if !is_ref => {
1238 vec![(".result_ok { true => Ok(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.result)) }})", var_access)),
1239 ("), false => Err(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.err)) }})", var_access))],
1240 ")}", ContainerPrefixLocation::PerConv))
1242 "Slice" if is_ref => {
1243 Some(("Vec::new(); for mut item in ", vec![(format!(".as_slice().iter() {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1246 Some(("Vec::new(); for mut item in ", vec![(format!(".into_rust().drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1249 if let Some(syn::Type::Path(p)) = single_contained {
1250 let inner_path = self.resolve_path(&p.path, generics);
1251 if self.is_primitive(&inner_path) {
1252 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::NoPrefix))
1253 } else if self.c_type_has_inner_from_path(&inner_path) {
1255 return Some(("if ", vec![(".inner.is_null() { None } else { Some((*".to_string(), format!("{}", var_access))], ").clone()) }", ContainerPrefixLocation::PerConv))
1257 return Some(("if ", vec![(".inner.is_null() { None } else { Some(".to_string(), format!("{}", var_access))], ") }", ContainerPrefixLocation::PerConv));
1262 if let Some(t) = single_contained {
1264 syn::Type::Reference(_)|syn::Type::Path(_)|syn::Type::Slice(_) => {
1265 let mut v = Vec::new();
1266 let ret_ref = self.write_empty_rust_val_check_suffix(generics, &mut v, t);
1267 let s = String::from_utf8(v).unwrap();
1269 EmptyValExpectedTy::ReferenceAsPointer =>
1270 return Some(("if ", vec![
1271 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ &mut *{} }}", var_access))
1272 ], ") }", ContainerPrefixLocation::NoPrefix)),
1273 EmptyValExpectedTy::OwnedPointer => {
1274 if let syn::Type::Slice(_) = t {
1277 return Some(("if ", vec![
1278 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ *Box::from_raw({}) }}", var_access))
1279 ], ") }", ContainerPrefixLocation::NoPrefix));
1281 EmptyValExpectedTy::NonPointer =>
1282 return Some(("if ", vec![
1283 (format!("{} {{ None }} else {{ Some(", s), format!("{}", var_access))
1284 ], ") }", ContainerPrefixLocation::PerConv)),
1287 syn::Type::Tuple(_) => {
1288 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::PerConv))
1290 _ => unimplemented!(),
1292 } else { unreachable!(); }
1298 // *************************************************
1299 // *** Type definition during main.rs processing ***
1300 // *************************************************
1302 pub fn get_declared_type(&'a self, ident: &syn::Ident) -> Option<&'a DeclType<'c>> {
1303 self.types.get_declared_type(ident)
1305 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1306 pub fn c_type_has_inner_from_path(&self, full_path: &str) -> bool {
1307 self.crate_types.opaques.get(full_path).is_some()
1309 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1310 pub fn c_type_has_inner(&self, ty: &syn::Type) -> bool {
1312 syn::Type::Path(p) => {
1313 let full_path = self.resolve_path(&p.path, None);
1314 self.c_type_has_inner_from_path(&full_path)
1320 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
1321 self.types.maybe_resolve_ident(id)
1324 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
1325 self.types.maybe_resolve_non_ignored_ident(id)
1328 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
1329 self.types.maybe_resolve_path(p_arg, generics)
1331 pub fn resolve_path(&self, p: &syn::Path, generics: Option<&GenericTypes>) -> String {
1332 self.maybe_resolve_path(p, generics).unwrap()
1335 // ***********************************
1336 // *** Original Rust Type Printing ***
1337 // ***********************************
1339 fn in_rust_prelude(resolved_path: &str) -> bool {
1340 match resolved_path {
1348 fn write_rust_path<W: std::io::Write>(&self, w: &mut W, generics_resolver: Option<&GenericTypes>, path: &syn::Path) {
1349 if let Some(resolved) = self.maybe_resolve_path(&path, generics_resolver) {
1350 if self.is_primitive(&resolved) {
1351 write!(w, "{}", path.get_ident().unwrap()).unwrap();
1353 // TODO: We should have a generic "is from a dependency" check here instead of
1354 // checking for "bitcoin" explicitly.
1355 if resolved.starts_with("bitcoin::") || Self::in_rust_prelude(&resolved) {
1356 write!(w, "{}", resolved).unwrap();
1357 // If we're printing a generic argument, it needs to reference the crate, otherwise
1358 // the original crate:
1359 } else if self.maybe_resolve_path(&path, None).as_ref() == Some(&resolved) {
1360 write!(w, "{}", resolved).unwrap();
1362 write!(w, "crate::{}", resolved).unwrap();
1365 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().last().unwrap().arguments {
1366 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1369 if path.leading_colon.is_some() {
1370 write!(w, "::").unwrap();
1372 for (idx, seg) in path.segments.iter().enumerate() {
1373 if idx != 0 { write!(w, "::").unwrap(); }
1374 write!(w, "{}", seg.ident).unwrap();
1375 if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
1376 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1381 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>) {
1382 let mut had_params = false;
1383 for (idx, arg) in generics.enumerate() {
1384 if idx != 0 { write!(w, ", ").unwrap(); } else { write!(w, "<").unwrap(); }
1387 syn::GenericParam::Lifetime(lt) => write!(w, "'{}", lt.lifetime.ident).unwrap(),
1388 syn::GenericParam::Type(t) => {
1389 write!(w, "{}", t.ident).unwrap();
1390 if t.colon_token.is_some() { write!(w, ":").unwrap(); }
1391 for (idx, bound) in t.bounds.iter().enumerate() {
1392 if idx != 0 { write!(w, " + ").unwrap(); }
1394 syn::TypeParamBound::Trait(tb) => {
1395 if tb.paren_token.is_some() || tb.lifetimes.is_some() { unimplemented!(); }
1396 self.write_rust_path(w, generics_resolver, &tb.path);
1398 _ => unimplemented!(),
1401 if t.eq_token.is_some() || t.default.is_some() { unimplemented!(); }
1403 _ => unimplemented!(),
1406 if had_params { write!(w, ">").unwrap(); }
1409 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>) {
1410 write!(w, "<").unwrap();
1411 for (idx, arg) in generics.enumerate() {
1412 if idx != 0 { write!(w, ", ").unwrap(); }
1414 syn::GenericArgument::Type(t) => self.write_rust_type(w, generics_resolver, t),
1415 _ => unimplemented!(),
1418 write!(w, ">").unwrap();
1420 pub fn write_rust_type<W: std::io::Write>(&self, w: &mut W, generics: Option<&GenericTypes>, t: &syn::Type) {
1422 syn::Type::Path(p) => {
1423 if p.qself.is_some() {
1426 self.write_rust_path(w, generics, &p.path);
1428 syn::Type::Reference(r) => {
1429 write!(w, "&").unwrap();
1430 if let Some(lft) = &r.lifetime {
1431 write!(w, "'{} ", lft.ident).unwrap();
1433 if r.mutability.is_some() {
1434 write!(w, "mut ").unwrap();
1436 self.write_rust_type(w, generics, &*r.elem);
1438 syn::Type::Array(a) => {
1439 write!(w, "[").unwrap();
1440 self.write_rust_type(w, generics, &a.elem);
1441 if let syn::Expr::Lit(l) = &a.len {
1442 if let syn::Lit::Int(i) = &l.lit {
1443 write!(w, "; {}]", i).unwrap();
1444 } else { unimplemented!(); }
1445 } else { unimplemented!(); }
1447 syn::Type::Slice(s) => {
1448 write!(w, "[").unwrap();
1449 self.write_rust_type(w, generics, &s.elem);
1450 write!(w, "]").unwrap();
1452 syn::Type::Tuple(s) => {
1453 write!(w, "(").unwrap();
1454 for (idx, t) in s.elems.iter().enumerate() {
1455 if idx != 0 { write!(w, ", ").unwrap(); }
1456 self.write_rust_type(w, generics, &t);
1458 write!(w, ")").unwrap();
1460 _ => unimplemented!(),
1464 /// Prints a constructor for something which is "uninitialized" (but obviously not actually
1465 /// unint'd memory).
1466 pub fn write_empty_rust_val<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) {
1468 syn::Type::Path(p) => {
1469 let resolved = self.resolve_path(&p.path, generics);
1470 if self.crate_types.opaques.get(&resolved).is_some() {
1471 write!(w, "crate::{} {{ inner: std::ptr::null_mut(), is_owned: true }}", resolved).unwrap();
1473 // Assume its a manually-mapped C type, where we can just define an null() fn
1474 write!(w, "{}::null()", self.c_type_from_path(&resolved, false, false).unwrap()).unwrap();
1477 syn::Type::Array(a) => {
1478 if let syn::Expr::Lit(l) = &a.len {
1479 if let syn::Lit::Int(i) = &l.lit {
1480 if i.base10_digits().parse::<usize>().unwrap() < 32 {
1481 // Blindly assume that if we're trying to create an empty value for an
1482 // array < 32 entries that all-0s may be a valid state.
1485 let arrty = format!("[u8; {}]", i.base10_digits());
1486 write!(w, "{}", self.to_c_conversion_inline_prefix_from_path(&arrty, false, false).unwrap()).unwrap();
1487 write!(w, "[0; {}]", i.base10_digits()).unwrap();
1488 write!(w, "{}", self.to_c_conversion_inline_suffix_from_path(&arrty, false, false).unwrap()).unwrap();
1489 } else { unimplemented!(); }
1490 } else { unimplemented!(); }
1492 _ => unimplemented!(),
1496 fn is_real_type_array(&self, resolved_type: &str) -> Option<syn::Type> {
1497 if let Some(real_ty) = self.c_type_from_path(&resolved_type, true, false) {
1498 if real_ty.ends_with("]") && real_ty.starts_with("*const [u8; ") {
1499 let mut split = real_ty.split("; ");
1500 split.next().unwrap();
1501 let tail_str = split.next().unwrap();
1502 assert!(split.next().is_none());
1503 let len = usize::from_str_radix(&tail_str[..tail_str.len() - 1], 10).unwrap();
1504 Some(parse_quote!([u8; #len]))
1509 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1510 /// See EmptyValExpectedTy for information on return types.
1511 fn write_empty_rust_val_check_suffix<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) -> EmptyValExpectedTy {
1513 syn::Type::Path(p) => {
1514 let resolved = self.resolve_path(&p.path, generics);
1515 if let Some(arr_ty) = self.is_real_type_array(&resolved) {
1516 write!(w, ".data").unwrap();
1517 return self.write_empty_rust_val_check_suffix(generics, w, &arr_ty);
1519 if self.crate_types.opaques.get(&resolved).is_some() {
1520 write!(w, ".inner.is_null()").unwrap();
1521 EmptyValExpectedTy::NonPointer
1523 if let Some(suffix) = self.empty_val_check_suffix_from_path(&resolved) {
1524 write!(w, "{}", suffix).unwrap();
1525 // We may eventually need to allow empty_val_check_suffix_from_path to specify if we need a deref or not
1526 EmptyValExpectedTy::NonPointer
1528 write!(w, " == std::ptr::null_mut()").unwrap();
1529 EmptyValExpectedTy::OwnedPointer
1533 syn::Type::Array(a) => {
1534 if let syn::Expr::Lit(l) = &a.len {
1535 if let syn::Lit::Int(i) = &l.lit {
1536 write!(w, " == [0; {}]", i.base10_digits()).unwrap();
1537 EmptyValExpectedTy::NonPointer
1538 } else { unimplemented!(); }
1539 } else { unimplemented!(); }
1541 syn::Type::Slice(_) => {
1542 // Option<[]> always implies that we want to treat len() == 0 differently from
1543 // None, so we always map an Option<[]> into a pointer.
1544 write!(w, " == std::ptr::null_mut()").unwrap();
1545 EmptyValExpectedTy::ReferenceAsPointer
1547 _ => unimplemented!(),
1551 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1552 pub fn write_empty_rust_val_check<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type, var_access: &str) {
1554 syn::Type::Path(_) => {
1555 write!(w, "{}", var_access).unwrap();
1556 self.write_empty_rust_val_check_suffix(generics, w, t);
1558 syn::Type::Array(a) => {
1559 if let syn::Expr::Lit(l) = &a.len {
1560 if let syn::Lit::Int(i) = &l.lit {
1561 let arrty = format!("[u8; {}]", i.base10_digits());
1562 // We don't (yet) support a new-var conversion here.
1563 assert!(self.from_c_conversion_new_var_from_path(&arrty, false).is_none());
1565 self.from_c_conversion_prefix_from_path(&arrty, false).unwrap(),
1567 self.from_c_conversion_suffix_from_path(&arrty, false).unwrap()).unwrap();
1568 self.write_empty_rust_val_check_suffix(generics, w, t);
1569 } else { unimplemented!(); }
1570 } else { unimplemented!(); }
1572 _ => unimplemented!(),
1576 // ********************************
1577 // *** Type conversion printing ***
1578 // ********************************
1580 /// Returns true we if can just skip passing this to C entirely
1581 pub fn skip_arg(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
1583 syn::Type::Path(p) => {
1584 if p.qself.is_some() { unimplemented!(); }
1585 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1586 self.skip_path(&full_path)
1589 syn::Type::Reference(r) => {
1590 self.skip_arg(&*r.elem, generics)
1595 pub fn no_arg_to_rust<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1597 syn::Type::Path(p) => {
1598 if p.qself.is_some() { unimplemented!(); }
1599 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1600 write!(w, "{}", self.no_arg_path_to_rust(&full_path)).unwrap();
1603 syn::Type::Reference(r) => {
1604 self.no_arg_to_rust(w, &*r.elem, generics);
1610 fn write_conversion_inline_intern<W: std::io::Write,
1611 LP: Fn(&str, bool, bool) -> Option<String>, DL: Fn(&mut W, &DeclType, &str, bool, bool), SC: Fn(bool, Option<&str>) -> String>
1612 (&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool,
1613 tupleconv: &str, prefix: bool, sliceconv: SC, path_lookup: LP, decl_lookup: DL) {
1615 syn::Type::Reference(r) => {
1616 self.write_conversion_inline_intern(w, &*r.elem, generics, true, r.mutability.is_some(),
1617 ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1619 syn::Type::Path(p) => {
1620 if p.qself.is_some() {
1624 let resolved_path = self.resolve_path(&p.path, generics);
1625 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1626 return self.write_conversion_inline_intern(w, aliased_type, None, is_ref, is_mut, ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1627 } else if self.is_primitive(&resolved_path) {
1628 if is_ref && prefix {
1629 write!(w, "*").unwrap();
1631 } else if let Some(c_type) = path_lookup(&resolved_path, is_ref, ptr_for_ref) {
1632 write!(w, "{}", c_type).unwrap();
1633 } else if self.crate_types.opaques.get(&resolved_path).is_some() {
1634 decl_lookup(w, &DeclType::StructImported, &resolved_path, is_ref, is_mut);
1635 } else if self.crate_types.mirrored_enums.get(&resolved_path).is_some() {
1636 decl_lookup(w, &DeclType::MirroredEnum, &resolved_path, is_ref, is_mut);
1637 } else if let Some(t) = self.crate_types.traits.get(&resolved_path) {
1638 decl_lookup(w, &DeclType::Trait(t), &resolved_path, is_ref, is_mut);
1639 } else if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
1640 if let Some(decl_type) = self.types.maybe_resolve_declared(ident) {
1641 decl_lookup(w, decl_type, &self.maybe_resolve_ident(ident).unwrap(), is_ref, is_mut);
1642 } else { unimplemented!(); }
1643 } else { unimplemented!(); }
1645 syn::Type::Array(a) => {
1646 // We assume all arrays contain only [int_literal; X]s.
1647 // This may result in some outputs not compiling.
1648 if let syn::Expr::Lit(l) = &a.len {
1649 if let syn::Lit::Int(i) = &l.lit {
1650 write!(w, "{}", path_lookup(&format!("[u8; {}]", i.base10_digits()), is_ref, ptr_for_ref).unwrap()).unwrap();
1651 } else { unimplemented!(); }
1652 } else { unimplemented!(); }
1654 syn::Type::Slice(s) => {
1655 // We assume all slices contain only literals or references.
1656 // This may result in some outputs not compiling.
1657 if let syn::Type::Path(p) = &*s.elem {
1658 let resolved = self.resolve_path(&p.path, generics);
1659 assert!(self.is_primitive(&resolved));
1660 write!(w, "{}", path_lookup("[u8]", is_ref, ptr_for_ref).unwrap()).unwrap();
1661 } else if let syn::Type::Reference(r) = &*s.elem {
1662 if let syn::Type::Path(p) = &*r.elem {
1663 write!(w, "{}", sliceconv(self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)), None)).unwrap();
1664 } else { unimplemented!(); }
1665 } else if let syn::Type::Tuple(t) = &*s.elem {
1666 assert!(!t.elems.is_empty());
1668 write!(w, "{}", sliceconv(false, None)).unwrap();
1670 let mut needs_map = false;
1671 for e in t.elems.iter() {
1672 if let syn::Type::Reference(_) = e {
1677 let mut map_str = Vec::new();
1678 write!(&mut map_str, ".map(|(").unwrap();
1679 for i in 0..t.elems.len() {
1680 write!(&mut map_str, "{}{}", if i != 0 { ", " } else { "" }, ('a' as u8 + i as u8) as char).unwrap();
1682 write!(&mut map_str, ")| (").unwrap();
1683 for (idx, e) in t.elems.iter().enumerate() {
1684 if let syn::Type::Reference(_) = e {
1685 write!(&mut map_str, "{}{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1686 } else if let syn::Type::Path(_) = e {
1687 write!(&mut map_str, "{}*{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1688 } else { unimplemented!(); }
1690 write!(&mut map_str, "))").unwrap();
1691 write!(w, "{}", sliceconv(false, Some(&String::from_utf8(map_str).unwrap()))).unwrap();
1693 write!(w, "{}", sliceconv(false, None)).unwrap();
1696 } else { unimplemented!(); }
1698 syn::Type::Tuple(t) => {
1699 if t.elems.is_empty() {
1700 // cbindgen has poor support for (), see, eg https://github.com/eqrion/cbindgen/issues/527
1701 // so work around it by just pretending its a 0u8
1702 write!(w, "{}", tupleconv).unwrap();
1704 if prefix { write!(w, "local_").unwrap(); }
1707 _ => unimplemented!(),
1711 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) {
1712 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "0u8 /*", true, |_, _| "local_".to_owned(),
1713 |a, b, c| self.to_c_conversion_inline_prefix_from_path(a, b, c),
1714 |w, decl_type, decl_path, is_ref, _is_mut| {
1716 DeclType::MirroredEnum if is_ref && ptr_for_ref => write!(w, "crate::{}::from_native(", decl_path).unwrap(),
1717 DeclType::MirroredEnum if is_ref => write!(w, "&crate::{}::from_native(", decl_path).unwrap(),
1718 DeclType::MirroredEnum => write!(w, "crate::{}::native_into(", decl_path).unwrap(),
1719 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1720 write!(w, "crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1721 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1722 write!(w, "crate::{} {{ inner: unsafe {{ ( (&(*", decl_path).unwrap(),
1723 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1724 write!(w, "&crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1725 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1726 write!(w, "crate::{} {{ inner: ", decl_path).unwrap(),
1727 DeclType::EnumIgnored|DeclType::StructImported if !is_ref =>
1728 write!(w, "crate::{} {{ inner: Box::into_raw(Box::new(", decl_path).unwrap(),
1729 DeclType::Trait(_) if is_ref => write!(w, "").unwrap(),
1730 DeclType::Trait(_) if !is_ref => {},
1731 _ => panic!("{:?}", decl_path),
1735 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) {
1736 self.write_to_c_conversion_inline_prefix_inner(w, t, generics, false, ptr_for_ref, false);
1738 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) {
1739 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "*/", false, |_, _| ".into()".to_owned(),
1740 |a, b, c| self.to_c_conversion_inline_suffix_from_path(a, b, c),
1741 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1742 DeclType::MirroredEnum => write!(w, ")").unwrap(),
1743 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1744 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1745 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1746 write!(w, ") as *const _) as *mut _) }}, is_owned: false }}").unwrap(),
1747 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1748 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1749 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1750 write!(w, ", is_owned: true }}").unwrap(),
1751 DeclType::EnumIgnored|DeclType::StructImported if !is_ref => write!(w, ")), is_owned: true }}").unwrap(),
1752 DeclType::Trait(_) if is_ref => {},
1753 DeclType::Trait(_) => {
1754 // This is used when we're converting a concrete Rust type into a C trait
1755 // for use when a Rust trait method returns an associated type.
1756 // Because all of our C traits implement From<RustTypesImplementingTraits>
1757 // we can just call .into() here and be done.
1758 write!(w, ".into()").unwrap()
1760 _ => unimplemented!(),
1763 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) {
1764 self.write_to_c_conversion_inline_suffix_inner(w, t, generics, false, ptr_for_ref, false);
1767 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) {
1768 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "() /*", true, |_, _| "&local_".to_owned(),
1769 |a, b, _c| self.from_c_conversion_prefix_from_path(a, b),
1770 |w, decl_type, _full_path, is_ref, is_mut| match decl_type {
1771 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, "unsafe {{ &*(*").unwrap(),
1772 DeclType::StructImported if is_mut && is_ref => write!(w, "unsafe {{ &mut *").unwrap(),
1773 DeclType::StructImported if is_ref => write!(w, "unsafe {{ &*").unwrap(),
1774 DeclType::StructImported if !is_ref => write!(w, "*unsafe {{ Box::from_raw(").unwrap(),
1775 DeclType::MirroredEnum if is_ref => write!(w, "&").unwrap(),
1776 DeclType::MirroredEnum => {},
1777 DeclType::Trait(_) => {},
1778 _ => unimplemented!(),
1781 pub fn write_from_c_conversion_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1782 self.write_from_c_conversion_prefix_inner(w, t, generics, false, false);
1784 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) {
1785 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "*/", false,
1786 |has_inner, map_str_opt| match (has_inner, map_str_opt) {
1787 (false, Some(map_str)) => format!(".iter(){}.collect::<Vec<_>>()[..]", map_str),
1788 (false, None) => ".iter().collect::<Vec<_>>()[..]".to_owned(),
1789 (true, None) => "[..]".to_owned(),
1790 (true, Some(_)) => unreachable!(),
1792 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1793 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1794 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, ").inner }}").unwrap(),
1795 DeclType::StructImported if is_ref => write!(w, ".inner }}").unwrap(),
1796 DeclType::StructImported if !is_ref => write!(w, ".take_inner()) }}").unwrap(),
1797 DeclType::MirroredEnum if is_ref => write!(w, ".to_native()").unwrap(),
1798 DeclType::MirroredEnum => write!(w, ".into_native()").unwrap(),
1799 DeclType::Trait(_) => {},
1800 _ => unimplemented!(),
1803 pub fn write_from_c_conversion_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1804 self.write_from_c_conversion_suffix_inner(w, t, generics, false, false);
1806 // Note that compared to the above conversion functions, the following two are generally
1807 // significantly undertested:
1808 pub fn write_from_c_conversion_to_ref_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1809 self.write_conversion_inline_intern(w, t, generics, false, false, false, "() /*", true, |_, _| "&local_".to_owned(),
1811 if let Some(conv) = self.from_c_conversion_prefix_from_path(a, b) {
1812 Some(format!("&{}", conv))
1815 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1816 DeclType::StructImported if !is_ref => write!(w, "unsafe {{ &*").unwrap(),
1817 _ => unimplemented!(),
1820 pub fn write_from_c_conversion_to_ref_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1821 self.write_conversion_inline_intern(w, t, generics, false, false, false, "*/", false,
1822 |has_inner, map_str_opt| match (has_inner, map_str_opt) {
1823 (false, Some(map_str)) => format!(".iter(){}.collect::<Vec<_>>()[..]", map_str),
1824 (false, None) => ".iter().collect::<Vec<_>>()[..]".to_owned(),
1825 (true, None) => "[..]".to_owned(),
1826 (true, Some(_)) => unreachable!(),
1828 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1829 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1830 DeclType::StructImported if !is_ref => write!(w, ".inner }}").unwrap(),
1831 _ => unimplemented!(),
1835 fn write_conversion_new_var_intern<'b, W: std::io::Write,
1836 LP: Fn(&str, bool) -> Option<(&str, &str)>,
1837 LC: Fn(&str, bool, Option<&syn::Type>, &syn::Ident, &str) -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)>,
1838 VP: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool),
1839 VS: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool)>
1840 (&self, w: &mut W, ident: &syn::Ident, var: &str, t: &syn::Type, generics: Option<&GenericTypes>,
1841 mut is_ref: bool, mut ptr_for_ref: bool, to_c: bool,
1842 path_lookup: &LP, container_lookup: &LC, var_prefix: &VP, var_suffix: &VS) -> bool {
1844 macro_rules! convert_container {
1845 ($container_type: expr, $args_len: expr, $args_iter: expr) => { {
1846 // For slices (and Options), we refuse to directly map them as is_ref when they
1847 // aren't opaque types containing an inner pointer. This is due to the fact that,
1848 // in both cases, the actual higher-level type is non-is_ref.
1849 let ty_has_inner = if $args_len == 1 {
1850 let ty = $args_iter().next().unwrap();
1851 if $container_type == "Slice" && to_c {
1852 // "To C ptr_for_ref" means "return the regular object with is_owned
1853 // set to false", which is totally what we want in a slice if we're about to
1854 // set ty_has_inner.
1857 if let syn::Type::Reference(t) = ty {
1858 if let syn::Type::Path(p) = &*t.elem {
1859 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1861 } else if let syn::Type::Path(p) = ty {
1862 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1866 // Options get a bunch of special handling, since in general we map Option<>al
1867 // types into the same C type as non-Option-wrapped types. This ends up being
1868 // pretty manual here and most of the below special-cases are for Options.
1869 let mut needs_ref_map = false;
1870 let mut only_contained_type = None;
1871 let mut only_contained_has_inner = false;
1872 let mut contains_slice = false;
1874 only_contained_has_inner = ty_has_inner;
1875 let arg = $args_iter().next().unwrap();
1876 if let syn::Type::Reference(t) = arg {
1877 only_contained_type = Some(&*t.elem);
1878 if let syn::Type::Path(_) = &*t.elem {
1880 } else if let syn::Type::Slice(_) = &*t.elem {
1881 contains_slice = true;
1882 } else { return false; }
1883 // If the inner element contains an inner pointer, we will just use that,
1884 // avoiding the need to map elements to references. Otherwise we'll need to
1885 // do an extra mapping step.
1886 needs_ref_map = !only_contained_has_inner;
1888 only_contained_type = Some(&arg);
1892 if let Some((prefix, conversions, suffix, prefix_location)) = container_lookup(&$container_type, is_ref && ty_has_inner, only_contained_type, ident, var) {
1893 assert_eq!(conversions.len(), $args_len);
1894 write!(w, "let mut local_{}{} = ", ident, if !to_c && needs_ref_map {"_base"} else { "" }).unwrap();
1895 if prefix_location == ContainerPrefixLocation::OutsideConv {
1896 var_prefix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
1898 write!(w, "{}{}", prefix, var).unwrap();
1900 for ((pfx, var_name), (idx, ty)) in conversions.iter().zip($args_iter().enumerate()) {
1901 let mut var = std::io::Cursor::new(Vec::new());
1902 write!(&mut var, "{}", var_name).unwrap();
1903 let var_access = String::from_utf8(var.into_inner()).unwrap();
1905 let conv_ty = if needs_ref_map { only_contained_type.as_ref().unwrap() } else { ty };
1907 write!(w, "{} {{ ", pfx).unwrap();
1908 let new_var_name = format!("{}_{}", ident, idx);
1909 let new_var = self.write_conversion_new_var_intern(w, &format_ident!("{}", new_var_name),
1910 &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);
1911 if new_var { write!(w, " ").unwrap(); }
1913 if prefix_location == ContainerPrefixLocation::PerConv {
1914 var_prefix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1915 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
1916 write!(w, "Box::into_raw(Box::new(").unwrap();
1919 write!(w, "{}{}", if contains_slice { "local_" } else { "" }, if new_var { new_var_name } else { var_access }).unwrap();
1920 if prefix_location == ContainerPrefixLocation::PerConv {
1921 var_suffix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1922 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
1923 write!(w, "))").unwrap();
1925 write!(w, " }}").unwrap();
1927 write!(w, "{}", suffix).unwrap();
1928 if prefix_location == ContainerPrefixLocation::OutsideConv {
1929 var_suffix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
1931 write!(w, ";").unwrap();
1932 if !to_c && needs_ref_map {
1933 write!(w, " let mut local_{} = local_{}_base.as_ref()", ident, ident).unwrap();
1935 write!(w, ".map(|a| &a[..])").unwrap();
1937 write!(w, ";").unwrap();
1945 syn::Type::Reference(r) => {
1946 if let syn::Type::Slice(_) = &*r.elem {
1947 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)
1949 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)
1952 syn::Type::Path(p) => {
1953 if p.qself.is_some() {
1956 let resolved_path = self.resolve_path(&p.path, generics);
1957 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1958 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);
1960 if self.is_known_container(&resolved_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
1961 if let syn::PathArguments::AngleBracketed(args) = &p.path.segments.iter().next().unwrap().arguments {
1962 convert_container!(resolved_path, args.args.len(), || args.args.iter().map(|arg| {
1963 if let syn::GenericArgument::Type(ty) = arg {
1965 } else { unimplemented!(); }
1967 } else { unimplemented!(); }
1969 if self.is_primitive(&resolved_path) {
1971 } else if let Some(ty_ident) = single_ident_generic_path_to_ident(&p.path) {
1972 if let Some((prefix, suffix)) = path_lookup(&resolved_path, is_ref) {
1973 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
1975 } else if self.types.maybe_resolve_declared(ty_ident).is_some() {
1980 syn::Type::Array(_) => {
1981 // We assume all arrays contain only primitive types.
1982 // This may result in some outputs not compiling.
1985 syn::Type::Slice(s) => {
1986 if let syn::Type::Path(p) = &*s.elem {
1987 let resolved = self.resolve_path(&p.path, generics);
1988 assert!(self.is_primitive(&resolved));
1989 let slice_path = format!("[{}]", resolved);
1990 if let Some((prefix, suffix)) = path_lookup(&slice_path, true) {
1991 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
1994 } else if let syn::Type::Reference(ty) = &*s.elem {
1995 let tyref = [&*ty.elem];
1997 convert_container!("Slice", 1, || tyref.iter().map(|t| *t));
1998 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
1999 } else if let syn::Type::Tuple(t) = &*s.elem {
2000 // When mapping into a temporary new var, we need to own all the underlying objects.
2001 // Thus, we drop any references inside the tuple and convert with non-reference types.
2002 let mut elems = syn::punctuated::Punctuated::new();
2003 for elem in t.elems.iter() {
2004 if let syn::Type::Reference(r) = elem {
2005 elems.push((*r.elem).clone());
2007 elems.push(elem.clone());
2010 let ty = [syn::Type::Tuple(syn::TypeTuple {
2011 paren_token: t.paren_token, elems
2015 convert_container!("Slice", 1, || ty.iter());
2016 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
2017 } else { unimplemented!() }
2019 syn::Type::Tuple(t) => {
2020 if !t.elems.is_empty() {
2021 // We don't (yet) support tuple elements which cannot be converted inline
2022 write!(w, "let (").unwrap();
2023 for idx in 0..t.elems.len() {
2024 if idx != 0 { write!(w, ", ").unwrap(); }
2025 write!(w, "{} orig_{}_{}", if is_ref { "ref" } else { "mut" }, ident, idx).unwrap();
2027 write!(w, ") = {}{}; ", var, if !to_c { ".to_rust()" } else { "" }).unwrap();
2028 // Like other template types, tuples are always mapped as their non-ref
2029 // versions for types which have different ref mappings. Thus, we convert to
2030 // non-ref versions and handle opaque types with inner pointers manually.
2031 for (idx, elem) in t.elems.iter().enumerate() {
2032 if let syn::Type::Path(p) = elem {
2033 let v_name = format!("orig_{}_{}", ident, idx);
2034 let tuple_elem_ident = format_ident!("{}", &v_name);
2035 if self.write_conversion_new_var_intern(w, &tuple_elem_ident, &v_name, elem, generics,
2036 false, ptr_for_ref, to_c,
2037 path_lookup, container_lookup, var_prefix, var_suffix) {
2038 write!(w, " ").unwrap();
2039 // Opaque types with inner pointers shouldn't ever create new stack
2040 // variables, so we don't handle it and just assert that it doesn't
2042 assert!(!self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)));
2046 write!(w, "let mut local_{} = (", ident).unwrap();
2047 for (idx, elem) in t.elems.iter().enumerate() {
2048 let ty_has_inner = {
2050 // "To C ptr_for_ref" means "return the regular object with
2051 // is_owned set to false", which is totally what we want
2052 // if we're about to set ty_has_inner.
2055 if let syn::Type::Reference(t) = elem {
2056 if let syn::Type::Path(p) = &*t.elem {
2057 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2059 } else if let syn::Type::Path(p) = elem {
2060 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2063 if idx != 0 { write!(w, ", ").unwrap(); }
2064 var_prefix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2065 if is_ref && ty_has_inner {
2066 // For ty_has_inner, the regular var_prefix mapping will take a
2067 // reference, so deref once here to make sure we keep the original ref.
2068 write!(w, "*").unwrap();
2070 write!(w, "orig_{}_{}", ident, idx).unwrap();
2071 if is_ref && !ty_has_inner {
2072 // If we don't have an inner variable's reference to maintain, just
2073 // hope the type is Clonable and use that.
2074 write!(w, ".clone()").unwrap();
2076 var_suffix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2078 write!(w, "){};", if to_c { ".into()" } else { "" }).unwrap();
2082 _ => unimplemented!(),
2086 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 {
2087 self.write_conversion_new_var_intern(w, ident, var_access, t, generics, false, ptr_for_ref, true,
2088 &|a, b| self.to_c_conversion_new_var_from_path(a, b),
2089 &|a, b, c, d, e| self.to_c_conversion_container_new_var(generics, a, b, c, d, e),
2090 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
2091 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_prefix_inner(a, b, c, d, e, f),
2092 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_suffix_inner(a, b, c, d, e, f))
2094 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 {
2095 self.write_to_c_conversion_new_var_inner(w, ident, &format!("{}", ident), t, generics, ptr_for_ref)
2097 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 {
2098 self.write_conversion_new_var_intern(w, ident, &format!("{}", ident), t, generics, false, false, false,
2099 &|a, b| self.from_c_conversion_new_var_from_path(a, b),
2100 &|a, b, c, d, e| self.from_c_conversion_container_new_var(generics, a, b, c, d, e),
2101 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
2102 &|a, b, c, d, e, _f| self.write_from_c_conversion_prefix_inner(a, b, c, d, e),
2103 &|a, b, c, d, e, _f| self.write_from_c_conversion_suffix_inner(a, b, c, d, e))
2106 // ******************************************************
2107 // *** C Container Type Equivalent and alias Printing ***
2108 // ******************************************************
2110 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 {
2111 for (idx, t) in args.enumerate() {
2113 write!(w, ", ").unwrap();
2115 if let syn::Type::Reference(r_arg) = t {
2116 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2118 if !self.write_c_type_intern(w, &*r_arg.elem, generics, false, false, false) { return false; }
2120 // While write_c_type_intern, above is correct, we don't want to blindly convert a
2121 // reference to something stupid, so check that the container is either opaque or a
2122 // predefined type (currently only Transaction).
2123 if let syn::Type::Path(p_arg) = &*r_arg.elem {
2124 let resolved = self.resolve_path(&p_arg.path, generics);
2125 assert!(self.crate_types.opaques.get(&resolved).is_some() ||
2126 self.c_type_from_path(&resolved, true, true).is_some(), "Template generics should be opaque or have a predefined mapping");
2127 } else { unimplemented!(); }
2128 } else if let syn::Type::Path(p_arg) = t {
2129 if let Some(resolved) = self.maybe_resolve_path(&p_arg.path, generics) {
2130 if !self.is_primitive(&resolved) {
2131 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2134 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2136 if !self.write_c_type_intern(w, t, generics, false, false, false) { return false; }
2138 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2139 if !self.write_c_type_intern(w, t, generics, false, false, false) { return false; }
2144 fn check_create_container(&self, mangled_container: String, container_type: &str, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
2145 if !self.crate_types.templates_defined.borrow().get(&mangled_container).is_some() {
2146 let mut created_container: Vec<u8> = Vec::new();
2148 if container_type == "Result" {
2149 let mut a_ty: Vec<u8> = Vec::new();
2150 if let syn::Type::Tuple(tup) = args.iter().next().unwrap() {
2151 if tup.elems.is_empty() {
2152 write!(&mut a_ty, "()").unwrap();
2154 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
2157 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
2160 let mut b_ty: Vec<u8> = Vec::new();
2161 if let syn::Type::Tuple(tup) = args.iter().skip(1).next().unwrap() {
2162 if tup.elems.is_empty() {
2163 write!(&mut b_ty, "()").unwrap();
2165 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
2168 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
2171 let ok_str = String::from_utf8(a_ty).unwrap();
2172 let err_str = String::from_utf8(b_ty).unwrap();
2173 let is_clonable = self.is_clonable(&ok_str) && self.is_clonable(&err_str);
2174 write_result_block(&mut created_container, &mangled_container, &ok_str, &err_str, is_clonable);
2176 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2178 } else if container_type == "Vec" {
2179 let mut a_ty: Vec<u8> = Vec::new();
2180 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2181 let ty = String::from_utf8(a_ty).unwrap();
2182 let is_clonable = self.is_clonable(&ty);
2183 write_vec_block(&mut created_container, &mangled_container, &ty, is_clonable);
2185 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2187 } else if container_type.ends_with("Tuple") {
2188 let mut tuple_args = Vec::new();
2189 let mut is_clonable = true;
2190 for arg in args.iter() {
2191 let mut ty: Vec<u8> = Vec::new();
2192 if !self.write_template_generics(&mut ty, &mut [arg].iter().map(|t| **t), generics, is_ref) { return false; }
2193 let ty_str = String::from_utf8(ty).unwrap();
2194 if !self.is_clonable(&ty_str) {
2195 is_clonable = false;
2197 tuple_args.push(ty_str);
2199 write_tuple_block(&mut created_container, &mangled_container, &tuple_args, is_clonable);
2201 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2203 } else if container_type == "Option" {
2204 let mut a_ty: Vec<u8> = Vec::new();
2205 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2206 let ty = String::from_utf8(a_ty).unwrap();
2207 let is_clonable = self.is_clonable(&ty);
2208 write_option_block(&mut created_container, &mangled_container, &ty, is_clonable);
2210 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2215 self.crate_types.write_new_template(mangled_container.clone(), true, &created_container);
2219 fn path_to_generic_args(path: &syn::Path) -> Vec<&syn::Type> {
2220 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().next().unwrap().arguments {
2221 args.args.iter().map(|gen| if let syn::GenericArgument::Type(t) = gen { t } else { unimplemented!() }).collect()
2222 } else { unimplemented!(); }
2224 fn write_c_mangled_container_path_intern<W: std::io::Write>
2225 (&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 {
2226 let mut mangled_type: Vec<u8> = Vec::new();
2227 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2228 write!(w, "C{}_", ident).unwrap();
2229 write!(mangled_type, "C{}_", ident).unwrap();
2230 } else { assert_eq!(args.len(), 1); }
2231 for arg in args.iter() {
2232 macro_rules! write_path {
2233 ($p_arg: expr, $extra_write: expr) => {
2234 if let Some(subtype) = self.maybe_resolve_path(&$p_arg.path, generics) {
2235 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2237 if self.c_type_has_inner_from_path(&subtype) {
2238 if !self.write_c_path_intern(w, &$p_arg.path, generics, is_ref, is_mut, ptr_for_ref) { return false; }
2240 if let Some(arr_ty) = self.is_real_type_array(&subtype) {
2241 if !self.write_c_type_intern(w, &arr_ty, generics, false, true, false) { return false; }
2243 // Option<T> needs to be converted to a *mut T, ie mut ptr-for-ref
2244 if !self.write_c_path_intern(w, &$p_arg.path, generics, true, true, true) { return false; }
2248 write!(w, "{}", $p_arg.path.segments.last().unwrap().ident).unwrap();
2250 } else if self.is_known_container(&subtype, is_ref) || self.is_path_transparent_container(&$p_arg.path, generics, is_ref) {
2251 if !self.write_c_mangled_container_path_intern(w, Self::path_to_generic_args(&$p_arg.path), generics,
2252 &subtype, is_ref, is_mut, ptr_for_ref, true) {
2255 self.write_c_mangled_container_path_intern(&mut mangled_type, Self::path_to_generic_args(&$p_arg.path),
2256 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2257 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2258 self.write_c_mangled_container_path_intern(w2, Self::path_to_generic_args(&$p_arg.path),
2259 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2262 let id = subtype.rsplitn(2, ':').next().unwrap(); // Get the "Base" name of the resolved type
2263 write!(w, "{}", id).unwrap();
2264 write!(mangled_type, "{}", id).unwrap();
2265 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2266 write!(w2, "{}", id).unwrap();
2269 } else { return false; }
2272 if let syn::Type::Tuple(tuple) = arg {
2273 if tuple.elems.len() == 0 {
2274 write!(w, "None").unwrap();
2275 write!(mangled_type, "None").unwrap();
2277 let mut mangled_tuple_type: Vec<u8> = Vec::new();
2279 // Figure out what the mangled type should look like. To disambiguate
2280 // ((A, B), C) and (A, B, C) we prefix the generic args with a _ and suffix
2281 // them with a Z. Ideally we wouldn't use Z, but not many special chars are
2282 // available for use in type names.
2283 write!(w, "C{}Tuple_", tuple.elems.len()).unwrap();
2284 write!(mangled_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2285 write!(mangled_tuple_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2286 for elem in tuple.elems.iter() {
2287 if let syn::Type::Path(p) = elem {
2288 write_path!(p, Some(&mut mangled_tuple_type));
2289 } else if let syn::Type::Reference(refelem) = elem {
2290 if let syn::Type::Path(p) = &*refelem.elem {
2291 write_path!(p, Some(&mut mangled_tuple_type));
2292 } else { return false; }
2293 } else { return false; }
2295 write!(w, "Z").unwrap();
2296 write!(mangled_type, "Z").unwrap();
2297 write!(mangled_tuple_type, "Z").unwrap();
2298 if !self.check_create_container(String::from_utf8(mangled_tuple_type).unwrap(),
2299 &format!("{}Tuple", tuple.elems.len()), tuple.elems.iter().collect(), generics, is_ref) {
2303 } else if let syn::Type::Path(p_arg) = arg {
2304 write_path!(p_arg, None);
2305 } else if let syn::Type::Reference(refty) = arg {
2306 if let syn::Type::Path(p_arg) = &*refty.elem {
2307 write_path!(p_arg, None);
2308 } else if let syn::Type::Slice(_) = &*refty.elem {
2309 // write_c_type will actually do exactly what we want here, we just need to
2310 // make it a pointer so that its an option. Note that we cannot always convert
2311 // the Vec-as-slice (ie non-ref types) containers, so sometimes need to be able
2312 // to edit it, hence we use *mut here instead of *const.
2313 if args.len() != 1 { return false; }
2314 write!(w, "*mut ").unwrap();
2315 self.write_c_type(w, arg, None, true);
2316 } else { return false; }
2317 } else if let syn::Type::Array(a) = arg {
2318 if let syn::Type::Path(p_arg) = &*a.elem {
2319 let resolved = self.resolve_path(&p_arg.path, generics);
2320 if !self.is_primitive(&resolved) { return false; }
2321 if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(len), .. }) = &a.len {
2322 if self.c_type_from_path(&format!("[{}; {}]", resolved, len.base10_digits()), is_ref, ptr_for_ref).is_none() { return false; }
2323 write!(w, "_{}{}", resolved, len.base10_digits()).unwrap();
2324 write!(mangled_type, "_{}{}", resolved, len.base10_digits()).unwrap();
2325 } else { return false; }
2326 } else { return false; }
2327 } else { return false; }
2329 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) { return true; }
2330 // Push the "end of type" Z
2331 write!(w, "Z").unwrap();
2332 write!(mangled_type, "Z").unwrap();
2334 // Make sure the type is actually defined:
2335 self.check_create_container(String::from_utf8(mangled_type).unwrap(), ident, args, generics, is_ref)
2337 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 {
2338 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2339 write!(w, "{}::", Self::generated_container_path()).unwrap();
2341 self.write_c_mangled_container_path_intern(w, args, generics, ident, is_ref, is_mut, ptr_for_ref, false)
2344 // **********************************
2345 // *** C Type Equivalent Printing ***
2346 // **********************************
2348 fn write_c_path_intern<W: std::io::Write>(&self, w: &mut W, path: &syn::Path, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool) -> bool {
2349 let full_path = match self.maybe_resolve_path(&path, generics) {
2350 Some(path) => path, None => return false };
2351 if let Some(c_type) = self.c_type_from_path(&full_path, is_ref, ptr_for_ref) {
2352 write!(w, "{}", c_type).unwrap();
2354 } else if self.crate_types.traits.get(&full_path).is_some() {
2355 if is_ref && ptr_for_ref {
2356 write!(w, "*{} crate::{}", if is_mut { "mut" } else { "const" }, full_path).unwrap();
2358 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2360 write!(w, "crate::{}", full_path).unwrap();
2363 } else if self.crate_types.opaques.get(&full_path).is_some() || self.crate_types.mirrored_enums.get(&full_path).is_some() {
2364 if is_ref && ptr_for_ref {
2365 // ptr_for_ref implies we're returning the object, which we can't really do for
2366 // opaque or mirrored types without box'ing them, which is quite a waste, so return
2367 // the actual object itself (for opaque types we'll set the pointer to the actual
2368 // type and note that its a reference).
2369 write!(w, "crate::{}", full_path).unwrap();
2371 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2373 write!(w, "crate::{}", full_path).unwrap();
2380 fn write_c_type_intern<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool) -> bool {
2382 syn::Type::Path(p) => {
2383 if p.qself.is_some() {
2386 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
2387 if self.is_known_container(&full_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
2388 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);
2390 if let Some(aliased_type) = self.crate_types.type_aliases.get(&full_path).cloned() {
2391 return self.write_c_type_intern(w, &aliased_type, None, is_ref, is_mut, ptr_for_ref);
2394 self.write_c_path_intern(w, &p.path, generics, is_ref, is_mut, ptr_for_ref)
2396 syn::Type::Reference(r) => {
2397 self.write_c_type_intern(w, &*r.elem, generics, true, r.mutability.is_some(), ptr_for_ref)
2399 syn::Type::Array(a) => {
2400 if is_ref && is_mut {
2401 write!(w, "*mut [").unwrap();
2402 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2404 write!(w, "*const [").unwrap();
2405 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2407 let mut typecheck = Vec::new();
2408 if !self.write_c_type_intern(&mut typecheck, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2409 if typecheck[..] != ['u' as u8, '8' as u8] { return false; }
2411 if let syn::Expr::Lit(l) = &a.len {
2412 if let syn::Lit::Int(i) = &l.lit {
2414 if let Some(ty) = self.c_type_from_path(&format!("[u8; {}]", i.base10_digits()), false, ptr_for_ref) {
2415 write!(w, "{}", ty).unwrap();
2419 write!(w, "; {}]", i).unwrap();
2425 syn::Type::Slice(s) => {
2426 if !is_ref || is_mut { return false; }
2427 if let syn::Type::Path(p) = &*s.elem {
2428 let resolved = self.resolve_path(&p.path, generics);
2429 if self.is_primitive(&resolved) {
2430 write!(w, "{}::{}slice", Self::container_templ_path(), resolved).unwrap();
2433 } else if let syn::Type::Reference(r) = &*s.elem {
2434 if let syn::Type::Path(p) = &*r.elem {
2435 // Slices with "real types" inside are mapped as the equivalent non-ref Vec
2436 let resolved = self.resolve_path(&p.path, generics);
2437 let mangled_container = if let Some(ident) = self.crate_types.opaques.get(&resolved) {
2438 format!("CVec_{}Z", ident)
2439 } else if let Some(en) = self.crate_types.mirrored_enums.get(&resolved) {
2440 format!("CVec_{}Z", en.ident)
2441 } else if let Some(id) = p.path.get_ident() {
2442 format!("CVec_{}Z", id)
2443 } else { return false; };
2444 write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
2445 self.check_create_container(mangled_container, "Vec", vec![&*r.elem], generics, false)
2447 } else if let syn::Type::Tuple(_) = &*s.elem {
2448 let mut args = syn::punctuated::Punctuated::<_, syn::token::Comma>::new();
2449 args.push(syn::GenericArgument::Type((*s.elem).clone()));
2450 let mut segments = syn::punctuated::Punctuated::new();
2451 segments.push(parse_quote!(Vec<#args>));
2452 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)
2455 syn::Type::Tuple(t) => {
2456 if t.elems.len() == 0 {
2459 self.write_c_mangled_container_path(w, t.elems.iter().collect(), generics,
2460 &format!("{}Tuple", t.elems.len()), is_ref, is_mut, ptr_for_ref)
2466 pub fn write_c_type<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) {
2467 assert!(self.write_c_type_intern(w, t, generics, false, false, ptr_for_ref));
2469 pub fn understood_c_path(&self, p: &syn::Path) -> bool {
2470 if p.leading_colon.is_some() { return false; }
2471 self.write_c_path_intern(&mut std::io::sink(), p, None, false, false, false)
2473 pub fn understood_c_type(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
2474 self.write_c_type_intern(&mut std::io::sink(), t, generics, false, false, false)