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};
19 // The following utils are used purely to build our known types maps - they break down all the
20 // types we need to resolve to include the given object, and no more.
22 pub fn first_seg_self<'a>(t: &'a syn::Type) -> Option<impl Iterator<Item=&syn::PathSegment> + 'a> {
24 syn::Type::Path(p) => {
25 if p.qself.is_some() || p.path.leading_colon.is_some() {
28 let mut segs = p.path.segments.iter();
29 let ty = segs.next().unwrap();
30 if !ty.arguments.is_empty() { return None; }
31 if format!("{}", ty.ident) == "Self" {
39 pub fn get_single_remaining_path_seg<'a, I: Iterator<Item=&'a syn::PathSegment>>(segs: &mut I) -> Option<&'a syn::Ident> {
40 if let Some(ty) = segs.next() {
41 if !ty.arguments.is_empty() { unimplemented!(); }
42 if segs.next().is_some() { return None; }
47 pub fn single_ident_generic_path_to_ident(p: &syn::Path) -> Option<&syn::Ident> {
48 if p.segments.len() == 1 {
49 Some(&p.segments.iter().next().unwrap().ident)
53 pub fn path_matches_nongeneric(p: &syn::Path, exp: &[&str]) -> bool {
54 if p.segments.len() != exp.len() { return false; }
55 for (seg, e) in p.segments.iter().zip(exp.iter()) {
56 if seg.arguments != syn::PathArguments::None { return false; }
57 if &format!("{}", seg.ident) != *e { return false; }
62 #[derive(Debug, PartialEq)]
63 pub enum ExportStatus {
68 /// Gets the ExportStatus of an object (struct, fn, etc) given its attributes.
69 pub fn export_status(attrs: &[syn::Attribute]) -> ExportStatus {
70 for attr in attrs.iter() {
71 let tokens_clone = attr.tokens.clone();
72 let mut token_iter = tokens_clone.into_iter();
73 if let Some(token) = token_iter.next() {
75 TokenTree::Punct(c) if c.as_char() == '=' => {
76 // Really not sure where syn gets '=' from here -
77 // it somehow represents '///' or '//!'
79 TokenTree::Group(g) => {
80 if format!("{}", single_ident_generic_path_to_ident(&attr.path).unwrap()) == "cfg" {
81 let mut iter = g.stream().into_iter();
82 if let TokenTree::Ident(i) = iter.next().unwrap() {
84 // #[cfg(any(test, feature = ""))]
85 if let TokenTree::Group(g) = iter.next().unwrap() {
86 let mut all_test = true;
87 for token in g.stream().into_iter() {
88 if let TokenTree::Ident(i) = token {
89 match format!("{}", i).as_str() {
92 _ => all_test = false,
94 } else if let TokenTree::Literal(lit) = token {
95 if format!("{}", lit) != "fuzztarget" {
100 if all_test { return ExportStatus::TestOnly; }
102 } else if i == "test" || i == "feature" {
103 // If its cfg(feature(...)) we assume its test-only
104 return ExportStatus::TestOnly;
108 continue; // eg #[derive()]
110 _ => unimplemented!(),
113 match token_iter.next().unwrap() {
114 TokenTree::Literal(lit) => {
115 let line = format!("{}", lit);
116 if line.contains("(C-not exported)") {
117 return ExportStatus::NoExport;
120 _ => unimplemented!(),
126 pub fn assert_simple_bound(bound: &syn::TraitBound) {
127 if bound.paren_token.is_some() || bound.lifetimes.is_some() { unimplemented!(); }
128 if let syn::TraitBoundModifier::Maybe(_) = bound.modifier { unimplemented!(); }
131 /// Returns true if the enum will be mapped as an opaue (ie struct with a pointer to the underlying
132 /// type), otherwise it is mapped into a transparent, C-compatible version of itself.
133 pub fn is_enum_opaque(e: &syn::ItemEnum) -> bool {
134 for var in e.variants.iter() {
135 if let syn::Fields::Named(fields) = &var.fields {
136 for field in fields.named.iter() {
137 match export_status(&field.attrs) {
138 ExportStatus::Export|ExportStatus::TestOnly => {},
139 ExportStatus::NoExport => return true,
142 } else if let syn::Fields::Unnamed(fields) = &var.fields {
143 for field in fields.unnamed.iter() {
144 match export_status(&field.attrs) {
145 ExportStatus::Export|ExportStatus::TestOnly => {},
146 ExportStatus::NoExport => return true,
154 /// A stack of sets of generic resolutions.
156 /// This tracks the template parameters for a function, struct, or trait, allowing resolution into
157 /// a concrete type. By pushing a new context onto the stack, this can track a function's template
158 /// parameters inside of a generic struct or trait.
160 /// It maps both direct types as well as Deref<Target = X>, mapping them via the provided
161 /// TypeResolver's resolve_path function (ie traits map to the concrete jump table, structs to the
162 /// concrete C container struct, etc).
164 pub struct GenericTypes<'a, 'b> {
165 parent: Option<&'b GenericTypes<'b, 'b>>,
166 typed_generics: HashMap<&'a syn::Ident, (String, Option<&'a syn::Path>)>,
168 impl<'a, 'p: 'a> GenericTypes<'a, 'p> {
169 pub fn new() -> Self {
170 Self { parent: None, typed_generics: HashMap::new(), }
173 /// push a new context onto the stack, allowing for a new set of generics to be learned which
174 /// will override any lower contexts, but which will still fall back to resoltion via lower
176 pub fn push_ctx<'c>(&'c self) -> GenericTypes<'a, 'c> {
177 GenericTypes { parent: Some(self), typed_generics: HashMap::new(), }
180 /// Learn the generics in generics in the current context, given a TypeResolver.
181 pub fn learn_generics<'b, 'c>(&mut self, generics: &'a syn::Generics, types: &'b TypeResolver<'a, 'c>) -> bool {
182 // First learn simple generics...
183 for generic in generics.params.iter() {
185 syn::GenericParam::Type(type_param) => {
186 let mut non_lifetimes_processed = false;
187 for bound in type_param.bounds.iter() {
188 if let syn::TypeParamBound::Trait(trait_bound) = bound {
189 if let Some(ident) = single_ident_generic_path_to_ident(&trait_bound.path) {
190 match &format!("{}", ident) as &str { "Send" => continue, "Sync" => continue, _ => {} }
192 if path_matches_nongeneric(&trait_bound.path, &["core", "clone", "Clone"]) { continue; }
194 assert_simple_bound(&trait_bound);
195 if let Some(mut path) = types.maybe_resolve_path(&trait_bound.path, None) {
196 if types.skip_path(&path) { continue; }
197 if non_lifetimes_processed { return false; }
198 non_lifetimes_processed = true;
199 let new_ident = if path != "std::ops::Deref" {
200 path = "crate::".to_string() + &path;
201 Some(&trait_bound.path)
203 self.typed_generics.insert(&type_param.ident, (path, new_ident));
204 } else { return false; }
211 // Then find generics where we are required to pass a Deref<Target=X> and pretend its just X.
212 if let Some(wh) = &generics.where_clause {
213 for pred in wh.predicates.iter() {
214 if let syn::WherePredicate::Type(t) = pred {
215 if let syn::Type::Path(p) = &t.bounded_ty {
216 if p.qself.is_some() { return false; }
217 if p.path.leading_colon.is_some() { return false; }
218 let mut p_iter = p.path.segments.iter();
219 if let Some(gen) = self.typed_generics.get_mut(&p_iter.next().unwrap().ident) {
220 if gen.0 != "std::ops::Deref" { return false; }
221 if &format!("{}", p_iter.next().unwrap().ident) != "Target" { return false; }
223 let mut non_lifetimes_processed = false;
224 for bound in t.bounds.iter() {
225 if let syn::TypeParamBound::Trait(trait_bound) = bound {
226 if non_lifetimes_processed { return false; }
227 non_lifetimes_processed = true;
228 assert_simple_bound(&trait_bound);
229 *gen = ("crate::".to_string() + &types.resolve_path(&trait_bound.path, None),
230 Some(&trait_bound.path));
233 } else { return false; }
234 } else { return false; }
238 for (_, (_, ident)) in self.typed_generics.iter() {
239 if ident.is_none() { return false; }
244 /// Learn the associated types from the trait in the current context.
245 pub fn learn_associated_types<'b, 'c>(&mut self, t: &'a syn::ItemTrait, types: &'b TypeResolver<'a, 'c>) {
246 for item in t.items.iter() {
248 &syn::TraitItem::Type(ref t) => {
249 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
250 let mut bounds_iter = t.bounds.iter();
251 match bounds_iter.next().unwrap() {
252 syn::TypeParamBound::Trait(tr) => {
253 assert_simple_bound(&tr);
254 if let Some(mut path) = types.maybe_resolve_path(&tr.path, None) {
255 if types.skip_path(&path) { continue; }
256 // In general we handle Deref<Target=X> as if it were just X (and
257 // implement Deref<Target=Self> for relevant types). We don't
258 // bother to implement it for associated types, however, so we just
259 // ignore such bounds.
260 let new_ident = if path != "std::ops::Deref" {
261 path = "crate::".to_string() + &path;
264 self.typed_generics.insert(&t.ident, (path, new_ident));
265 } else { unimplemented!(); }
267 _ => unimplemented!(),
269 if bounds_iter.next().is_some() { unimplemented!(); }
276 /// Attempt to resolve an Ident as a generic parameter and return the full path.
277 pub fn maybe_resolve_ident<'b>(&'b self, ident: &syn::Ident) -> Option<&'b String> {
278 if let Some(res) = self.typed_generics.get(ident).map(|(a, _)| a) {
281 if let Some(parent) = self.parent {
282 parent.maybe_resolve_ident(ident)
287 /// Attempt to resolve a Path as a generic parameter and return the full path. as both a string
289 pub fn maybe_resolve_path<'b>(&'b self, path: &syn::Path) -> Option<(&'b String, &'a syn::Path)> {
290 if let Some(ident) = path.get_ident() {
291 if let Some(res) = self.typed_generics.get(ident).map(|(a, b)| (a, b.unwrap())) {
295 // Associated types are usually specified as "Self::Generic", so we check for that
297 let mut it = path.segments.iter();
298 if path.segments.len() == 2 && format!("{}", it.next().unwrap().ident) == "Self" {
299 let ident = &it.next().unwrap().ident;
300 if let Some(res) = self.typed_generics.get(ident).map(|(a, b)| (a, b.unwrap())) {
305 if let Some(parent) = self.parent {
306 parent.maybe_resolve_path(path)
313 #[derive(Clone, PartialEq)]
314 // The type of declaration and the object itself
315 pub enum DeclType<'a> {
317 Trait(&'a syn::ItemTrait),
323 pub struct ImportResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
324 module_path: &'mod_lifetime str,
325 imports: HashMap<syn::Ident, (String, syn::Path)>,
326 declared: HashMap<syn::Ident, DeclType<'crate_lft>>,
327 priv_modules: HashSet<syn::Ident>,
329 impl<'mod_lifetime, 'crate_lft: 'mod_lifetime> ImportResolver<'mod_lifetime, 'crate_lft> {
330 fn process_use_intern(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::UseTree, partial_path: &str, mut path: syn::punctuated::Punctuated<syn::PathSegment, syn::token::Colon2>) {
332 syn::UseTree::Path(p) => {
333 let new_path = format!("{}{}::", partial_path, p.ident);
334 path.push(syn::PathSegment { ident: p.ident.clone(), arguments: syn::PathArguments::None });
335 Self::process_use_intern(imports, &p.tree, &new_path, path);
337 syn::UseTree::Name(n) => {
338 let full_path = format!("{}{}", partial_path, n.ident);
339 path.push(syn::PathSegment { ident: n.ident.clone(), arguments: syn::PathArguments::None });
340 imports.insert(n.ident.clone(), (full_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
342 syn::UseTree::Group(g) => {
343 for i in g.items.iter() {
344 Self::process_use_intern(imports, i, partial_path, path.clone());
347 syn::UseTree::Rename(r) => {
348 let full_path = format!("{}{}", partial_path, r.ident);
349 path.push(syn::PathSegment { ident: r.ident.clone(), arguments: syn::PathArguments::None });
350 imports.insert(r.rename.clone(), (full_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
352 syn::UseTree::Glob(_) => {
353 eprintln!("Ignoring * use for {} - this may result in resolution failures", partial_path);
358 fn process_use(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::ItemUse) {
359 if let syn::Visibility::Public(_) = u.vis {
360 // We actually only use these for #[cfg(fuzztarget)]
361 eprintln!("Ignoring pub(use) tree!");
364 if u.leading_colon.is_some() { eprintln!("Ignoring leading-colon use!"); return; }
365 Self::process_use_intern(imports, &u.tree, "", syn::punctuated::Punctuated::new());
368 fn insert_primitive(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, id: &str) {
369 let ident = syn::Ident::new(id, Span::call_site());
370 let mut path = syn::punctuated::Punctuated::new();
371 path.push(syn::PathSegment { ident: ident.clone(), arguments: syn::PathArguments::None });
372 imports.insert(ident, (id.to_owned(), syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
375 pub fn new(module_path: &'mod_lifetime str, contents: &'crate_lft [syn::Item]) -> Self {
376 let mut imports = HashMap::new();
377 // Add primitives to the "imports" list:
378 Self::insert_primitive(&mut imports, "bool");
379 Self::insert_primitive(&mut imports, "u64");
380 Self::insert_primitive(&mut imports, "u32");
381 Self::insert_primitive(&mut imports, "u16");
382 Self::insert_primitive(&mut imports, "u8");
383 Self::insert_primitive(&mut imports, "usize");
384 Self::insert_primitive(&mut imports, "str");
385 Self::insert_primitive(&mut imports, "String");
387 // These are here to allow us to print native Rust types in trait fn impls even if we don't
389 Self::insert_primitive(&mut imports, "Result");
390 Self::insert_primitive(&mut imports, "Vec");
391 Self::insert_primitive(&mut imports, "Option");
393 let mut declared = HashMap::new();
394 let mut priv_modules = HashSet::new();
396 for item in contents.iter() {
398 syn::Item::Use(u) => Self::process_use(&mut imports, &u),
399 syn::Item::Struct(s) => {
400 if let syn::Visibility::Public(_) = s.vis {
401 match export_status(&s.attrs) {
402 ExportStatus::Export => { declared.insert(s.ident.clone(), DeclType::StructImported); },
403 ExportStatus::NoExport => { declared.insert(s.ident.clone(), DeclType::StructIgnored); },
404 ExportStatus::TestOnly => continue,
408 syn::Item::Type(t) if export_status(&t.attrs) == ExportStatus::Export => {
409 if let syn::Visibility::Public(_) = t.vis {
410 let mut process_alias = true;
411 for tok in t.generics.params.iter() {
412 if let syn::GenericParam::Lifetime(_) = tok {}
413 else { process_alias = false; }
416 declared.insert(t.ident.clone(), DeclType::StructImported);
420 syn::Item::Enum(e) => {
421 if let syn::Visibility::Public(_) = e.vis {
422 match export_status(&e.attrs) {
423 ExportStatus::Export if is_enum_opaque(e) => { declared.insert(e.ident.clone(), DeclType::EnumIgnored); },
424 ExportStatus::Export => { declared.insert(e.ident.clone(), DeclType::MirroredEnum); },
429 syn::Item::Trait(t) if export_status(&t.attrs) == ExportStatus::Export => {
430 if let syn::Visibility::Public(_) = t.vis {
431 declared.insert(t.ident.clone(), DeclType::Trait(t));
434 syn::Item::Mod(m) => {
435 priv_modules.insert(m.ident.clone());
441 Self { module_path, imports, declared, priv_modules }
444 pub fn get_declared_type(&self, ident: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
445 self.declared.get(ident)
448 pub fn maybe_resolve_declared(&self, id: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
449 self.declared.get(id)
452 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
453 if let Some((imp, _)) = self.imports.get(id) {
455 } else if self.declared.get(id).is_some() {
456 Some(self.module_path.to_string() + "::" + &format!("{}", id))
460 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
461 if let Some((imp, _)) = self.imports.get(id) {
463 } else if let Some(decl_type) = self.declared.get(id) {
465 DeclType::StructIgnored => None,
466 _ => Some(self.module_path.to_string() + "::" + &format!("{}", id)),
471 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
472 let p = if let Some(gen_types) = generics {
473 if let Some((_, synpath)) = gen_types.maybe_resolve_path(p_arg) {
478 if p.leading_colon.is_some() {
479 Some(p.segments.iter().enumerate().map(|(idx, seg)| {
480 format!("{}{}", if idx == 0 { "" } else { "::" }, seg.ident)
482 } else if let Some(id) = p.get_ident() {
483 self.maybe_resolve_ident(id)
485 if p.segments.len() == 1 {
486 let seg = p.segments.iter().next().unwrap();
487 return self.maybe_resolve_ident(&seg.ident);
489 let mut seg_iter = p.segments.iter();
490 let first_seg = seg_iter.next().unwrap();
491 let remaining: String = seg_iter.map(|seg| {
492 format!("::{}", seg.ident)
494 if let Some((imp, _)) = self.imports.get(&first_seg.ident) {
496 Some(imp.clone() + &remaining)
500 } else if let Some(_) = self.priv_modules.get(&first_seg.ident) {
501 Some(format!("{}::{}{}", self.module_path, first_seg.ident, remaining))
506 /// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern)
507 pub fn resolve_imported_refs(&self, mut ty: syn::Type) -> syn::Type {
509 syn::Type::Path(p) => {
510 if let Some(ident) = p.path.get_ident() {
511 if let Some((_, newpath)) = self.imports.get(ident) {
512 p.path = newpath.clone();
514 } else { unimplemented!(); }
516 syn::Type::Reference(r) => {
517 r.elem = Box::new(self.resolve_imported_refs((*r.elem).clone()));
519 syn::Type::Slice(s) => {
520 s.elem = Box::new(self.resolve_imported_refs((*s.elem).clone()));
522 syn::Type::Tuple(t) => {
523 for e in t.elems.iter_mut() {
524 *e = self.resolve_imported_refs(e.clone());
527 _ => unimplemented!(),
533 // templates_defined is walked to write the C++ header, so if we use the default hashing it get
534 // reordered on each genbindings run. Instead, we use SipHasher (which defaults to 0-keys) so that
535 // the sorting is stable across runs. It is deprecated, but the "replacement" doesn't actually
536 // accomplish the same goals, so we just ignore it.
538 pub type NonRandomHash = hash::BuildHasherDefault<hash::SipHasher>;
541 pub struct ASTModule {
542 pub attrs: Vec<syn::Attribute>,
543 pub items: Vec<syn::Item>,
544 pub submods: Vec<String>,
546 /// A struct containing the syn::File AST for each file in the crate.
547 pub struct FullLibraryAST {
548 pub modules: HashMap<String, ASTModule, NonRandomHash>,
550 impl FullLibraryAST {
551 fn load_module(&mut self, module: String, attrs: Vec<syn::Attribute>, mut items: Vec<syn::Item>) {
552 let mut non_mod_items = Vec::with_capacity(items.len());
553 let mut submods = Vec::with_capacity(items.len());
554 for item in items.drain(..) {
556 syn::Item::Mod(m) if m.content.is_some() => {
557 if export_status(&m.attrs) == ExportStatus::Export {
558 if let syn::Visibility::Public(_) = m.vis {
559 let modident = format!("{}", m.ident);
560 let modname = if module != "" {
561 module.clone() + "::" + &modident
565 self.load_module(modname, m.attrs, m.content.unwrap().1);
566 submods.push(modident);
568 non_mod_items.push(syn::Item::Mod(m));
572 syn::Item::Mod(_) => panic!("--pretty=expanded output should never have non-body modules"),
573 _ => { non_mod_items.push(item); }
576 self.modules.insert(module, ASTModule { attrs, items: non_mod_items, submods });
579 pub fn load_lib(lib: syn::File) -> Self {
580 assert_eq!(export_status(&lib.attrs), ExportStatus::Export);
581 let mut res = Self { modules: HashMap::default() };
582 res.load_module("".to_owned(), lib.attrs, lib.items);
587 /// Top-level struct tracking everything which has been defined while walking the crate.
588 pub struct CrateTypes<'a> {
589 /// This may contain structs or enums, but only when either is mapped as
590 /// struct X { inner: *mut originalX, .. }
591 pub opaques: HashMap<String, &'a syn::Ident>,
592 /// Enums which are mapped as C enums with conversion functions
593 pub mirrored_enums: HashMap<String, &'a syn::ItemEnum>,
594 /// Traits which are mapped as a pointer + jump table
595 pub traits: HashMap<String, &'a syn::ItemTrait>,
596 /// Aliases from paths to some other Type
597 pub type_aliases: HashMap<String, syn::Type>,
598 /// Value is an alias to Key (maybe with some generics)
599 pub reverse_alias_map: HashMap<String, Vec<(syn::Path, syn::PathArguments)>>,
600 /// Template continer types defined, map from mangled type name -> whether a destructor fn
603 /// This is used at the end of processing to make C++ wrapper classes
604 pub templates_defined: RefCell<HashMap<String, bool, NonRandomHash>>,
605 /// The output file for any created template container types, written to as we find new
606 /// template containers which need to be defined.
607 template_file: RefCell<&'a mut File>,
608 /// Set of containers which are clonable
609 clonable_types: RefCell<HashSet<String>>,
611 pub trait_impls: HashMap<String, Vec<String>>,
612 /// The full set of modules in the crate(s)
613 pub lib_ast: &'a FullLibraryAST,
616 impl<'a> CrateTypes<'a> {
617 pub fn new(template_file: &'a mut File, libast: &'a FullLibraryAST) -> Self {
619 opaques: HashMap::new(), mirrored_enums: HashMap::new(), traits: HashMap::new(),
620 type_aliases: HashMap::new(), reverse_alias_map: HashMap::new(),
621 templates_defined: RefCell::new(HashMap::default()),
622 clonable_types: RefCell::new(HashSet::new()), trait_impls: HashMap::new(),
623 template_file: RefCell::new(template_file), lib_ast: &libast,
626 pub fn set_clonable(&self, object: String) {
627 self.clonable_types.borrow_mut().insert(object);
629 pub fn is_clonable(&self, object: &str) -> bool {
630 self.clonable_types.borrow().contains(object)
632 pub fn write_new_template(&self, mangled_container: String, has_destructor: bool, created_container: &[u8]) {
633 self.template_file.borrow_mut().write(created_container).unwrap();
634 self.templates_defined.borrow_mut().insert(mangled_container, has_destructor);
638 /// A struct which tracks resolving rust types into C-mapped equivalents, exists for one specific
639 /// module but contains a reference to the overall CrateTypes tracking.
640 pub struct TypeResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
641 pub orig_crate: &'mod_lifetime str,
642 pub module_path: &'mod_lifetime str,
643 pub crate_types: &'mod_lifetime CrateTypes<'crate_lft>,
644 types: ImportResolver<'mod_lifetime, 'crate_lft>,
647 /// Returned by write_empty_rust_val_check_suffix to indicate what type of dereferencing needs to
648 /// happen to get the inner value of a generic.
649 enum EmptyValExpectedTy {
650 /// A type which has a flag for being empty (eg an array where we treat all-0s as empty).
652 /// A pointer that we want to dereference and move out of.
654 /// A pointer which we want to convert to a reference.
659 /// Describes the appropriate place to print a general type-conversion string when converting a
661 enum ContainerPrefixLocation {
662 /// Prints a general type-conversion string prefix and suffix outside of the
663 /// container-conversion strings.
665 /// Prints a general type-conversion string prefix and suffix inside of the
666 /// container-conversion strings.
668 /// Does not print the usual type-conversion string prefix and suffix.
672 impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
673 pub fn new(orig_crate: &'a str, module_path: &'a str, types: ImportResolver<'a, 'c>, crate_types: &'a CrateTypes<'c>) -> Self {
674 Self { orig_crate, module_path, types, crate_types }
677 // *************************************************
678 // *** Well know type and conversion definitions ***
679 // *************************************************
681 /// Returns true we if can just skip passing this to C entirely
682 fn skip_path(&self, full_path: &str) -> bool {
683 full_path == "bitcoin::secp256k1::Secp256k1" ||
684 full_path == "bitcoin::secp256k1::Signing" ||
685 full_path == "bitcoin::secp256k1::Verification"
687 /// Returns true we if can just skip passing this to C entirely
688 fn no_arg_path_to_rust(&self, full_path: &str) -> &str {
689 if full_path == "bitcoin::secp256k1::Secp256k1" {
690 "secp256k1::SECP256K1"
691 } else { unimplemented!(); }
694 /// Returns true if the object is a primitive and is mapped as-is with no conversion
696 pub fn is_primitive(&self, full_path: &str) -> bool {
707 pub fn is_clonable(&self, ty: &str) -> bool {
708 if self.crate_types.is_clonable(ty) { return true; }
709 if self.is_primitive(ty) { return true; }
712 "crate::c_types::Signature" => true,
713 "crate::c_types::TxOut" => true,
717 /// Gets the C-mapped type for types which are outside of the crate, or which are manually
718 /// ignored by for some reason need mapping anyway.
719 fn c_type_from_path<'b>(&self, full_path: &'b str, is_ref: bool, _ptr_for_ref: bool) -> Option<&'b str> {
720 if self.is_primitive(full_path) {
721 return Some(full_path);
724 "Result" => Some("crate::c_types::derived::CResult"),
725 "Vec" if !is_ref => Some("crate::c_types::derived::CVec"),
726 "Option" => Some(""),
728 // Note that no !is_ref types can map to an array because Rust and C's call semantics
729 // for arrays are different (https://github.com/eqrion/cbindgen/issues/528)
731 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
732 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes"),
733 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes"),
734 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes"),
735 "[u8; 3]" if !is_ref => Some("crate::c_types::ThreeBytes"), // Used for RGB values
737 "str" if is_ref => Some("crate::c_types::Str"),
738 "String" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
739 "String" if is_ref => Some("crate::c_types::Str"),
741 "std::time::Duration" => Some("u64"),
743 "bitcoin::secp256k1::key::PublicKey" => Some("crate::c_types::PublicKey"),
744 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature"),
745 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some("*const [u8; 32]"),
746 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some("crate::c_types::SecretKey"),
747 "bitcoin::secp256k1::Error" if !is_ref => Some("crate::c_types::Secp256k1Error"),
748 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice"),
749 "bitcoin::blockdata::script::Script" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
750 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::chain::transaction::OutPoint"),
751 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction"),
752 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut"),
753 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network"),
754 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("*const [u8; 80]"),
755 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice"),
757 // Newtypes that we just expose in their original form.
758 "bitcoin::hash_types::Txid" if is_ref => Some("*const [u8; 32]"),
759 "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
760 "bitcoin::hash_types::BlockHash" if is_ref => Some("*const [u8; 32]"),
761 "bitcoin::hash_types::BlockHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
762 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
763 "ln::channelmanager::PaymentHash" if is_ref => Some("*const [u8; 32]"),
764 "ln::channelmanager::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
765 "ln::channelmanager::PaymentPreimage" if is_ref => Some("*const [u8; 32]"),
766 "ln::channelmanager::PaymentPreimage" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
767 "ln::channelmanager::PaymentSecret" if is_ref => Some("crate::c_types::ThirtyTwoBytes"),
768 "ln::channelmanager::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
770 // Override the default since Records contain an fmt with a lifetime:
771 "util::logger::Record" => Some("*const std::os::raw::c_char"),
777 fn from_c_conversion_new_var_from_path<'b>(&self, _full_path: &str, _is_ref: bool) -> Option<(&'b str, &'b str)> {
780 fn from_c_conversion_prefix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
781 if self.is_primitive(full_path) {
782 return Some("".to_owned());
785 "Vec" if !is_ref => Some("local_"),
786 "Result" if !is_ref => Some("local_"),
787 "Option" if is_ref => Some("&local_"),
788 "Option" => Some("local_"),
790 "[u8; 32]" if is_ref => Some("unsafe { &*"),
791 "[u8; 32]" if !is_ref => Some(""),
792 "[u8; 16]" if !is_ref => Some(""),
793 "[u8; 10]" if !is_ref => Some(""),
794 "[u8; 4]" if !is_ref => Some(""),
795 "[u8; 3]" if !is_ref => Some(""),
797 "[u8]" if is_ref => Some(""),
798 "[usize]" if is_ref => Some(""),
800 "str" if is_ref => Some(""),
801 "String" if !is_ref => Some("String::from_utf8("),
802 // Note that we'll panic for String if is_ref, as we only have non-owned memory, we
803 // cannot create a &String.
805 "std::time::Duration" => Some("std::time::Duration::from_secs("),
807 "bitcoin::secp256k1::key::PublicKey" if is_ref => Some("&"),
808 "bitcoin::secp256k1::key::PublicKey" => Some(""),
809 "bitcoin::secp256k1::Signature" if is_ref => Some("&"),
810 "bitcoin::secp256k1::Signature" => Some(""),
811 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some("&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *"),
812 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some(""),
813 "bitcoin::blockdata::script::Script" if is_ref => Some("&::bitcoin::blockdata::script::Script::from(Vec::from("),
814 "bitcoin::blockdata::script::Script" if !is_ref => Some("::bitcoin::blockdata::script::Script::from("),
815 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some("&"),
816 "bitcoin::blockdata::transaction::Transaction" => Some(""),
817 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(""),
818 "bitcoin::network::constants::Network" => Some(""),
819 "bitcoin::blockdata::block::BlockHeader" => Some("&::bitcoin::consensus::encode::deserialize(unsafe { &*"),
820 "bitcoin::blockdata::block::Block" if is_ref => Some("&::bitcoin::consensus::encode::deserialize("),
822 // Newtypes that we just expose in their original form.
823 "bitcoin::hash_types::Txid" if is_ref => Some("&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*"),
824 "bitcoin::hash_types::Txid" if !is_ref => Some("::bitcoin::hash_types::Txid::from_slice(&"),
825 "bitcoin::hash_types::BlockHash" => Some("::bitcoin::hash_types::BlockHash::from_slice(&"),
826 "ln::channelmanager::PaymentHash" if !is_ref => Some("::lightning::ln::channelmanager::PaymentHash("),
827 "ln::channelmanager::PaymentHash" if is_ref => Some("&::lightning::ln::channelmanager::PaymentHash(unsafe { *"),
828 "ln::channelmanager::PaymentPreimage" if !is_ref => Some("::lightning::ln::channelmanager::PaymentPreimage("),
829 "ln::channelmanager::PaymentPreimage" if is_ref => Some("&::lightning::ln::channelmanager::PaymentPreimage(unsafe { *"),
830 "ln::channelmanager::PaymentSecret" => Some("::lightning::ln::channelmanager::PaymentSecret("),
832 // List of traits we map (possibly during processing of other files):
833 "crate::util::logger::Logger" => Some(""),
836 }.map(|s| s.to_owned())
838 fn from_c_conversion_suffix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
839 if self.is_primitive(full_path) {
840 return Some("".to_owned());
843 "Vec" if !is_ref => Some(""),
844 "Option" => Some(""),
845 "Result" if !is_ref => Some(""),
847 "[u8; 32]" if is_ref => Some("}"),
848 "[u8; 32]" if !is_ref => Some(".data"),
849 "[u8; 16]" if !is_ref => Some(".data"),
850 "[u8; 10]" if !is_ref => Some(".data"),
851 "[u8; 4]" if !is_ref => Some(".data"),
852 "[u8; 3]" if !is_ref => Some(".data"),
854 "[u8]" if is_ref => Some(".to_slice()"),
855 "[usize]" if is_ref => Some(".to_slice()"),
857 "str" if is_ref => Some(".into()"),
858 "String" if !is_ref => Some(".into_rust()).unwrap()"),
860 "std::time::Duration" => Some(")"),
862 "bitcoin::secp256k1::key::PublicKey" => Some(".into_rust()"),
863 "bitcoin::secp256k1::Signature" => Some(".into_rust()"),
864 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some(".into_rust()"),
865 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some("}[..]).unwrap()"),
866 "bitcoin::blockdata::script::Script" if is_ref => Some(".to_slice()))"),
867 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_rust())"),
868 "bitcoin::blockdata::transaction::Transaction" => Some(".into_bitcoin()"),
869 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(".into_rust()"),
870 "bitcoin::network::constants::Network" => Some(".into_bitcoin()"),
871 "bitcoin::blockdata::block::BlockHeader" => Some(" }).unwrap()"),
872 "bitcoin::blockdata::block::Block" => Some(".to_slice()).unwrap()"),
874 // Newtypes that we just expose in their original form.
875 "bitcoin::hash_types::Txid" if is_ref => Some(" }[..]).unwrap()"),
876 "bitcoin::hash_types::Txid" => Some(".data[..]).unwrap()"),
877 "bitcoin::hash_types::BlockHash" if !is_ref => Some(".data[..]).unwrap()"),
878 "ln::channelmanager::PaymentHash" if !is_ref => Some(".data)"),
879 "ln::channelmanager::PaymentHash" if is_ref => Some(" })"),
880 "ln::channelmanager::PaymentPreimage" if !is_ref => Some(".data)"),
881 "ln::channelmanager::PaymentPreimage" if is_ref => Some(" })"),
882 "ln::channelmanager::PaymentSecret" => Some(".data)"),
884 // List of traits we map (possibly during processing of other files):
885 "crate::util::logger::Logger" => Some(""),
888 }.map(|s| s.to_owned())
891 fn to_c_conversion_new_var_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<(&'b str, &'b str)> {
892 if self.is_primitive(full_path) {
896 "[u8]" if is_ref => Some(("crate::c_types::u8slice::from_slice(", ")")),
897 "[usize]" if is_ref => Some(("crate::c_types::usizeslice::from_slice(", ")")),
899 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
900 "bitcoin::blockdata::transaction::Transaction" if !is_ref => Some(("::bitcoin::consensus::encode::serialize(&", ")")),
901 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(("{ let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(", ")); s }")),
902 "bitcoin::blockdata::block::Block" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
903 "bitcoin::hash_types::Txid" => None,
905 // Override the default since Records contain an fmt with a lifetime:
906 // TODO: We should include the other record fields
907 "util::logger::Record" => Some(("std::ffi::CString::new(format!(\"{}\", ", ".args)).unwrap()")),
909 }.map(|s| s.to_owned())
911 fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
912 if self.is_primitive(full_path) {
913 return Some("".to_owned());
916 "Result" if !is_ref => Some("local_"),
917 "Vec" if !is_ref => Some("local_"),
918 "Option" => Some("local_"),
920 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
921 "[u8; 32]" if is_ref => Some("&"),
922 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes { data: "),
923 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes { data: "),
924 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes { data: "),
925 "[u8; 3]" if is_ref => Some("&"),
927 "[u8]" if is_ref => Some("local_"),
928 "[usize]" if is_ref => Some("local_"),
930 "str" if is_ref => Some(""),
931 "String" => Some(""),
933 "std::time::Duration" => Some(""),
935 "bitcoin::secp256k1::key::PublicKey" => Some("crate::c_types::PublicKey::from_rust(&"),
936 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature::from_rust(&"),
937 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some(""),
938 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some("crate::c_types::SecretKey::from_rust("),
939 "bitcoin::secp256k1::Error" if !is_ref => Some("crate::c_types::Secp256k1Error::from_rust("),
940 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice::from_slice(&"),
941 "bitcoin::blockdata::script::Script" if !is_ref => Some(""),
942 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction::from_vec(local_"),
943 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::c_types::bitcoin_to_C_outpoint("),
944 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut::from_rust("),
945 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network::from_bitcoin("),
946 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("&local_"),
947 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice::from_slice(&local_"),
949 "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
951 // Newtypes that we just expose in their original form.
952 "bitcoin::hash_types::Txid" if is_ref => Some(""),
953 "bitcoin::hash_types::BlockHash" if is_ref => Some(""),
954 "bitcoin::hash_types::BlockHash" => Some("crate::c_types::ThirtyTwoBytes { data: "),
955 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
956 "ln::channelmanager::PaymentHash" if is_ref => Some("&"),
957 "ln::channelmanager::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
958 "ln::channelmanager::PaymentPreimage" if is_ref => Some("&"),
959 "ln::channelmanager::PaymentPreimage" => Some("crate::c_types::ThirtyTwoBytes { data: "),
960 "ln::channelmanager::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
962 // Override the default since Records contain an fmt with a lifetime:
963 "util::logger::Record" => Some("local_"),
966 }.map(|s| s.to_owned())
968 fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
969 if self.is_primitive(full_path) {
970 return Some("".to_owned());
973 "Result" if !is_ref => Some(""),
974 "Vec" if !is_ref => Some(".into()"),
975 "Option" => Some(""),
977 "[u8; 32]" if !is_ref => Some(" }"),
978 "[u8; 32]" if is_ref => Some(""),
979 "[u8; 16]" if !is_ref => Some(" }"),
980 "[u8; 10]" if !is_ref => Some(" }"),
981 "[u8; 4]" if !is_ref => Some(" }"),
982 "[u8; 3]" if is_ref => Some(""),
984 "[u8]" if is_ref => Some(""),
985 "[usize]" if is_ref => Some(""),
987 "str" if is_ref => Some(".into()"),
988 "String" if !is_ref => Some(".into_bytes().into()"),
989 "String" if is_ref => Some(".as_str().into()"),
991 "std::time::Duration" => Some(".as_secs()"),
993 "bitcoin::secp256k1::key::PublicKey" => Some(")"),
994 "bitcoin::secp256k1::Signature" => Some(")"),
995 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some(")"),
996 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some(".as_ref()"),
997 "bitcoin::secp256k1::Error" if !is_ref => Some(")"),
998 "bitcoin::blockdata::script::Script" if is_ref => Some("[..])"),
999 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_bytes().into()"),
1000 "bitcoin::blockdata::transaction::Transaction" => Some(")"),
1001 "bitcoin::blockdata::transaction::OutPoint" => Some(")"),
1002 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(")"),
1003 "bitcoin::network::constants::Network" => Some(")"),
1004 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(""),
1005 "bitcoin::blockdata::block::Block" if is_ref => Some(")"),
1007 "bitcoin::hash_types::Txid" if !is_ref => Some(".into_inner() }"),
1009 // Newtypes that we just expose in their original form.
1010 "bitcoin::hash_types::Txid" if is_ref => Some(".as_inner()"),
1011 "bitcoin::hash_types::BlockHash" if is_ref => Some(".as_inner()"),
1012 "bitcoin::hash_types::BlockHash" => Some(".into_inner() }"),
1013 "bitcoin::secp256k1::Message" if !is_ref => Some(".as_ref().clone() }"),
1014 "ln::channelmanager::PaymentHash" if is_ref => Some(".0"),
1015 "ln::channelmanager::PaymentHash" => Some(".0 }"),
1016 "ln::channelmanager::PaymentPreimage" if is_ref => Some(".0"),
1017 "ln::channelmanager::PaymentPreimage" => Some(".0 }"),
1018 "ln::channelmanager::PaymentSecret" if !is_ref => Some(".0 }"),
1020 // Override the default since Records contain an fmt with a lifetime:
1021 "util::logger::Record" => Some(".as_ptr()"),
1024 }.map(|s| s.to_owned())
1027 fn empty_val_check_suffix_from_path(&self, full_path: &str) -> Option<&str> {
1029 "ln::channelmanager::PaymentSecret" => Some(".data == [0; 32]"),
1030 "bitcoin::secp256k1::key::PublicKey" => Some(".is_null()"),
1031 "bitcoin::secp256k1::Signature" => Some(".is_null()"),
1036 // ****************************
1037 // *** Container Processing ***
1038 // ****************************
1040 /// Returns the module path in the generated mapping crate to the containers which we generate
1041 /// when writing to CrateTypes::template_file.
1042 pub fn generated_container_path() -> &'static str {
1043 "crate::c_types::derived"
1045 /// Returns the module path in the generated mapping crate to the container templates, which
1046 /// are then concretized and put in the generated container path/template_file.
1047 fn container_templ_path() -> &'static str {
1051 /// Returns true if the path containing the given args is a "transparent" container, ie an
1052 /// Option or a container which does not require a generated continer class.
1053 fn is_transparent_container<'i, I: Iterator<Item=&'i syn::Type>>(&self, full_path: &str, _is_ref: bool, mut args: I) -> bool {
1054 if full_path == "Option" {
1055 let inner = args.next().unwrap();
1056 assert!(args.next().is_none());
1058 syn::Type::Reference(_) => true,
1059 syn::Type::Path(p) => {
1060 if let Some(resolved) = self.maybe_resolve_path(&p.path, None) {
1061 if self.is_primitive(&resolved) { false } else { true }
1064 syn::Type::Tuple(_) => false,
1065 _ => unimplemented!(),
1069 /// Returns true if the path is a "transparent" container, ie an Option or a container which does
1070 /// not require a generated continer class.
1071 fn is_path_transparent_container(&self, full_path: &syn::Path, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
1072 let inner_iter = match &full_path.segments.last().unwrap().arguments {
1073 syn::PathArguments::None => return false,
1074 syn::PathArguments::AngleBracketed(args) => args.args.iter().map(|arg| {
1075 if let syn::GenericArgument::Type(ref ty) = arg {
1077 } else { unimplemented!() }
1079 syn::PathArguments::Parenthesized(_) => unimplemented!(),
1081 self.is_transparent_container(&self.resolve_path(full_path, generics), is_ref, inner_iter)
1083 /// Returns true if this is a known, supported, non-transparent container.
1084 fn is_known_container(&self, full_path: &str, is_ref: bool) -> bool {
1085 (full_path == "Result" && !is_ref) || (full_path == "Vec" && !is_ref) || full_path.ends_with("Tuple") || full_path == "Option"
1087 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)
1088 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1089 // expecting one element in the vec per generic type, each of which is inline-converted
1090 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1092 "Result" if !is_ref => {
1094 vec![(" { Ok(mut o) => crate::c_types::CResultTempl::ok(".to_string(), "o".to_string()),
1095 (").into(), Err(mut e) => crate::c_types::CResultTempl::err(".to_string(), "e".to_string())],
1096 ").into() }", ContainerPrefixLocation::PerConv))
1098 "Vec" if !is_ref => {
1099 Some(("Vec::new(); for mut item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1102 Some(("Vec::new(); for item in ", vec![(format!(".iter() {{ local_{}.push(", var_name), "**item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1105 if let Some(syn::Type::Path(p)) = single_contained {
1106 let inner_path = self.resolve_path(&p.path, generics);
1107 if self.is_primitive(&inner_path) {
1108 return Some(("if ", vec![
1109 (format!(".is_none() {{ {}::COption_{}Z::None }} else {{ ", Self::generated_container_path(), inner_path),
1110 format!("{}::COption_{}Z::Some({}.unwrap())", Self::generated_container_path(), inner_path, var_access))
1111 ], " }", ContainerPrefixLocation::NoPrefix));
1112 } else if self.c_type_has_inner_from_path(&inner_path) {
1114 return Some(("if ", vec![
1115 (".is_none() { std::ptr::null() } else { ".to_owned(), format!("({}.as_ref().unwrap())", var_access))
1116 ], " }", ContainerPrefixLocation::OutsideConv));
1118 return Some(("if ", vec![
1119 (".is_none() { std::ptr::null_mut() } else { ".to_owned(), format!("({}.unwrap())", var_access))
1120 ], " }", ContainerPrefixLocation::OutsideConv));
1124 if let Some(t) = single_contained {
1125 let mut v = Vec::new();
1126 self.write_empty_rust_val(generics, &mut v, t);
1127 let s = String::from_utf8(v).unwrap();
1128 return Some(("if ", vec![
1129 (format!(".is_none() {{ {} }} else {{ ", s), format!("({}.unwrap())", var_access))
1130 ], " }", ContainerPrefixLocation::PerConv));
1131 } else { unreachable!(); }
1137 /// only_contained_has_inner implies that there is only one contained element in the container
1138 /// and it has an inner field (ie is an "opaque" type we've defined).
1139 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)
1140 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1141 // expecting one element in the vec per generic type, each of which is inline-converted
1142 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1144 "Result" if !is_ref => {
1146 vec![(".result_ok { true => Ok(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.result)) }})", var_access)),
1147 ("), false => Err(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.err)) }})", var_access))],
1148 ")}", ContainerPrefixLocation::PerConv))
1150 "Slice" if is_ref => {
1151 Some(("Vec::new(); for mut item in ", vec![(format!(".as_slice().iter() {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1154 Some(("Vec::new(); for mut item in ", vec![(format!(".into_rust().drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1157 if let Some(syn::Type::Path(p)) = single_contained {
1158 let inner_path = self.resolve_path(&p.path, generics);
1159 if self.is_primitive(&inner_path) {
1160 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::NoPrefix))
1161 } else if self.c_type_has_inner_from_path(&inner_path) {
1163 return Some(("if ", vec![(".inner.is_null() { None } else { Some((*".to_string(), format!("{}", var_access))], ").clone()) }", ContainerPrefixLocation::PerConv))
1165 return Some(("if ", vec![(".inner.is_null() { None } else { Some(".to_string(), format!("{}", var_access))], ") }", ContainerPrefixLocation::PerConv));
1170 if let Some(t) = single_contained {
1172 syn::Type::Reference(_)|syn::Type::Path(_)|syn::Type::Slice(_) => {
1173 let mut v = Vec::new();
1174 let ret_ref = self.write_empty_rust_val_check_suffix(generics, &mut v, t);
1175 let s = String::from_utf8(v).unwrap();
1177 EmptyValExpectedTy::ReferenceAsPointer =>
1178 return Some(("if ", vec![
1179 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ &mut *{} }}", var_access))
1180 ], ") }", ContainerPrefixLocation::NoPrefix)),
1181 EmptyValExpectedTy::OwnedPointer => {
1182 if let syn::Type::Slice(_) = t {
1185 return Some(("if ", vec![
1186 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ *Box::from_raw({}) }}", var_access))
1187 ], ") }", ContainerPrefixLocation::NoPrefix));
1189 EmptyValExpectedTy::NonPointer =>
1190 return Some(("if ", vec![
1191 (format!("{} {{ None }} else {{ Some(", s), format!("{}", var_access))
1192 ], ") }", ContainerPrefixLocation::PerConv)),
1195 syn::Type::Tuple(_) => {
1196 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::PerConv))
1198 _ => unimplemented!(),
1200 } else { unreachable!(); }
1206 // *************************************************
1207 // *** Type definition during main.rs processing ***
1208 // *************************************************
1210 pub fn get_declared_type(&'a self, ident: &syn::Ident) -> Option<&'a DeclType<'c>> {
1211 self.types.get_declared_type(ident)
1213 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1214 pub fn c_type_has_inner_from_path(&self, full_path: &str) -> bool{
1215 self.crate_types.opaques.get(full_path).is_some()
1218 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
1219 self.types.maybe_resolve_ident(id)
1222 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
1223 self.types.maybe_resolve_non_ignored_ident(id)
1226 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
1227 self.types.maybe_resolve_path(p_arg, generics)
1229 pub fn resolve_path(&self, p: &syn::Path, generics: Option<&GenericTypes>) -> String {
1230 self.maybe_resolve_path(p, generics).unwrap()
1233 // ***********************************
1234 // *** Original Rust Type Printing ***
1235 // ***********************************
1237 fn in_rust_prelude(resolved_path: &str) -> bool {
1238 match resolved_path {
1246 fn write_rust_path<W: std::io::Write>(&self, w: &mut W, generics_resolver: Option<&GenericTypes>, path: &syn::Path) {
1247 if let Some(resolved) = self.maybe_resolve_path(&path, generics_resolver) {
1248 if self.is_primitive(&resolved) {
1249 write!(w, "{}", path.get_ident().unwrap()).unwrap();
1251 // TODO: We should have a generic "is from a dependency" check here instead of
1252 // checking for "bitcoin" explicitly.
1253 if resolved.starts_with("bitcoin::") || Self::in_rust_prelude(&resolved) {
1254 write!(w, "{}", resolved).unwrap();
1255 // If we're printing a generic argument, it needs to reference the crate, otherwise
1256 // the original crate:
1257 } else if self.maybe_resolve_path(&path, None).as_ref() == Some(&resolved) {
1258 write!(w, "{}::{}", self.orig_crate, resolved).unwrap();
1260 write!(w, "crate::{}", resolved).unwrap();
1263 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().last().unwrap().arguments {
1264 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1267 if path.leading_colon.is_some() {
1268 write!(w, "::").unwrap();
1270 for (idx, seg) in path.segments.iter().enumerate() {
1271 if idx != 0 { write!(w, "::").unwrap(); }
1272 write!(w, "{}", seg.ident).unwrap();
1273 if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
1274 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1279 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>) {
1280 let mut had_params = false;
1281 for (idx, arg) in generics.enumerate() {
1282 if idx != 0 { write!(w, ", ").unwrap(); } else { write!(w, "<").unwrap(); }
1285 syn::GenericParam::Lifetime(lt) => write!(w, "'{}", lt.lifetime.ident).unwrap(),
1286 syn::GenericParam::Type(t) => {
1287 write!(w, "{}", t.ident).unwrap();
1288 if t.colon_token.is_some() { write!(w, ":").unwrap(); }
1289 for (idx, bound) in t.bounds.iter().enumerate() {
1290 if idx != 0 { write!(w, " + ").unwrap(); }
1292 syn::TypeParamBound::Trait(tb) => {
1293 if tb.paren_token.is_some() || tb.lifetimes.is_some() { unimplemented!(); }
1294 self.write_rust_path(w, generics_resolver, &tb.path);
1296 _ => unimplemented!(),
1299 if t.eq_token.is_some() || t.default.is_some() { unimplemented!(); }
1301 _ => unimplemented!(),
1304 if had_params { write!(w, ">").unwrap(); }
1307 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>) {
1308 write!(w, "<").unwrap();
1309 for (idx, arg) in generics.enumerate() {
1310 if idx != 0 { write!(w, ", ").unwrap(); }
1312 syn::GenericArgument::Type(t) => self.write_rust_type(w, generics_resolver, t),
1313 _ => unimplemented!(),
1316 write!(w, ">").unwrap();
1318 pub fn write_rust_type<W: std::io::Write>(&self, w: &mut W, generics: Option<&GenericTypes>, t: &syn::Type) {
1320 syn::Type::Path(p) => {
1321 if p.qself.is_some() {
1324 self.write_rust_path(w, generics, &p.path);
1326 syn::Type::Reference(r) => {
1327 write!(w, "&").unwrap();
1328 if let Some(lft) = &r.lifetime {
1329 write!(w, "'{} ", lft.ident).unwrap();
1331 if r.mutability.is_some() {
1332 write!(w, "mut ").unwrap();
1334 self.write_rust_type(w, generics, &*r.elem);
1336 syn::Type::Array(a) => {
1337 write!(w, "[").unwrap();
1338 self.write_rust_type(w, generics, &a.elem);
1339 if let syn::Expr::Lit(l) = &a.len {
1340 if let syn::Lit::Int(i) = &l.lit {
1341 write!(w, "; {}]", i).unwrap();
1342 } else { unimplemented!(); }
1343 } else { unimplemented!(); }
1345 syn::Type::Slice(s) => {
1346 write!(w, "[").unwrap();
1347 self.write_rust_type(w, generics, &s.elem);
1348 write!(w, "]").unwrap();
1350 syn::Type::Tuple(s) => {
1351 write!(w, "(").unwrap();
1352 for (idx, t) in s.elems.iter().enumerate() {
1353 if idx != 0 { write!(w, ", ").unwrap(); }
1354 self.write_rust_type(w, generics, &t);
1356 write!(w, ")").unwrap();
1358 _ => unimplemented!(),
1362 /// Prints a constructor for something which is "uninitialized" (but obviously not actually
1363 /// unint'd memory).
1364 pub fn write_empty_rust_val<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) {
1366 syn::Type::Path(p) => {
1367 let resolved = self.resolve_path(&p.path, generics);
1368 if self.crate_types.opaques.get(&resolved).is_some() {
1369 write!(w, "crate::{} {{ inner: std::ptr::null_mut(), is_owned: true }}", resolved).unwrap();
1371 // Assume its a manually-mapped C type, where we can just define an null() fn
1372 write!(w, "{}::null()", self.c_type_from_path(&resolved, false, false).unwrap()).unwrap();
1375 syn::Type::Array(a) => {
1376 if let syn::Expr::Lit(l) = &a.len {
1377 if let syn::Lit::Int(i) = &l.lit {
1378 if i.base10_digits().parse::<usize>().unwrap() < 32 {
1379 // Blindly assume that if we're trying to create an empty value for an
1380 // array < 32 entries that all-0s may be a valid state.
1383 let arrty = format!("[u8; {}]", i.base10_digits());
1384 write!(w, "{}", self.to_c_conversion_inline_prefix_from_path(&arrty, false, false).unwrap()).unwrap();
1385 write!(w, "[0; {}]", i.base10_digits()).unwrap();
1386 write!(w, "{}", self.to_c_conversion_inline_suffix_from_path(&arrty, false, false).unwrap()).unwrap();
1387 } else { unimplemented!(); }
1388 } else { unimplemented!(); }
1390 _ => unimplemented!(),
1394 fn is_real_type_array(&self, resolved_type: &str) -> Option<syn::Type> {
1395 if let Some(real_ty) = self.c_type_from_path(&resolved_type, true, false) {
1396 if real_ty.ends_with("]") && real_ty.starts_with("*const [u8; ") {
1397 let mut split = real_ty.split("; ");
1398 split.next().unwrap();
1399 let tail_str = split.next().unwrap();
1400 assert!(split.next().is_none());
1401 let len = &tail_str[..tail_str.len() - 1];
1402 Some(syn::Type::Array(syn::TypeArray {
1403 bracket_token: syn::token::Bracket { span: Span::call_site() },
1404 elem: Box::new(syn::Type::Path(syn::TypePath {
1406 path: syn::Path::from(syn::PathSegment::from(syn::Ident::new("u8", Span::call_site()))),
1408 semi_token: syn::Token!(;)(Span::call_site()),
1409 len: syn::Expr::Lit(syn::ExprLit { attrs: Vec::new(), lit: syn::Lit::Int(syn::LitInt::new(len, Span::call_site())) }),
1415 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1416 /// See EmptyValExpectedTy for information on return types.
1417 fn write_empty_rust_val_check_suffix<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) -> EmptyValExpectedTy {
1419 syn::Type::Path(p) => {
1420 let resolved = self.resolve_path(&p.path, generics);
1421 if let Some(arr_ty) = self.is_real_type_array(&resolved) {
1422 write!(w, ".data").unwrap();
1423 return self.write_empty_rust_val_check_suffix(generics, w, &arr_ty);
1425 if self.crate_types.opaques.get(&resolved).is_some() {
1426 write!(w, ".inner.is_null()").unwrap();
1427 EmptyValExpectedTy::NonPointer
1429 if let Some(suffix) = self.empty_val_check_suffix_from_path(&resolved) {
1430 write!(w, "{}", suffix).unwrap();
1431 // We may eventually need to allow empty_val_check_suffix_from_path to specify if we need a deref or not
1432 EmptyValExpectedTy::NonPointer
1434 write!(w, " == std::ptr::null_mut()").unwrap();
1435 EmptyValExpectedTy::OwnedPointer
1439 syn::Type::Array(a) => {
1440 if let syn::Expr::Lit(l) = &a.len {
1441 if let syn::Lit::Int(i) = &l.lit {
1442 write!(w, " == [0; {}]", i.base10_digits()).unwrap();
1443 EmptyValExpectedTy::NonPointer
1444 } else { unimplemented!(); }
1445 } else { unimplemented!(); }
1447 syn::Type::Slice(_) => {
1448 // Option<[]> always implies that we want to treat len() == 0 differently from
1449 // None, so we always map an Option<[]> into a pointer.
1450 write!(w, " == std::ptr::null_mut()").unwrap();
1451 EmptyValExpectedTy::ReferenceAsPointer
1453 _ => unimplemented!(),
1457 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1458 pub fn write_empty_rust_val_check<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type, var_access: &str) {
1460 syn::Type::Path(_) => {
1461 write!(w, "{}", var_access).unwrap();
1462 self.write_empty_rust_val_check_suffix(generics, w, t);
1464 syn::Type::Array(a) => {
1465 if let syn::Expr::Lit(l) = &a.len {
1466 if let syn::Lit::Int(i) = &l.lit {
1467 let arrty = format!("[u8; {}]", i.base10_digits());
1468 // We don't (yet) support a new-var conversion here.
1469 assert!(self.from_c_conversion_new_var_from_path(&arrty, false).is_none());
1471 self.from_c_conversion_prefix_from_path(&arrty, false).unwrap(),
1473 self.from_c_conversion_suffix_from_path(&arrty, false).unwrap()).unwrap();
1474 self.write_empty_rust_val_check_suffix(generics, w, t);
1475 } else { unimplemented!(); }
1476 } else { unimplemented!(); }
1478 _ => unimplemented!(),
1482 // ********************************
1483 // *** Type conversion printing ***
1484 // ********************************
1486 /// Returns true we if can just skip passing this to C entirely
1487 pub fn skip_arg(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
1489 syn::Type::Path(p) => {
1490 if p.qself.is_some() { unimplemented!(); }
1491 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1492 self.skip_path(&full_path)
1495 syn::Type::Reference(r) => {
1496 self.skip_arg(&*r.elem, generics)
1501 pub fn no_arg_to_rust<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1503 syn::Type::Path(p) => {
1504 if p.qself.is_some() { unimplemented!(); }
1505 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1506 write!(w, "{}", self.no_arg_path_to_rust(&full_path)).unwrap();
1509 syn::Type::Reference(r) => {
1510 self.no_arg_to_rust(w, &*r.elem, generics);
1516 fn write_conversion_inline_intern<W: std::io::Write,
1517 LP: Fn(&str, bool, bool) -> Option<String>, DL: Fn(&mut W, &DeclType, &str, bool, bool), SC: Fn(bool) -> &'static str>
1518 (&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool,
1519 tupleconv: &str, prefix: bool, sliceconv: SC, path_lookup: LP, decl_lookup: DL) {
1521 syn::Type::Reference(r) => {
1522 self.write_conversion_inline_intern(w, &*r.elem, generics, true, r.mutability.is_some(),
1523 ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1525 syn::Type::Path(p) => {
1526 if p.qself.is_some() {
1530 let resolved_path = self.resolve_path(&p.path, generics);
1531 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1532 return self.write_conversion_inline_intern(w, aliased_type, None, is_ref, is_mut, ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1533 } else if let Some(c_type) = path_lookup(&resolved_path, is_ref, ptr_for_ref) {
1534 write!(w, "{}", c_type).unwrap();
1535 } else if self.crate_types.opaques.get(&resolved_path).is_some() {
1536 decl_lookup(w, &DeclType::StructImported, &resolved_path, is_ref, is_mut);
1537 } else if self.crate_types.mirrored_enums.get(&resolved_path).is_some() {
1538 decl_lookup(w, &DeclType::MirroredEnum, &resolved_path, is_ref, is_mut);
1539 } else if let Some(t) = self.crate_types.traits.get(&resolved_path) {
1540 decl_lookup(w, &DeclType::Trait(t), &resolved_path, is_ref, is_mut);
1541 } else if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
1542 if let Some(decl_type) = self.types.maybe_resolve_declared(ident) {
1543 decl_lookup(w, decl_type, &self.maybe_resolve_ident(ident).unwrap(), is_ref, is_mut);
1544 } else { unimplemented!(); }
1545 } else { unimplemented!(); }
1547 syn::Type::Array(a) => {
1548 // We assume all arrays contain only [int_literal; X]s.
1549 // This may result in some outputs not compiling.
1550 if let syn::Expr::Lit(l) = &a.len {
1551 if let syn::Lit::Int(i) = &l.lit {
1552 write!(w, "{}", path_lookup(&format!("[u8; {}]", i.base10_digits()), is_ref, ptr_for_ref).unwrap()).unwrap();
1553 } else { unimplemented!(); }
1554 } else { unimplemented!(); }
1556 syn::Type::Slice(s) => {
1557 // We assume all slices contain only literals or references.
1558 // This may result in some outputs not compiling.
1559 if let syn::Type::Path(p) = &*s.elem {
1560 let resolved = self.resolve_path(&p.path, generics);
1561 assert!(self.is_primitive(&resolved));
1562 write!(w, "{}", path_lookup("[u8]", is_ref, ptr_for_ref).unwrap()).unwrap();
1563 } else if let syn::Type::Reference(r) = &*s.elem {
1564 if let syn::Type::Path(p) = &*r.elem {
1565 write!(w, "{}", sliceconv(self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)))).unwrap();
1566 } else { unimplemented!(); }
1567 } else if let syn::Type::Tuple(t) = &*s.elem {
1568 assert!(!t.elems.is_empty());
1570 write!(w, "&local_").unwrap();
1572 let mut needs_map = false;
1573 for e in t.elems.iter() {
1574 if let syn::Type::Reference(_) = e {
1579 write!(w, ".iter().map(|(").unwrap();
1580 for i in 0..t.elems.len() {
1581 write!(w, "{}{}", if i != 0 { ", " } else { "" }, ('a' as u8 + i as u8) as char).unwrap();
1583 write!(w, ")| (").unwrap();
1584 for (idx, e) in t.elems.iter().enumerate() {
1585 if let syn::Type::Reference(_) = e {
1586 write!(w, "{}{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1587 } else if let syn::Type::Path(_) = e {
1588 write!(w, "{}*{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1589 } else { unimplemented!(); }
1591 write!(w, ")).collect::<Vec<_>>()[..]").unwrap();
1594 } else { unimplemented!(); }
1596 syn::Type::Tuple(t) => {
1597 if t.elems.is_empty() {
1598 // cbindgen has poor support for (), see, eg https://github.com/eqrion/cbindgen/issues/527
1599 // so work around it by just pretending its a 0u8
1600 write!(w, "{}", tupleconv).unwrap();
1602 if prefix { write!(w, "local_").unwrap(); }
1605 _ => unimplemented!(),
1609 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) {
1610 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "0u8 /*", true, |_| "local_",
1611 |a, b, c| self.to_c_conversion_inline_prefix_from_path(a, b, c),
1612 |w, decl_type, decl_path, is_ref, _is_mut| {
1614 DeclType::MirroredEnum if is_ref && ptr_for_ref => write!(w, "crate::{}::from_native(&", decl_path).unwrap(),
1615 DeclType::MirroredEnum if is_ref => write!(w, "&crate::{}::from_native(&", decl_path).unwrap(),
1616 DeclType::MirroredEnum => write!(w, "crate::{}::native_into(", decl_path).unwrap(),
1617 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1618 write!(w, "crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1619 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1620 write!(w, "crate::{} {{ inner: unsafe {{ ( (&(", decl_path).unwrap(),
1621 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1622 write!(w, "&crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1623 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1624 write!(w, "crate::{} {{ inner: ", decl_path).unwrap(),
1625 DeclType::EnumIgnored|DeclType::StructImported if !is_ref =>
1626 write!(w, "crate::{} {{ inner: Box::into_raw(Box::new(", decl_path).unwrap(),
1627 DeclType::Trait(_) if is_ref => write!(w, "&").unwrap(),
1628 DeclType::Trait(_) if !is_ref => {},
1629 _ => panic!("{:?}", decl_path),
1633 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) {
1634 self.write_to_c_conversion_inline_prefix_inner(w, t, generics, false, ptr_for_ref, false);
1636 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) {
1637 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "*/", false, |_| ".into()",
1638 |a, b, c| self.to_c_conversion_inline_suffix_from_path(a, b, c),
1639 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1640 DeclType::MirroredEnum => write!(w, ")").unwrap(),
1641 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1642 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1643 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1644 write!(w, ") as *const _) as *mut _) }}, is_owned: false }}").unwrap(),
1645 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1646 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1647 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1648 write!(w, ", is_owned: true }}").unwrap(),
1649 DeclType::EnumIgnored|DeclType::StructImported if !is_ref => write!(w, ")), is_owned: true }}").unwrap(),
1650 DeclType::Trait(_) if is_ref => {},
1651 DeclType::Trait(_) => {
1652 // This is used when we're converting a concrete Rust type into a C trait
1653 // for use when a Rust trait method returns an associated type.
1654 // Because all of our C traits implement From<RustTypesImplementingTraits>
1655 // we can just call .into() here and be done.
1656 write!(w, ".into()").unwrap()
1658 _ => unimplemented!(),
1661 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) {
1662 self.write_to_c_conversion_inline_suffix_inner(w, t, generics, false, ptr_for_ref, false);
1665 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) {
1666 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "() /*", true, |_| "&local_",
1667 |a, b, _c| self.from_c_conversion_prefix_from_path(a, b),
1668 |w, decl_type, _full_path, is_ref, is_mut| match decl_type {
1669 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, "unsafe {{ &*(*").unwrap(),
1670 DeclType::StructImported if is_mut && is_ref => write!(w, "unsafe {{ &mut *").unwrap(),
1671 DeclType::StructImported if is_ref => write!(w, "unsafe {{ &*").unwrap(),
1672 DeclType::StructImported if !is_ref => write!(w, "*unsafe {{ Box::from_raw(").unwrap(),
1673 DeclType::MirroredEnum if is_ref => write!(w, "&").unwrap(),
1674 DeclType::MirroredEnum => {},
1675 DeclType::Trait(_) => {},
1676 _ => unimplemented!(),
1679 pub fn write_from_c_conversion_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1680 self.write_from_c_conversion_prefix_inner(w, t, generics, false, false);
1682 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) {
1683 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "*/", false,
1684 |has_inner| match has_inner {
1685 false => ".iter().collect::<Vec<_>>()[..]",
1688 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1689 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1690 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, ").inner }}").unwrap(),
1691 DeclType::StructImported if is_ref => write!(w, ".inner }}").unwrap(),
1692 DeclType::StructImported if !is_ref => write!(w, ".take_inner()) }}").unwrap(),
1693 DeclType::MirroredEnum if is_ref => write!(w, ".to_native()").unwrap(),
1694 DeclType::MirroredEnum => write!(w, ".into_native()").unwrap(),
1695 DeclType::Trait(_) => {},
1696 _ => unimplemented!(),
1699 pub fn write_from_c_conversion_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1700 self.write_from_c_conversion_suffix_inner(w, t, generics, false, false);
1702 // Note that compared to the above conversion functions, the following two are generally
1703 // significantly undertested:
1704 pub fn write_from_c_conversion_to_ref_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1705 self.write_conversion_inline_intern(w, t, generics, false, false, false, "() /*", true, |_| "&local_",
1707 if let Some(conv) = self.from_c_conversion_prefix_from_path(a, b) {
1708 Some(format!("&{}", conv))
1711 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1712 DeclType::StructImported if !is_ref => write!(w, "unsafe {{ &*").unwrap(),
1713 _ => unimplemented!(),
1716 pub fn write_from_c_conversion_to_ref_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1717 self.write_conversion_inline_intern(w, t, generics, false, false, false, "*/", false,
1718 |has_inner| match has_inner {
1719 false => ".iter().collect::<Vec<_>>()[..]",
1722 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1723 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1724 DeclType::StructImported if !is_ref => write!(w, ".inner }}").unwrap(),
1725 _ => unimplemented!(),
1729 fn write_conversion_new_var_intern<'b, W: std::io::Write,
1730 LP: Fn(&str, bool) -> Option<(&str, &str)>,
1731 LC: Fn(&str, bool, Option<&syn::Type>, &syn::Ident, &str) -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)>,
1732 VP: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool),
1733 VS: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool)>
1734 (&self, w: &mut W, ident: &syn::Ident, var: &str, t: &syn::Type, generics: Option<&GenericTypes>,
1735 mut is_ref: bool, mut ptr_for_ref: bool, to_c: bool,
1736 path_lookup: &LP, container_lookup: &LC, var_prefix: &VP, var_suffix: &VS) -> bool {
1738 macro_rules! convert_container {
1739 ($container_type: expr, $args_len: expr, $args_iter: expr) => { {
1740 // For slices (and Options), we refuse to directly map them as is_ref when they
1741 // aren't opaque types containing an inner pointer. This is due to the fact that,
1742 // in both cases, the actual higher-level type is non-is_ref.
1743 let ty_has_inner = if $args_len == 1 {
1744 let ty = $args_iter().next().unwrap();
1745 if $container_type == "Slice" && to_c {
1746 // "To C ptr_for_ref" means "return the regular object with is_owned
1747 // set to false", which is totally what we want in a slice if we're about to
1748 // set ty_has_inner.
1751 if let syn::Type::Reference(t) = ty {
1752 if let syn::Type::Path(p) = &*t.elem {
1753 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1755 } else if let syn::Type::Path(p) = ty {
1756 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1760 // Options get a bunch of special handling, since in general we map Option<>al
1761 // types into the same C type as non-Option-wrapped types. This ends up being
1762 // pretty manual here and most of the below special-cases are for Options.
1763 let mut needs_ref_map = false;
1764 let mut only_contained_type = None;
1765 let mut only_contained_has_inner = false;
1766 let mut contains_slice = false;
1768 only_contained_has_inner = ty_has_inner;
1769 let arg = $args_iter().next().unwrap();
1770 if let syn::Type::Reference(t) = arg {
1771 only_contained_type = Some(&*t.elem);
1772 if let syn::Type::Path(_) = &*t.elem {
1774 } else if let syn::Type::Slice(_) = &*t.elem {
1775 contains_slice = true;
1776 } else { return false; }
1777 // If the inner element contains an inner pointer, we will just use that,
1778 // avoiding the need to map elements to references. Otherwise we'll need to
1779 // do an extra mapping step.
1780 needs_ref_map = !only_contained_has_inner;
1782 only_contained_type = Some(&arg);
1786 if let Some((prefix, conversions, suffix, prefix_location)) = container_lookup(&$container_type, is_ref && ty_has_inner, only_contained_type, ident, var) {
1787 assert_eq!(conversions.len(), $args_len);
1788 write!(w, "let mut local_{}{} = ", ident, if !to_c && needs_ref_map {"_base"} else { "" }).unwrap();
1789 if prefix_location == ContainerPrefixLocation::OutsideConv {
1790 var_prefix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
1792 write!(w, "{}{}", prefix, var).unwrap();
1794 for ((pfx, var_name), (idx, ty)) in conversions.iter().zip($args_iter().enumerate()) {
1795 let mut var = std::io::Cursor::new(Vec::new());
1796 write!(&mut var, "{}", var_name).unwrap();
1797 let var_access = String::from_utf8(var.into_inner()).unwrap();
1799 let conv_ty = if needs_ref_map { only_contained_type.as_ref().unwrap() } else { ty };
1801 write!(w, "{} {{ ", pfx).unwrap();
1802 let new_var_name = format!("{}_{}", ident, idx);
1803 let new_var = self.write_conversion_new_var_intern(w, &syn::Ident::new(&new_var_name, Span::call_site()),
1804 &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);
1805 if new_var { write!(w, " ").unwrap(); }
1807 if prefix_location == ContainerPrefixLocation::PerConv {
1808 var_prefix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1809 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
1810 write!(w, "Box::into_raw(Box::new(").unwrap();
1813 write!(w, "{}{}", if contains_slice { "local_" } else { "" }, if new_var { new_var_name } else { var_access }).unwrap();
1814 if prefix_location == ContainerPrefixLocation::PerConv {
1815 var_suffix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1816 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
1817 write!(w, "))").unwrap();
1819 write!(w, " }}").unwrap();
1821 write!(w, "{}", suffix).unwrap();
1822 if prefix_location == ContainerPrefixLocation::OutsideConv {
1823 var_suffix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
1825 write!(w, ";").unwrap();
1826 if !to_c && needs_ref_map {
1827 write!(w, " let mut local_{} = local_{}_base.as_ref()", ident, ident).unwrap();
1829 write!(w, ".map(|a| &a[..])").unwrap();
1831 write!(w, ";").unwrap();
1839 syn::Type::Reference(r) => {
1840 if let syn::Type::Slice(_) = &*r.elem {
1841 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)
1843 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)
1846 syn::Type::Path(p) => {
1847 if p.qself.is_some() {
1850 let resolved_path = self.resolve_path(&p.path, generics);
1851 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1852 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);
1854 if self.is_known_container(&resolved_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
1855 if let syn::PathArguments::AngleBracketed(args) = &p.path.segments.iter().next().unwrap().arguments {
1856 convert_container!(resolved_path, args.args.len(), || args.args.iter().map(|arg| {
1857 if let syn::GenericArgument::Type(ty) = arg {
1859 } else { unimplemented!(); }
1861 } else { unimplemented!(); }
1863 if self.is_primitive(&resolved_path) {
1865 } else if let Some(ty_ident) = single_ident_generic_path_to_ident(&p.path) {
1866 if let Some((prefix, suffix)) = path_lookup(&resolved_path, is_ref) {
1867 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
1869 } else if self.types.maybe_resolve_declared(ty_ident).is_some() {
1874 syn::Type::Array(_) => {
1875 // We assume all arrays contain only primitive types.
1876 // This may result in some outputs not compiling.
1879 syn::Type::Slice(s) => {
1880 if let syn::Type::Path(p) = &*s.elem {
1881 let resolved = self.resolve_path(&p.path, generics);
1882 assert!(self.is_primitive(&resolved));
1883 let slice_path = format!("[{}]", resolved);
1884 if let Some((prefix, suffix)) = path_lookup(&slice_path, true) {
1885 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
1888 } else if let syn::Type::Reference(ty) = &*s.elem {
1889 let tyref = [&*ty.elem];
1891 convert_container!("Slice", 1, || tyref.iter().map(|t| *t));
1892 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
1893 } else if let syn::Type::Tuple(t) = &*s.elem {
1894 // When mapping into a temporary new var, we need to own all the underlying objects.
1895 // Thus, we drop any references inside the tuple and convert with non-reference types.
1896 let mut elems = syn::punctuated::Punctuated::new();
1897 for elem in t.elems.iter() {
1898 if let syn::Type::Reference(r) = elem {
1899 elems.push((*r.elem).clone());
1901 elems.push(elem.clone());
1904 let ty = [syn::Type::Tuple(syn::TypeTuple {
1905 paren_token: t.paren_token, elems
1909 convert_container!("Slice", 1, || ty.iter());
1910 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
1911 } else { unimplemented!() }
1913 syn::Type::Tuple(t) => {
1914 if !t.elems.is_empty() {
1915 // We don't (yet) support tuple elements which cannot be converted inline
1916 write!(w, "let (").unwrap();
1917 for idx in 0..t.elems.len() {
1918 if idx != 0 { write!(w, ", ").unwrap(); }
1919 write!(w, "{} orig_{}_{}", if is_ref { "ref" } else { "mut" }, ident, idx).unwrap();
1921 write!(w, ") = {}{}; ", var, if !to_c { ".to_rust()" } else { "" }).unwrap();
1922 // Like other template types, tuples are always mapped as their non-ref
1923 // versions for types which have different ref mappings. Thus, we convert to
1924 // non-ref versions and handle opaque types with inner pointers manually.
1925 for (idx, elem) in t.elems.iter().enumerate() {
1926 if let syn::Type::Path(p) = elem {
1927 let v_name = format!("orig_{}_{}", ident, idx);
1928 let tuple_elem_ident = syn::Ident::new(&v_name, Span::call_site());
1929 if self.write_conversion_new_var_intern(w, &tuple_elem_ident, &v_name, elem, generics,
1930 false, ptr_for_ref, to_c,
1931 path_lookup, container_lookup, var_prefix, var_suffix) {
1932 write!(w, " ").unwrap();
1933 // Opaque types with inner pointers shouldn't ever create new stack
1934 // variables, so we don't handle it and just assert that it doesn't
1936 assert!(!self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)));
1940 write!(w, "let mut local_{} = (", ident).unwrap();
1941 for (idx, elem) in t.elems.iter().enumerate() {
1942 let ty_has_inner = {
1944 // "To C ptr_for_ref" means "return the regular object with
1945 // is_owned set to false", which is totally what we want
1946 // if we're about to set ty_has_inner.
1949 if let syn::Type::Reference(t) = elem {
1950 if let syn::Type::Path(p) = &*t.elem {
1951 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1953 } else if let syn::Type::Path(p) = elem {
1954 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1957 if idx != 0 { write!(w, ", ").unwrap(); }
1958 var_prefix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1959 if is_ref && ty_has_inner {
1960 // For ty_has_inner, the regular var_prefix mapping will take a
1961 // reference, so deref once here to make sure we keep the original ref.
1962 write!(w, "*").unwrap();
1964 write!(w, "orig_{}_{}", ident, idx).unwrap();
1965 if is_ref && !ty_has_inner {
1966 // If we don't have an inner variable's reference to maintain, just
1967 // hope the type is Clonable and use that.
1968 write!(w, ".clone()").unwrap();
1970 var_suffix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1972 write!(w, "){};", if to_c { ".into()" } else { "" }).unwrap();
1976 _ => unimplemented!(),
1980 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 {
1981 self.write_conversion_new_var_intern(w, ident, var_access, t, generics, false, ptr_for_ref, true,
1982 &|a, b| self.to_c_conversion_new_var_from_path(a, b),
1983 &|a, b, c, d, e| self.to_c_conversion_container_new_var(generics, a, b, c, d, e),
1984 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
1985 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_prefix_inner(a, b, c, d, e, f),
1986 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_suffix_inner(a, b, c, d, e, f))
1988 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 {
1989 self.write_to_c_conversion_new_var_inner(w, ident, &format!("{}", ident), t, generics, ptr_for_ref)
1991 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 {
1992 self.write_conversion_new_var_intern(w, ident, &format!("{}", ident), t, generics, false, false, false,
1993 &|a, b| self.from_c_conversion_new_var_from_path(a, b),
1994 &|a, b, c, d, e| self.from_c_conversion_container_new_var(generics, a, b, c, d, e),
1995 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
1996 &|a, b, c, d, e, _f| self.write_from_c_conversion_prefix_inner(a, b, c, d, e),
1997 &|a, b, c, d, e, _f| self.write_from_c_conversion_suffix_inner(a, b, c, d, e))
2000 // ******************************************************
2001 // *** C Container Type Equivalent and alias Printing ***
2002 // ******************************************************
2004 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 {
2005 for (idx, t) in args.enumerate() {
2007 write!(w, ", ").unwrap();
2009 if let syn::Type::Reference(r_arg) = t {
2010 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2012 if !self.write_c_type_intern(w, &*r_arg.elem, generics, false, false, false) { return false; }
2014 // While write_c_type_intern, above is correct, we don't want to blindly convert a
2015 // reference to something stupid, so check that the container is either opaque or a
2016 // predefined type (currently only Transaction).
2017 if let syn::Type::Path(p_arg) = &*r_arg.elem {
2018 let resolved = self.resolve_path(&p_arg.path, generics);
2019 assert!(self.crate_types.opaques.get(&resolved).is_some() ||
2020 self.c_type_from_path(&resolved, true, true).is_some(), "Template generics should be opaque or have a predefined mapping");
2021 } else { unimplemented!(); }
2022 } else if let syn::Type::Path(p_arg) = t {
2023 if let Some(resolved) = self.maybe_resolve_path(&p_arg.path, generics) {
2024 if !self.is_primitive(&resolved) {
2025 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2028 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2030 if !self.write_c_type_intern(w, t, generics, false, false, false) { return false; }
2032 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2033 if !self.write_c_type_intern(w, t, generics, false, false, false) { return false; }
2038 fn check_create_container(&self, mangled_container: String, container_type: &str, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
2039 if !self.crate_types.templates_defined.borrow().get(&mangled_container).is_some() {
2040 let mut created_container: Vec<u8> = Vec::new();
2042 if container_type == "Result" {
2043 let mut a_ty: Vec<u8> = Vec::new();
2044 if let syn::Type::Tuple(tup) = args.iter().next().unwrap() {
2045 if tup.elems.is_empty() {
2046 write!(&mut a_ty, "()").unwrap();
2048 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
2051 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
2054 let mut b_ty: Vec<u8> = Vec::new();
2055 if let syn::Type::Tuple(tup) = args.iter().skip(1).next().unwrap() {
2056 if tup.elems.is_empty() {
2057 write!(&mut b_ty, "()").unwrap();
2059 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
2062 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
2065 let ok_str = String::from_utf8(a_ty).unwrap();
2066 let err_str = String::from_utf8(b_ty).unwrap();
2067 let is_clonable = self.is_clonable(&ok_str) && self.is_clonable(&err_str);
2068 write_result_block(&mut created_container, &mangled_container, &ok_str, &err_str, is_clonable);
2070 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2072 } else if container_type == "Vec" {
2073 let mut a_ty: Vec<u8> = Vec::new();
2074 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2075 let ty = String::from_utf8(a_ty).unwrap();
2076 let is_clonable = self.is_clonable(&ty);
2077 write_vec_block(&mut created_container, &mangled_container, &ty, is_clonable);
2079 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2081 } else if container_type.ends_with("Tuple") {
2082 let mut tuple_args = Vec::new();
2083 let mut is_clonable = true;
2084 for arg in args.iter() {
2085 let mut ty: Vec<u8> = Vec::new();
2086 if !self.write_template_generics(&mut ty, &mut [arg].iter().map(|t| **t), generics, is_ref) { return false; }
2087 let ty_str = String::from_utf8(ty).unwrap();
2088 if !self.is_clonable(&ty_str) {
2089 is_clonable = false;
2091 tuple_args.push(ty_str);
2093 write_tuple_block(&mut created_container, &mangled_container, &tuple_args, is_clonable);
2095 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2097 } else if container_type == "Option" {
2098 let mut a_ty: Vec<u8> = Vec::new();
2099 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2100 let ty = String::from_utf8(a_ty).unwrap();
2101 let is_clonable = self.is_clonable(&ty);
2102 write_option_block(&mut created_container, &mangled_container, &ty, is_clonable);
2104 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2109 self.crate_types.write_new_template(mangled_container.clone(), true, &created_container);
2113 fn path_to_generic_args(path: &syn::Path) -> Vec<&syn::Type> {
2114 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().next().unwrap().arguments {
2115 args.args.iter().map(|gen| if let syn::GenericArgument::Type(t) = gen { t } else { unimplemented!() }).collect()
2116 } else { unimplemented!(); }
2118 fn write_c_mangled_container_path_intern<W: std::io::Write>
2119 (&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 {
2120 let mut mangled_type: Vec<u8> = Vec::new();
2121 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2122 write!(w, "C{}_", ident).unwrap();
2123 write!(mangled_type, "C{}_", ident).unwrap();
2124 } else { assert_eq!(args.len(), 1); }
2125 for arg in args.iter() {
2126 macro_rules! write_path {
2127 ($p_arg: expr, $extra_write: expr) => {
2128 if let Some(subtype) = self.maybe_resolve_path(&$p_arg.path, generics) {
2129 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2131 if self.c_type_has_inner_from_path(&subtype) {
2132 if !self.write_c_path_intern(w, &$p_arg.path, generics, is_ref, is_mut, ptr_for_ref) { return false; }
2134 if let Some(arr_ty) = self.is_real_type_array(&subtype) {
2135 if !self.write_c_type_intern(w, &arr_ty, generics, false, true, false) { return false; }
2137 // Option<T> needs to be converted to a *mut T, ie mut ptr-for-ref
2138 if !self.write_c_path_intern(w, &$p_arg.path, generics, true, true, true) { return false; }
2142 write!(w, "{}", $p_arg.path.segments.last().unwrap().ident).unwrap();
2144 } else if self.is_known_container(&subtype, is_ref) || self.is_path_transparent_container(&$p_arg.path, generics, is_ref) {
2145 if !self.write_c_mangled_container_path_intern(w, Self::path_to_generic_args(&$p_arg.path), generics,
2146 &subtype, is_ref, is_mut, ptr_for_ref, true) {
2149 self.write_c_mangled_container_path_intern(&mut mangled_type, Self::path_to_generic_args(&$p_arg.path),
2150 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2151 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2152 self.write_c_mangled_container_path_intern(w2, Self::path_to_generic_args(&$p_arg.path),
2153 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2156 let id = subtype.rsplitn(2, ':').next().unwrap(); // Get the "Base" name of the resolved type
2157 write!(w, "{}", id).unwrap();
2158 write!(mangled_type, "{}", id).unwrap();
2159 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2160 write!(w2, "{}", id).unwrap();
2163 } else { return false; }
2166 if let syn::Type::Tuple(tuple) = arg {
2167 if tuple.elems.len() == 0 {
2168 write!(w, "None").unwrap();
2169 write!(mangled_type, "None").unwrap();
2171 let mut mangled_tuple_type: Vec<u8> = Vec::new();
2173 // Figure out what the mangled type should look like. To disambiguate
2174 // ((A, B), C) and (A, B, C) we prefix the generic args with a _ and suffix
2175 // them with a Z. Ideally we wouldn't use Z, but not many special chars are
2176 // available for use in type names.
2177 write!(w, "C{}Tuple_", tuple.elems.len()).unwrap();
2178 write!(mangled_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2179 write!(mangled_tuple_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2180 for elem in tuple.elems.iter() {
2181 if let syn::Type::Path(p) = elem {
2182 write_path!(p, Some(&mut mangled_tuple_type));
2183 } else if let syn::Type::Reference(refelem) = elem {
2184 if let syn::Type::Path(p) = &*refelem.elem {
2185 write_path!(p, Some(&mut mangled_tuple_type));
2186 } else { return false; }
2187 } else { return false; }
2189 write!(w, "Z").unwrap();
2190 write!(mangled_type, "Z").unwrap();
2191 write!(mangled_tuple_type, "Z").unwrap();
2192 if !self.check_create_container(String::from_utf8(mangled_tuple_type).unwrap(),
2193 &format!("{}Tuple", tuple.elems.len()), tuple.elems.iter().collect(), generics, is_ref) {
2197 } else if let syn::Type::Path(p_arg) = arg {
2198 write_path!(p_arg, None);
2199 } else if let syn::Type::Reference(refty) = arg {
2200 if let syn::Type::Path(p_arg) = &*refty.elem {
2201 write_path!(p_arg, None);
2202 } else if let syn::Type::Slice(_) = &*refty.elem {
2203 // write_c_type will actually do exactly what we want here, we just need to
2204 // make it a pointer so that its an option. Note that we cannot always convert
2205 // the Vec-as-slice (ie non-ref types) containers, so sometimes need to be able
2206 // to edit it, hence we use *mut here instead of *const.
2207 if args.len() != 1 { return false; }
2208 write!(w, "*mut ").unwrap();
2209 self.write_c_type(w, arg, None, true);
2210 } else { return false; }
2211 } else if let syn::Type::Array(a) = arg {
2212 if let syn::Type::Path(p_arg) = &*a.elem {
2213 let resolved = self.resolve_path(&p_arg.path, generics);
2214 if !self.is_primitive(&resolved) { return false; }
2215 if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(len), .. }) = &a.len {
2216 if self.c_type_from_path(&format!("[{}; {}]", resolved, len.base10_digits()), is_ref, ptr_for_ref).is_none() { return false; }
2217 write!(w, "_{}{}", resolved, len.base10_digits()).unwrap();
2218 write!(mangled_type, "_{}{}", resolved, len.base10_digits()).unwrap();
2219 } else { return false; }
2220 } else { return false; }
2221 } else { return false; }
2223 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) { return true; }
2224 // Push the "end of type" Z
2225 write!(w, "Z").unwrap();
2226 write!(mangled_type, "Z").unwrap();
2228 // Make sure the type is actually defined:
2229 self.check_create_container(String::from_utf8(mangled_type).unwrap(), ident, args, generics, is_ref)
2231 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 {
2232 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2233 write!(w, "{}::", Self::generated_container_path()).unwrap();
2235 self.write_c_mangled_container_path_intern(w, args, generics, ident, is_ref, is_mut, ptr_for_ref, false)
2238 // **********************************
2239 // *** C Type Equivalent Printing ***
2240 // **********************************
2242 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 {
2243 let full_path = match self.maybe_resolve_path(&path, generics) {
2244 Some(path) => path, None => return false };
2245 if let Some(c_type) = self.c_type_from_path(&full_path, is_ref, ptr_for_ref) {
2246 write!(w, "{}", c_type).unwrap();
2248 } else if self.crate_types.traits.get(&full_path).is_some() {
2249 if is_ref && ptr_for_ref {
2250 write!(w, "*{} crate::{}", if is_mut { "mut" } else { "const" }, full_path).unwrap();
2252 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2254 write!(w, "crate::{}", full_path).unwrap();
2257 } else if self.crate_types.opaques.get(&full_path).is_some() || self.crate_types.mirrored_enums.get(&full_path).is_some() {
2258 if is_ref && ptr_for_ref {
2259 // ptr_for_ref implies we're returning the object, which we can't really do for
2260 // opaque or mirrored types without box'ing them, which is quite a waste, so return
2261 // the actual object itself (for opaque types we'll set the pointer to the actual
2262 // type and note that its a reference).
2263 write!(w, "crate::{}", full_path).unwrap();
2265 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2267 write!(w, "crate::{}", full_path).unwrap();
2274 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 {
2276 syn::Type::Path(p) => {
2277 if p.qself.is_some() {
2280 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
2281 if self.is_known_container(&full_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
2282 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);
2284 if let Some(aliased_type) = self.crate_types.type_aliases.get(&full_path).cloned() {
2285 return self.write_c_type_intern(w, &aliased_type, None, is_ref, is_mut, ptr_for_ref);
2288 self.write_c_path_intern(w, &p.path, generics, is_ref, is_mut, ptr_for_ref)
2290 syn::Type::Reference(r) => {
2291 self.write_c_type_intern(w, &*r.elem, generics, true, r.mutability.is_some(), ptr_for_ref)
2293 syn::Type::Array(a) => {
2294 if is_ref && is_mut {
2295 write!(w, "*mut [").unwrap();
2296 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2298 write!(w, "*const [").unwrap();
2299 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2301 let mut typecheck = Vec::new();
2302 if !self.write_c_type_intern(&mut typecheck, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2303 if typecheck[..] != ['u' as u8, '8' as u8] { return false; }
2305 if let syn::Expr::Lit(l) = &a.len {
2306 if let syn::Lit::Int(i) = &l.lit {
2308 if let Some(ty) = self.c_type_from_path(&format!("[u8; {}]", i.base10_digits()), false, ptr_for_ref) {
2309 write!(w, "{}", ty).unwrap();
2313 write!(w, "; {}]", i).unwrap();
2319 syn::Type::Slice(s) => {
2320 if !is_ref || is_mut { return false; }
2321 if let syn::Type::Path(p) = &*s.elem {
2322 let resolved = self.resolve_path(&p.path, generics);
2323 if self.is_primitive(&resolved) {
2324 write!(w, "{}::{}slice", Self::container_templ_path(), resolved).unwrap();
2327 } else if let syn::Type::Reference(r) = &*s.elem {
2328 if let syn::Type::Path(p) = &*r.elem {
2329 // Slices with "real types" inside are mapped as the equivalent non-ref Vec
2330 let resolved = self.resolve_path(&p.path, generics);
2331 let mangled_container = if let Some(ident) = self.crate_types.opaques.get(&resolved) {
2332 format!("CVec_{}Z", ident)
2333 } else if let Some(en) = self.crate_types.mirrored_enums.get(&resolved) {
2334 format!("CVec_{}Z", en.ident)
2335 } else if let Some(id) = p.path.get_ident() {
2336 format!("CVec_{}Z", id)
2337 } else { return false; };
2338 write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
2339 self.check_create_container(mangled_container, "Vec", vec![&*r.elem], generics, false)
2341 } else if let syn::Type::Tuple(_) = &*s.elem {
2342 let mut args = syn::punctuated::Punctuated::new();
2343 args.push(syn::GenericArgument::Type((*s.elem).clone()));
2344 let mut segments = syn::punctuated::Punctuated::new();
2345 segments.push(syn::PathSegment {
2346 ident: syn::Ident::new("Vec", Span::call_site()),
2347 arguments: syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
2348 colon2_token: None, lt_token: syn::Token![<](Span::call_site()), args, gt_token: syn::Token![>](Span::call_site()),
2351 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)
2354 syn::Type::Tuple(t) => {
2355 if t.elems.len() == 0 {
2358 self.write_c_mangled_container_path(w, t.elems.iter().collect(), generics,
2359 &format!("{}Tuple", t.elems.len()), is_ref, is_mut, ptr_for_ref)
2365 pub fn write_c_type<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) {
2366 assert!(self.write_c_type_intern(w, t, generics, false, false, ptr_for_ref));
2368 pub fn understood_c_path(&self, p: &syn::Path) -> bool {
2369 if p.leading_colon.is_some() { return false; }
2370 self.write_c_path_intern(&mut std::io::sink(), p, None, false, false, false)
2372 pub fn understood_c_type(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
2373 self.write_c_type_intern(&mut std::io::sink(), t, generics, false, false, false)