1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE>
5 // or the MIT license <LICENSE-MIT>, at your option.
6 // You may not use this file except in accordance with one or both of these
9 use std::cell::RefCell;
10 use std::collections::{HashMap, HashSet};
17 use proc_macro2::{TokenTree, Span};
18 use quote::format_ident;
21 // The following utils are used purely to build our known types maps - they break down all the
22 // types we need to resolve to include the given object, and no more.
24 pub fn first_seg_self<'a>(t: &'a syn::Type) -> Option<impl Iterator<Item=&syn::PathSegment> + 'a> {
26 syn::Type::Path(p) => {
27 if p.qself.is_some() || p.path.leading_colon.is_some() {
30 let mut segs = p.path.segments.iter();
31 let ty = segs.next().unwrap();
32 if !ty.arguments.is_empty() { return None; }
33 if format!("{}", ty.ident) == "Self" {
41 pub fn get_single_remaining_path_seg<'a, I: Iterator<Item=&'a syn::PathSegment>>(segs: &mut I) -> Option<&'a syn::Ident> {
42 if let Some(ty) = segs.next() {
43 if !ty.arguments.is_empty() { unimplemented!(); }
44 if segs.next().is_some() { return None; }
49 pub fn first_seg_is_stdlib(first_seg_str: &str) -> bool {
50 first_seg_str == "std" || first_seg_str == "core" || first_seg_str == "alloc"
53 pub fn single_ident_generic_path_to_ident(p: &syn::Path) -> Option<&syn::Ident> {
54 if p.segments.len() == 1 {
55 Some(&p.segments.iter().next().unwrap().ident)
59 pub fn path_matches_nongeneric(p: &syn::Path, exp: &[&str]) -> bool {
60 if p.segments.len() != exp.len() { return false; }
61 for (seg, e) in p.segments.iter().zip(exp.iter()) {
62 if seg.arguments != syn::PathArguments::None { return false; }
63 if &format!("{}", seg.ident) != *e { return false; }
68 #[derive(Debug, PartialEq)]
69 pub enum ExportStatus {
73 /// This is used only for traits to indicate that users should not be able to implement their
74 /// own version of a trait, but we should export Rust implementations of the trait (and the
76 /// Concretly, this means that we do not implement the Rust trait for the C trait struct.
79 /// Gets the ExportStatus of an object (struct, fn, etc) given its attributes.
80 pub fn export_status(attrs: &[syn::Attribute]) -> ExportStatus {
81 for attr in attrs.iter() {
82 let tokens_clone = attr.tokens.clone();
83 let mut token_iter = tokens_clone.into_iter();
84 if let Some(token) = token_iter.next() {
86 TokenTree::Punct(c) if c.as_char() == '=' => {
87 // Really not sure where syn gets '=' from here -
88 // it somehow represents '///' or '//!'
90 TokenTree::Group(g) => {
91 if format!("{}", single_ident_generic_path_to_ident(&attr.path).unwrap()) == "cfg" {
92 let mut iter = g.stream().into_iter();
93 if let TokenTree::Ident(i) = iter.next().unwrap() {
95 // #[cfg(any(test, feature = ""))]
96 if let TokenTree::Group(g) = iter.next().unwrap() {
97 let mut all_test = true;
98 for token in g.stream().into_iter() {
99 if let TokenTree::Ident(i) = token {
100 match format!("{}", i).as_str() {
103 _ => all_test = false,
105 } else if let TokenTree::Literal(lit) = token {
106 if format!("{}", lit) != "fuzztarget" {
111 if all_test { return ExportStatus::TestOnly; }
113 } else if i == "test" {
114 return ExportStatus::TestOnly;
118 continue; // eg #[derive()]
120 _ => unimplemented!(),
123 match token_iter.next().unwrap() {
124 TokenTree::Literal(lit) => {
125 let line = format!("{}", lit);
126 if line.contains("(C-not exported)") {
127 return ExportStatus::NoExport;
128 } else if line.contains("(C-not implementable)") {
129 return ExportStatus::NotImplementable;
132 _ => unimplemented!(),
138 pub fn assert_simple_bound(bound: &syn::TraitBound) {
139 if bound.paren_token.is_some() || bound.lifetimes.is_some() { unimplemented!(); }
140 if let syn::TraitBoundModifier::Maybe(_) = bound.modifier { unimplemented!(); }
143 /// Returns true if the enum will be mapped as an opaue (ie struct with a pointer to the underlying
144 /// type), otherwise it is mapped into a transparent, C-compatible version of itself.
145 pub fn is_enum_opaque(e: &syn::ItemEnum) -> bool {
146 for var in e.variants.iter() {
147 if let syn::Fields::Named(fields) = &var.fields {
148 for field in fields.named.iter() {
149 match export_status(&field.attrs) {
150 ExportStatus::Export|ExportStatus::TestOnly => {},
151 ExportStatus::NotImplementable => panic!("(C-not implementable) should only appear on traits!"),
152 ExportStatus::NoExport => return true,
155 } else if let syn::Fields::Unnamed(fields) = &var.fields {
156 for field in fields.unnamed.iter() {
157 match export_status(&field.attrs) {
158 ExportStatus::Export|ExportStatus::TestOnly => {},
159 ExportStatus::NotImplementable => panic!("(C-not implementable) should only appear on traits!"),
160 ExportStatus::NoExport => return true,
168 /// A stack of sets of generic resolutions.
170 /// This tracks the template parameters for a function, struct, or trait, allowing resolution into
171 /// a concrete type. By pushing a new context onto the stack, this can track a function's template
172 /// parameters inside of a generic struct or trait.
174 /// It maps both direct types as well as Deref<Target = X>, mapping them via the provided
175 /// TypeResolver's resolve_path function (ie traits map to the concrete jump table, structs to the
176 /// concrete C container struct, etc).
178 pub struct GenericTypes<'a, 'b> {
179 self_ty: Option<String>,
180 parent: Option<&'b GenericTypes<'b, 'b>>,
181 typed_generics: HashMap<&'a syn::Ident, String>,
182 default_generics: HashMap<&'a syn::Ident, (syn::Type, syn::Type)>,
184 impl<'a, 'p: 'a> GenericTypes<'a, 'p> {
185 pub fn new(self_ty: Option<String>) -> Self {
186 Self { self_ty, parent: None, typed_generics: HashMap::new(), default_generics: HashMap::new(), }
189 /// push a new context onto the stack, allowing for a new set of generics to be learned which
190 /// will override any lower contexts, but which will still fall back to resoltion via lower
192 pub fn push_ctx<'c>(&'c self) -> GenericTypes<'a, 'c> {
193 GenericTypes { self_ty: None, parent: Some(self), typed_generics: HashMap::new(), default_generics: HashMap::new(), }
196 /// Learn the generics in generics in the current context, given a TypeResolver.
197 pub fn learn_generics<'b, 'c>(&mut self, generics: &'a syn::Generics, types: &'b TypeResolver<'a, 'c>) -> bool {
198 let mut new_typed_generics = HashMap::new();
199 // First learn simple generics...
200 for generic in generics.params.iter() {
202 syn::GenericParam::Type(type_param) => {
203 let mut non_lifetimes_processed = false;
204 'bound_loop: for bound in type_param.bounds.iter() {
205 if let syn::TypeParamBound::Trait(trait_bound) = bound {
206 if let Some(ident) = single_ident_generic_path_to_ident(&trait_bound.path) {
207 match &format!("{}", ident) as &str { "Send" => continue, "Sync" => continue, _ => {} }
209 if path_matches_nongeneric(&trait_bound.path, &["core", "clone", "Clone"]) { continue; }
211 assert_simple_bound(&trait_bound);
212 if let Some(path) = types.maybe_resolve_path(&trait_bound.path, None) {
213 if types.skip_path(&path) { continue; }
214 if path == "Sized" { continue; }
215 if non_lifetimes_processed { return false; }
216 non_lifetimes_processed = true;
217 if path != "std::ops::Deref" && path != "core::ops::Deref" {
218 new_typed_generics.insert(&type_param.ident, Some(path));
219 } else if trait_bound.path.segments.len() == 1 {
220 // If we're templated on Deref<Target = ConcreteThing>, store
221 // the reference type in `default_generics` which handles full
222 // types and not just paths.
223 if let syn::PathArguments::AngleBracketed(ref args) =
224 trait_bound.path.segments[0].arguments {
225 for subargument in args.args.iter() {
227 syn::GenericArgument::Lifetime(_) => {},
228 syn::GenericArgument::Binding(ref b) => {
229 if &format!("{}", b.ident) != "Target" { return false; }
231 self.default_generics.insert(&type_param.ident, (parse_quote!(&#default), parse_quote!(&#default)));
234 _ => unimplemented!(),
238 new_typed_generics.insert(&type_param.ident, None);
244 if let Some(default) = type_param.default.as_ref() {
245 assert!(type_param.bounds.is_empty());
246 self.default_generics.insert(&type_param.ident, (default.clone(), parse_quote!(&#default)));
252 // Then find generics where we are required to pass a Deref<Target=X> and pretend its just X.
253 if let Some(wh) = &generics.where_clause {
254 for pred in wh.predicates.iter() {
255 if let syn::WherePredicate::Type(t) = pred {
256 if let syn::Type::Path(p) = &t.bounded_ty {
257 if p.qself.is_some() { return false; }
258 if p.path.leading_colon.is_some() { return false; }
259 let mut p_iter = p.path.segments.iter();
260 if let Some(gen) = new_typed_generics.get_mut(&p_iter.next().unwrap().ident) {
261 if gen.is_some() { return false; }
262 if &format!("{}", p_iter.next().unwrap().ident) != "Target" {return false; }
264 let mut non_lifetimes_processed = false;
265 for bound in t.bounds.iter() {
266 if let syn::TypeParamBound::Trait(trait_bound) = bound {
267 if let Some(id) = trait_bound.path.get_ident() {
268 if format!("{}", id) == "Sized" { continue; }
270 if non_lifetimes_processed { return false; }
271 non_lifetimes_processed = true;
272 assert_simple_bound(&trait_bound);
273 *gen = Some(types.resolve_path(&trait_bound.path, None));
276 } else { return false; }
277 } else { return false; }
281 for (key, value) in new_typed_generics.drain() {
282 if let Some(v) = value {
283 assert!(self.typed_generics.insert(key, v).is_none());
284 } else { return false; }
289 /// Learn the associated types from the trait in the current context.
290 pub fn learn_associated_types<'b, 'c>(&mut self, t: &'a syn::ItemTrait, types: &'b TypeResolver<'a, 'c>) {
291 for item in t.items.iter() {
293 &syn::TraitItem::Type(ref t) => {
294 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
295 let mut bounds_iter = t.bounds.iter();
297 match bounds_iter.next().unwrap() {
298 syn::TypeParamBound::Trait(tr) => {
299 assert_simple_bound(&tr);
300 if let Some(path) = types.maybe_resolve_path(&tr.path, None) {
301 if types.skip_path(&path) { continue; }
302 // In general we handle Deref<Target=X> as if it were just X (and
303 // implement Deref<Target=Self> for relevant types). We don't
304 // bother to implement it for associated types, however, so we just
305 // ignore such bounds.
306 if path != "std::ops::Deref" && path != "core::ops::Deref" {
307 self.typed_generics.insert(&t.ident, path);
309 } else { unimplemented!(); }
310 for bound in bounds_iter {
311 if let syn::TypeParamBound::Trait(_) = bound { unimplemented!(); }
315 syn::TypeParamBound::Lifetime(_) => {},
324 /// Attempt to resolve a Path as a generic parameter and return the full path. as both a string
326 pub fn maybe_resolve_path<'b>(&'b self, path: &syn::Path) -> Option<&'b String> {
327 if let Some(ident) = path.get_ident() {
328 if let Some(ty) = &self.self_ty {
329 if format!("{}", ident) == "Self" {
333 if let Some(res) = self.typed_generics.get(ident) {
337 // Associated types are usually specified as "Self::Generic", so we check for that
339 let mut it = path.segments.iter();
340 if path.segments.len() == 2 && format!("{}", it.next().unwrap().ident) == "Self" {
341 let ident = &it.next().unwrap().ident;
342 if let Some(res) = self.typed_generics.get(ident) {
347 if let Some(parent) = self.parent {
348 parent.maybe_resolve_path(path)
355 pub trait ResolveType<'a> { fn resolve_type(&'a self, ty: &'a syn::Type) -> &'a syn::Type; }
356 impl<'a, 'b, 'c: 'a + 'b> ResolveType<'c> for Option<&GenericTypes<'a, 'b>> {
357 fn resolve_type(&'c self, ty: &'c syn::Type) -> &'c syn::Type {
358 if let Some(us) = self {
360 syn::Type::Path(p) => {
361 if let Some(ident) = p.path.get_ident() {
362 if let Some((ty, _)) = us.default_generics.get(ident) {
367 syn::Type::Reference(syn::TypeReference { elem, .. }) => {
368 if let syn::Type::Path(p) = &**elem {
369 if let Some(ident) = p.path.get_ident() {
370 if let Some((_, refty)) = us.default_generics.get(ident) {
378 us.parent.resolve_type(ty)
383 #[derive(Clone, PartialEq)]
384 // The type of declaration and the object itself
385 pub enum DeclType<'a> {
387 Trait(&'a syn::ItemTrait),
388 StructImported { generics: &'a syn::Generics },
390 EnumIgnored { generics: &'a syn::Generics },
393 pub struct ImportResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
394 crate_name: &'mod_lifetime str,
395 dependencies: &'mod_lifetime HashSet<syn::Ident>,
396 module_path: &'mod_lifetime str,
397 imports: HashMap<syn::Ident, (String, syn::Path)>,
398 declared: HashMap<syn::Ident, DeclType<'crate_lft>>,
399 priv_modules: HashSet<syn::Ident>,
401 impl<'mod_lifetime, 'crate_lft: 'mod_lifetime> ImportResolver<'mod_lifetime, 'crate_lft> {
402 fn process_use_intern(crate_name: &str, module_path: &str, dependencies: &HashSet<syn::Ident>, imports: &mut HashMap<syn::Ident, (String, syn::Path)>,
403 u: &syn::UseTree, partial_path: &str, mut path: syn::punctuated::Punctuated<syn::PathSegment, syn::token::Colon2>) {
406 macro_rules! push_path {
407 ($ident: expr, $path_suffix: expr) => {
408 if partial_path == "" && format!("{}", $ident) == "super" {
409 let mut mod_iter = module_path.rsplitn(2, "::");
410 mod_iter.next().unwrap();
411 let super_mod = mod_iter.next().unwrap();
412 new_path = format!("{}{}", super_mod, $path_suffix);
413 assert_eq!(path.len(), 0);
414 for module in super_mod.split("::") {
415 path.push(syn::PathSegment { ident: syn::Ident::new(module, Span::call_site()), arguments: syn::PathArguments::None });
417 } else if partial_path == "" && format!("{}", $ident) == "self" {
418 new_path = format!("{}{}", module_path, $path_suffix);
419 for module in module_path.split("::") {
420 path.push(syn::PathSegment { ident: syn::Ident::new(module, Span::call_site()), arguments: syn::PathArguments::None });
422 } else if partial_path == "" && format!("{}", $ident) == "crate" {
423 new_path = format!("{}{}", crate_name, $path_suffix);
424 let crate_name_ident = format_ident!("{}", crate_name);
425 path.push(parse_quote!(#crate_name_ident));
426 } else if partial_path == "" && !dependencies.contains(&$ident) {
427 new_path = format!("{}::{}{}", crate_name, $ident, $path_suffix);
428 let crate_name_ident = format_ident!("{}", crate_name);
429 path.push(parse_quote!(#crate_name_ident));
431 new_path = format!("{}{}{}", partial_path, $ident, $path_suffix);
434 path.push(parse_quote!(#ident));
438 syn::UseTree::Path(p) => {
439 push_path!(p.ident, "::");
440 Self::process_use_intern(crate_name, module_path, dependencies, imports, &p.tree, &new_path, path);
442 syn::UseTree::Name(n) => {
443 push_path!(n.ident, "");
444 imports.insert(n.ident.clone(), (new_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
446 syn::UseTree::Group(g) => {
447 for i in g.items.iter() {
448 Self::process_use_intern(crate_name, module_path, dependencies, imports, i, partial_path, path.clone());
451 syn::UseTree::Rename(r) => {
452 push_path!(r.ident, "");
453 imports.insert(r.rename.clone(), (new_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
455 syn::UseTree::Glob(_) => {
456 eprintln!("Ignoring * use for {} - this may result in resolution failures", partial_path);
461 fn process_use(crate_name: &str, module_path: &str, dependencies: &HashSet<syn::Ident>, imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::ItemUse) {
462 if let syn::Visibility::Public(_) = u.vis {
463 // We actually only use these for #[cfg(fuzztarget)]
464 eprintln!("Ignoring pub(use) tree!");
467 if u.leading_colon.is_some() { eprintln!("Ignoring leading-colon use!"); return; }
468 Self::process_use_intern(crate_name, module_path, dependencies, imports, &u.tree, "", syn::punctuated::Punctuated::new());
471 fn insert_primitive(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, id: &str) {
472 let ident = format_ident!("{}", id);
473 let path = parse_quote!(#ident);
474 imports.insert(ident, (id.to_owned(), path));
477 pub fn new(crate_name: &'mod_lifetime str, dependencies: &'mod_lifetime HashSet<syn::Ident>, module_path: &'mod_lifetime str, contents: &'crate_lft [syn::Item]) -> Self {
478 Self::from_borrowed_items(crate_name, dependencies, module_path, &contents.iter().map(|a| a).collect::<Vec<_>>())
480 pub fn from_borrowed_items(crate_name: &'mod_lifetime str, dependencies: &'mod_lifetime HashSet<syn::Ident>, module_path: &'mod_lifetime str, contents: &[&'crate_lft syn::Item]) -> Self {
481 let mut imports = HashMap::new();
482 // Add primitives to the "imports" list:
483 Self::insert_primitive(&mut imports, "bool");
484 Self::insert_primitive(&mut imports, "u64");
485 Self::insert_primitive(&mut imports, "u32");
486 Self::insert_primitive(&mut imports, "u16");
487 Self::insert_primitive(&mut imports, "u8");
488 Self::insert_primitive(&mut imports, "usize");
489 Self::insert_primitive(&mut imports, "str");
490 Self::insert_primitive(&mut imports, "String");
492 // These are here to allow us to print native Rust types in trait fn impls even if we don't
494 Self::insert_primitive(&mut imports, "Result");
495 Self::insert_primitive(&mut imports, "Vec");
496 Self::insert_primitive(&mut imports, "Option");
498 let mut declared = HashMap::new();
499 let mut priv_modules = HashSet::new();
501 for item in contents.iter() {
503 syn::Item::Use(u) => Self::process_use(crate_name, module_path, dependencies, &mut imports, &u),
504 syn::Item::Struct(s) => {
505 if let syn::Visibility::Public(_) = s.vis {
506 match export_status(&s.attrs) {
507 ExportStatus::Export => { declared.insert(s.ident.clone(), DeclType::StructImported { generics: &s.generics }); },
508 ExportStatus::NoExport => { declared.insert(s.ident.clone(), DeclType::StructIgnored); },
509 ExportStatus::TestOnly => continue,
510 ExportStatus::NotImplementable => panic!("(C-not implementable) should only appear on traits!"),
514 syn::Item::Type(t) if export_status(&t.attrs) == ExportStatus::Export => {
515 if let syn::Visibility::Public(_) = t.vis {
516 declared.insert(t.ident.clone(), DeclType::StructImported { generics: &t.generics });
519 syn::Item::Enum(e) => {
520 if let syn::Visibility::Public(_) = e.vis {
521 match export_status(&e.attrs) {
522 ExportStatus::Export if is_enum_opaque(e) => { declared.insert(e.ident.clone(), DeclType::EnumIgnored { generics: &e.generics }); },
523 ExportStatus::Export => { declared.insert(e.ident.clone(), DeclType::MirroredEnum); },
524 ExportStatus::NotImplementable => panic!("(C-not implementable) should only appear on traits!"),
529 syn::Item::Trait(t) => {
530 match export_status(&t.attrs) {
531 ExportStatus::Export|ExportStatus::NotImplementable => {
532 if let syn::Visibility::Public(_) = t.vis {
533 declared.insert(t.ident.clone(), DeclType::Trait(t));
539 syn::Item::Mod(m) => {
540 priv_modules.insert(m.ident.clone());
546 Self { crate_name, dependencies, module_path, imports, declared, priv_modules }
549 pub fn get_declared_type(&self, ident: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
550 self.declared.get(ident)
553 pub fn maybe_resolve_declared(&self, id: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
554 self.declared.get(id)
557 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
558 if let Some((imp, _)) = self.imports.get(id) {
560 } else if self.declared.get(id).is_some() {
561 Some(self.module_path.to_string() + "::" + &format!("{}", id))
565 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
566 if let Some((imp, _)) = self.imports.get(id) {
568 } else if let Some(decl_type) = self.declared.get(id) {
570 DeclType::StructIgnored => None,
571 _ => Some(self.module_path.to_string() + "::" + &format!("{}", id)),
576 pub fn maybe_resolve_path(&self, p: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
577 if let Some(gen_types) = generics {
578 if let Some(resp) = gen_types.maybe_resolve_path(p) {
579 return Some(resp.clone());
583 if p.leading_colon.is_some() {
584 let mut res: String = p.segments.iter().enumerate().map(|(idx, seg)| {
585 format!("{}{}", if idx == 0 { "" } else { "::" }, seg.ident)
587 let firstseg = p.segments.iter().next().unwrap();
588 if !self.dependencies.contains(&firstseg.ident) {
589 res = self.crate_name.to_owned() + "::" + &res;
592 } else if let Some(id) = p.get_ident() {
593 self.maybe_resolve_ident(id)
595 if p.segments.len() == 1 {
596 let seg = p.segments.iter().next().unwrap();
597 return self.maybe_resolve_ident(&seg.ident);
599 let mut seg_iter = p.segments.iter();
600 let first_seg = seg_iter.next().unwrap();
601 let remaining: String = seg_iter.map(|seg| {
602 format!("::{}", seg.ident)
604 let first_seg_str = format!("{}", first_seg.ident);
605 if let Some((imp, _)) = self.imports.get(&first_seg.ident) {
607 Some(imp.clone() + &remaining)
611 } else if let Some(_) = self.priv_modules.get(&first_seg.ident) {
612 Some(format!("{}::{}{}", self.module_path, first_seg.ident, remaining))
613 } else if first_seg_is_stdlib(&first_seg_str) || self.dependencies.contains(&first_seg.ident) {
614 Some(first_seg_str + &remaining)
619 /// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern)
620 pub fn resolve_imported_refs(&self, mut ty: syn::Type) -> syn::Type {
622 syn::Type::Path(p) => {
623 if p.path.segments.len() != 1 { unimplemented!(); }
624 let mut args = p.path.segments[0].arguments.clone();
625 if let syn::PathArguments::AngleBracketed(ref mut generics) = &mut args {
626 for arg in generics.args.iter_mut() {
627 if let syn::GenericArgument::Type(ref mut t) = arg {
628 *t = self.resolve_imported_refs(t.clone());
632 if let Some((_, newpath)) = self.imports.get(single_ident_generic_path_to_ident(&p.path).unwrap()) {
633 p.path = newpath.clone();
635 p.path.segments[0].arguments = args;
637 syn::Type::Reference(r) => {
638 r.elem = Box::new(self.resolve_imported_refs((*r.elem).clone()));
640 syn::Type::Slice(s) => {
641 s.elem = Box::new(self.resolve_imported_refs((*s.elem).clone()));
643 syn::Type::Tuple(t) => {
644 for e in t.elems.iter_mut() {
645 *e = self.resolve_imported_refs(e.clone());
648 _ => unimplemented!(),
654 // templates_defined is walked to write the C++ header, so if we use the default hashing it get
655 // reordered on each genbindings run. Instead, we use SipHasher (which defaults to 0-keys) so that
656 // the sorting is stable across runs. It is deprecated, but the "replacement" doesn't actually
657 // accomplish the same goals, so we just ignore it.
659 pub type NonRandomHash = hash::BuildHasherDefault<hash::SipHasher>;
662 pub struct ASTModule {
663 pub attrs: Vec<syn::Attribute>,
664 pub items: Vec<syn::Item>,
665 pub submods: Vec<String>,
667 /// A struct containing the syn::File AST for each file in the crate.
668 pub struct FullLibraryAST {
669 pub modules: HashMap<String, ASTModule, NonRandomHash>,
670 pub dependencies: HashSet<syn::Ident>,
672 impl FullLibraryAST {
673 fn load_module(&mut self, module: String, attrs: Vec<syn::Attribute>, mut items: Vec<syn::Item>) {
674 let mut non_mod_items = Vec::with_capacity(items.len());
675 let mut submods = Vec::with_capacity(items.len());
676 for item in items.drain(..) {
678 syn::Item::Mod(m) if m.content.is_some() => {
679 if export_status(&m.attrs) == ExportStatus::Export {
680 if let syn::Visibility::Public(_) = m.vis {
681 let modident = format!("{}", m.ident);
682 let modname = if module != "" {
683 module.clone() + "::" + &modident
687 self.load_module(modname, m.attrs, m.content.unwrap().1);
688 submods.push(modident);
690 non_mod_items.push(syn::Item::Mod(m));
694 syn::Item::Mod(_) => panic!("--pretty=expanded output should never have non-body modules"),
695 syn::Item::ExternCrate(c) => {
696 if export_status(&c.attrs) == ExportStatus::Export {
697 self.dependencies.insert(c.ident);
700 _ => { non_mod_items.push(item); }
703 self.modules.insert(module, ASTModule { attrs, items: non_mod_items, submods });
706 pub fn load_lib(lib: syn::File) -> Self {
707 assert_eq!(export_status(&lib.attrs), ExportStatus::Export);
708 let mut res = Self { modules: HashMap::default(), dependencies: HashSet::new() };
709 res.load_module("".to_owned(), lib.attrs, lib.items);
714 /// List of manually-generated types which are clonable
715 fn initial_clonable_types() -> HashSet<String> {
716 let mut res = HashSet::new();
717 res.insert("crate::c_types::u5".to_owned());
718 res.insert("crate::c_types::ThirtyTwoBytes".to_owned());
719 res.insert("crate::c_types::SecretKey".to_owned());
720 res.insert("crate::c_types::PublicKey".to_owned());
721 res.insert("crate::c_types::Transaction".to_owned());
722 res.insert("crate::c_types::TxOut".to_owned());
723 res.insert("crate::c_types::Signature".to_owned());
724 res.insert("crate::c_types::RecoverableSignature".to_owned());
725 res.insert("crate::c_types::Secp256k1Error".to_owned());
726 res.insert("crate::c_types::IOError".to_owned());
730 /// Top-level struct tracking everything which has been defined while walking the crate.
731 pub struct CrateTypes<'a> {
732 /// This may contain structs or enums, but only when either is mapped as
733 /// struct X { inner: *mut originalX, .. }
734 pub opaques: HashMap<String, (&'a syn::Ident, &'a syn::Generics)>,
735 /// structs that weren't exposed
736 pub priv_structs: HashMap<String, &'a syn::Generics>,
737 /// Enums which are mapped as C enums with conversion functions
738 pub mirrored_enums: HashMap<String, &'a syn::ItemEnum>,
739 /// Traits which are mapped as a pointer + jump table
740 pub traits: HashMap<String, &'a syn::ItemTrait>,
741 /// Aliases from paths to some other Type
742 pub type_aliases: HashMap<String, syn::Type>,
743 /// Value is an alias to Key (maybe with some generics)
744 pub reverse_alias_map: HashMap<String, Vec<(syn::Path, syn::PathArguments)>>,
745 /// Template continer types defined, map from mangled type name -> whether a destructor fn
748 /// This is used at the end of processing to make C++ wrapper classes
749 pub templates_defined: RefCell<HashMap<String, bool, NonRandomHash>>,
750 /// The output file for any created template container types, written to as we find new
751 /// template containers which need to be defined.
752 template_file: RefCell<&'a mut File>,
753 /// Set of containers which are clonable
754 clonable_types: RefCell<HashSet<String>>,
756 pub trait_impls: HashMap<String, Vec<String>>,
757 /// The full set of modules in the crate(s)
758 pub lib_ast: &'a FullLibraryAST,
761 impl<'a> CrateTypes<'a> {
762 pub fn new(template_file: &'a mut File, libast: &'a FullLibraryAST) -> Self {
764 opaques: HashMap::new(), mirrored_enums: HashMap::new(), traits: HashMap::new(),
765 type_aliases: HashMap::new(), reverse_alias_map: HashMap::new(),
766 templates_defined: RefCell::new(HashMap::default()), priv_structs: HashMap::new(),
767 clonable_types: RefCell::new(initial_clonable_types()), trait_impls: HashMap::new(),
768 template_file: RefCell::new(template_file), lib_ast: &libast,
771 pub fn set_clonable(&self, object: String) {
772 self.clonable_types.borrow_mut().insert(object);
774 pub fn is_clonable(&self, object: &str) -> bool {
775 self.clonable_types.borrow().contains(object)
777 pub fn write_new_template(&self, mangled_container: String, has_destructor: bool, created_container: &[u8]) {
778 self.template_file.borrow_mut().write(created_container).unwrap();
779 self.templates_defined.borrow_mut().insert(mangled_container, has_destructor);
783 /// A struct which tracks resolving rust types into C-mapped equivalents, exists for one specific
784 /// module but contains a reference to the overall CrateTypes tracking.
785 pub struct TypeResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
786 pub module_path: &'mod_lifetime str,
787 pub crate_types: &'mod_lifetime CrateTypes<'crate_lft>,
788 types: ImportResolver<'mod_lifetime, 'crate_lft>,
791 /// Returned by write_empty_rust_val_check_suffix to indicate what type of dereferencing needs to
792 /// happen to get the inner value of a generic.
793 enum EmptyValExpectedTy {
794 /// A type which has a flag for being empty (eg an array where we treat all-0s as empty).
796 /// A Option mapped as a COption_*Z
798 /// A pointer which we want to convert to a reference.
803 /// Describes the appropriate place to print a general type-conversion string when converting a
805 enum ContainerPrefixLocation {
806 /// Prints a general type-conversion string prefix and suffix outside of the
807 /// container-conversion strings.
809 /// Prints a general type-conversion string prefix and suffix inside of the
810 /// container-conversion strings.
812 /// Does not print the usual type-conversion string prefix and suffix.
816 impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
817 pub fn new(module_path: &'a str, types: ImportResolver<'a, 'c>, crate_types: &'a CrateTypes<'c>) -> Self {
818 Self { module_path, types, crate_types }
821 // *************************************************
822 // *** Well know type and conversion definitions ***
823 // *************************************************
825 /// Returns true we if can just skip passing this to C entirely
826 pub fn skip_path(&self, full_path: &str) -> bool {
827 full_path == "bitcoin::secp256k1::Secp256k1" ||
828 full_path == "bitcoin::secp256k1::Signing" ||
829 full_path == "bitcoin::secp256k1::Verification"
831 /// Returns true we if can just skip passing this to C entirely
832 fn no_arg_path_to_rust(&self, full_path: &str) -> &str {
833 if full_path == "bitcoin::secp256k1::Secp256k1" {
834 "secp256k1::SECP256K1"
835 } else { unimplemented!(); }
838 /// Returns true if the object is a primitive and is mapped as-is with no conversion
840 pub fn is_primitive(&self, full_path: &str) -> bool {
851 pub fn is_clonable(&self, ty: &str) -> bool {
852 if self.crate_types.is_clonable(ty) { return true; }
853 if self.is_primitive(ty) { return true; }
859 /// Gets the C-mapped type for types which are outside of the crate, or which are manually
860 /// ignored by for some reason need mapping anyway.
861 fn c_type_from_path<'b>(&self, full_path: &'b str, is_ref: bool, _ptr_for_ref: bool) -> Option<&'b str> {
862 if self.is_primitive(full_path) {
863 return Some(full_path);
866 // Note that no !is_ref types can map to an array because Rust and C's call semantics
867 // for arrays are different (https://github.com/eqrion/cbindgen/issues/528)
869 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
870 "[u8; 20]" if !is_ref => Some("crate::c_types::TwentyBytes"),
871 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes"),
872 "[u8; 12]" if !is_ref => Some("crate::c_types::TwelveBytes"),
873 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes"),
874 "[u8; 3]" if !is_ref => Some("crate::c_types::ThreeBytes"), // Used for RGB values
876 "str" if is_ref => Some("crate::c_types::Str"),
877 "alloc::string::String"|"String" => Some("crate::c_types::Str"),
879 "std::time::Duration"|"core::time::Duration" => Some("u64"),
880 "std::time::SystemTime" => Some("u64"),
881 "std::io::Error" => Some("crate::c_types::IOError"),
882 "core::fmt::Arguments" if is_ref => Some("crate::c_types::Str"),
884 "core::convert::Infallible" => Some("crate::c_types::NotConstructable"),
886 "bitcoin::bech32::Error"|"bech32::Error"
887 if !is_ref => Some("crate::c_types::Bech32Error"),
888 "bitcoin::secp256k1::Error"|"secp256k1::Error"
889 if !is_ref => Some("crate::c_types::Secp256k1Error"),
891 "core::num::ParseIntError" => Some("crate::c_types::Error"),
892 "core::str::Utf8Error" => Some("crate::c_types::Error"),
894 "bitcoin::bech32::u5"|"bech32::u5" => Some("crate::c_types::u5"),
895 "core::num::NonZeroU8" => Some("u8"),
897 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
898 => Some("crate::c_types::PublicKey"),
899 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature"),
900 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some("crate::c_types::RecoverableSignature"),
901 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
902 if is_ref => Some("*const [u8; 32]"),
903 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
904 if !is_ref => Some("crate::c_types::SecretKey"),
905 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice"),
906 "bitcoin::blockdata::script::Script" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
907 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::lightning::chain::transaction::OutPoint"),
908 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" => Some("crate::c_types::Transaction"),
909 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut"),
910 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network"),
911 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("*const [u8; 80]"),
912 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice"),
914 "bitcoin::hash_types::PubkeyHash"|"bitcoin::hash_types::WPubkeyHash"|"bitcoin::hash_types::ScriptHash"
915 if is_ref => Some("*const [u8; 20]"),
916 "bitcoin::hash_types::WScriptHash"
917 if is_ref => Some("*const [u8; 32]"),
919 // Newtypes that we just expose in their original form.
920 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
921 if is_ref => Some("*const [u8; 32]"),
922 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
923 if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
924 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
925 "lightning::ln::PaymentHash"|"lightning::ln::PaymentPreimage"|"lightning::ln::PaymentSecret"
926 |"lightning::ln::channelmanager::PaymentId"|"lightning::chain::keysinterface::KeyMaterial"
927 if is_ref => Some("*const [u8; 32]"),
928 "lightning::ln::PaymentHash"|"lightning::ln::PaymentPreimage"|"lightning::ln::PaymentSecret"
929 |"lightning::ln::channelmanager::PaymentId"|"lightning::chain::keysinterface::KeyMaterial"
930 if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
932 "lightning::io::Read" => Some("crate::c_types::u8slice"),
938 fn from_c_conversion_new_var_from_path<'b>(&self, _full_path: &str, _is_ref: bool) -> Option<(&'b str, &'b str)> {
941 fn from_c_conversion_prefix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
942 if self.is_primitive(full_path) {
943 return Some("".to_owned());
946 "Vec" if !is_ref => Some("local_"),
947 "Result" if !is_ref => Some("local_"),
948 "Option" if is_ref => Some("&local_"),
949 "Option" => Some("local_"),
951 "[u8; 32]" if is_ref => Some("unsafe { &*"),
952 "[u8; 32]" if !is_ref => Some(""),
953 "[u8; 20]" if !is_ref => Some(""),
954 "[u8; 16]" if !is_ref => Some(""),
955 "[u8; 12]" if !is_ref => Some(""),
956 "[u8; 4]" if !is_ref => Some(""),
957 "[u8; 3]" if !is_ref => Some(""),
959 "[u8]" if is_ref => Some(""),
960 "[usize]" if is_ref => Some(""),
962 "str" if is_ref => Some(""),
963 "alloc::string::String"|"String" => Some(""),
964 "std::io::Error" if !is_ref => Some(""),
965 // Note that we'll panic for String if is_ref, as we only have non-owned memory, we
966 // cannot create a &String.
968 "core::convert::Infallible" => Some("panic!(\"You must never construct a NotConstructable! : "),
970 "bitcoin::bech32::Error"|"bech32::Error" if !is_ref => Some(""),
971 "bitcoin::secp256k1::Error"|"secp256k1::Error" if !is_ref => Some(""),
973 "core::num::ParseIntError" => Some("u8::from_str_radix(\" a\", 10).unwrap_err() /*"),
974 "core::str::Utf8Error" => Some("core::str::from_utf8(&[0xff]).unwrap_err() /*"),
976 "std::time::Duration"|"core::time::Duration" => Some("core::time::Duration::from_secs("),
977 "std::time::SystemTime" => Some("(::std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs("),
979 "bitcoin::bech32::u5"|"bech32::u5" => Some(""),
980 "core::num::NonZeroU8" => Some("core::num::NonZeroU8::new("),
982 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
983 if is_ref => Some("&"),
984 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
986 "bitcoin::secp256k1::Signature" if is_ref => Some("&"),
987 "bitcoin::secp256k1::Signature" => Some(""),
988 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(""),
989 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
990 if is_ref => Some("&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *"),
991 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
992 if !is_ref => Some(""),
993 "bitcoin::blockdata::script::Script" if is_ref => Some("&::bitcoin::blockdata::script::Script::from(Vec::from("),
994 "bitcoin::blockdata::script::Script" if !is_ref => Some("::bitcoin::blockdata::script::Script::from("),
995 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" if is_ref => Some("&"),
996 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" => Some(""),
997 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::c_types::C_to_bitcoin_outpoint("),
998 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(""),
999 "bitcoin::network::constants::Network" => Some(""),
1000 "bitcoin::blockdata::block::BlockHeader" => Some("&::bitcoin::consensus::encode::deserialize(unsafe { &*"),
1001 "bitcoin::blockdata::block::Block" if is_ref => Some("&::bitcoin::consensus::encode::deserialize("),
1003 "bitcoin::hash_types::PubkeyHash" if is_ref =>
1004 Some("&bitcoin::hash_types::PubkeyHash::from_hash(bitcoin::hashes::Hash::from_inner(unsafe { *"),
1005 "bitcoin::hash_types::WPubkeyHash" if is_ref =>
1006 Some("&bitcoin::hash_types::WPubkeyHash::from_hash(bitcoin::hashes::Hash::from_inner(unsafe { *"),
1007 "bitcoin::hash_types::ScriptHash" if is_ref =>
1008 Some("&bitcoin::hash_types::ScriptHash::from_hash(bitcoin::hashes::Hash::from_inner(unsafe { *"),
1009 "bitcoin::hash_types::WScriptHash" if is_ref =>
1010 Some("&bitcoin::hash_types::WScriptHash::from_hash(bitcoin::hashes::Hash::from_inner(unsafe { *"),
1012 // Newtypes that we just expose in their original form.
1013 "bitcoin::hash_types::Txid" if is_ref => Some("&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*"),
1014 "bitcoin::hash_types::Txid" if !is_ref => Some("::bitcoin::hash_types::Txid::from_slice(&"),
1015 "bitcoin::hash_types::BlockHash" => Some("::bitcoin::hash_types::BlockHash::from_slice(&"),
1016 "lightning::ln::PaymentHash" if !is_ref => Some("::lightning::ln::PaymentHash("),
1017 "lightning::ln::PaymentHash" if is_ref => Some("&::lightning::ln::PaymentHash(unsafe { *"),
1018 "lightning::ln::PaymentPreimage" if !is_ref => Some("::lightning::ln::PaymentPreimage("),
1019 "lightning::ln::PaymentPreimage" if is_ref => Some("&::lightning::ln::PaymentPreimage(unsafe { *"),
1020 "lightning::ln::PaymentSecret" if !is_ref => Some("::lightning::ln::PaymentSecret("),
1021 "lightning::ln::channelmanager::PaymentId" if !is_ref => Some("::lightning::ln::channelmanager::PaymentId("),
1022 "lightning::ln::channelmanager::PaymentId" if is_ref=> Some("&::lightning::ln::channelmanager::PaymentId( unsafe { *"),
1023 "lightning::chain::keysinterface::KeyMaterial" if !is_ref => Some("::lightning::chain::keysinterface::KeyMaterial("),
1024 "lightning::chain::keysinterface::KeyMaterial" if is_ref=> Some("&::lightning::chain::keysinterface::KeyMaterial( unsafe { *"),
1026 // List of traits we map (possibly during processing of other files):
1027 "lightning::io::Read" => Some("&mut "),
1030 }.map(|s| s.to_owned())
1032 fn from_c_conversion_suffix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
1033 if self.is_primitive(full_path) {
1034 return Some("".to_owned());
1037 "Vec" if !is_ref => Some(""),
1038 "Option" => Some(""),
1039 "Result" if !is_ref => Some(""),
1041 "[u8; 32]" if is_ref => Some("}"),
1042 "[u8; 32]" if !is_ref => Some(".data"),
1043 "[u8; 20]" if !is_ref => Some(".data"),
1044 "[u8; 16]" if !is_ref => Some(".data"),
1045 "[u8; 12]" if !is_ref => Some(".data"),
1046 "[u8; 4]" if !is_ref => Some(".data"),
1047 "[u8; 3]" if !is_ref => Some(".data"),
1049 "[u8]" if is_ref => Some(".to_slice()"),
1050 "[usize]" if is_ref => Some(".to_slice()"),
1052 "str" if is_ref => Some(".into_str()"),
1053 "alloc::string::String"|"String" => Some(".into_string()"),
1054 "std::io::Error" if !is_ref => Some(".to_rust()"),
1056 "core::convert::Infallible" => Some("\")"),
1058 "bitcoin::bech32::Error"|"bech32::Error" if !is_ref => Some(".into_rust()"),
1059 "bitcoin::secp256k1::Error"|"secp256k1::Error" if !is_ref => Some(".into_rust()"),
1061 "core::num::ParseIntError" => Some("*/"),
1062 "core::str::Utf8Error" => Some("*/"),
1064 "std::time::Duration"|"core::time::Duration" => Some(")"),
1065 "std::time::SystemTime" => Some("))"),
1067 "bitcoin::bech32::u5"|"bech32::u5" => Some(".into()"),
1068 "core::num::NonZeroU8" => Some(").expect(\"Value must be non-zero\")"),
1070 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1071 => Some(".into_rust()"),
1072 "bitcoin::secp256k1::Signature" => Some(".into_rust()"),
1073 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(".into_rust()"),
1074 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1075 if !is_ref => Some(".into_rust()"),
1076 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1077 if is_ref => Some("}[..]).unwrap()"),
1078 "bitcoin::blockdata::script::Script" if is_ref => Some(".to_slice()))"),
1079 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_rust())"),
1080 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" => Some(".into_bitcoin()"),
1081 "bitcoin::blockdata::transaction::OutPoint" => Some(")"),
1082 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(".into_rust()"),
1083 "bitcoin::network::constants::Network" => Some(".into_bitcoin()"),
1084 "bitcoin::blockdata::block::BlockHeader" => Some(" }).unwrap()"),
1085 "bitcoin::blockdata::block::Block" => Some(".to_slice()).unwrap()"),
1087 "bitcoin::hash_types::PubkeyHash"|"bitcoin::hash_types::WPubkeyHash"|
1088 "bitcoin::hash_types::ScriptHash"|"bitcoin::hash_types::WScriptHash"
1089 if is_ref => Some(" }.clone()))"),
1091 // Newtypes that we just expose in their original form.
1092 "bitcoin::hash_types::Txid" if is_ref => Some(" }[..]).unwrap()"),
1093 "bitcoin::hash_types::Txid" => Some(".data[..]).unwrap()"),
1094 "bitcoin::hash_types::BlockHash" if !is_ref => Some(".data[..]).unwrap()"),
1095 "lightning::ln::PaymentHash"|"lightning::ln::PaymentPreimage"|"lightning::ln::PaymentSecret"
1096 |"lightning::ln::channelmanager::PaymentId"|"lightning::chain::keysinterface::KeyMaterial"
1097 if !is_ref => Some(".data)"),
1098 "lightning::ln::PaymentHash"|"lightning::ln::PaymentPreimage"|"lightning::ln::PaymentSecret"
1099 |"lightning::ln::channelmanager::PaymentId"|"lightning::chain::keysinterface::KeyMaterial"
1100 if is_ref => Some(" })"),
1102 // List of traits we map (possibly during processing of other files):
1103 "lightning::io::Read" => Some(".to_reader()"),
1106 }.map(|s| s.to_owned())
1109 fn to_c_conversion_new_var_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<(&'b str, &'b str)> {
1110 if self.is_primitive(full_path) {
1114 "[u8]" if is_ref => Some(("crate::c_types::u8slice::from_slice(", ")")),
1115 "[usize]" if is_ref => Some(("crate::c_types::usizeslice::from_slice(", ")")),
1117 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(("{ let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(", ")); s }")),
1118 "bitcoin::blockdata::block::Block" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
1119 "bitcoin::hash_types::Txid" => None,
1122 }.map(|s| s.to_owned())
1124 fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
1125 if self.is_primitive(full_path) {
1126 return Some("".to_owned());
1129 "Result" if !is_ref => Some("local_"),
1130 "Vec" if !is_ref => Some("local_"),
1131 "Option" => Some("local_"),
1133 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1134 "[u8; 32]" if is_ref => Some(""),
1135 "[u8; 20]" if !is_ref => Some("crate::c_types::TwentyBytes { data: "),
1136 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes { data: "),
1137 "[u8; 12]" if !is_ref => Some("crate::c_types::TwelveBytes { data: "),
1138 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes { data: "),
1139 "[u8; 3]" if is_ref => Some(""),
1141 "[u8]" if is_ref => Some("local_"),
1142 "[usize]" if is_ref => Some("local_"),
1144 "str" if is_ref => Some(""),
1145 "alloc::string::String"|"String" => Some(""),
1147 "std::time::Duration"|"core::time::Duration" => Some(""),
1148 "std::time::SystemTime" => Some(""),
1149 "std::io::Error" if !is_ref => Some("crate::c_types::IOError::from_rust("),
1150 "core::fmt::Arguments" => Some("alloc::format!(\"{}\", "),
1152 "core::convert::Infallible" => Some("panic!(\"Cannot construct an Infallible: "),
1154 "bitcoin::bech32::Error"|"bech32::Error"
1155 if !is_ref => Some("crate::c_types::Bech32Error::from_rust("),
1156 "bitcoin::secp256k1::Error"|"secp256k1::Error"
1157 if !is_ref => Some("crate::c_types::Secp256k1Error::from_rust("),
1159 "core::num::ParseIntError" => Some("crate::c_types::Error { _dummy: 0 } /*"),
1160 "core::str::Utf8Error" => Some("crate::c_types::Error { _dummy: 0 } /*"),
1162 "bitcoin::bech32::u5"|"bech32::u5" => Some(""),
1164 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1165 => Some("crate::c_types::PublicKey::from_rust(&"),
1166 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature::from_rust(&"),
1167 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some("crate::c_types::RecoverableSignature::from_rust(&"),
1168 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1169 if is_ref => Some(""),
1170 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1171 if !is_ref => Some("crate::c_types::SecretKey::from_rust("),
1172 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice::from_slice(&"),
1173 "bitcoin::blockdata::script::Script" if !is_ref => Some(""),
1174 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" if is_ref => Some("crate::c_types::Transaction::from_bitcoin("),
1175 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" => Some("crate::c_types::Transaction::from_bitcoin(&"),
1176 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::c_types::bitcoin_to_C_outpoint("),
1177 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut::from_rust("),
1178 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network::from_bitcoin("),
1179 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("&local_"),
1180 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice::from_slice(&local_"),
1182 "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1184 // Newtypes that we just expose in their original form.
1185 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1186 if is_ref => Some(""),
1187 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1188 if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1189 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1190 "lightning::ln::PaymentHash"|"lightning::ln::PaymentPreimage"|"lightning::ln::PaymentSecret"
1191 |"lightning::ln::channelmanager::PaymentId"|"lightning::chain::keysinterface::KeyMaterial"
1192 if is_ref => Some("&"),
1193 "lightning::ln::PaymentHash"|"lightning::ln::PaymentPreimage"|"lightning::ln::PaymentSecret"
1194 |"lightning::ln::channelmanager::PaymentId"|"lightning::chain::keysinterface::KeyMaterial"
1195 if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1197 "lightning::io::Read" => Some("crate::c_types::u8slice::from_vec(&crate::c_types::reader_to_vec("),
1200 }.map(|s| s.to_owned())
1202 fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
1203 if self.is_primitive(full_path) {
1204 return Some("".to_owned());
1207 "Result" if !is_ref => Some(""),
1208 "Vec" if !is_ref => Some(".into()"),
1209 "Option" => Some(""),
1211 "[u8; 32]" if !is_ref => Some(" }"),
1212 "[u8; 32]" if is_ref => Some(""),
1213 "[u8; 20]" if !is_ref => Some(" }"),
1214 "[u8; 16]" if !is_ref => Some(" }"),
1215 "[u8; 12]" if !is_ref => Some(" }"),
1216 "[u8; 4]" if !is_ref => Some(" }"),
1217 "[u8; 3]" if is_ref => Some(""),
1219 "[u8]" if is_ref => Some(""),
1220 "[usize]" if is_ref => Some(""),
1222 "str" if is_ref => Some(".into()"),
1223 "alloc::string::String"|"String" if is_ref => Some(".as_str().into()"),
1224 "alloc::string::String"|"String" => Some(".into()"),
1226 "std::time::Duration"|"core::time::Duration" => Some(".as_secs()"),
1227 "std::time::SystemTime" => Some(".duration_since(::std::time::SystemTime::UNIX_EPOCH).expect(\"Times must be post-1970\").as_secs()"),
1228 "std::io::Error" if !is_ref => Some(")"),
1229 "core::fmt::Arguments" => Some(").into()"),
1231 "core::convert::Infallible" => Some("\")"),
1233 "bitcoin::secp256k1::Error"|"bech32::Error"
1234 if !is_ref => Some(")"),
1235 "bitcoin::secp256k1::Error"|"secp256k1::Error"
1236 if !is_ref => Some(")"),
1238 "core::num::ParseIntError" => Some("*/"),
1239 "core::str::Utf8Error" => Some("*/"),
1241 "bitcoin::bech32::u5"|"bech32::u5" => Some(".into()"),
1243 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1245 "bitcoin::secp256k1::Signature" => Some(")"),
1246 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(")"),
1247 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1248 if !is_ref => Some(")"),
1249 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1250 if is_ref => Some(".as_ref()"),
1251 "bitcoin::blockdata::script::Script" if is_ref => Some("[..])"),
1252 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_bytes().into()"),
1253 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" => Some(")"),
1254 "bitcoin::blockdata::transaction::OutPoint" => Some(")"),
1255 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(")"),
1256 "bitcoin::network::constants::Network" => Some(")"),
1257 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(""),
1258 "bitcoin::blockdata::block::Block" if is_ref => Some(")"),
1260 "bitcoin::hash_types::Txid" if !is_ref => Some(".into_inner() }"),
1262 // Newtypes that we just expose in their original form.
1263 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1264 if is_ref => Some(".as_inner()"),
1265 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1266 if !is_ref => Some(".into_inner() }"),
1267 "bitcoin::secp256k1::Message" if !is_ref => Some(".as_ref().clone() }"),
1268 "lightning::ln::PaymentHash"|"lightning::ln::PaymentPreimage"|"lightning::ln::PaymentSecret"
1269 |"lightning::ln::channelmanager::PaymentId"|"lightning::chain::keysinterface::KeyMaterial"
1270 if is_ref => Some(".0"),
1271 "lightning::ln::PaymentHash"|"lightning::ln::PaymentPreimage"|"lightning::ln::PaymentSecret"
1272 |"lightning::ln::channelmanager::PaymentId"|"lightning::chain::keysinterface::KeyMaterial"
1273 if !is_ref => Some(".0 }"),
1275 "lightning::io::Read" => Some("))"),
1278 }.map(|s| s.to_owned())
1281 fn empty_val_check_suffix_from_path(&self, full_path: &str) -> Option<&str> {
1283 "lightning::ln::PaymentSecret" => Some(".data == [0; 32]"),
1284 "secp256k1::key::PublicKey"|"bitcoin::secp256k1::key::PublicKey" => Some(".is_null()"),
1285 "bitcoin::secp256k1::Signature" => Some(".is_null()"),
1290 /// When printing a reference to the source crate's rust type, if we need to map it to a
1291 /// different "real" type, it can be done so here.
1292 /// This is useful to work around limitations in the binding type resolver, where we reference
1293 /// a non-public `use` alias.
1294 /// TODO: We should never need to use this!
1295 fn real_rust_type_mapping<'equiv>(&self, thing: &'equiv str) -> &'equiv str {
1297 "lightning::io::Read" => "crate::c_types::io::Read",
1302 // ****************************
1303 // *** Container Processing ***
1304 // ****************************
1306 /// Returns the module path in the generated mapping crate to the containers which we generate
1307 /// when writing to CrateTypes::template_file.
1308 pub fn generated_container_path() -> &'static str {
1309 "crate::c_types::derived"
1311 /// Returns the module path in the generated mapping crate to the container templates, which
1312 /// are then concretized and put in the generated container path/template_file.
1313 fn container_templ_path() -> &'static str {
1317 /// Returns true if the path containing the given args is a "transparent" container, ie an
1318 /// Option or a container which does not require a generated continer class.
1319 fn is_transparent_container<'i, I: Iterator<Item=&'i syn::Type>>(&self, full_path: &str, _is_ref: bool, mut args: I, generics: Option<&GenericTypes>) -> bool {
1320 if full_path == "Option" {
1321 let inner = args.next().unwrap();
1322 assert!(args.next().is_none());
1324 syn::Type::Reference(_) => true,
1325 syn::Type::Array(a) => {
1326 if let syn::Expr::Lit(l) = &a.len {
1327 if let syn::Lit::Int(i) = &l.lit {
1328 if i.base10_digits().parse::<usize>().unwrap() >= 32 {
1329 let mut buf = Vec::new();
1330 self.write_rust_type(&mut buf, generics, &a.elem);
1331 let ty = String::from_utf8(buf).unwrap();
1334 // Blindly assume that if we're trying to create an empty value for an
1335 // array < 32 entries that all-0s may be a valid state.
1338 } else { unimplemented!(); }
1339 } else { unimplemented!(); }
1341 syn::Type::Path(p) => {
1342 if let Some(resolved) = self.maybe_resolve_path(&p.path, generics) {
1343 if self.c_type_has_inner_from_path(&resolved) { return true; }
1344 if self.is_primitive(&resolved) { return false; }
1345 if self.c_type_from_path(&resolved, false, false).is_some() { true } else { false }
1348 syn::Type::Tuple(_) => false,
1349 _ => unimplemented!(),
1353 /// Returns true if the path is a "transparent" container, ie an Option or a container which does
1354 /// not require a generated continer class.
1355 pub fn is_path_transparent_container(&self, full_path: &syn::Path, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
1356 let inner_iter = match &full_path.segments.last().unwrap().arguments {
1357 syn::PathArguments::None => return false,
1358 syn::PathArguments::AngleBracketed(args) => args.args.iter().map(|arg| {
1359 if let syn::GenericArgument::Type(ref ty) = arg {
1361 } else { unimplemented!() }
1363 syn::PathArguments::Parenthesized(_) => unimplemented!(),
1365 self.is_transparent_container(&self.resolve_path(full_path, generics), is_ref, inner_iter, generics)
1367 /// Returns true if this is a known, supported, non-transparent container.
1368 fn is_known_container(&self, full_path: &str, is_ref: bool) -> bool {
1369 (full_path == "Result" && !is_ref) || (full_path == "Vec" && !is_ref) || full_path.ends_with("Tuple") || full_path == "Option"
1371 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)
1372 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1373 // expecting one element in the vec per generic type, each of which is inline-converted
1374 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1376 "Result" if !is_ref => {
1378 vec![(" { Ok(mut o) => crate::c_types::CResultTempl::ok(".to_string(), "o".to_string()),
1379 (").into(), Err(mut e) => crate::c_types::CResultTempl::err(".to_string(), "e".to_string())],
1380 ").into() }", ContainerPrefixLocation::PerConv))
1384 // We should only get here if the single contained has an inner
1385 assert!(self.c_type_has_inner(single_contained.unwrap()));
1387 Some(("Vec::new(); for mut item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1390 if let Some(syn::Type::Reference(_)) = single_contained {
1391 Some(("Vec::new(); for item in ", vec![(format!(".iter() {{ local_{}.push(", var_name), "(*item)".to_string())], "); }", ContainerPrefixLocation::PerConv))
1393 Some(("Vec::new(); for item in ", vec![(format!(".iter() {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1397 let mut is_contained_ref = false;
1398 let contained_struct = if let Some(syn::Type::Path(p)) = single_contained {
1399 Some(self.resolve_path(&p.path, generics))
1400 } else if let Some(syn::Type::Reference(r)) = single_contained {
1401 is_contained_ref = true;
1402 if let syn::Type::Path(p) = &*r.elem {
1403 Some(self.resolve_path(&p.path, generics))
1406 if let Some(inner_path) = contained_struct {
1407 let only_contained_has_inner = self.c_type_has_inner_from_path(&inner_path);
1408 if self.c_type_has_inner_from_path(&inner_path) {
1409 let is_inner_ref = if let Some(syn::Type::Reference(_)) = single_contained { true } else { false };
1411 return Some(("if ", vec![
1412 (".is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner(".to_owned(),
1413 format!("({}{}.unwrap())", var_access, if is_inner_ref { "" } else { ".as_ref()" }))
1414 ], ") }", ContainerPrefixLocation::OutsideConv));
1416 return Some(("if ", vec![
1417 (".is_none() { core::ptr::null_mut() } else { ".to_owned(), format!("({}.unwrap())", var_access))
1418 ], " }", ContainerPrefixLocation::OutsideConv));
1420 } else if self.is_primitive(&inner_path) || self.c_type_from_path(&inner_path, false, false).is_none() {
1421 if self.is_primitive(&inner_path) || (!is_contained_ref && !is_ref) || only_contained_has_inner {
1422 let inner_name = self.get_c_mangled_container_type(vec![single_contained.unwrap()], generics, "Option").unwrap();
1423 return Some(("if ", vec![
1424 (format!(".is_none() {{ {}::None }} else {{ {}::Some(", inner_name, inner_name),
1425 format!("{}.unwrap()", var_access))
1426 ], ") }", ContainerPrefixLocation::PerConv));
1428 let inner_name = self.get_c_mangled_container_type(vec![single_contained.unwrap()], generics, "Option").unwrap();
1429 return Some(("if ", vec![
1430 (format!(".is_none() {{ {}::None }} else {{ {}::Some(/* WARNING: CLONING CONVERSION HERE! &Option<Enum> is otherwise un-expressable. */", inner_name, inner_name),
1431 format!("{}.clone().unwrap()", var_access))
1432 ], ") }", ContainerPrefixLocation::PerConv));
1435 // If c_type_from_path is some (ie there's a manual mapping for the inner
1436 // type), lean on write_empty_rust_val, below.
1439 if let Some(t) = single_contained {
1440 if let syn::Type::Tuple(syn::TypeTuple { elems, .. }) = t {
1441 assert!(elems.is_empty());
1442 let inner_name = self.get_c_mangled_container_type(vec![single_contained.unwrap()], generics, "Option").unwrap();
1443 return Some(("if ", vec![
1444 (format!(".is_none() {{ {}::None }} else {{ {}::Some /*",
1445 inner_name, inner_name), format!(""))
1446 ], " */}", ContainerPrefixLocation::PerConv));
1448 if let syn::Type::Reference(syn::TypeReference { elem, .. }) = t {
1449 if let syn::Type::Slice(_) = &**elem {
1450 return Some(("if ", vec![
1451 (".is_none() { SmartPtr::null() } else { SmartPtr::from_obj(".to_string(),
1452 format!("({}.unwrap())", var_access))
1453 ], ") }", ContainerPrefixLocation::PerConv));
1456 let mut v = Vec::new();
1457 self.write_empty_rust_val(generics, &mut v, t);
1458 let s = String::from_utf8(v).unwrap();
1459 return Some(("if ", vec![
1460 (format!(".is_none() {{ {} }} else {{ ", s), format!("({}.unwrap())", var_access))
1461 ], " }", ContainerPrefixLocation::PerConv));
1462 } else { unreachable!(); }
1468 /// only_contained_has_inner implies that there is only one contained element in the container
1469 /// and it has an inner field (ie is an "opaque" type we've defined).
1470 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)
1471 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1472 // expecting one element in the vec per generic type, each of which is inline-converted
1473 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1474 let mut only_contained_has_inner = false;
1475 let only_contained_resolved = if let Some(syn::Type::Path(p)) = single_contained {
1476 let res = self.resolve_path(&p.path, generics);
1477 only_contained_has_inner = self.c_type_has_inner_from_path(&res);
1481 "Result" if !is_ref => {
1483 vec![(".result_ok { true => Ok(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.result)) }})", var_access)),
1484 ("), false => Err(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.err)) }})", var_access))],
1485 ")}", ContainerPrefixLocation::PerConv))
1487 "Slice" if is_ref && only_contained_has_inner => {
1488 Some(("Vec::new(); for mut item in ", vec![(format!(".as_slice().iter() {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1491 Some(("Vec::new(); for mut item in ", vec![(format!(".into_rust().drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1494 if let Some(resolved) = only_contained_resolved {
1495 if self.is_primitive(&resolved) {
1496 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::NoPrefix))
1497 } else if only_contained_has_inner {
1499 return Some(("if ", vec![(".inner.is_null() { None } else { Some((*".to_string(), format!("{}", var_access))], ").clone()) }", ContainerPrefixLocation::PerConv))
1501 return Some(("if ", vec![(".inner.is_null() { None } else { Some(".to_string(), format!("{}", var_access))], ") }", ContainerPrefixLocation::PerConv));
1506 if let Some(t) = single_contained {
1508 syn::Type::Reference(_)|syn::Type::Path(_)|syn::Type::Slice(_) => {
1509 let mut v = Vec::new();
1510 let ret_ref = self.write_empty_rust_val_check_suffix(generics, &mut v, t);
1511 let s = String::from_utf8(v).unwrap();
1513 EmptyValExpectedTy::ReferenceAsPointer =>
1514 return Some(("if ", vec![
1515 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ &mut *{} }}", var_access))
1516 ], ") }", ContainerPrefixLocation::NoPrefix)),
1517 EmptyValExpectedTy::OptionType =>
1518 return Some(("{ /* ", vec![
1519 (format!("*/ let {}_opt = {};", var_name, var_access),
1520 format!("}} if {}_opt{} {{ None }} else {{ Some({{ {}_opt.take()", var_name, s, var_name))
1521 ], ") } }", ContainerPrefixLocation::PerConv)),
1522 EmptyValExpectedTy::NonPointer =>
1523 return Some(("if ", vec![
1524 (format!("{} {{ None }} else {{ Some(", s), format!("{}", var_access))
1525 ], ") }", ContainerPrefixLocation::PerConv)),
1528 syn::Type::Tuple(_) => {
1529 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::PerConv))
1531 _ => unimplemented!(),
1533 } else { unreachable!(); }
1539 /// Constructs a reference to the given type, possibly tweaking the type if relevant to make it
1540 /// convertable to C.
1541 pub fn create_ownable_reference(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> Option<syn::Type> {
1542 let default_value = Some(syn::Type::Reference(syn::TypeReference {
1543 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
1544 elem: Box::new(t.clone()) }));
1545 match generics.resolve_type(t) {
1546 syn::Type::Path(p) => {
1547 if let Some(resolved_path) = self.maybe_resolve_path(&p.path, generics) {
1548 if resolved_path != "Vec" { return default_value; }
1549 if p.path.segments.len() != 1 { unimplemented!(); }
1550 let only_seg = p.path.segments.iter().next().unwrap();
1551 if let syn::PathArguments::AngleBracketed(args) = &only_seg.arguments {
1552 if args.args.len() != 1 { unimplemented!(); }
1553 let inner_arg = args.args.iter().next().unwrap();
1554 if let syn::GenericArgument::Type(ty) = &inner_arg {
1555 let mut can_create = self.c_type_has_inner(&ty);
1556 if let syn::Type::Path(inner) = ty {
1557 if inner.path.segments.len() == 1 &&
1558 format!("{}", inner.path.segments[0].ident) == "Vec" {
1562 if !can_create { return default_value; }
1563 if let Some(inner_ty) = self.create_ownable_reference(&ty, generics) {
1564 return Some(syn::Type::Reference(syn::TypeReference {
1565 and_token: syn::Token![&](Span::call_site()),
1568 elem: Box::new(syn::Type::Slice(syn::TypeSlice {
1569 bracket_token: syn::token::Bracket { span: Span::call_site() },
1570 elem: Box::new(inner_ty)
1573 } else { return default_value; }
1574 } else { unimplemented!(); }
1575 } else { unimplemented!(); }
1576 } else { return None; }
1582 // *************************************************
1583 // *** Type definition during main.rs processing ***
1584 // *************************************************
1586 pub fn get_declared_type(&'a self, ident: &syn::Ident) -> Option<&'a DeclType<'c>> {
1587 self.types.get_declared_type(ident)
1589 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1590 pub fn c_type_has_inner_from_path(&self, full_path: &str) -> bool {
1591 self.crate_types.opaques.get(full_path).is_some()
1594 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1595 pub fn c_type_has_inner(&self, ty: &syn::Type) -> bool {
1597 syn::Type::Path(p) => {
1598 if let Some(full_path) = self.maybe_resolve_path(&p.path, None) {
1599 self.c_type_has_inner_from_path(&full_path)
1602 syn::Type::Reference(r) => {
1603 self.c_type_has_inner(&*r.elem)
1609 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
1610 self.types.maybe_resolve_ident(id)
1613 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
1614 self.types.maybe_resolve_non_ignored_ident(id)
1617 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
1618 self.types.maybe_resolve_path(p_arg, generics)
1620 pub fn resolve_path(&self, p: &syn::Path, generics: Option<&GenericTypes>) -> String {
1621 self.maybe_resolve_path(p, generics).unwrap()
1624 // ***********************************
1625 // *** Original Rust Type Printing ***
1626 // ***********************************
1628 fn in_rust_prelude(resolved_path: &str) -> bool {
1629 match resolved_path {
1637 fn write_rust_path<W: std::io::Write>(&self, w: &mut W, generics_resolver: Option<&GenericTypes>, path: &syn::Path) {
1638 if let Some(resolved) = self.maybe_resolve_path(&path, generics_resolver) {
1639 if self.is_primitive(&resolved) {
1640 write!(w, "{}", path.get_ident().unwrap()).unwrap();
1642 // TODO: We should have a generic "is from a dependency" check here instead of
1643 // checking for "bitcoin" explicitly.
1644 if resolved.starts_with("bitcoin::") || Self::in_rust_prelude(&resolved) {
1645 write!(w, "{}", resolved).unwrap();
1646 // If we're printing a generic argument, it needs to reference the crate, otherwise
1647 // the original crate:
1648 } else if self.maybe_resolve_path(&path, None).as_ref() == Some(&resolved) {
1649 write!(w, "{}", self.real_rust_type_mapping(&resolved)).unwrap();
1651 write!(w, "crate::{}", resolved).unwrap();
1654 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().last().unwrap().arguments {
1655 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1658 if path.leading_colon.is_some() {
1659 write!(w, "::").unwrap();
1661 for (idx, seg) in path.segments.iter().enumerate() {
1662 if idx != 0 { write!(w, "::").unwrap(); }
1663 write!(w, "{}", seg.ident).unwrap();
1664 if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
1665 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1670 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>) {
1671 let mut had_params = false;
1672 for (idx, arg) in generics.enumerate() {
1673 if idx != 0 { write!(w, ", ").unwrap(); } else { write!(w, "<").unwrap(); }
1676 syn::GenericParam::Lifetime(lt) => write!(w, "'{}", lt.lifetime.ident).unwrap(),
1677 syn::GenericParam::Type(t) => {
1678 write!(w, "{}", t.ident).unwrap();
1679 if t.colon_token.is_some() { write!(w, ":").unwrap(); }
1680 for (idx, bound) in t.bounds.iter().enumerate() {
1681 if idx != 0 { write!(w, " + ").unwrap(); }
1683 syn::TypeParamBound::Trait(tb) => {
1684 if tb.paren_token.is_some() || tb.lifetimes.is_some() { unimplemented!(); }
1685 self.write_rust_path(w, generics_resolver, &tb.path);
1687 _ => unimplemented!(),
1690 if t.eq_token.is_some() || t.default.is_some() { unimplemented!(); }
1692 _ => unimplemented!(),
1695 if had_params { write!(w, ">").unwrap(); }
1698 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>) {
1699 write!(w, "<").unwrap();
1700 for (idx, arg) in generics.enumerate() {
1701 if idx != 0 { write!(w, ", ").unwrap(); }
1703 syn::GenericArgument::Type(t) => self.write_rust_type(w, generics_resolver, t),
1704 _ => unimplemented!(),
1707 write!(w, ">").unwrap();
1709 pub fn write_rust_type<W: std::io::Write>(&self, w: &mut W, generics: Option<&GenericTypes>, t: &syn::Type) {
1710 match generics.resolve_type(t) {
1711 syn::Type::Path(p) => {
1712 if p.qself.is_some() {
1715 self.write_rust_path(w, generics, &p.path);
1717 syn::Type::Reference(r) => {
1718 write!(w, "&").unwrap();
1719 if let Some(lft) = &r.lifetime {
1720 write!(w, "'{} ", lft.ident).unwrap();
1722 if r.mutability.is_some() {
1723 write!(w, "mut ").unwrap();
1725 self.write_rust_type(w, generics, &*r.elem);
1727 syn::Type::Array(a) => {
1728 write!(w, "[").unwrap();
1729 self.write_rust_type(w, generics, &a.elem);
1730 if let syn::Expr::Lit(l) = &a.len {
1731 if let syn::Lit::Int(i) = &l.lit {
1732 write!(w, "; {}]", i).unwrap();
1733 } else { unimplemented!(); }
1734 } else { unimplemented!(); }
1736 syn::Type::Slice(s) => {
1737 write!(w, "[").unwrap();
1738 self.write_rust_type(w, generics, &s.elem);
1739 write!(w, "]").unwrap();
1741 syn::Type::Tuple(s) => {
1742 write!(w, "(").unwrap();
1743 for (idx, t) in s.elems.iter().enumerate() {
1744 if idx != 0 { write!(w, ", ").unwrap(); }
1745 self.write_rust_type(w, generics, &t);
1747 write!(w, ")").unwrap();
1749 _ => unimplemented!(),
1753 /// Prints a constructor for something which is "uninitialized" (but obviously not actually
1754 /// unint'd memory).
1755 pub fn write_empty_rust_val<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) {
1757 syn::Type::Reference(r) => {
1758 self.write_empty_rust_val(generics, w, &*r.elem)
1760 syn::Type::Path(p) => {
1761 let resolved = self.resolve_path(&p.path, generics);
1762 if self.crate_types.opaques.get(&resolved).is_some() {
1763 write!(w, "crate::{} {{ inner: core::ptr::null_mut(), is_owned: true }}", resolved).unwrap();
1765 // Assume its a manually-mapped C type, where we can just define an null() fn
1766 write!(w, "{}::null()", self.c_type_from_path(&resolved, false, false).unwrap()).unwrap();
1769 syn::Type::Array(a) => {
1770 if let syn::Expr::Lit(l) = &a.len {
1771 if let syn::Lit::Int(i) = &l.lit {
1772 if i.base10_digits().parse::<usize>().unwrap() < 32 {
1773 // Blindly assume that if we're trying to create an empty value for an
1774 // array < 32 entries that all-0s may be a valid state.
1777 let arrty = format!("[u8; {}]", i.base10_digits());
1778 write!(w, "{}", self.to_c_conversion_inline_prefix_from_path(&arrty, false, false).unwrap()).unwrap();
1779 write!(w, "[0; {}]", i.base10_digits()).unwrap();
1780 write!(w, "{}", self.to_c_conversion_inline_suffix_from_path(&arrty, false, false).unwrap()).unwrap();
1781 } else { unimplemented!(); }
1782 } else { unimplemented!(); }
1784 _ => unimplemented!(),
1788 fn is_real_type_array(&self, resolved_type: &str) -> Option<syn::Type> {
1789 if let Some(real_ty) = self.c_type_from_path(&resolved_type, true, false) {
1790 if real_ty.ends_with("]") && real_ty.starts_with("*const [u8; ") {
1791 let mut split = real_ty.split("; ");
1792 split.next().unwrap();
1793 let tail_str = split.next().unwrap();
1794 assert!(split.next().is_none());
1795 let len = usize::from_str_radix(&tail_str[..tail_str.len() - 1], 10).unwrap();
1796 Some(parse_quote!([u8; #len]))
1801 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1802 /// See EmptyValExpectedTy for information on return types.
1803 fn write_empty_rust_val_check_suffix<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) -> EmptyValExpectedTy {
1805 syn::Type::Reference(r) => {
1806 return self.write_empty_rust_val_check_suffix(generics, w, &*r.elem);
1808 syn::Type::Path(p) => {
1809 let resolved = self.resolve_path(&p.path, generics);
1810 if let Some(arr_ty) = self.is_real_type_array(&resolved) {
1811 write!(w, ".data").unwrap();
1812 return self.write_empty_rust_val_check_suffix(generics, w, &arr_ty);
1814 if self.crate_types.opaques.get(&resolved).is_some() {
1815 write!(w, ".inner.is_null()").unwrap();
1816 EmptyValExpectedTy::NonPointer
1818 if let Some(suffix) = self.empty_val_check_suffix_from_path(&resolved) {
1819 write!(w, "{}", suffix).unwrap();
1820 // We may eventually need to allow empty_val_check_suffix_from_path to specify if we need a deref or not
1821 EmptyValExpectedTy::NonPointer
1823 write!(w, ".is_none()").unwrap();
1824 EmptyValExpectedTy::OptionType
1828 syn::Type::Array(a) => {
1829 if let syn::Expr::Lit(l) = &a.len {
1830 if let syn::Lit::Int(i) = &l.lit {
1831 write!(w, " == [0; {}]", i.base10_digits()).unwrap();
1832 EmptyValExpectedTy::NonPointer
1833 } else { unimplemented!(); }
1834 } else { unimplemented!(); }
1836 syn::Type::Slice(_) => {
1837 // Option<[]> always implies that we want to treat len() == 0 differently from
1838 // None, so we always map an Option<[]> into a pointer.
1839 write!(w, " == core::ptr::null_mut()").unwrap();
1840 EmptyValExpectedTy::ReferenceAsPointer
1842 _ => unimplemented!(),
1846 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1847 pub fn write_empty_rust_val_check<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type, var_access: &str) {
1849 syn::Type::Reference(r) => {
1850 self.write_empty_rust_val_check(generics, w, &*r.elem, var_access);
1852 syn::Type::Path(_) => {
1853 write!(w, "{}", var_access).unwrap();
1854 self.write_empty_rust_val_check_suffix(generics, w, t);
1856 syn::Type::Array(a) => {
1857 if let syn::Expr::Lit(l) = &a.len {
1858 if let syn::Lit::Int(i) = &l.lit {
1859 let arrty = format!("[u8; {}]", i.base10_digits());
1860 // We don't (yet) support a new-var conversion here.
1861 assert!(self.from_c_conversion_new_var_from_path(&arrty, false).is_none());
1863 self.from_c_conversion_prefix_from_path(&arrty, false).unwrap(),
1865 self.from_c_conversion_suffix_from_path(&arrty, false).unwrap()).unwrap();
1866 self.write_empty_rust_val_check_suffix(generics, w, t);
1867 } else { unimplemented!(); }
1868 } else { unimplemented!(); }
1870 _ => unimplemented!(),
1874 // ********************************
1875 // *** Type conversion printing ***
1876 // ********************************
1878 /// Returns true we if can just skip passing this to C entirely
1879 pub fn skip_arg(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
1881 syn::Type::Path(p) => {
1882 if p.qself.is_some() { unimplemented!(); }
1883 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1884 self.skip_path(&full_path)
1887 syn::Type::Reference(r) => {
1888 self.skip_arg(&*r.elem, generics)
1893 pub fn no_arg_to_rust<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1895 syn::Type::Path(p) => {
1896 if p.qself.is_some() { unimplemented!(); }
1897 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1898 write!(w, "{}", self.no_arg_path_to_rust(&full_path)).unwrap();
1901 syn::Type::Reference(r) => {
1902 self.no_arg_to_rust(w, &*r.elem, generics);
1908 fn write_conversion_inline_intern<W: std::io::Write,
1909 LP: Fn(&str, bool, bool) -> Option<String>, DL: Fn(&mut W, &DeclType, &str, bool, bool), SC: Fn(bool, Option<&str>) -> String>
1910 (&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool,
1911 tupleconv: &str, prefix: bool, sliceconv: SC, path_lookup: LP, decl_lookup: DL) {
1912 match generics.resolve_type(t) {
1913 syn::Type::Reference(r) => {
1914 self.write_conversion_inline_intern(w, &*r.elem, generics, true, r.mutability.is_some(),
1915 ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1917 syn::Type::Path(p) => {
1918 if p.qself.is_some() {
1922 let resolved_path = self.resolve_path(&p.path, generics);
1923 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1924 return self.write_conversion_inline_intern(w, aliased_type, None, is_ref, is_mut, ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1925 } else if self.is_primitive(&resolved_path) {
1926 if is_ref && prefix {
1927 write!(w, "*").unwrap();
1929 } else if let Some(c_type) = path_lookup(&resolved_path, is_ref, ptr_for_ref) {
1930 write!(w, "{}", c_type).unwrap();
1931 } else if let Some((_, generics)) = self.crate_types.opaques.get(&resolved_path) {
1932 decl_lookup(w, &DeclType::StructImported { generics: &generics }, &resolved_path, is_ref, is_mut);
1933 } else if self.crate_types.mirrored_enums.get(&resolved_path).is_some() {
1934 decl_lookup(w, &DeclType::MirroredEnum, &resolved_path, is_ref, is_mut);
1935 } else if let Some(t) = self.crate_types.traits.get(&resolved_path) {
1936 decl_lookup(w, &DeclType::Trait(t), &resolved_path, is_ref, is_mut);
1937 } else if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
1938 if let Some(decl_type) = self.types.maybe_resolve_declared(ident) {
1939 decl_lookup(w, decl_type, &self.maybe_resolve_ident(ident).unwrap(), is_ref, is_mut);
1940 } else { unimplemented!(); }
1941 } else { unimplemented!(); }
1943 syn::Type::Array(a) => {
1944 // We assume all arrays contain only [int_literal; X]s.
1945 // This may result in some outputs not compiling.
1946 if let syn::Expr::Lit(l) = &a.len {
1947 if let syn::Lit::Int(i) = &l.lit {
1948 write!(w, "{}", path_lookup(&format!("[u8; {}]", i.base10_digits()), is_ref, ptr_for_ref).unwrap()).unwrap();
1949 } else { unimplemented!(); }
1950 } else { unimplemented!(); }
1952 syn::Type::Slice(s) => {
1953 // We assume all slices contain only literals or references.
1954 // This may result in some outputs not compiling.
1955 if let syn::Type::Path(p) = &*s.elem {
1956 let resolved = self.resolve_path(&p.path, generics);
1957 if self.is_primitive(&resolved) {
1958 write!(w, "{}", path_lookup("[u8]", is_ref, ptr_for_ref).unwrap()).unwrap();
1960 write!(w, "{}", sliceconv(true, None)).unwrap();
1962 } else if let syn::Type::Reference(r) = &*s.elem {
1963 if let syn::Type::Path(p) = &*r.elem {
1964 write!(w, "{}", sliceconv(self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)), None)).unwrap();
1965 } else if let syn::Type::Slice(_) = &*r.elem {
1966 write!(w, "{}", sliceconv(false, None)).unwrap();
1967 } else { unimplemented!(); }
1968 } else if let syn::Type::Tuple(t) = &*s.elem {
1969 assert!(!t.elems.is_empty());
1971 write!(w, "{}", sliceconv(false, None)).unwrap();
1973 let mut needs_map = false;
1974 for e in t.elems.iter() {
1975 if let syn::Type::Reference(_) = e {
1980 let mut map_str = Vec::new();
1981 write!(&mut map_str, ".map(|(").unwrap();
1982 for i in 0..t.elems.len() {
1983 write!(&mut map_str, "{}{}", if i != 0 { ", " } else { "" }, ('a' as u8 + i as u8) as char).unwrap();
1985 write!(&mut map_str, ")| (").unwrap();
1986 for (idx, e) in t.elems.iter().enumerate() {
1987 if let syn::Type::Reference(_) = e {
1988 write!(&mut map_str, "{}{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1989 } else if let syn::Type::Path(_) = e {
1990 write!(&mut map_str, "{}*{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1991 } else { unimplemented!(); }
1993 write!(&mut map_str, "))").unwrap();
1994 write!(w, "{}", sliceconv(false, Some(&String::from_utf8(map_str).unwrap()))).unwrap();
1996 write!(w, "{}", sliceconv(false, None)).unwrap();
1999 } else { unimplemented!(); }
2001 syn::Type::Tuple(t) => {
2002 if t.elems.is_empty() {
2003 // cbindgen has poor support for (), see, eg https://github.com/eqrion/cbindgen/issues/527
2004 // so work around it by just pretending its a 0u8
2005 write!(w, "{}", tupleconv).unwrap();
2007 if prefix { write!(w, "local_").unwrap(); }
2010 _ => unimplemented!(),
2014 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) {
2015 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "() /*", true, |_, _| "local_".to_owned(),
2016 |a, b, c| self.to_c_conversion_inline_prefix_from_path(a, b, c),
2017 |w, decl_type, decl_path, is_ref, _is_mut| {
2019 DeclType::MirroredEnum if is_ref && ptr_for_ref => write!(w, "crate::{}::from_native(", decl_path).unwrap(),
2020 DeclType::MirroredEnum if is_ref => write!(w, "&crate::{}::from_native(", decl_path).unwrap(),
2021 DeclType::MirroredEnum => write!(w, "crate::{}::native_into(", decl_path).unwrap(),
2022 DeclType::EnumIgnored {..}|DeclType::StructImported {..} if is_ref && from_ptr => {
2023 if !ptr_for_ref { write!(w, "&").unwrap(); }
2024 write!(w, "crate::{} {{ inner: unsafe {{ (", decl_path).unwrap()
2026 DeclType::EnumIgnored {..}|DeclType::StructImported {..} if is_ref => {
2027 if !ptr_for_ref { write!(w, "&").unwrap(); }
2028 write!(w, "crate::{} {{ inner: unsafe {{ ObjOps::nonnull_ptr_to_inner((", decl_path).unwrap()
2030 DeclType::EnumIgnored {..}|DeclType::StructImported {..} if !is_ref && from_ptr =>
2031 write!(w, "crate::{} {{ inner: ", decl_path).unwrap(),
2032 DeclType::EnumIgnored {..}|DeclType::StructImported {..} if !is_ref =>
2033 write!(w, "crate::{} {{ inner: ObjOps::heap_alloc(", decl_path).unwrap(),
2034 DeclType::Trait(_) if is_ref => write!(w, "").unwrap(),
2035 DeclType::Trait(_) if !is_ref => write!(w, "Into::into(").unwrap(),
2036 _ => panic!("{:?}", decl_path),
2040 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) {
2041 self.write_to_c_conversion_inline_prefix_inner(w, t, generics, false, ptr_for_ref, false);
2043 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) {
2044 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "*/", false, |_, _| ".into()".to_owned(),
2045 |a, b, c| self.to_c_conversion_inline_suffix_from_path(a, b, c),
2046 |w, decl_type, full_path, is_ref, _is_mut| match decl_type {
2047 DeclType::MirroredEnum => write!(w, ")").unwrap(),
2048 DeclType::EnumIgnored { generics }|DeclType::StructImported { generics } if is_ref => {
2049 write!(w, " as *const {}<", full_path).unwrap();
2050 for param in generics.params.iter() {
2051 if let syn::GenericParam::Lifetime(_) = param {
2052 write!(w, "'_, ").unwrap();
2054 write!(w, "_, ").unwrap();
2058 write!(w, ">) as *mut _ }}, is_owned: false }}").unwrap();
2060 write!(w, ">) as *mut _) }}, is_owned: false }}").unwrap();
2063 DeclType::EnumIgnored {..}|DeclType::StructImported {..} if !is_ref && from_ptr =>
2064 write!(w, ", is_owned: true }}").unwrap(),
2065 DeclType::EnumIgnored {..}|DeclType::StructImported {..} if !is_ref => write!(w, "), is_owned: true }}").unwrap(),
2066 DeclType::Trait(_) if is_ref => {},
2067 DeclType::Trait(_) => {
2068 // This is used when we're converting a concrete Rust type into a C trait
2069 // for use when a Rust trait method returns an associated type.
2070 // Because all of our C traits implement From<RustTypesImplementingTraits>
2071 // we can just call .into() here and be done.
2072 write!(w, ")").unwrap()
2074 _ => unimplemented!(),
2077 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) {
2078 self.write_to_c_conversion_inline_suffix_inner(w, t, generics, false, ptr_for_ref, false);
2081 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) {
2082 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "() /*", true, |_, _| "&local_".to_owned(),
2083 |a, b, _c| self.from_c_conversion_prefix_from_path(a, b),
2084 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
2085 DeclType::StructImported {..} if is_ref => write!(w, "").unwrap(),
2086 DeclType::StructImported {..} if !is_ref => write!(w, "*unsafe {{ Box::from_raw(").unwrap(),
2087 DeclType::MirroredEnum if is_ref => write!(w, "&").unwrap(),
2088 DeclType::MirroredEnum => {},
2089 DeclType::Trait(_) => {},
2090 _ => unimplemented!(),
2093 pub fn write_from_c_conversion_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
2094 self.write_from_c_conversion_prefix_inner(w, t, generics, false, false);
2096 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) {
2097 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "*/", false,
2098 |has_inner, map_str_opt| match (has_inner, map_str_opt) {
2099 (false, Some(map_str)) => format!(".iter(){}.collect::<Vec<_>>()[..]", map_str),
2100 (false, None) => ".iter().collect::<Vec<_>>()[..]".to_owned(),
2101 (true, None) => "[..]".to_owned(),
2102 (true, Some(_)) => unreachable!(),
2104 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
2105 |w, decl_type, _full_path, is_ref, is_mut| match decl_type {
2106 DeclType::StructImported {..} if is_ref && ptr_for_ref => write!(w, "XXX unimplemented").unwrap(),
2107 DeclType::StructImported {..} if is_mut && is_ref => write!(w, ".get_native_mut_ref()").unwrap(),
2108 DeclType::StructImported {..} if is_ref => write!(w, ".get_native_ref()").unwrap(),
2109 DeclType::StructImported {..} if !is_ref => write!(w, ".take_inner()) }}").unwrap(),
2110 DeclType::MirroredEnum if is_ref => write!(w, ".to_native()").unwrap(),
2111 DeclType::MirroredEnum => write!(w, ".into_native()").unwrap(),
2112 DeclType::Trait(_) => {},
2113 _ => unimplemented!(),
2116 pub fn write_from_c_conversion_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
2117 self.write_from_c_conversion_suffix_inner(w, t, generics, false, false);
2119 // Note that compared to the above conversion functions, the following two are generally
2120 // significantly undertested:
2121 pub fn write_from_c_conversion_to_ref_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
2122 self.write_conversion_inline_intern(w, t, generics, false, false, false, "() /*", true, |_, _| "&local_".to_owned(),
2124 if let Some(conv) = self.from_c_conversion_prefix_from_path(a, b) {
2125 Some(format!("&{}", conv))
2128 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
2129 DeclType::StructImported {..} if !is_ref => write!(w, "").unwrap(),
2130 _ => unimplemented!(),
2133 pub fn write_from_c_conversion_to_ref_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
2134 self.write_conversion_inline_intern(w, t, generics, false, false, false, "*/", false,
2135 |has_inner, map_str_opt| match (has_inner, map_str_opt) {
2136 (false, Some(map_str)) => format!(".iter(){}.collect::<Vec<_>>()[..]", map_str),
2137 (false, None) => ".iter().collect::<Vec<_>>()[..]".to_owned(),
2138 (true, None) => "[..]".to_owned(),
2139 (true, Some(_)) => unreachable!(),
2141 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
2142 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
2143 DeclType::StructImported {..} if !is_ref => write!(w, ".get_native_ref()").unwrap(),
2144 _ => unimplemented!(),
2148 fn write_conversion_new_var_intern<'b, W: std::io::Write,
2149 LP: Fn(&str, bool) -> Option<(&str, &str)>,
2150 LC: Fn(&str, bool, Option<&syn::Type>, &syn::Ident, &str) -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)>,
2151 VP: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool),
2152 VS: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool)>
2153 (&self, w: &mut W, ident: &syn::Ident, var: &str, t: &syn::Type, generics: Option<&GenericTypes>,
2154 mut is_ref: bool, mut ptr_for_ref: bool, to_c: bool, from_ownable_ref: bool,
2155 path_lookup: &LP, container_lookup: &LC, var_prefix: &VP, var_suffix: &VS) -> bool {
2157 macro_rules! convert_container {
2158 ($container_type: expr, $args_len: expr, $args_iter: expr) => { {
2159 // For slices (and Options), we refuse to directly map them as is_ref when they
2160 // aren't opaque types containing an inner pointer. This is due to the fact that,
2161 // in both cases, the actual higher-level type is non-is_ref.
2162 let ty_has_inner = if $args_len == 1 {
2163 let ty = $args_iter().next().unwrap();
2164 if $container_type == "Slice" && to_c {
2165 // "To C ptr_for_ref" means "return the regular object with is_owned
2166 // set to false", which is totally what we want in a slice if we're about to
2167 // set ty_has_inner.
2170 if let syn::Type::Reference(t) = ty {
2171 if let syn::Type::Path(p) = &*t.elem {
2172 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2174 } else if let syn::Type::Path(p) = ty {
2175 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2179 // Options get a bunch of special handling, since in general we map Option<>al
2180 // types into the same C type as non-Option-wrapped types. This ends up being
2181 // pretty manual here and most of the below special-cases are for Options.
2182 let mut needs_ref_map = false;
2183 let mut only_contained_type = None;
2184 let mut only_contained_type_nonref = None;
2185 let mut only_contained_has_inner = false;
2186 let mut contains_slice = false;
2188 only_contained_has_inner = ty_has_inner;
2189 let arg = $args_iter().next().unwrap();
2190 if let syn::Type::Reference(t) = arg {
2191 only_contained_type = Some(arg);
2192 only_contained_type_nonref = Some(&*t.elem);
2193 if let syn::Type::Path(_) = &*t.elem {
2195 } else if let syn::Type::Slice(_) = &*t.elem {
2196 contains_slice = true;
2197 } else { return false; }
2198 // If the inner element contains an inner pointer, we will just use that,
2199 // avoiding the need to map elements to references. Otherwise we'll need to
2200 // do an extra mapping step.
2201 needs_ref_map = !only_contained_has_inner && $container_type == "Option";
2203 only_contained_type = Some(arg);
2204 only_contained_type_nonref = Some(arg);
2208 if let Some((prefix, conversions, suffix, prefix_location)) = container_lookup(&$container_type, is_ref, only_contained_type, ident, var) {
2209 assert_eq!(conversions.len(), $args_len);
2210 write!(w, "let mut local_{}{} = ", ident,
2211 if (!to_c && needs_ref_map) || (to_c && $container_type == "Option" && contains_slice) {"_base"} else { "" }).unwrap();
2212 if prefix_location == ContainerPrefixLocation::OutsideConv {
2213 var_prefix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
2215 write!(w, "{}{}", prefix, var).unwrap();
2217 for ((pfx, var_name), (idx, ty)) in conversions.iter().zip($args_iter().enumerate()) {
2218 let mut var = std::io::Cursor::new(Vec::new());
2219 write!(&mut var, "{}", var_name).unwrap();
2220 let var_access = String::from_utf8(var.into_inner()).unwrap();
2222 let conv_ty = if needs_ref_map { only_contained_type_nonref.as_ref().unwrap() } else { ty };
2224 write!(w, "{} {{ ", pfx).unwrap();
2225 let new_var_name = format!("{}_{}", ident, idx);
2226 let new_var = self.write_conversion_new_var_intern(w, &format_ident!("{}", new_var_name),
2227 &var_access, conv_ty, generics, contains_slice || (is_ref && ty_has_inner), ptr_for_ref,
2228 to_c, from_ownable_ref, path_lookup, container_lookup, var_prefix, var_suffix);
2229 if new_var { write!(w, " ").unwrap(); }
2231 if prefix_location == ContainerPrefixLocation::PerConv {
2232 var_prefix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2233 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
2234 write!(w, "ObjOps::heap_alloc(").unwrap();
2237 write!(w, "{}{}", if contains_slice && !to_c { "local_" } else { "" }, if new_var { new_var_name } else { var_access }).unwrap();
2238 if prefix_location == ContainerPrefixLocation::PerConv {
2239 var_suffix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2240 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
2241 write!(w, ")").unwrap();
2243 write!(w, " }}").unwrap();
2245 write!(w, "{}", suffix).unwrap();
2246 if prefix_location == ContainerPrefixLocation::OutsideConv {
2247 var_suffix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
2249 write!(w, ";").unwrap();
2250 if !to_c && needs_ref_map {
2251 write!(w, " let mut local_{} = local_{}_base.as_ref()", ident, ident).unwrap();
2253 write!(w, ".map(|a| &a[..])").unwrap();
2255 write!(w, ";").unwrap();
2256 } else if to_c && $container_type == "Option" && contains_slice {
2257 write!(w, " let mut local_{} = *local_{}_base;", ident, ident).unwrap();
2264 match generics.resolve_type(t) {
2265 syn::Type::Reference(r) => {
2266 if let syn::Type::Slice(_) = &*r.elem {
2267 self.write_conversion_new_var_intern(w, ident, var, &*r.elem, generics, is_ref, ptr_for_ref, to_c, from_ownable_ref, path_lookup, container_lookup, var_prefix, var_suffix)
2269 self.write_conversion_new_var_intern(w, ident, var, &*r.elem, generics, true, ptr_for_ref, to_c, from_ownable_ref, path_lookup, container_lookup, var_prefix, var_suffix)
2272 syn::Type::Path(p) => {
2273 if p.qself.is_some() {
2276 let resolved_path = self.resolve_path(&p.path, generics);
2277 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
2278 return self.write_conversion_new_var_intern(w, ident, var, aliased_type, None, is_ref, ptr_for_ref, to_c, from_ownable_ref, path_lookup, container_lookup, var_prefix, var_suffix);
2280 if self.is_known_container(&resolved_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
2281 if let syn::PathArguments::AngleBracketed(args) = &p.path.segments.iter().next().unwrap().arguments {
2282 convert_container!(resolved_path, args.args.len(), || args.args.iter().map(|arg| {
2283 if let syn::GenericArgument::Type(ty) = arg {
2284 generics.resolve_type(ty)
2285 } else { unimplemented!(); }
2287 } else { unimplemented!(); }
2289 if self.is_primitive(&resolved_path) {
2291 } else if let Some(ty_ident) = single_ident_generic_path_to_ident(&p.path) {
2292 if let Some((prefix, suffix)) = path_lookup(&resolved_path, is_ref) {
2293 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
2295 } else if self.types.maybe_resolve_declared(ty_ident).is_some() {
2300 syn::Type::Array(_) => {
2301 // We assume all arrays contain only primitive types.
2302 // This may result in some outputs not compiling.
2305 syn::Type::Slice(s) => {
2306 if let syn::Type::Path(p) = &*s.elem {
2307 let resolved = self.resolve_path(&p.path, generics);
2308 if self.is_primitive(&resolved) {
2309 let slice_path = format!("[{}]", resolved);
2310 if let Some((prefix, suffix)) = path_lookup(&slice_path, true) {
2311 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
2315 let tyref = [&*s.elem];
2317 // If we're converting from a slice to a Vec, assume we can clone the
2318 // elements and clone them into a new Vec first. Next we'll walk the
2319 // new Vec here and convert them to C types.
2320 write!(w, "let mut local_{}_clone = Vec::new(); local_{}_clone.extend_from_slice({}); let mut {} = local_{}_clone; ", ident, ident, ident, ident, ident).unwrap();
2323 convert_container!("Vec", 1, || tyref.iter().map(|t| generics.resolve_type(*t)));
2324 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
2326 } else if let syn::Type::Reference(ty) = &*s.elem {
2327 let tyref = if from_ownable_ref || !to_c { [&*ty.elem] } else { [&*s.elem] };
2329 convert_container!("Slice", 1, || tyref.iter().map(|t| generics.resolve_type(*t)));
2330 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
2331 } else if let syn::Type::Tuple(t) = &*s.elem {
2332 // When mapping into a temporary new var, we need to own all the underlying objects.
2333 // Thus, we drop any references inside the tuple and convert with non-reference types.
2334 let mut elems = syn::punctuated::Punctuated::new();
2335 for elem in t.elems.iter() {
2336 if let syn::Type::Reference(r) = elem {
2337 elems.push((*r.elem).clone());
2339 elems.push(elem.clone());
2342 let ty = [syn::Type::Tuple(syn::TypeTuple {
2343 paren_token: t.paren_token, elems
2347 convert_container!("Slice", 1, || ty.iter());
2348 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
2349 } else { unimplemented!() }
2351 syn::Type::Tuple(t) => {
2352 if !t.elems.is_empty() {
2353 // We don't (yet) support tuple elements which cannot be converted inline
2354 write!(w, "let (").unwrap();
2355 for idx in 0..t.elems.len() {
2356 if idx != 0 { write!(w, ", ").unwrap(); }
2357 write!(w, "{} orig_{}_{}", if is_ref { "ref" } else { "mut" }, ident, idx).unwrap();
2359 write!(w, ") = {}{}; ", var, if !to_c { ".to_rust()" } else { "" }).unwrap();
2360 // Like other template types, tuples are always mapped as their non-ref
2361 // versions for types which have different ref mappings. Thus, we convert to
2362 // non-ref versions and handle opaque types with inner pointers manually.
2363 for (idx, elem) in t.elems.iter().enumerate() {
2364 if let syn::Type::Path(p) = elem {
2365 let v_name = format!("orig_{}_{}", ident, idx);
2366 let tuple_elem_ident = format_ident!("{}", &v_name);
2367 if self.write_conversion_new_var_intern(w, &tuple_elem_ident, &v_name, elem, generics,
2368 false, ptr_for_ref, to_c, from_ownable_ref,
2369 path_lookup, container_lookup, var_prefix, var_suffix) {
2370 write!(w, " ").unwrap();
2371 // Opaque types with inner pointers shouldn't ever create new stack
2372 // variables, so we don't handle it and just assert that it doesn't
2374 assert!(!self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)));
2378 write!(w, "let mut local_{} = (", ident).unwrap();
2379 for (idx, elem) in t.elems.iter().enumerate() {
2380 let real_elem = generics.resolve_type(&elem);
2381 let ty_has_inner = {
2383 // "To C ptr_for_ref" means "return the regular object with
2384 // is_owned set to false", which is totally what we want
2385 // if we're about to set ty_has_inner.
2388 if let syn::Type::Reference(t) = real_elem {
2389 if let syn::Type::Path(p) = &*t.elem {
2390 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2392 } else if let syn::Type::Path(p) = real_elem {
2393 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2396 if idx != 0 { write!(w, ", ").unwrap(); }
2397 var_prefix(w, real_elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2398 if is_ref && ty_has_inner {
2399 // For ty_has_inner, the regular var_prefix mapping will take a
2400 // reference, so deref once here to make sure we keep the original ref.
2401 write!(w, "*").unwrap();
2403 write!(w, "orig_{}_{}", ident, idx).unwrap();
2404 if is_ref && !ty_has_inner {
2405 // If we don't have an inner variable's reference to maintain, just
2406 // hope the type is Clonable and use that.
2407 write!(w, ".clone()").unwrap();
2409 var_suffix(w, real_elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2411 write!(w, "){};", if to_c { ".into()" } else { "" }).unwrap();
2415 _ => unimplemented!(),
2419 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, from_ownable_ref: bool) -> bool {
2420 self.write_conversion_new_var_intern(w, ident, var_access, t, generics, from_ownable_ref, ptr_for_ref, true, from_ownable_ref,
2421 &|a, b| self.to_c_conversion_new_var_from_path(a, b),
2422 &|a, b, c, d, e| self.to_c_conversion_container_new_var(generics, a, b, c, d, e),
2423 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
2424 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_prefix_inner(a, b, c, d, e, f),
2425 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_suffix_inner(a, b, c, d, e, f))
2427 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 {
2428 self.write_to_c_conversion_new_var_inner(w, ident, &format!("{}", ident), t, generics, ptr_for_ref, false)
2430 /// Prints new-var conversion for an "ownable_ref" type, ie prints conversion for
2431 /// `create_ownable_reference(t)`, not `t` itself.
2432 pub fn write_to_c_conversion_from_ownable_ref_new_var<W: std::io::Write>(&self, w: &mut W, ident: &syn::Ident, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
2433 self.write_to_c_conversion_new_var_inner(w, ident, &format!("{}", ident), t, generics, true, true)
2435 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 {
2436 self.write_conversion_new_var_intern(w, ident, &format!("{}", ident), t, generics, false, false, false, false,
2437 &|a, b| self.from_c_conversion_new_var_from_path(a, b),
2438 &|a, b, c, d, e| self.from_c_conversion_container_new_var(generics, a, b, c, d, e),
2439 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
2440 &|a, b, c, d, e, _f| self.write_from_c_conversion_prefix_inner(a, b, c, d, e),
2441 &|a, b, c, d, e, _f| self.write_from_c_conversion_suffix_inner(a, b, c, d, e))
2444 // ******************************************************
2445 // *** C Container Type Equivalent and alias Printing ***
2446 // ******************************************************
2448 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 {
2449 for (idx, t) in args.enumerate() {
2451 write!(w, ", ").unwrap();
2453 if let syn::Type::Reference(r_arg) = t {
2454 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2456 if !self.write_c_type_intern(w, &*r_arg.elem, generics, false, false, false, true, true) { return false; }
2458 // While write_c_type_intern, above is correct, we don't want to blindly convert a
2459 // reference to something stupid, so check that the container is either opaque or a
2460 // predefined type (currently only Transaction).
2461 if let syn::Type::Path(p_arg) = &*r_arg.elem {
2462 let resolved = self.resolve_path(&p_arg.path, generics);
2463 assert!(self.crate_types.opaques.get(&resolved).is_some() ||
2464 self.c_type_from_path(&resolved, true, true).is_some(), "Template generics should be opaque or have a predefined mapping");
2465 } else { unimplemented!(); }
2466 } else if let syn::Type::Path(p_arg) = t {
2467 if let Some(resolved) = self.maybe_resolve_path(&p_arg.path, generics) {
2468 if !self.is_primitive(&resolved) {
2469 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2472 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2474 if !self.write_c_type_intern(w, t, generics, false, false, false, true, true) { return false; }
2476 // We don't currently support outer reference types for non-primitive inners,
2477 // except for the empty tuple.
2478 if let syn::Type::Tuple(t_arg) = t {
2479 assert!(t_arg.elems.len() == 0 || !is_ref);
2483 if !self.write_c_type_intern(w, t, generics, false, false, false, true, true) { return false; }
2488 fn check_create_container(&self, mangled_container: String, container_type: &str, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
2489 if !self.crate_types.templates_defined.borrow().get(&mangled_container).is_some() {
2490 let mut created_container: Vec<u8> = Vec::new();
2492 if container_type == "Result" {
2493 let mut a_ty: Vec<u8> = Vec::new();
2494 if let syn::Type::Tuple(tup) = args.iter().next().unwrap() {
2495 if tup.elems.is_empty() {
2496 write!(&mut a_ty, "()").unwrap();
2498 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
2501 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
2504 let mut b_ty: Vec<u8> = Vec::new();
2505 if let syn::Type::Tuple(tup) = args.iter().skip(1).next().unwrap() {
2506 if tup.elems.is_empty() {
2507 write!(&mut b_ty, "()").unwrap();
2509 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
2512 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
2515 let ok_str = String::from_utf8(a_ty).unwrap();
2516 let err_str = String::from_utf8(b_ty).unwrap();
2517 let is_clonable = self.is_clonable(&ok_str) && self.is_clonable(&err_str);
2518 write_result_block(&mut created_container, &mangled_container, &ok_str, &err_str, is_clonable);
2520 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2522 } else if container_type == "Vec" {
2523 let mut a_ty: Vec<u8> = Vec::new();
2524 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2525 let ty = String::from_utf8(a_ty).unwrap();
2526 let is_clonable = self.is_clonable(&ty);
2527 write_vec_block(&mut created_container, &mangled_container, &ty, is_clonable);
2529 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2531 } else if container_type.ends_with("Tuple") {
2532 let mut tuple_args = Vec::new();
2533 let mut is_clonable = true;
2534 for arg in args.iter() {
2535 let mut ty: Vec<u8> = Vec::new();
2536 if !self.write_template_generics(&mut ty, &mut [arg].iter().map(|t| **t), generics, is_ref) { return false; }
2537 let ty_str = String::from_utf8(ty).unwrap();
2538 if !self.is_clonable(&ty_str) {
2539 is_clonable = false;
2541 tuple_args.push(ty_str);
2543 write_tuple_block(&mut created_container, &mangled_container, &tuple_args, is_clonable);
2545 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2547 } else if container_type == "Option" {
2548 let mut a_ty: Vec<u8> = Vec::new();
2549 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2550 let ty = String::from_utf8(a_ty).unwrap();
2551 let is_clonable = self.is_clonable(&ty);
2552 write_option_block(&mut created_container, &mangled_container, &ty, is_clonable);
2554 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2559 self.crate_types.write_new_template(mangled_container.clone(), true, &created_container);
2563 fn path_to_generic_args(path: &syn::Path) -> Vec<&syn::Type> {
2564 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().next().unwrap().arguments {
2565 args.args.iter().map(|gen| if let syn::GenericArgument::Type(t) = gen { t } else { unimplemented!() }).collect()
2566 } else { unimplemented!(); }
2568 fn write_c_mangled_container_path_intern<W: std::io::Write>
2569 (&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 {
2570 let mut mangled_type: Vec<u8> = Vec::new();
2571 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a), generics) {
2572 write!(w, "C{}_", ident).unwrap();
2573 write!(mangled_type, "C{}_", ident).unwrap();
2574 } else { assert_eq!(args.len(), 1); }
2575 for arg in args.iter() {
2576 macro_rules! write_path {
2577 ($p_arg: expr, $extra_write: expr) => {
2578 if let Some(subtype) = self.maybe_resolve_path(&$p_arg.path, generics) {
2579 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a), generics) {
2581 if self.c_type_has_inner_from_path(&subtype) {
2582 if !self.write_c_path_intern(w, &$p_arg.path, generics, is_ref, is_mut, ptr_for_ref, false, true) { return false; }
2584 if let Some(arr_ty) = self.is_real_type_array(&subtype) {
2585 if !self.write_c_type_intern(w, &arr_ty, generics, false, true, false, false, true) { return false; }
2587 // Option<T> needs to be converted to a *mut T, ie mut ptr-for-ref
2588 if !self.write_c_path_intern(w, &$p_arg.path, generics, true, true, true, false, true) { return false; }
2592 write!(w, "{}", $p_arg.path.segments.last().unwrap().ident).unwrap();
2594 } else if self.is_known_container(&subtype, is_ref) || self.is_path_transparent_container(&$p_arg.path, generics, is_ref) {
2595 if !self.write_c_mangled_container_path_intern(w, Self::path_to_generic_args(&$p_arg.path), generics,
2596 &subtype, is_ref, is_mut, ptr_for_ref, true) {
2599 self.write_c_mangled_container_path_intern(&mut mangled_type, Self::path_to_generic_args(&$p_arg.path),
2600 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2601 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2602 self.write_c_mangled_container_path_intern(w2, Self::path_to_generic_args(&$p_arg.path),
2603 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2606 let id = subtype.rsplitn(2, ':').next().unwrap(); // Get the "Base" name of the resolved type
2607 write!(w, "{}", id).unwrap();
2608 write!(mangled_type, "{}", id).unwrap();
2609 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2610 write!(w2, "{}", id).unwrap();
2613 } else { return false; }
2616 match generics.resolve_type(arg) {
2617 syn::Type::Tuple(tuple) => {
2618 if tuple.elems.len() == 0 {
2619 write!(w, "None").unwrap();
2620 write!(mangled_type, "None").unwrap();
2622 let mut mangled_tuple_type: Vec<u8> = Vec::new();
2624 // Figure out what the mangled type should look like. To disambiguate
2625 // ((A, B), C) and (A, B, C) we prefix the generic args with a _ and suffix
2626 // them with a Z. Ideally we wouldn't use Z, but not many special chars are
2627 // available for use in type names.
2628 write!(w, "C{}Tuple_", tuple.elems.len()).unwrap();
2629 write!(mangled_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2630 write!(mangled_tuple_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2631 for elem in tuple.elems.iter() {
2632 if let syn::Type::Path(p) = elem {
2633 write_path!(p, Some(&mut mangled_tuple_type));
2634 } else if let syn::Type::Reference(refelem) = elem {
2635 if let syn::Type::Path(p) = &*refelem.elem {
2636 write_path!(p, Some(&mut mangled_tuple_type));
2637 } else { return false; }
2638 } else { return false; }
2640 write!(w, "Z").unwrap();
2641 write!(mangled_type, "Z").unwrap();
2642 write!(mangled_tuple_type, "Z").unwrap();
2643 if !self.check_create_container(String::from_utf8(mangled_tuple_type).unwrap(),
2644 &format!("{}Tuple", tuple.elems.len()), tuple.elems.iter().collect(), generics, is_ref) {
2649 syn::Type::Path(p_arg) => {
2650 write_path!(p_arg, None);
2652 syn::Type::Reference(refty) => {
2653 if let syn::Type::Path(p_arg) = &*refty.elem {
2654 write_path!(p_arg, None);
2655 } else if let syn::Type::Slice(_) = &*refty.elem {
2656 // write_c_type will actually do exactly what we want here, we just need to
2657 // make it a pointer so that its an option. Note that we cannot always convert
2658 // the Vec-as-slice (ie non-ref types) containers, so sometimes need to be able
2659 // to edit it, hence we use *mut here instead of *const.
2660 if args.len() != 1 { return false; }
2661 write!(w, "*mut ").unwrap();
2662 self.write_c_type(w, arg, None, true);
2663 } else { return false; }
2665 syn::Type::Array(a) => {
2666 if let syn::Type::Path(p_arg) = &*a.elem {
2667 let resolved = self.resolve_path(&p_arg.path, generics);
2668 if !self.is_primitive(&resolved) { return false; }
2669 if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(len), .. }) = &a.len {
2670 if self.c_type_from_path(&format!("[{}; {}]", resolved, len.base10_digits()), is_ref, ptr_for_ref).is_none() { return false; }
2671 if in_type || args.len() != 1 {
2672 write!(w, "_{}{}", resolved, len.base10_digits()).unwrap();
2673 write!(mangled_type, "_{}{}", resolved, len.base10_digits()).unwrap();
2675 let arrty = format!("[{}; {}]", resolved, len.base10_digits());
2676 let realty = self.c_type_from_path(&arrty, is_ref, ptr_for_ref).unwrap_or(&arrty);
2677 write!(w, "{}", realty).unwrap();
2678 write!(mangled_type, "{}", realty).unwrap();
2680 } else { return false; }
2681 } else { return false; }
2683 _ => { return false; },
2686 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a), generics) { return true; }
2687 // Push the "end of type" Z
2688 write!(w, "Z").unwrap();
2689 write!(mangled_type, "Z").unwrap();
2691 // Make sure the type is actually defined:
2692 self.check_create_container(String::from_utf8(mangled_type).unwrap(), ident, args, generics, is_ref)
2694 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 {
2695 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a), generics) {
2696 write!(w, "{}::", Self::generated_container_path()).unwrap();
2698 self.write_c_mangled_container_path_intern(w, args, generics, ident, is_ref, is_mut, ptr_for_ref, false)
2700 pub fn get_c_mangled_container_type(&self, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, template_name: &str) -> Option<String> {
2701 let mut out = Vec::new();
2702 if !self.write_c_mangled_container_path(&mut out, args, generics, template_name, false, false, false) {
2705 Some(String::from_utf8(out).unwrap())
2708 // **********************************
2709 // *** C Type Equivalent Printing ***
2710 // **********************************
2712 fn write_c_path_intern<W: std::io::Write>(&self, w: &mut W, path: &syn::Path, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool, with_ref_lifetime: bool, c_ty: bool) -> bool {
2713 let full_path = match self.maybe_resolve_path(&path, generics) {
2714 Some(path) => path, None => return false };
2715 if let Some(c_type) = self.c_type_from_path(&full_path, is_ref, ptr_for_ref) {
2716 write!(w, "{}", c_type).unwrap();
2718 } else if self.crate_types.traits.get(&full_path).is_some() {
2719 // Note that we always use the crate:: prefix here as we are always referring to a
2720 // concrete object which is of the generated type, it just implements the upstream
2722 if is_ref && ptr_for_ref {
2723 write!(w, "*{} crate::{}", if is_mut { "mut" } else { "const" }, full_path).unwrap();
2725 if with_ref_lifetime { unimplemented!(); }
2726 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2728 write!(w, "crate::{}", full_path).unwrap();
2731 } else if self.crate_types.opaques.get(&full_path).is_some() || self.crate_types.mirrored_enums.get(&full_path).is_some() {
2732 let crate_pfx = if c_ty { "crate::" } else { "" };
2733 if is_ref && ptr_for_ref {
2734 // ptr_for_ref implies we're returning the object, which we can't really do for
2735 // opaque or mirrored types without box'ing them, which is quite a waste, so return
2736 // the actual object itself (for opaque types we'll set the pointer to the actual
2737 // type and note that its a reference).
2738 write!(w, "{}{}", crate_pfx, full_path).unwrap();
2739 } else if is_ref && with_ref_lifetime {
2741 // If we're concretizing something with a lifetime parameter, we have to pick a
2742 // lifetime, of which the only real available choice is `static`, obviously.
2743 write!(w, "&'static {}", crate_pfx).unwrap();
2745 self.write_rust_path(w, generics, path);
2747 // We shouldn't be mapping references in types, so panic here
2751 write!(w, "&{}{}{}", if is_mut { "mut " } else { "" }, crate_pfx, full_path).unwrap();
2753 write!(w, "{}{}", crate_pfx, full_path).unwrap();
2760 fn write_c_type_intern<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool, with_ref_lifetime: bool, c_ty: bool) -> bool {
2761 match generics.resolve_type(t) {
2762 syn::Type::Path(p) => {
2763 if p.qself.is_some() {
2766 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
2767 if self.is_known_container(&full_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
2768 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);
2770 if let Some(aliased_type) = self.crate_types.type_aliases.get(&full_path).cloned() {
2771 return self.write_c_type_intern(w, &aliased_type, None, is_ref, is_mut, ptr_for_ref, with_ref_lifetime, c_ty);
2774 self.write_c_path_intern(w, &p.path, generics, is_ref, is_mut, ptr_for_ref, with_ref_lifetime, c_ty)
2776 syn::Type::Reference(r) => {
2777 self.write_c_type_intern(w, &*r.elem, generics, true, r.mutability.is_some(), ptr_for_ref, with_ref_lifetime, c_ty)
2779 syn::Type::Array(a) => {
2780 if is_ref && is_mut {
2781 write!(w, "*mut [").unwrap();
2782 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref, with_ref_lifetime, c_ty) { return false; }
2784 write!(w, "*const [").unwrap();
2785 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref, with_ref_lifetime, c_ty) { return false; }
2787 let mut typecheck = Vec::new();
2788 if !self.write_c_type_intern(&mut typecheck, &a.elem, generics, false, false, ptr_for_ref, with_ref_lifetime, c_ty) { return false; }
2789 if typecheck[..] != ['u' as u8, '8' as u8] { return false; }
2791 if let syn::Expr::Lit(l) = &a.len {
2792 if let syn::Lit::Int(i) = &l.lit {
2794 if let Some(ty) = self.c_type_from_path(&format!("[u8; {}]", i.base10_digits()), false, ptr_for_ref) {
2795 write!(w, "{}", ty).unwrap();
2799 write!(w, "; {}]", i).unwrap();
2805 syn::Type::Slice(s) => {
2806 if !is_ref || is_mut { return false; }
2807 if let syn::Type::Path(p) = &*s.elem {
2808 let resolved = self.resolve_path(&p.path, generics);
2809 if self.is_primitive(&resolved) {
2810 write!(w, "{}::{}slice", Self::container_templ_path(), resolved).unwrap();
2813 let mut inner_c_ty = Vec::new();
2814 assert!(self.write_c_path_intern(&mut inner_c_ty, &p.path, generics, true, false, ptr_for_ref, with_ref_lifetime, c_ty));
2815 if self.is_clonable(&String::from_utf8(inner_c_ty).unwrap()) {
2816 if let Some(id) = p.path.get_ident() {
2817 let mangled_container = format!("CVec_{}Z", id);
2818 write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
2819 self.check_create_container(mangled_container, "Vec", vec![&*s.elem], generics, false)
2823 } else if let syn::Type::Reference(r) = &*s.elem {
2824 if let syn::Type::Path(p) = &*r.elem {
2825 // Slices with "real types" inside are mapped as the equivalent non-ref Vec
2826 let resolved = self.resolve_path(&p.path, generics);
2827 let mangled_container = if let Some((ident, _)) = self.crate_types.opaques.get(&resolved) {
2828 format!("CVec_{}Z", ident)
2829 } else if let Some(en) = self.crate_types.mirrored_enums.get(&resolved) {
2830 format!("CVec_{}Z", en.ident)
2831 } else if let Some(id) = p.path.get_ident() {
2832 format!("CVec_{}Z", id)
2833 } else { return false; };
2834 write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
2835 self.check_create_container(mangled_container, "Vec", vec![&*r.elem], generics, false)
2836 } else if let syn::Type::Slice(sl2) = &*r.elem {
2837 if let syn::Type::Reference(r2) = &*sl2.elem {
2838 if let syn::Type::Path(p) = &*r2.elem {
2839 // Slices with slices with opaque types (with is_owned flags) are mapped as non-ref Vecs
2840 let resolved = self.resolve_path(&p.path, generics);
2841 let mangled_container = if let Some((ident, _)) = self.crate_types.opaques.get(&resolved) {
2842 format!("CVec_CVec_{}ZZ", ident)
2843 } else { return false; };
2844 write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
2845 let inner = &r2.elem;
2846 let vec_ty: syn::Type = syn::parse_quote!(Vec<#inner>);
2847 self.check_create_container(mangled_container, "Vec", vec![&vec_ty], generics, false)
2851 } else if let syn::Type::Tuple(_) = &*s.elem {
2852 let mut args = syn::punctuated::Punctuated::<_, syn::token::Comma>::new();
2853 args.push(syn::GenericArgument::Type((*s.elem).clone()));
2854 let mut segments = syn::punctuated::Punctuated::new();
2855 segments.push(parse_quote!(Vec<#args>));
2856 self.write_c_type_intern(w, &syn::Type::Path(syn::TypePath { qself: None, path: syn::Path { leading_colon: None, segments } }), generics, false, is_mut, ptr_for_ref, with_ref_lifetime, c_ty)
2859 syn::Type::Tuple(t) => {
2860 if t.elems.len() == 0 {
2863 self.write_c_mangled_container_path(w, t.elems.iter().collect(), generics,
2864 &format!("{}Tuple", t.elems.len()), is_ref, is_mut, ptr_for_ref)
2870 pub fn write_c_type<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) {
2871 assert!(self.write_c_type_intern(w, t, generics, false, false, ptr_for_ref, false, true));
2873 pub fn write_c_type_in_generic_param<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) {
2874 assert!(self.write_c_type_intern(w, t, generics, false, false, ptr_for_ref, true, false));
2876 pub fn understood_c_path(&self, p: &syn::Path) -> bool {
2877 if p.leading_colon.is_some() { return false; }
2878 self.write_c_path_intern(&mut std::io::sink(), p, None, false, false, false, false, true)
2880 pub fn understood_c_type(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
2881 self.write_c_type_intern(&mut std::io::sink(), t, generics, false, false, false, false, true)