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 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 let mut process_alias = true;
517 for tok in t.generics.params.iter() {
518 if let syn::GenericParam::Lifetime(_) = tok {}
519 else { process_alias = false; }
522 declared.insert(t.ident.clone(), DeclType::StructImported { generics: &t.generics });
526 syn::Item::Enum(e) => {
527 if let syn::Visibility::Public(_) = e.vis {
528 match export_status(&e.attrs) {
529 ExportStatus::Export if is_enum_opaque(e) => { declared.insert(e.ident.clone(), DeclType::EnumIgnored { generics: &e.generics }); },
530 ExportStatus::Export => { declared.insert(e.ident.clone(), DeclType::MirroredEnum); },
531 ExportStatus::NotImplementable => panic!("(C-not implementable) should only appear on traits!"),
536 syn::Item::Trait(t) => {
537 match export_status(&t.attrs) {
538 ExportStatus::Export|ExportStatus::NotImplementable => {
539 if let syn::Visibility::Public(_) = t.vis {
540 declared.insert(t.ident.clone(), DeclType::Trait(t));
546 syn::Item::Mod(m) => {
547 priv_modules.insert(m.ident.clone());
553 Self { crate_name, dependencies, module_path, imports, declared, priv_modules }
556 pub fn get_declared_type(&self, ident: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
557 self.declared.get(ident)
560 pub fn maybe_resolve_declared(&self, id: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
561 self.declared.get(id)
564 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
565 if let Some((imp, _)) = self.imports.get(id) {
567 } else if self.declared.get(id).is_some() {
568 Some(self.module_path.to_string() + "::" + &format!("{}", id))
572 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
573 if let Some((imp, _)) = self.imports.get(id) {
575 } else if let Some(decl_type) = self.declared.get(id) {
577 DeclType::StructIgnored => None,
578 _ => Some(self.module_path.to_string() + "::" + &format!("{}", id)),
583 pub fn maybe_resolve_path(&self, p: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
584 if let Some(gen_types) = generics {
585 if let Some(resp) = gen_types.maybe_resolve_path(p) {
586 return Some(resp.clone());
590 if p.leading_colon.is_some() {
591 let mut res: String = p.segments.iter().enumerate().map(|(idx, seg)| {
592 format!("{}{}", if idx == 0 { "" } else { "::" }, seg.ident)
594 let firstseg = p.segments.iter().next().unwrap();
595 if !self.dependencies.contains(&firstseg.ident) {
596 res = self.crate_name.to_owned() + "::" + &res;
599 } else if let Some(id) = p.get_ident() {
600 self.maybe_resolve_ident(id)
602 if p.segments.len() == 1 {
603 let seg = p.segments.iter().next().unwrap();
604 return self.maybe_resolve_ident(&seg.ident);
606 let mut seg_iter = p.segments.iter();
607 let first_seg = seg_iter.next().unwrap();
608 let remaining: String = seg_iter.map(|seg| {
609 format!("::{}", seg.ident)
611 let first_seg_str = format!("{}", first_seg.ident);
612 if let Some((imp, _)) = self.imports.get(&first_seg.ident) {
614 Some(imp.clone() + &remaining)
618 } else if let Some(_) = self.priv_modules.get(&first_seg.ident) {
619 Some(format!("{}::{}{}", self.module_path, first_seg.ident, remaining))
620 } else if first_seg_is_stdlib(&first_seg_str) || self.dependencies.contains(&first_seg.ident) {
621 Some(first_seg_str + &remaining)
626 /// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern)
627 pub fn resolve_imported_refs(&self, mut ty: syn::Type) -> syn::Type {
629 syn::Type::Path(p) => {
630 if p.path.segments.len() != 1 { unimplemented!(); }
631 let mut args = p.path.segments[0].arguments.clone();
632 if let syn::PathArguments::AngleBracketed(ref mut generics) = &mut args {
633 for arg in generics.args.iter_mut() {
634 if let syn::GenericArgument::Type(ref mut t) = arg {
635 *t = self.resolve_imported_refs(t.clone());
639 if let Some((_, newpath)) = self.imports.get(single_ident_generic_path_to_ident(&p.path).unwrap()) {
640 p.path = newpath.clone();
642 p.path.segments[0].arguments = args;
644 syn::Type::Reference(r) => {
645 r.elem = Box::new(self.resolve_imported_refs((*r.elem).clone()));
647 syn::Type::Slice(s) => {
648 s.elem = Box::new(self.resolve_imported_refs((*s.elem).clone()));
650 syn::Type::Tuple(t) => {
651 for e in t.elems.iter_mut() {
652 *e = self.resolve_imported_refs(e.clone());
655 _ => unimplemented!(),
661 // templates_defined is walked to write the C++ header, so if we use the default hashing it get
662 // reordered on each genbindings run. Instead, we use SipHasher (which defaults to 0-keys) so that
663 // the sorting is stable across runs. It is deprecated, but the "replacement" doesn't actually
664 // accomplish the same goals, so we just ignore it.
666 pub type NonRandomHash = hash::BuildHasherDefault<hash::SipHasher>;
669 pub struct ASTModule {
670 pub attrs: Vec<syn::Attribute>,
671 pub items: Vec<syn::Item>,
672 pub submods: Vec<String>,
674 /// A struct containing the syn::File AST for each file in the crate.
675 pub struct FullLibraryAST {
676 pub modules: HashMap<String, ASTModule, NonRandomHash>,
677 pub dependencies: HashSet<syn::Ident>,
679 impl FullLibraryAST {
680 fn load_module(&mut self, module: String, attrs: Vec<syn::Attribute>, mut items: Vec<syn::Item>) {
681 let mut non_mod_items = Vec::with_capacity(items.len());
682 let mut submods = Vec::with_capacity(items.len());
683 for item in items.drain(..) {
685 syn::Item::Mod(m) if m.content.is_some() => {
686 if export_status(&m.attrs) == ExportStatus::Export {
687 if let syn::Visibility::Public(_) = m.vis {
688 let modident = format!("{}", m.ident);
689 let modname = if module != "" {
690 module.clone() + "::" + &modident
694 self.load_module(modname, m.attrs, m.content.unwrap().1);
695 submods.push(modident);
697 non_mod_items.push(syn::Item::Mod(m));
701 syn::Item::Mod(_) => panic!("--pretty=expanded output should never have non-body modules"),
702 syn::Item::ExternCrate(c) => {
703 if export_status(&c.attrs) == ExportStatus::Export {
704 self.dependencies.insert(c.ident);
707 _ => { non_mod_items.push(item); }
710 self.modules.insert(module, ASTModule { attrs, items: non_mod_items, submods });
713 pub fn load_lib(lib: syn::File) -> Self {
714 assert_eq!(export_status(&lib.attrs), ExportStatus::Export);
715 let mut res = Self { modules: HashMap::default(), dependencies: HashSet::new() };
716 res.load_module("".to_owned(), lib.attrs, lib.items);
721 /// List of manually-generated types which are clonable
722 fn initial_clonable_types() -> HashSet<String> {
723 let mut res = HashSet::new();
724 res.insert("crate::c_types::u5".to_owned());
725 res.insert("crate::c_types::ThirtyTwoBytes".to_owned());
726 res.insert("crate::c_types::PublicKey".to_owned());
727 res.insert("crate::c_types::Transaction".to_owned());
728 res.insert("crate::c_types::TxOut".to_owned());
729 res.insert("crate::c_types::Signature".to_owned());
730 res.insert("crate::c_types::RecoverableSignature".to_owned());
731 res.insert("crate::c_types::Secp256k1Error".to_owned());
732 res.insert("crate::c_types::IOError".to_owned());
736 /// Top-level struct tracking everything which has been defined while walking the crate.
737 pub struct CrateTypes<'a> {
738 /// This may contain structs or enums, but only when either is mapped as
739 /// struct X { inner: *mut originalX, .. }
740 pub opaques: HashMap<String, (&'a syn::Ident, &'a syn::Generics)>,
741 /// Enums which are mapped as C enums with conversion functions
742 pub mirrored_enums: HashMap<String, &'a syn::ItemEnum>,
743 /// Traits which are mapped as a pointer + jump table
744 pub traits: HashMap<String, &'a syn::ItemTrait>,
745 /// Aliases from paths to some other Type
746 pub type_aliases: HashMap<String, syn::Type>,
747 /// Value is an alias to Key (maybe with some generics)
748 pub reverse_alias_map: HashMap<String, Vec<(syn::Path, syn::PathArguments)>>,
749 /// Template continer types defined, map from mangled type name -> whether a destructor fn
752 /// This is used at the end of processing to make C++ wrapper classes
753 pub templates_defined: RefCell<HashMap<String, bool, NonRandomHash>>,
754 /// The output file for any created template container types, written to as we find new
755 /// template containers which need to be defined.
756 template_file: RefCell<&'a mut File>,
757 /// Set of containers which are clonable
758 clonable_types: RefCell<HashSet<String>>,
760 pub trait_impls: HashMap<String, Vec<String>>,
761 /// The full set of modules in the crate(s)
762 pub lib_ast: &'a FullLibraryAST,
765 impl<'a> CrateTypes<'a> {
766 pub fn new(template_file: &'a mut File, libast: &'a FullLibraryAST) -> Self {
768 opaques: HashMap::new(), mirrored_enums: HashMap::new(), traits: HashMap::new(),
769 type_aliases: HashMap::new(), reverse_alias_map: HashMap::new(),
770 templates_defined: RefCell::new(HashMap::default()),
771 clonable_types: RefCell::new(initial_clonable_types()), trait_impls: HashMap::new(),
772 template_file: RefCell::new(template_file), lib_ast: &libast,
775 pub fn set_clonable(&self, object: String) {
776 self.clonable_types.borrow_mut().insert(object);
778 pub fn is_clonable(&self, object: &str) -> bool {
779 self.clonable_types.borrow().contains(object)
781 pub fn write_new_template(&self, mangled_container: String, has_destructor: bool, created_container: &[u8]) {
782 self.template_file.borrow_mut().write(created_container).unwrap();
783 self.templates_defined.borrow_mut().insert(mangled_container, has_destructor);
787 /// A struct which tracks resolving rust types into C-mapped equivalents, exists for one specific
788 /// module but contains a reference to the overall CrateTypes tracking.
789 pub struct TypeResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
790 pub module_path: &'mod_lifetime str,
791 pub crate_types: &'mod_lifetime CrateTypes<'crate_lft>,
792 types: ImportResolver<'mod_lifetime, 'crate_lft>,
795 /// Returned by write_empty_rust_val_check_suffix to indicate what type of dereferencing needs to
796 /// happen to get the inner value of a generic.
797 enum EmptyValExpectedTy {
798 /// A type which has a flag for being empty (eg an array where we treat all-0s as empty).
800 /// A Option mapped as a COption_*Z
802 /// A pointer which we want to convert to a reference.
807 /// Describes the appropriate place to print a general type-conversion string when converting a
809 enum ContainerPrefixLocation {
810 /// Prints a general type-conversion string prefix and suffix outside of the
811 /// container-conversion strings.
813 /// Prints a general type-conversion string prefix and suffix inside of the
814 /// container-conversion strings.
816 /// Does not print the usual type-conversion string prefix and suffix.
820 impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
821 pub fn new(module_path: &'a str, types: ImportResolver<'a, 'c>, crate_types: &'a CrateTypes<'c>) -> Self {
822 Self { module_path, types, crate_types }
825 // *************************************************
826 // *** Well know type and conversion definitions ***
827 // *************************************************
829 /// Returns true we if can just skip passing this to C entirely
830 fn skip_path(&self, full_path: &str) -> bool {
831 full_path == "bitcoin::secp256k1::Secp256k1" ||
832 full_path == "bitcoin::secp256k1::Signing" ||
833 full_path == "bitcoin::secp256k1::Verification"
835 /// Returns true we if can just skip passing this to C entirely
836 fn no_arg_path_to_rust(&self, full_path: &str) -> &str {
837 if full_path == "bitcoin::secp256k1::Secp256k1" {
838 "secp256k1::SECP256K1"
839 } else { unimplemented!(); }
842 /// Returns true if the object is a primitive and is mapped as-is with no conversion
844 pub fn is_primitive(&self, full_path: &str) -> bool {
855 pub fn is_clonable(&self, ty: &str) -> bool {
856 if self.crate_types.is_clonable(ty) { return true; }
857 if self.is_primitive(ty) { return true; }
863 /// Gets the C-mapped type for types which are outside of the crate, or which are manually
864 /// ignored by for some reason need mapping anyway.
865 fn c_type_from_path<'b>(&self, full_path: &'b str, is_ref: bool, _ptr_for_ref: bool) -> Option<&'b str> {
866 if self.is_primitive(full_path) {
867 return Some(full_path);
870 // Note that no !is_ref types can map to an array because Rust and C's call semantics
871 // for arrays are different (https://github.com/eqrion/cbindgen/issues/528)
873 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
874 "[u8; 20]" if !is_ref => Some("crate::c_types::TwentyBytes"),
875 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes"),
876 "[u8; 12]" if !is_ref => Some("crate::c_types::TwelveBytes"),
877 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes"),
878 "[u8; 3]" if !is_ref => Some("crate::c_types::ThreeBytes"), // Used for RGB values
880 "str" if is_ref => Some("crate::c_types::Str"),
881 "alloc::string::String"|"String" => Some("crate::c_types::Str"),
883 "std::time::Duration"|"core::time::Duration" => Some("u64"),
884 "std::time::SystemTime" => Some("u64"),
885 "std::io::Error" => Some("crate::c_types::IOError"),
886 "core::fmt::Arguments" if is_ref => Some("crate::c_types::Str"),
888 "core::convert::Infallible" => Some("crate::c_types::NotConstructable"),
890 "bitcoin::bech32::u5"|"bech32::u5" => Some("crate::c_types::u5"),
891 "core::num::NonZeroU8" => Some("u8"),
893 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
894 => Some("crate::c_types::PublicKey"),
895 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature"),
896 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some("crate::c_types::RecoverableSignature"),
897 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
898 if is_ref => Some("*const [u8; 32]"),
899 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
900 if !is_ref => Some("crate::c_types::SecretKey"),
901 "bitcoin::secp256k1::Error"|"secp256k1::Error"
902 if !is_ref => Some("crate::c_types::Secp256k1Error"),
903 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice"),
904 "bitcoin::blockdata::script::Script" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
905 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::lightning::chain::transaction::OutPoint"),
906 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" => Some("crate::c_types::Transaction"),
907 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut"),
908 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network"),
909 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("*const [u8; 80]"),
910 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice"),
912 "bitcoin::hash_types::PubkeyHash"|"bitcoin::hash_types::WPubkeyHash"|"bitcoin::hash_types::ScriptHash"
913 if is_ref => Some("*const [u8; 20]"),
914 "bitcoin::hash_types::WScriptHash"
915 if is_ref => Some("*const [u8; 32]"),
917 // Newtypes that we just expose in their original form.
918 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
919 if is_ref => Some("*const [u8; 32]"),
920 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
921 if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
922 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
923 "lightning::ln::PaymentHash"|"lightning::ln::PaymentPreimage"|"lightning::ln::PaymentSecret"
924 |"lightning::ln::channelmanager::PaymentId"|"lightning::chain::keysinterface::KeyMaterial"
925 if is_ref => Some("*const [u8; 32]"),
926 "lightning::ln::PaymentHash"|"lightning::ln::PaymentPreimage"|"lightning::ln::PaymentSecret"
927 |"lightning::ln::channelmanager::PaymentId"|"lightning::chain::keysinterface::KeyMaterial"
928 if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
930 "lightning::io::Read" => Some("crate::c_types::u8slice"),
936 fn from_c_conversion_new_var_from_path<'b>(&self, _full_path: &str, _is_ref: bool) -> Option<(&'b str, &'b str)> {
939 fn from_c_conversion_prefix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
940 if self.is_primitive(full_path) {
941 return Some("".to_owned());
944 "Vec" if !is_ref => Some("local_"),
945 "Result" if !is_ref => Some("local_"),
946 "Option" if is_ref => Some("&local_"),
947 "Option" => Some("local_"),
949 "[u8; 32]" if is_ref => Some("unsafe { &*"),
950 "[u8; 32]" if !is_ref => Some(""),
951 "[u8; 20]" if !is_ref => Some(""),
952 "[u8; 16]" if !is_ref => Some(""),
953 "[u8; 12]" if !is_ref => Some(""),
954 "[u8; 4]" if !is_ref => Some(""),
955 "[u8; 3]" if !is_ref => Some(""),
957 "[u8]" if is_ref => Some(""),
958 "[usize]" if is_ref => Some(""),
960 "str" if is_ref => Some(""),
961 "alloc::string::String"|"String" => Some(""),
962 "std::io::Error" if !is_ref => Some(""),
963 // Note that we'll panic for String if is_ref, as we only have non-owned memory, we
964 // cannot create a &String.
966 "core::convert::Infallible" => Some("panic!(\"You must never construct a NotConstructable! : "),
968 "std::time::Duration"|"core::time::Duration" => Some("core::time::Duration::from_secs("),
969 "std::time::SystemTime" => Some("(::std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs("),
971 "bitcoin::bech32::u5"|"bech32::u5" => Some(""),
972 "core::num::NonZeroU8" => Some("core::num::NonZeroU8::new("),
974 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
975 if is_ref => Some("&"),
976 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
978 "bitcoin::secp256k1::Signature" if is_ref => Some("&"),
979 "bitcoin::secp256k1::Signature" => Some(""),
980 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(""),
981 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
982 if is_ref => Some("&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *"),
983 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
984 if !is_ref => Some(""),
985 "bitcoin::blockdata::script::Script" if is_ref => Some("&::bitcoin::blockdata::script::Script::from(Vec::from("),
986 "bitcoin::blockdata::script::Script" if !is_ref => Some("::bitcoin::blockdata::script::Script::from("),
987 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" if is_ref => Some("&"),
988 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" => Some(""),
989 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::c_types::C_to_bitcoin_outpoint("),
990 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(""),
991 "bitcoin::network::constants::Network" => Some(""),
992 "bitcoin::blockdata::block::BlockHeader" => Some("&::bitcoin::consensus::encode::deserialize(unsafe { &*"),
993 "bitcoin::blockdata::block::Block" if is_ref => Some("&::bitcoin::consensus::encode::deserialize("),
995 "bitcoin::hash_types::PubkeyHash" if is_ref =>
996 Some("&bitcoin::hash_types::PubkeyHash::from_hash(bitcoin::hashes::Hash::from_inner(unsafe { *"),
997 "bitcoin::hash_types::WPubkeyHash" if is_ref =>
998 Some("&bitcoin::hash_types::WPubkeyHash::from_hash(bitcoin::hashes::Hash::from_inner(unsafe { *"),
999 "bitcoin::hash_types::ScriptHash" if is_ref =>
1000 Some("&bitcoin::hash_types::ScriptHash::from_hash(bitcoin::hashes::Hash::from_inner(unsafe { *"),
1001 "bitcoin::hash_types::WScriptHash" if is_ref =>
1002 Some("&bitcoin::hash_types::WScriptHash::from_hash(bitcoin::hashes::Hash::from_inner(unsafe { *"),
1004 // Newtypes that we just expose in their original form.
1005 "bitcoin::hash_types::Txid" if is_ref => Some("&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*"),
1006 "bitcoin::hash_types::Txid" if !is_ref => Some("::bitcoin::hash_types::Txid::from_slice(&"),
1007 "bitcoin::hash_types::BlockHash" => Some("::bitcoin::hash_types::BlockHash::from_slice(&"),
1008 "lightning::ln::PaymentHash" if !is_ref => Some("::lightning::ln::PaymentHash("),
1009 "lightning::ln::PaymentHash" if is_ref => Some("&::lightning::ln::PaymentHash(unsafe { *"),
1010 "lightning::ln::PaymentPreimage" if !is_ref => Some("::lightning::ln::PaymentPreimage("),
1011 "lightning::ln::PaymentPreimage" if is_ref => Some("&::lightning::ln::PaymentPreimage(unsafe { *"),
1012 "lightning::ln::PaymentSecret" if !is_ref => Some("::lightning::ln::PaymentSecret("),
1013 "lightning::ln::channelmanager::PaymentId" if !is_ref => Some("::lightning::ln::channelmanager::PaymentId("),
1014 "lightning::ln::channelmanager::PaymentId" if is_ref=> Some("&::lightning::ln::channelmanager::PaymentId( unsafe { *"),
1015 "lightning::chain::keysinterface::KeyMaterial" if !is_ref => Some("::lightning::chain::keysinterface::KeyMaterial("),
1016 "lightning::chain::keysinterface::KeyMaterial" if is_ref=> Some("&::lightning::chain::keysinterface::KeyMaterial( unsafe { *"),
1018 // List of traits we map (possibly during processing of other files):
1019 "lightning::io::Read" => Some("&mut "),
1022 }.map(|s| s.to_owned())
1024 fn from_c_conversion_suffix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
1025 if self.is_primitive(full_path) {
1026 return Some("".to_owned());
1029 "Vec" if !is_ref => Some(""),
1030 "Option" => Some(""),
1031 "Result" if !is_ref => Some(""),
1033 "[u8; 32]" if is_ref => Some("}"),
1034 "[u8; 32]" if !is_ref => Some(".data"),
1035 "[u8; 20]" if !is_ref => Some(".data"),
1036 "[u8; 16]" if !is_ref => Some(".data"),
1037 "[u8; 12]" if !is_ref => Some(".data"),
1038 "[u8; 4]" if !is_ref => Some(".data"),
1039 "[u8; 3]" if !is_ref => Some(".data"),
1041 "[u8]" if is_ref => Some(".to_slice()"),
1042 "[usize]" if is_ref => Some(".to_slice()"),
1044 "str" if is_ref => Some(".into_str()"),
1045 "alloc::string::String"|"String" => Some(".into_string()"),
1046 "std::io::Error" if !is_ref => Some(".to_rust()"),
1048 "core::convert::Infallible" => Some("\")"),
1050 "std::time::Duration"|"core::time::Duration" => Some(")"),
1051 "std::time::SystemTime" => Some("))"),
1053 "bitcoin::bech32::u5"|"bech32::u5" => Some(".into()"),
1054 "core::num::NonZeroU8" => Some(").expect(\"Value must be non-zero\")"),
1056 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1057 => Some(".into_rust()"),
1058 "bitcoin::secp256k1::Signature" => Some(".into_rust()"),
1059 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(".into_rust()"),
1060 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1061 if !is_ref => Some(".into_rust()"),
1062 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1063 if is_ref => Some("}[..]).unwrap()"),
1064 "bitcoin::blockdata::script::Script" if is_ref => Some(".to_slice()))"),
1065 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_rust())"),
1066 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" => Some(".into_bitcoin()"),
1067 "bitcoin::blockdata::transaction::OutPoint" => Some(")"),
1068 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(".into_rust()"),
1069 "bitcoin::network::constants::Network" => Some(".into_bitcoin()"),
1070 "bitcoin::blockdata::block::BlockHeader" => Some(" }).unwrap()"),
1071 "bitcoin::blockdata::block::Block" => Some(".to_slice()).unwrap()"),
1073 "bitcoin::hash_types::PubkeyHash"|"bitcoin::hash_types::WPubkeyHash"|
1074 "bitcoin::hash_types::ScriptHash"|"bitcoin::hash_types::WScriptHash"
1075 if is_ref => Some(" }.clone()))"),
1077 // Newtypes that we just expose in their original form.
1078 "bitcoin::hash_types::Txid" if is_ref => Some(" }[..]).unwrap()"),
1079 "bitcoin::hash_types::Txid" => Some(".data[..]).unwrap()"),
1080 "bitcoin::hash_types::BlockHash" if !is_ref => Some(".data[..]).unwrap()"),
1081 "lightning::ln::PaymentHash"|"lightning::ln::PaymentPreimage"|"lightning::ln::PaymentSecret"
1082 |"lightning::ln::channelmanager::PaymentId"|"lightning::chain::keysinterface::KeyMaterial"
1083 if !is_ref => Some(".data)"),
1084 "lightning::ln::PaymentHash"|"lightning::ln::PaymentPreimage"|"lightning::ln::PaymentSecret"
1085 |"lightning::ln::channelmanager::PaymentId"|"lightning::chain::keysinterface::KeyMaterial"
1086 if is_ref => Some(" })"),
1088 // List of traits we map (possibly during processing of other files):
1089 "lightning::io::Read" => Some(".to_reader()"),
1092 }.map(|s| s.to_owned())
1095 fn to_c_conversion_new_var_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<(&'b str, &'b str)> {
1096 if self.is_primitive(full_path) {
1100 "[u8]" if is_ref => Some(("crate::c_types::u8slice::from_slice(", ")")),
1101 "[usize]" if is_ref => Some(("crate::c_types::usizeslice::from_slice(", ")")),
1103 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(("{ let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(", ")); s }")),
1104 "bitcoin::blockdata::block::Block" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
1105 "bitcoin::hash_types::Txid" => None,
1108 }.map(|s| s.to_owned())
1110 fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
1111 if self.is_primitive(full_path) {
1112 return Some("".to_owned());
1115 "Result" if !is_ref => Some("local_"),
1116 "Vec" if !is_ref => Some("local_"),
1117 "Option" => Some("local_"),
1119 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1120 "[u8; 32]" if is_ref => Some(""),
1121 "[u8; 20]" if !is_ref => Some("crate::c_types::TwentyBytes { data: "),
1122 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes { data: "),
1123 "[u8; 12]" if !is_ref => Some("crate::c_types::TwelveBytes { data: "),
1124 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes { data: "),
1125 "[u8; 3]" if is_ref => Some(""),
1127 "[u8]" if is_ref => Some("local_"),
1128 "[usize]" if is_ref => Some("local_"),
1130 "str" if is_ref => Some(""),
1131 "alloc::string::String"|"String" => Some(""),
1133 "std::time::Duration"|"core::time::Duration" => Some(""),
1134 "std::time::SystemTime" => Some(""),
1135 "std::io::Error" if !is_ref => Some("crate::c_types::IOError::from_rust("),
1136 "core::fmt::Arguments" => Some("format!(\"{}\", "),
1138 "core::convert::Infallible" => Some("panic!(\"Cannot construct an Infallible: "),
1140 "bitcoin::bech32::u5"|"bech32::u5" => Some(""),
1142 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1143 => Some("crate::c_types::PublicKey::from_rust(&"),
1144 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature::from_rust(&"),
1145 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some("crate::c_types::RecoverableSignature::from_rust(&"),
1146 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1147 if is_ref => Some(""),
1148 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1149 if !is_ref => Some("crate::c_types::SecretKey::from_rust("),
1150 "bitcoin::secp256k1::Error"|"secp256k1::Error"
1151 if !is_ref => Some("crate::c_types::Secp256k1Error::from_rust("),
1152 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice::from_slice(&"),
1153 "bitcoin::blockdata::script::Script" if !is_ref => Some(""),
1154 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" if is_ref => Some("crate::c_types::Transaction::from_bitcoin("),
1155 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" => Some("crate::c_types::Transaction::from_bitcoin(&"),
1156 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::c_types::bitcoin_to_C_outpoint("),
1157 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut::from_rust("),
1158 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network::from_bitcoin("),
1159 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("&local_"),
1160 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice::from_slice(&local_"),
1162 "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1164 // Newtypes that we just expose in their original form.
1165 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1166 if is_ref => Some(""),
1167 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1168 if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1169 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1170 "lightning::ln::PaymentHash"|"lightning::ln::PaymentPreimage"|"lightning::ln::PaymentSecret"
1171 |"lightning::ln::channelmanager::PaymentId"|"lightning::chain::keysinterface::KeyMaterial"
1172 if is_ref => Some("&"),
1173 "lightning::ln::PaymentHash"|"lightning::ln::PaymentPreimage"|"lightning::ln::PaymentSecret"
1174 |"lightning::ln::channelmanager::PaymentId"|"lightning::chain::keysinterface::KeyMaterial"
1175 if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
1177 "lightning::io::Read" => Some("crate::c_types::u8slice::from_vec(&crate::c_types::reader_to_vec("),
1180 }.map(|s| s.to_owned())
1182 fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
1183 if self.is_primitive(full_path) {
1184 return Some("".to_owned());
1187 "Result" if !is_ref => Some(""),
1188 "Vec" if !is_ref => Some(".into()"),
1189 "Option" => Some(""),
1191 "[u8; 32]" if !is_ref => Some(" }"),
1192 "[u8; 32]" if is_ref => Some(""),
1193 "[u8; 20]" if !is_ref => Some(" }"),
1194 "[u8; 16]" if !is_ref => Some(" }"),
1195 "[u8; 12]" if !is_ref => Some(" }"),
1196 "[u8; 4]" if !is_ref => Some(" }"),
1197 "[u8; 3]" if is_ref => Some(""),
1199 "[u8]" if is_ref => Some(""),
1200 "[usize]" if is_ref => Some(""),
1202 "str" if is_ref => Some(".into()"),
1203 "alloc::string::String"|"String" if is_ref => Some(".as_str().into()"),
1204 "alloc::string::String"|"String" => Some(".into()"),
1206 "std::time::Duration"|"core::time::Duration" => Some(".as_secs()"),
1207 "std::time::SystemTime" => Some(".duration_since(::std::time::SystemTime::UNIX_EPOCH).expect(\"Times must be post-1970\").as_secs()"),
1208 "std::io::Error" if !is_ref => Some(")"),
1209 "core::fmt::Arguments" => Some(").into()"),
1211 "core::convert::Infallible" => Some("\")"),
1213 "bitcoin::bech32::u5"|"bech32::u5" => Some(".into()"),
1215 "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey"
1217 "bitcoin::secp256k1::Signature" => Some(")"),
1218 "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(")"),
1219 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1220 if !is_ref => Some(")"),
1221 "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey"
1222 if is_ref => Some(".as_ref()"),
1223 "bitcoin::secp256k1::Error"|"secp256k1::Error"
1224 if !is_ref => Some(")"),
1225 "bitcoin::blockdata::script::Script" if is_ref => Some("[..])"),
1226 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_bytes().into()"),
1227 "bitcoin::blockdata::transaction::Transaction"|"bitcoin::Transaction" => Some(")"),
1228 "bitcoin::blockdata::transaction::OutPoint" => Some(")"),
1229 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(")"),
1230 "bitcoin::network::constants::Network" => Some(")"),
1231 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(""),
1232 "bitcoin::blockdata::block::Block" if is_ref => Some(")"),
1234 "bitcoin::hash_types::Txid" if !is_ref => Some(".into_inner() }"),
1236 // Newtypes that we just expose in their original form.
1237 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1238 if is_ref => Some(".as_inner()"),
1239 "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash"
1240 if !is_ref => Some(".into_inner() }"),
1241 "bitcoin::secp256k1::Message" if !is_ref => Some(".as_ref().clone() }"),
1242 "lightning::ln::PaymentHash"|"lightning::ln::PaymentPreimage"|"lightning::ln::PaymentSecret"
1243 |"lightning::ln::channelmanager::PaymentId"|"lightning::chain::keysinterface::KeyMaterial"
1244 if is_ref => Some(".0"),
1245 "lightning::ln::PaymentHash"|"lightning::ln::PaymentPreimage"|"lightning::ln::PaymentSecret"
1246 |"lightning::ln::channelmanager::PaymentId"|"lightning::chain::keysinterface::KeyMaterial"
1247 if !is_ref => Some(".0 }"),
1249 "lightning::io::Read" => Some("))"),
1252 }.map(|s| s.to_owned())
1255 fn empty_val_check_suffix_from_path(&self, full_path: &str) -> Option<&str> {
1257 "lightning::ln::PaymentSecret" => Some(".data == [0; 32]"),
1258 "secp256k1::key::PublicKey"|"bitcoin::secp256k1::key::PublicKey" => Some(".is_null()"),
1259 "bitcoin::secp256k1::Signature" => Some(".is_null()"),
1264 /// When printing a reference to the source crate's rust type, if we need to map it to a
1265 /// different "real" type, it can be done so here.
1266 /// This is useful to work around limitations in the binding type resolver, where we reference
1267 /// a non-public `use` alias.
1268 /// TODO: We should never need to use this!
1269 fn real_rust_type_mapping<'equiv>(&self, thing: &'equiv str) -> &'equiv str {
1271 "lightning::io::Read" => "crate::c_types::io::Read",
1276 // ****************************
1277 // *** Container Processing ***
1278 // ****************************
1280 /// Returns the module path in the generated mapping crate to the containers which we generate
1281 /// when writing to CrateTypes::template_file.
1282 pub fn generated_container_path() -> &'static str {
1283 "crate::c_types::derived"
1285 /// Returns the module path in the generated mapping crate to the container templates, which
1286 /// are then concretized and put in the generated container path/template_file.
1287 fn container_templ_path() -> &'static str {
1291 /// Returns true if the path containing the given args is a "transparent" container, ie an
1292 /// Option or a container which does not require a generated continer class.
1293 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 {
1294 if full_path == "Option" {
1295 let inner = args.next().unwrap();
1296 assert!(args.next().is_none());
1298 syn::Type::Reference(_) => true,
1299 syn::Type::Path(p) => {
1300 if let Some(resolved) = self.maybe_resolve_path(&p.path, generics) {
1301 if self.c_type_has_inner_from_path(&resolved) { return true; }
1302 if self.is_primitive(&resolved) { return false; }
1303 if self.c_type_from_path(&resolved, false, false).is_some() { true } else { false }
1306 syn::Type::Tuple(_) => false,
1307 _ => unimplemented!(),
1311 /// Returns true if the path is a "transparent" container, ie an Option or a container which does
1312 /// not require a generated continer class.
1313 pub fn is_path_transparent_container(&self, full_path: &syn::Path, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
1314 let inner_iter = match &full_path.segments.last().unwrap().arguments {
1315 syn::PathArguments::None => return false,
1316 syn::PathArguments::AngleBracketed(args) => args.args.iter().map(|arg| {
1317 if let syn::GenericArgument::Type(ref ty) = arg {
1319 } else { unimplemented!() }
1321 syn::PathArguments::Parenthesized(_) => unimplemented!(),
1323 self.is_transparent_container(&self.resolve_path(full_path, generics), is_ref, inner_iter, generics)
1325 /// Returns true if this is a known, supported, non-transparent container.
1326 fn is_known_container(&self, full_path: &str, is_ref: bool) -> bool {
1327 (full_path == "Result" && !is_ref) || (full_path == "Vec" && !is_ref) || full_path.ends_with("Tuple") || full_path == "Option"
1329 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)
1330 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1331 // expecting one element in the vec per generic type, each of which is inline-converted
1332 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1334 "Result" if !is_ref => {
1336 vec![(" { Ok(mut o) => crate::c_types::CResultTempl::ok(".to_string(), "o".to_string()),
1337 (").into(), Err(mut e) => crate::c_types::CResultTempl::err(".to_string(), "e".to_string())],
1338 ").into() }", ContainerPrefixLocation::PerConv))
1342 // We should only get here if the single contained has an inner
1343 assert!(self.c_type_has_inner(single_contained.unwrap()));
1345 Some(("Vec::new(); for mut item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1348 if let Some(syn::Type::Reference(_)) = single_contained {
1349 Some(("Vec::new(); for item in ", vec![(format!(".iter() {{ local_{}.push(", var_name), "(*item)".to_string())], "); }", ContainerPrefixLocation::PerConv))
1351 Some(("Vec::new(); for item in ", vec![(format!(".iter() {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1355 let contained_struct = if let Some(syn::Type::Path(p)) = single_contained {
1356 Some(self.resolve_path(&p.path, generics))
1357 } else if let Some(syn::Type::Reference(r)) = single_contained {
1358 if let syn::Type::Path(p) = &*r.elem {
1359 Some(self.resolve_path(&p.path, generics))
1362 if let Some(inner_path) = contained_struct {
1363 if self.c_type_has_inner_from_path(&inner_path) {
1364 let is_inner_ref = if let Some(syn::Type::Reference(_)) = single_contained { true } else { false };
1366 return Some(("if ", vec![
1367 (".is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner(".to_owned(),
1368 format!("({}{}.unwrap())", var_access, if is_inner_ref { "" } else { ".as_ref()" }))
1369 ], ") }", ContainerPrefixLocation::OutsideConv));
1371 return Some(("if ", vec![
1372 (".is_none() { core::ptr::null_mut() } else { ".to_owned(), format!("({}.unwrap())", var_access))
1373 ], " }", ContainerPrefixLocation::OutsideConv));
1375 } else if self.is_primitive(&inner_path) || self.c_type_from_path(&inner_path, false, false).is_none() {
1376 let inner_name = self.get_c_mangled_container_type(vec![single_contained.unwrap()], generics, "Option").unwrap();
1377 return Some(("if ", vec![
1378 (format!(".is_none() {{ {}::None }} else {{ {}::Some(",
1379 inner_name, inner_name),
1380 format!("{}.unwrap()", var_access))
1381 ], ") }", ContainerPrefixLocation::PerConv));
1383 // If c_type_from_path is some (ie there's a manual mapping for the inner
1384 // type), lean on write_empty_rust_val, below.
1387 if let Some(t) = single_contained {
1388 if let syn::Type::Tuple(syn::TypeTuple { elems, .. }) = t {
1389 assert!(elems.is_empty());
1390 let inner_name = self.get_c_mangled_container_type(vec![single_contained.unwrap()], generics, "Option").unwrap();
1391 return Some(("if ", vec![
1392 (format!(".is_none() {{ {}::None }} else {{ {}::Some /*",
1393 inner_name, inner_name), format!(""))
1394 ], " */}", ContainerPrefixLocation::PerConv));
1396 if let syn::Type::Reference(syn::TypeReference { elem, .. }) = t {
1397 if let syn::Type::Slice(_) = &**elem {
1398 return Some(("if ", vec![
1399 (".is_none() { SmartPtr::null() } else { SmartPtr::from_obj(".to_string(),
1400 format!("({}.unwrap())", var_access))
1401 ], ") }", ContainerPrefixLocation::PerConv));
1404 let mut v = Vec::new();
1405 self.write_empty_rust_val(generics, &mut v, t);
1406 let s = String::from_utf8(v).unwrap();
1407 return Some(("if ", vec![
1408 (format!(".is_none() {{ {} }} else {{ ", s), format!("({}.unwrap())", var_access))
1409 ], " }", ContainerPrefixLocation::PerConv));
1410 } else { unreachable!(); }
1416 /// only_contained_has_inner implies that there is only one contained element in the container
1417 /// and it has an inner field (ie is an "opaque" type we've defined).
1418 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)
1419 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1420 // expecting one element in the vec per generic type, each of which is inline-converted
1421 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1423 "Result" if !is_ref => {
1425 vec![(".result_ok { true => Ok(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.result)) }})", var_access)),
1426 ("), false => Err(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.err)) }})", var_access))],
1427 ")}", ContainerPrefixLocation::PerConv))
1429 "Slice" if is_ref => {
1430 Some(("Vec::new(); for mut item in ", vec![(format!(".as_slice().iter() {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1433 Some(("Vec::new(); for mut item in ", vec![(format!(".into_rust().drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1436 if let Some(syn::Type::Path(p)) = single_contained {
1437 let inner_path = self.resolve_path(&p.path, generics);
1438 if self.is_primitive(&inner_path) {
1439 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::NoPrefix))
1440 } else if self.c_type_has_inner_from_path(&inner_path) {
1442 return Some(("if ", vec![(".inner.is_null() { None } else { Some((*".to_string(), format!("{}", var_access))], ").clone()) }", ContainerPrefixLocation::PerConv))
1444 return Some(("if ", vec![(".inner.is_null() { None } else { Some(".to_string(), format!("{}", var_access))], ") }", ContainerPrefixLocation::PerConv));
1449 if let Some(t) = single_contained {
1451 syn::Type::Reference(_)|syn::Type::Path(_)|syn::Type::Slice(_) => {
1452 let mut v = Vec::new();
1453 let ret_ref = self.write_empty_rust_val_check_suffix(generics, &mut v, t);
1454 let s = String::from_utf8(v).unwrap();
1456 EmptyValExpectedTy::ReferenceAsPointer =>
1457 return Some(("if ", vec![
1458 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ &mut *{} }}", var_access))
1459 ], ") }", ContainerPrefixLocation::NoPrefix)),
1460 EmptyValExpectedTy::OptionType =>
1461 return Some(("{ /* ", vec![
1462 (format!("*/ let {}_opt = {};", var_name, var_access),
1463 format!("}} if {}_opt{} {{ None }} else {{ Some({{ {}_opt.take()", var_name, s, var_name))
1464 ], ") } }", ContainerPrefixLocation::PerConv)),
1465 EmptyValExpectedTy::NonPointer =>
1466 return Some(("if ", vec![
1467 (format!("{} {{ None }} else {{ Some(", s), format!("{}", var_access))
1468 ], ") }", ContainerPrefixLocation::PerConv)),
1471 syn::Type::Tuple(_) => {
1472 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::PerConv))
1474 _ => unimplemented!(),
1476 } else { unreachable!(); }
1482 /// Constructs a reference to the given type, possibly tweaking the type if relevant to make it
1483 /// convertable to C.
1484 pub fn create_ownable_reference(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> Option<syn::Type> {
1485 let default_value = Some(syn::Type::Reference(syn::TypeReference {
1486 and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
1487 elem: Box::new(t.clone()) }));
1488 match generics.resolve_type(t) {
1489 syn::Type::Path(p) => {
1490 if let Some(resolved_path) = self.maybe_resolve_path(&p.path, generics) {
1491 if resolved_path != "Vec" { return default_value; }
1492 if p.path.segments.len() != 1 { unimplemented!(); }
1493 let only_seg = p.path.segments.iter().next().unwrap();
1494 if let syn::PathArguments::AngleBracketed(args) = &only_seg.arguments {
1495 if args.args.len() != 1 { unimplemented!(); }
1496 let inner_arg = args.args.iter().next().unwrap();
1497 if let syn::GenericArgument::Type(ty) = &inner_arg {
1498 let mut can_create = self.c_type_has_inner(&ty);
1499 if let syn::Type::Path(inner) = ty {
1500 if inner.path.segments.len() == 1 &&
1501 format!("{}", inner.path.segments[0].ident) == "Vec" {
1505 if !can_create { return default_value; }
1506 if let Some(inner_ty) = self.create_ownable_reference(&ty, generics) {
1507 return Some(syn::Type::Reference(syn::TypeReference {
1508 and_token: syn::Token![&](Span::call_site()),
1511 elem: Box::new(syn::Type::Slice(syn::TypeSlice {
1512 bracket_token: syn::token::Bracket { span: Span::call_site() },
1513 elem: Box::new(inner_ty)
1516 } else { return default_value; }
1517 } else { unimplemented!(); }
1518 } else { unimplemented!(); }
1519 } else { return None; }
1525 // *************************************************
1526 // *** Type definition during main.rs processing ***
1527 // *************************************************
1529 pub fn get_declared_type(&'a self, ident: &syn::Ident) -> Option<&'a DeclType<'c>> {
1530 self.types.get_declared_type(ident)
1532 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1533 pub fn c_type_has_inner_from_path(&self, full_path: &str) -> bool {
1534 self.crate_types.opaques.get(full_path).is_some()
1537 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1538 pub fn c_type_has_inner(&self, ty: &syn::Type) -> bool {
1540 syn::Type::Path(p) => {
1541 if let Some(full_path) = self.maybe_resolve_path(&p.path, None) {
1542 self.c_type_has_inner_from_path(&full_path)
1545 syn::Type::Reference(r) => {
1546 self.c_type_has_inner(&*r.elem)
1552 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
1553 self.types.maybe_resolve_ident(id)
1556 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
1557 self.types.maybe_resolve_non_ignored_ident(id)
1560 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
1561 self.types.maybe_resolve_path(p_arg, generics)
1563 pub fn resolve_path(&self, p: &syn::Path, generics: Option<&GenericTypes>) -> String {
1564 self.maybe_resolve_path(p, generics).unwrap()
1567 // ***********************************
1568 // *** Original Rust Type Printing ***
1569 // ***********************************
1571 fn in_rust_prelude(resolved_path: &str) -> bool {
1572 match resolved_path {
1580 fn write_rust_path<W: std::io::Write>(&self, w: &mut W, generics_resolver: Option<&GenericTypes>, path: &syn::Path) {
1581 if let Some(resolved) = self.maybe_resolve_path(&path, generics_resolver) {
1582 if self.is_primitive(&resolved) {
1583 write!(w, "{}", path.get_ident().unwrap()).unwrap();
1585 // TODO: We should have a generic "is from a dependency" check here instead of
1586 // checking for "bitcoin" explicitly.
1587 if resolved.starts_with("bitcoin::") || Self::in_rust_prelude(&resolved) {
1588 write!(w, "{}", resolved).unwrap();
1589 // If we're printing a generic argument, it needs to reference the crate, otherwise
1590 // the original crate:
1591 } else if self.maybe_resolve_path(&path, None).as_ref() == Some(&resolved) {
1592 write!(w, "{}", self.real_rust_type_mapping(&resolved)).unwrap();
1594 write!(w, "crate::{}", resolved).unwrap();
1597 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().last().unwrap().arguments {
1598 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1601 if path.leading_colon.is_some() {
1602 write!(w, "::").unwrap();
1604 for (idx, seg) in path.segments.iter().enumerate() {
1605 if idx != 0 { write!(w, "::").unwrap(); }
1606 write!(w, "{}", seg.ident).unwrap();
1607 if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
1608 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1613 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>) {
1614 let mut had_params = false;
1615 for (idx, arg) in generics.enumerate() {
1616 if idx != 0 { write!(w, ", ").unwrap(); } else { write!(w, "<").unwrap(); }
1619 syn::GenericParam::Lifetime(lt) => write!(w, "'{}", lt.lifetime.ident).unwrap(),
1620 syn::GenericParam::Type(t) => {
1621 write!(w, "{}", t.ident).unwrap();
1622 if t.colon_token.is_some() { write!(w, ":").unwrap(); }
1623 for (idx, bound) in t.bounds.iter().enumerate() {
1624 if idx != 0 { write!(w, " + ").unwrap(); }
1626 syn::TypeParamBound::Trait(tb) => {
1627 if tb.paren_token.is_some() || tb.lifetimes.is_some() { unimplemented!(); }
1628 self.write_rust_path(w, generics_resolver, &tb.path);
1630 _ => unimplemented!(),
1633 if t.eq_token.is_some() || t.default.is_some() { unimplemented!(); }
1635 _ => unimplemented!(),
1638 if had_params { write!(w, ">").unwrap(); }
1641 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>) {
1642 write!(w, "<").unwrap();
1643 for (idx, arg) in generics.enumerate() {
1644 if idx != 0 { write!(w, ", ").unwrap(); }
1646 syn::GenericArgument::Type(t) => self.write_rust_type(w, generics_resolver, t),
1647 _ => unimplemented!(),
1650 write!(w, ">").unwrap();
1652 pub fn write_rust_type<W: std::io::Write>(&self, w: &mut W, generics: Option<&GenericTypes>, t: &syn::Type) {
1654 syn::Type::Path(p) => {
1655 if p.qself.is_some() {
1658 self.write_rust_path(w, generics, &p.path);
1660 syn::Type::Reference(r) => {
1661 write!(w, "&").unwrap();
1662 if let Some(lft) = &r.lifetime {
1663 write!(w, "'{} ", lft.ident).unwrap();
1665 if r.mutability.is_some() {
1666 write!(w, "mut ").unwrap();
1668 self.write_rust_type(w, generics, &*r.elem);
1670 syn::Type::Array(a) => {
1671 write!(w, "[").unwrap();
1672 self.write_rust_type(w, generics, &a.elem);
1673 if let syn::Expr::Lit(l) = &a.len {
1674 if let syn::Lit::Int(i) = &l.lit {
1675 write!(w, "; {}]", i).unwrap();
1676 } else { unimplemented!(); }
1677 } else { unimplemented!(); }
1679 syn::Type::Slice(s) => {
1680 write!(w, "[").unwrap();
1681 self.write_rust_type(w, generics, &s.elem);
1682 write!(w, "]").unwrap();
1684 syn::Type::Tuple(s) => {
1685 write!(w, "(").unwrap();
1686 for (idx, t) in s.elems.iter().enumerate() {
1687 if idx != 0 { write!(w, ", ").unwrap(); }
1688 self.write_rust_type(w, generics, &t);
1690 write!(w, ")").unwrap();
1692 _ => unimplemented!(),
1696 /// Prints a constructor for something which is "uninitialized" (but obviously not actually
1697 /// unint'd memory).
1698 pub fn write_empty_rust_val<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) {
1700 syn::Type::Reference(r) => {
1701 self.write_empty_rust_val(generics, w, &*r.elem)
1703 syn::Type::Path(p) => {
1704 let resolved = self.resolve_path(&p.path, generics);
1705 if self.crate_types.opaques.get(&resolved).is_some() {
1706 write!(w, "crate::{} {{ inner: core::ptr::null_mut(), is_owned: true }}", resolved).unwrap();
1708 // Assume its a manually-mapped C type, where we can just define an null() fn
1709 write!(w, "{}::null()", self.c_type_from_path(&resolved, false, false).unwrap()).unwrap();
1712 syn::Type::Array(a) => {
1713 if let syn::Expr::Lit(l) = &a.len {
1714 if let syn::Lit::Int(i) = &l.lit {
1715 if i.base10_digits().parse::<usize>().unwrap() < 32 {
1716 // Blindly assume that if we're trying to create an empty value for an
1717 // array < 32 entries that all-0s may be a valid state.
1720 let arrty = format!("[u8; {}]", i.base10_digits());
1721 write!(w, "{}", self.to_c_conversion_inline_prefix_from_path(&arrty, false, false).unwrap()).unwrap();
1722 write!(w, "[0; {}]", i.base10_digits()).unwrap();
1723 write!(w, "{}", self.to_c_conversion_inline_suffix_from_path(&arrty, false, false).unwrap()).unwrap();
1724 } else { unimplemented!(); }
1725 } else { unimplemented!(); }
1727 _ => unimplemented!(),
1731 fn is_real_type_array(&self, resolved_type: &str) -> Option<syn::Type> {
1732 if let Some(real_ty) = self.c_type_from_path(&resolved_type, true, false) {
1733 if real_ty.ends_with("]") && real_ty.starts_with("*const [u8; ") {
1734 let mut split = real_ty.split("; ");
1735 split.next().unwrap();
1736 let tail_str = split.next().unwrap();
1737 assert!(split.next().is_none());
1738 let len = usize::from_str_radix(&tail_str[..tail_str.len() - 1], 10).unwrap();
1739 Some(parse_quote!([u8; #len]))
1744 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1745 /// See EmptyValExpectedTy for information on return types.
1746 fn write_empty_rust_val_check_suffix<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) -> EmptyValExpectedTy {
1748 syn::Type::Reference(r) => {
1749 return self.write_empty_rust_val_check_suffix(generics, w, &*r.elem);
1751 syn::Type::Path(p) => {
1752 let resolved = self.resolve_path(&p.path, generics);
1753 if let Some(arr_ty) = self.is_real_type_array(&resolved) {
1754 write!(w, ".data").unwrap();
1755 return self.write_empty_rust_val_check_suffix(generics, w, &arr_ty);
1757 if self.crate_types.opaques.get(&resolved).is_some() {
1758 write!(w, ".inner.is_null()").unwrap();
1759 EmptyValExpectedTy::NonPointer
1761 if let Some(suffix) = self.empty_val_check_suffix_from_path(&resolved) {
1762 write!(w, "{}", suffix).unwrap();
1763 // We may eventually need to allow empty_val_check_suffix_from_path to specify if we need a deref or not
1764 EmptyValExpectedTy::NonPointer
1766 write!(w, ".is_none()").unwrap();
1767 EmptyValExpectedTy::OptionType
1771 syn::Type::Array(a) => {
1772 if let syn::Expr::Lit(l) = &a.len {
1773 if let syn::Lit::Int(i) = &l.lit {
1774 write!(w, " == [0; {}]", i.base10_digits()).unwrap();
1775 EmptyValExpectedTy::NonPointer
1776 } else { unimplemented!(); }
1777 } else { unimplemented!(); }
1779 syn::Type::Slice(_) => {
1780 // Option<[]> always implies that we want to treat len() == 0 differently from
1781 // None, so we always map an Option<[]> into a pointer.
1782 write!(w, " == core::ptr::null_mut()").unwrap();
1783 EmptyValExpectedTy::ReferenceAsPointer
1785 _ => unimplemented!(),
1789 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1790 pub fn write_empty_rust_val_check<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type, var_access: &str) {
1792 syn::Type::Reference(r) => {
1793 self.write_empty_rust_val_check(generics, w, &*r.elem, var_access);
1795 syn::Type::Path(_) => {
1796 write!(w, "{}", var_access).unwrap();
1797 self.write_empty_rust_val_check_suffix(generics, w, t);
1799 syn::Type::Array(a) => {
1800 if let syn::Expr::Lit(l) = &a.len {
1801 if let syn::Lit::Int(i) = &l.lit {
1802 let arrty = format!("[u8; {}]", i.base10_digits());
1803 // We don't (yet) support a new-var conversion here.
1804 assert!(self.from_c_conversion_new_var_from_path(&arrty, false).is_none());
1806 self.from_c_conversion_prefix_from_path(&arrty, false).unwrap(),
1808 self.from_c_conversion_suffix_from_path(&arrty, false).unwrap()).unwrap();
1809 self.write_empty_rust_val_check_suffix(generics, w, t);
1810 } else { unimplemented!(); }
1811 } else { unimplemented!(); }
1813 _ => unimplemented!(),
1817 // ********************************
1818 // *** Type conversion printing ***
1819 // ********************************
1821 /// Returns true we if can just skip passing this to C entirely
1822 pub fn skip_arg(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
1824 syn::Type::Path(p) => {
1825 if p.qself.is_some() { unimplemented!(); }
1826 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1827 self.skip_path(&full_path)
1830 syn::Type::Reference(r) => {
1831 self.skip_arg(&*r.elem, generics)
1836 pub fn no_arg_to_rust<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1838 syn::Type::Path(p) => {
1839 if p.qself.is_some() { unimplemented!(); }
1840 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1841 write!(w, "{}", self.no_arg_path_to_rust(&full_path)).unwrap();
1844 syn::Type::Reference(r) => {
1845 self.no_arg_to_rust(w, &*r.elem, generics);
1851 fn write_conversion_inline_intern<W: std::io::Write,
1852 LP: Fn(&str, bool, bool) -> Option<String>, DL: Fn(&mut W, &DeclType, &str, bool, bool), SC: Fn(bool, Option<&str>) -> String>
1853 (&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool,
1854 tupleconv: &str, prefix: bool, sliceconv: SC, path_lookup: LP, decl_lookup: DL) {
1855 match generics.resolve_type(t) {
1856 syn::Type::Reference(r) => {
1857 self.write_conversion_inline_intern(w, &*r.elem, generics, true, r.mutability.is_some(),
1858 ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1860 syn::Type::Path(p) => {
1861 if p.qself.is_some() {
1865 let resolved_path = self.resolve_path(&p.path, generics);
1866 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1867 return self.write_conversion_inline_intern(w, aliased_type, None, is_ref, is_mut, ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1868 } else if self.is_primitive(&resolved_path) {
1869 if is_ref && prefix {
1870 write!(w, "*").unwrap();
1872 } else if let Some(c_type) = path_lookup(&resolved_path, is_ref, ptr_for_ref) {
1873 write!(w, "{}", c_type).unwrap();
1874 } else if let Some((_, generics)) = self.crate_types.opaques.get(&resolved_path) {
1875 decl_lookup(w, &DeclType::StructImported { generics: &generics }, &resolved_path, is_ref, is_mut);
1876 } else if self.crate_types.mirrored_enums.get(&resolved_path).is_some() {
1877 decl_lookup(w, &DeclType::MirroredEnum, &resolved_path, is_ref, is_mut);
1878 } else if let Some(t) = self.crate_types.traits.get(&resolved_path) {
1879 decl_lookup(w, &DeclType::Trait(t), &resolved_path, is_ref, is_mut);
1880 } else if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
1881 if let Some(decl_type) = self.types.maybe_resolve_declared(ident) {
1882 decl_lookup(w, decl_type, &self.maybe_resolve_ident(ident).unwrap(), is_ref, is_mut);
1883 } else { unimplemented!(); }
1884 } else { unimplemented!(); }
1886 syn::Type::Array(a) => {
1887 // We assume all arrays contain only [int_literal; X]s.
1888 // This may result in some outputs not compiling.
1889 if let syn::Expr::Lit(l) = &a.len {
1890 if let syn::Lit::Int(i) = &l.lit {
1891 write!(w, "{}", path_lookup(&format!("[u8; {}]", i.base10_digits()), is_ref, ptr_for_ref).unwrap()).unwrap();
1892 } else { unimplemented!(); }
1893 } else { unimplemented!(); }
1895 syn::Type::Slice(s) => {
1896 // We assume all slices contain only literals or references.
1897 // This may result in some outputs not compiling.
1898 if let syn::Type::Path(p) = &*s.elem {
1899 let resolved = self.resolve_path(&p.path, generics);
1900 if self.is_primitive(&resolved) {
1901 write!(w, "{}", path_lookup("[u8]", is_ref, ptr_for_ref).unwrap()).unwrap();
1903 write!(w, "{}", sliceconv(true, None)).unwrap();
1905 } else if let syn::Type::Reference(r) = &*s.elem {
1906 if let syn::Type::Path(p) = &*r.elem {
1907 write!(w, "{}", sliceconv(self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)), None)).unwrap();
1908 } else if let syn::Type::Slice(_) = &*r.elem {
1909 write!(w, "{}", sliceconv(false, None)).unwrap();
1910 } else { unimplemented!(); }
1911 } else if let syn::Type::Tuple(t) = &*s.elem {
1912 assert!(!t.elems.is_empty());
1914 write!(w, "{}", sliceconv(false, None)).unwrap();
1916 let mut needs_map = false;
1917 for e in t.elems.iter() {
1918 if let syn::Type::Reference(_) = e {
1923 let mut map_str = Vec::new();
1924 write!(&mut map_str, ".map(|(").unwrap();
1925 for i in 0..t.elems.len() {
1926 write!(&mut map_str, "{}{}", if i != 0 { ", " } else { "" }, ('a' as u8 + i as u8) as char).unwrap();
1928 write!(&mut map_str, ")| (").unwrap();
1929 for (idx, e) in t.elems.iter().enumerate() {
1930 if let syn::Type::Reference(_) = e {
1931 write!(&mut map_str, "{}{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1932 } else if let syn::Type::Path(_) = e {
1933 write!(&mut map_str, "{}*{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1934 } else { unimplemented!(); }
1936 write!(&mut map_str, "))").unwrap();
1937 write!(w, "{}", sliceconv(false, Some(&String::from_utf8(map_str).unwrap()))).unwrap();
1939 write!(w, "{}", sliceconv(false, None)).unwrap();
1942 } else { unimplemented!(); }
1944 syn::Type::Tuple(t) => {
1945 if t.elems.is_empty() {
1946 // cbindgen has poor support for (), see, eg https://github.com/eqrion/cbindgen/issues/527
1947 // so work around it by just pretending its a 0u8
1948 write!(w, "{}", tupleconv).unwrap();
1950 if prefix { write!(w, "local_").unwrap(); }
1953 _ => unimplemented!(),
1957 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) {
1958 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "() /*", true, |_, _| "local_".to_owned(),
1959 |a, b, c| self.to_c_conversion_inline_prefix_from_path(a, b, c),
1960 |w, decl_type, decl_path, is_ref, _is_mut| {
1962 DeclType::MirroredEnum if is_ref && ptr_for_ref => write!(w, "crate::{}::from_native(", decl_path).unwrap(),
1963 DeclType::MirroredEnum if is_ref => write!(w, "&crate::{}::from_native(", decl_path).unwrap(),
1964 DeclType::MirroredEnum => write!(w, "crate::{}::native_into(", decl_path).unwrap(),
1965 DeclType::EnumIgnored {..}|DeclType::StructImported {..} if is_ref && from_ptr => {
1966 if !ptr_for_ref { write!(w, "&").unwrap(); }
1967 write!(w, "crate::{} {{ inner: unsafe {{ (", decl_path).unwrap()
1969 DeclType::EnumIgnored {..}|DeclType::StructImported {..} if is_ref => {
1970 if !ptr_for_ref { write!(w, "&").unwrap(); }
1971 write!(w, "crate::{} {{ inner: unsafe {{ ObjOps::nonnull_ptr_to_inner((", decl_path).unwrap()
1973 DeclType::EnumIgnored {..}|DeclType::StructImported {..} if !is_ref && from_ptr =>
1974 write!(w, "crate::{} {{ inner: ", decl_path).unwrap(),
1975 DeclType::EnumIgnored {..}|DeclType::StructImported {..} if !is_ref =>
1976 write!(w, "crate::{} {{ inner: ObjOps::heap_alloc(", decl_path).unwrap(),
1977 DeclType::Trait(_) if is_ref => write!(w, "").unwrap(),
1978 DeclType::Trait(_) if !is_ref => write!(w, "Into::into(").unwrap(),
1979 _ => panic!("{:?}", decl_path),
1983 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) {
1984 self.write_to_c_conversion_inline_prefix_inner(w, t, generics, false, ptr_for_ref, false);
1986 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) {
1987 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "*/", false, |_, _| ".into()".to_owned(),
1988 |a, b, c| self.to_c_conversion_inline_suffix_from_path(a, b, c),
1989 |w, decl_type, full_path, is_ref, _is_mut| match decl_type {
1990 DeclType::MirroredEnum => write!(w, ")").unwrap(),
1991 DeclType::EnumIgnored { generics }|DeclType::StructImported { generics } if is_ref => {
1992 write!(w, " as *const {}<", full_path).unwrap();
1993 for param in generics.params.iter() {
1994 if let syn::GenericParam::Lifetime(_) = param {
1995 write!(w, "'_, ").unwrap();
1997 write!(w, "_, ").unwrap();
2001 write!(w, ">) as *mut _ }}, is_owned: false }}").unwrap();
2003 write!(w, ">) as *mut _) }}, is_owned: false }}").unwrap();
2006 DeclType::EnumIgnored {..}|DeclType::StructImported {..} if !is_ref && from_ptr =>
2007 write!(w, ", is_owned: true }}").unwrap(),
2008 DeclType::EnumIgnored {..}|DeclType::StructImported {..} if !is_ref => write!(w, "), is_owned: true }}").unwrap(),
2009 DeclType::Trait(_) if is_ref => {},
2010 DeclType::Trait(_) => {
2011 // This is used when we're converting a concrete Rust type into a C trait
2012 // for use when a Rust trait method returns an associated type.
2013 // Because all of our C traits implement From<RustTypesImplementingTraits>
2014 // we can just call .into() here and be done.
2015 write!(w, ")").unwrap()
2017 _ => unimplemented!(),
2020 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) {
2021 self.write_to_c_conversion_inline_suffix_inner(w, t, generics, false, ptr_for_ref, false);
2024 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) {
2025 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "() /*", true, |_, _| "&local_".to_owned(),
2026 |a, b, _c| self.from_c_conversion_prefix_from_path(a, b),
2027 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
2028 DeclType::StructImported {..} if is_ref => write!(w, "").unwrap(),
2029 DeclType::StructImported {..} if !is_ref => write!(w, "*unsafe {{ Box::from_raw(").unwrap(),
2030 DeclType::MirroredEnum if is_ref => write!(w, "&").unwrap(),
2031 DeclType::MirroredEnum => {},
2032 DeclType::Trait(_) => {},
2033 _ => unimplemented!(),
2036 pub fn write_from_c_conversion_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
2037 self.write_from_c_conversion_prefix_inner(w, t, generics, false, false);
2039 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) {
2040 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "*/", false,
2041 |has_inner, map_str_opt| match (has_inner, map_str_opt) {
2042 (false, Some(map_str)) => format!(".iter(){}.collect::<Vec<_>>()[..]", map_str),
2043 (false, None) => ".iter().collect::<Vec<_>>()[..]".to_owned(),
2044 (true, None) => "[..]".to_owned(),
2045 (true, Some(_)) => unreachable!(),
2047 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
2048 |w, decl_type, _full_path, is_ref, is_mut| match decl_type {
2049 DeclType::StructImported {..} if is_ref && ptr_for_ref => write!(w, "XXX unimplemented").unwrap(),
2050 DeclType::StructImported {..} if is_mut && is_ref => write!(w, ".get_native_mut_ref()").unwrap(),
2051 DeclType::StructImported {..} if is_ref => write!(w, ".get_native_ref()").unwrap(),
2052 DeclType::StructImported {..} if !is_ref => write!(w, ".take_inner()) }}").unwrap(),
2053 DeclType::MirroredEnum if is_ref => write!(w, ".to_native()").unwrap(),
2054 DeclType::MirroredEnum => write!(w, ".into_native()").unwrap(),
2055 DeclType::Trait(_) => {},
2056 _ => unimplemented!(),
2059 pub fn write_from_c_conversion_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
2060 self.write_from_c_conversion_suffix_inner(w, t, generics, false, false);
2062 // Note that compared to the above conversion functions, the following two are generally
2063 // significantly undertested:
2064 pub fn write_from_c_conversion_to_ref_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
2065 self.write_conversion_inline_intern(w, t, generics, false, false, false, "() /*", true, |_, _| "&local_".to_owned(),
2067 if let Some(conv) = self.from_c_conversion_prefix_from_path(a, b) {
2068 Some(format!("&{}", conv))
2071 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
2072 DeclType::StructImported {..} if !is_ref => write!(w, "").unwrap(),
2073 _ => unimplemented!(),
2076 pub fn write_from_c_conversion_to_ref_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
2077 self.write_conversion_inline_intern(w, t, generics, false, false, false, "*/", false,
2078 |has_inner, map_str_opt| match (has_inner, map_str_opt) {
2079 (false, Some(map_str)) => format!(".iter(){}.collect::<Vec<_>>()[..]", map_str),
2080 (false, None) => ".iter().collect::<Vec<_>>()[..]".to_owned(),
2081 (true, None) => "[..]".to_owned(),
2082 (true, Some(_)) => unreachable!(),
2084 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
2085 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
2086 DeclType::StructImported {..} if !is_ref => write!(w, ".get_native_ref()").unwrap(),
2087 _ => unimplemented!(),
2091 fn write_conversion_new_var_intern<'b, W: std::io::Write,
2092 LP: Fn(&str, bool) -> Option<(&str, &str)>,
2093 LC: Fn(&str, bool, Option<&syn::Type>, &syn::Ident, &str) -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)>,
2094 VP: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool),
2095 VS: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool)>
2096 (&self, w: &mut W, ident: &syn::Ident, var: &str, t: &syn::Type, generics: Option<&GenericTypes>,
2097 mut is_ref: bool, mut ptr_for_ref: bool, to_c: bool, from_ownable_ref: bool,
2098 path_lookup: &LP, container_lookup: &LC, var_prefix: &VP, var_suffix: &VS) -> bool {
2100 macro_rules! convert_container {
2101 ($container_type: expr, $args_len: expr, $args_iter: expr) => { {
2102 // For slices (and Options), we refuse to directly map them as is_ref when they
2103 // aren't opaque types containing an inner pointer. This is due to the fact that,
2104 // in both cases, the actual higher-level type is non-is_ref.
2105 let ty_has_inner = if $args_len == 1 {
2106 let ty = $args_iter().next().unwrap();
2107 if $container_type == "Slice" && to_c {
2108 // "To C ptr_for_ref" means "return the regular object with is_owned
2109 // set to false", which is totally what we want in a slice if we're about to
2110 // set ty_has_inner.
2113 if let syn::Type::Reference(t) = ty {
2114 if let syn::Type::Path(p) = &*t.elem {
2115 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2117 } else if let syn::Type::Path(p) = ty {
2118 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2122 // Options get a bunch of special handling, since in general we map Option<>al
2123 // types into the same C type as non-Option-wrapped types. This ends up being
2124 // pretty manual here and most of the below special-cases are for Options.
2125 let mut needs_ref_map = false;
2126 let mut only_contained_type = None;
2127 let mut only_contained_type_nonref = None;
2128 let mut only_contained_has_inner = false;
2129 let mut contains_slice = false;
2131 only_contained_has_inner = ty_has_inner;
2132 let arg = $args_iter().next().unwrap();
2133 if let syn::Type::Reference(t) = arg {
2134 only_contained_type = Some(arg);
2135 only_contained_type_nonref = Some(&*t.elem);
2136 if let syn::Type::Path(_) = &*t.elem {
2138 } else if let syn::Type::Slice(_) = &*t.elem {
2139 contains_slice = true;
2140 } else { return false; }
2141 // If the inner element contains an inner pointer, we will just use that,
2142 // avoiding the need to map elements to references. Otherwise we'll need to
2143 // do an extra mapping step.
2144 needs_ref_map = !only_contained_has_inner && $container_type == "Option";
2146 only_contained_type = Some(arg);
2147 only_contained_type_nonref = Some(arg);
2151 if let Some((prefix, conversions, suffix, prefix_location)) = container_lookup(&$container_type, is_ref && ty_has_inner, only_contained_type, ident, var) {
2152 assert_eq!(conversions.len(), $args_len);
2153 write!(w, "let mut local_{}{} = ", ident,
2154 if (!to_c && needs_ref_map) || (to_c && $container_type == "Option" && contains_slice) {"_base"} else { "" }).unwrap();
2155 if prefix_location == ContainerPrefixLocation::OutsideConv {
2156 var_prefix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
2158 write!(w, "{}{}", prefix, var).unwrap();
2160 for ((pfx, var_name), (idx, ty)) in conversions.iter().zip($args_iter().enumerate()) {
2161 let mut var = std::io::Cursor::new(Vec::new());
2162 write!(&mut var, "{}", var_name).unwrap();
2163 let var_access = String::from_utf8(var.into_inner()).unwrap();
2165 let conv_ty = if needs_ref_map { only_contained_type_nonref.as_ref().unwrap() } else { ty };
2167 write!(w, "{} {{ ", pfx).unwrap();
2168 let new_var_name = format!("{}_{}", ident, idx);
2169 let new_var = self.write_conversion_new_var_intern(w, &format_ident!("{}", new_var_name),
2170 &var_access, conv_ty, generics, contains_slice || (is_ref && ty_has_inner), ptr_for_ref,
2171 to_c, from_ownable_ref, path_lookup, container_lookup, var_prefix, var_suffix);
2172 if new_var { write!(w, " ").unwrap(); }
2174 if prefix_location == ContainerPrefixLocation::PerConv {
2175 var_prefix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2176 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
2177 write!(w, "ObjOps::heap_alloc(").unwrap();
2180 write!(w, "{}{}", if contains_slice && !to_c { "local_" } else { "" }, if new_var { new_var_name } else { var_access }).unwrap();
2181 if prefix_location == ContainerPrefixLocation::PerConv {
2182 var_suffix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2183 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
2184 write!(w, ")").unwrap();
2186 write!(w, " }}").unwrap();
2188 write!(w, "{}", suffix).unwrap();
2189 if prefix_location == ContainerPrefixLocation::OutsideConv {
2190 var_suffix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
2192 write!(w, ";").unwrap();
2193 if !to_c && needs_ref_map {
2194 write!(w, " let mut local_{} = local_{}_base.as_ref()", ident, ident).unwrap();
2196 write!(w, ".map(|a| &a[..])").unwrap();
2198 write!(w, ";").unwrap();
2199 } else if to_c && $container_type == "Option" && contains_slice {
2200 write!(w, " let mut local_{} = *local_{}_base;", ident, ident).unwrap();
2207 match generics.resolve_type(t) {
2208 syn::Type::Reference(r) => {
2209 if let syn::Type::Slice(_) = &*r.elem {
2210 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)
2212 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)
2215 syn::Type::Path(p) => {
2216 if p.qself.is_some() {
2219 let resolved_path = self.resolve_path(&p.path, generics);
2220 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
2221 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);
2223 if self.is_known_container(&resolved_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
2224 if let syn::PathArguments::AngleBracketed(args) = &p.path.segments.iter().next().unwrap().arguments {
2225 convert_container!(resolved_path, args.args.len(), || args.args.iter().map(|arg| {
2226 if let syn::GenericArgument::Type(ty) = arg {
2227 generics.resolve_type(ty)
2228 } else { unimplemented!(); }
2230 } else { unimplemented!(); }
2232 if self.is_primitive(&resolved_path) {
2234 } else if let Some(ty_ident) = single_ident_generic_path_to_ident(&p.path) {
2235 if let Some((prefix, suffix)) = path_lookup(&resolved_path, is_ref) {
2236 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
2238 } else if self.types.maybe_resolve_declared(ty_ident).is_some() {
2243 syn::Type::Array(_) => {
2244 // We assume all arrays contain only primitive types.
2245 // This may result in some outputs not compiling.
2248 syn::Type::Slice(s) => {
2249 if let syn::Type::Path(p) = &*s.elem {
2250 let resolved = self.resolve_path(&p.path, generics);
2251 if self.is_primitive(&resolved) {
2252 let slice_path = format!("[{}]", resolved);
2253 if let Some((prefix, suffix)) = path_lookup(&slice_path, true) {
2254 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
2258 let tyref = [&*s.elem];
2260 // If we're converting from a slice to a Vec, assume we can clone the
2261 // elements and clone them into a new Vec first. Next we'll walk the
2262 // new Vec here and convert them to C types.
2263 write!(w, "let mut local_{}_clone = Vec::new(); local_{}_clone.extend_from_slice({}); let mut {} = local_{}_clone; ", ident, ident, ident, ident, ident).unwrap();
2266 convert_container!("Vec", 1, || tyref.iter().map(|t| generics.resolve_type(*t)));
2267 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
2269 } else if let syn::Type::Reference(ty) = &*s.elem {
2270 let tyref = if from_ownable_ref || !to_c { [&*ty.elem] } else { [&*s.elem] };
2272 convert_container!("Slice", 1, || tyref.iter().map(|t| generics.resolve_type(*t)));
2273 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
2274 } else if let syn::Type::Tuple(t) = &*s.elem {
2275 // When mapping into a temporary new var, we need to own all the underlying objects.
2276 // Thus, we drop any references inside the tuple and convert with non-reference types.
2277 let mut elems = syn::punctuated::Punctuated::new();
2278 for elem in t.elems.iter() {
2279 if let syn::Type::Reference(r) = elem {
2280 elems.push((*r.elem).clone());
2282 elems.push(elem.clone());
2285 let ty = [syn::Type::Tuple(syn::TypeTuple {
2286 paren_token: t.paren_token, elems
2290 convert_container!("Slice", 1, || ty.iter());
2291 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
2292 } else { unimplemented!() }
2294 syn::Type::Tuple(t) => {
2295 if !t.elems.is_empty() {
2296 // We don't (yet) support tuple elements which cannot be converted inline
2297 write!(w, "let (").unwrap();
2298 for idx in 0..t.elems.len() {
2299 if idx != 0 { write!(w, ", ").unwrap(); }
2300 write!(w, "{} orig_{}_{}", if is_ref { "ref" } else { "mut" }, ident, idx).unwrap();
2302 write!(w, ") = {}{}; ", var, if !to_c { ".to_rust()" } else { "" }).unwrap();
2303 // Like other template types, tuples are always mapped as their non-ref
2304 // versions for types which have different ref mappings. Thus, we convert to
2305 // non-ref versions and handle opaque types with inner pointers manually.
2306 for (idx, elem) in t.elems.iter().enumerate() {
2307 if let syn::Type::Path(p) = elem {
2308 let v_name = format!("orig_{}_{}", ident, idx);
2309 let tuple_elem_ident = format_ident!("{}", &v_name);
2310 if self.write_conversion_new_var_intern(w, &tuple_elem_ident, &v_name, elem, generics,
2311 false, ptr_for_ref, to_c, from_ownable_ref,
2312 path_lookup, container_lookup, var_prefix, var_suffix) {
2313 write!(w, " ").unwrap();
2314 // Opaque types with inner pointers shouldn't ever create new stack
2315 // variables, so we don't handle it and just assert that it doesn't
2317 assert!(!self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)));
2321 write!(w, "let mut local_{} = (", ident).unwrap();
2322 for (idx, elem) in t.elems.iter().enumerate() {
2323 let ty_has_inner = {
2325 // "To C ptr_for_ref" means "return the regular object with
2326 // is_owned set to false", which is totally what we want
2327 // if we're about to set ty_has_inner.
2330 if let syn::Type::Reference(t) = elem {
2331 if let syn::Type::Path(p) = &*t.elem {
2332 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2334 } else if let syn::Type::Path(p) = elem {
2335 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
2338 if idx != 0 { write!(w, ", ").unwrap(); }
2339 var_prefix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2340 if is_ref && ty_has_inner {
2341 // For ty_has_inner, the regular var_prefix mapping will take a
2342 // reference, so deref once here to make sure we keep the original ref.
2343 write!(w, "*").unwrap();
2345 write!(w, "orig_{}_{}", ident, idx).unwrap();
2346 if is_ref && !ty_has_inner {
2347 // If we don't have an inner variable's reference to maintain, just
2348 // hope the type is Clonable and use that.
2349 write!(w, ".clone()").unwrap();
2351 var_suffix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
2353 write!(w, "){};", if to_c { ".into()" } else { "" }).unwrap();
2357 _ => unimplemented!(),
2361 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 {
2362 self.write_conversion_new_var_intern(w, ident, var_access, t, generics, false, ptr_for_ref, true, from_ownable_ref,
2363 &|a, b| self.to_c_conversion_new_var_from_path(a, b),
2364 &|a, b, c, d, e| self.to_c_conversion_container_new_var(generics, a, b, c, d, e),
2365 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
2366 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_prefix_inner(a, b, c, d, e, f),
2367 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_suffix_inner(a, b, c, d, e, f))
2369 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 {
2370 self.write_to_c_conversion_new_var_inner(w, ident, &format!("{}", ident), t, generics, ptr_for_ref, false)
2372 /// Prints new-var conversion for an "ownable_ref" type, ie prints conversion for
2373 /// `create_ownable_reference(t)`, not `t` itself.
2374 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 {
2375 self.write_to_c_conversion_new_var_inner(w, ident, &format!("{}", ident), t, generics, true, true)
2377 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 {
2378 self.write_conversion_new_var_intern(w, ident, &format!("{}", ident), t, generics, false, false, false, false,
2379 &|a, b| self.from_c_conversion_new_var_from_path(a, b),
2380 &|a, b, c, d, e| self.from_c_conversion_container_new_var(generics, a, b, c, d, e),
2381 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
2382 &|a, b, c, d, e, _f| self.write_from_c_conversion_prefix_inner(a, b, c, d, e),
2383 &|a, b, c, d, e, _f| self.write_from_c_conversion_suffix_inner(a, b, c, d, e))
2386 // ******************************************************
2387 // *** C Container Type Equivalent and alias Printing ***
2388 // ******************************************************
2390 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 {
2391 for (idx, t) in args.enumerate() {
2393 write!(w, ", ").unwrap();
2395 if let syn::Type::Reference(r_arg) = t {
2396 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2398 if !self.write_c_type_intern(w, &*r_arg.elem, generics, false, false, false, false) { return false; }
2400 // While write_c_type_intern, above is correct, we don't want to blindly convert a
2401 // reference to something stupid, so check that the container is either opaque or a
2402 // predefined type (currently only Transaction).
2403 if let syn::Type::Path(p_arg) = &*r_arg.elem {
2404 let resolved = self.resolve_path(&p_arg.path, generics);
2405 assert!(self.crate_types.opaques.get(&resolved).is_some() ||
2406 self.c_type_from_path(&resolved, true, true).is_some(), "Template generics should be opaque or have a predefined mapping");
2407 } else { unimplemented!(); }
2408 } else if let syn::Type::Path(p_arg) = t {
2409 if let Some(resolved) = self.maybe_resolve_path(&p_arg.path, generics) {
2410 if !self.is_primitive(&resolved) {
2411 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2414 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
2416 if !self.write_c_type_intern(w, t, generics, false, false, false, false) { return false; }
2418 // We don't currently support outer reference types for non-primitive inners,
2419 // except for the empty tuple.
2420 if let syn::Type::Tuple(t_arg) = t {
2421 assert!(t_arg.elems.len() == 0 || !is_ref);
2425 if !self.write_c_type_intern(w, t, generics, false, false, false, false) { return false; }
2430 fn check_create_container(&self, mangled_container: String, container_type: &str, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
2431 if !self.crate_types.templates_defined.borrow().get(&mangled_container).is_some() {
2432 let mut created_container: Vec<u8> = Vec::new();
2434 if container_type == "Result" {
2435 let mut a_ty: Vec<u8> = Vec::new();
2436 if let syn::Type::Tuple(tup) = args.iter().next().unwrap() {
2437 if tup.elems.is_empty() {
2438 write!(&mut a_ty, "()").unwrap();
2440 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
2443 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
2446 let mut b_ty: Vec<u8> = Vec::new();
2447 if let syn::Type::Tuple(tup) = args.iter().skip(1).next().unwrap() {
2448 if tup.elems.is_empty() {
2449 write!(&mut b_ty, "()").unwrap();
2451 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
2454 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
2457 let ok_str = String::from_utf8(a_ty).unwrap();
2458 let err_str = String::from_utf8(b_ty).unwrap();
2459 let is_clonable = self.is_clonable(&ok_str) && self.is_clonable(&err_str);
2460 write_result_block(&mut created_container, &mangled_container, &ok_str, &err_str, is_clonable);
2462 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2464 } else if container_type == "Vec" {
2465 let mut a_ty: Vec<u8> = Vec::new();
2466 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2467 let ty = String::from_utf8(a_ty).unwrap();
2468 let is_clonable = self.is_clonable(&ty);
2469 write_vec_block(&mut created_container, &mangled_container, &ty, is_clonable);
2471 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2473 } else if container_type.ends_with("Tuple") {
2474 let mut tuple_args = Vec::new();
2475 let mut is_clonable = true;
2476 for arg in args.iter() {
2477 let mut ty: Vec<u8> = Vec::new();
2478 if !self.write_template_generics(&mut ty, &mut [arg].iter().map(|t| **t), generics, is_ref) { return false; }
2479 let ty_str = String::from_utf8(ty).unwrap();
2480 if !self.is_clonable(&ty_str) {
2481 is_clonable = false;
2483 tuple_args.push(ty_str);
2485 write_tuple_block(&mut created_container, &mangled_container, &tuple_args, is_clonable);
2487 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2489 } else if container_type == "Option" {
2490 let mut a_ty: Vec<u8> = Vec::new();
2491 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2492 let ty = String::from_utf8(a_ty).unwrap();
2493 let is_clonable = self.is_clonable(&ty);
2494 write_option_block(&mut created_container, &mangled_container, &ty, is_clonable);
2496 self.crate_types.set_clonable(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2501 self.crate_types.write_new_template(mangled_container.clone(), true, &created_container);
2505 fn path_to_generic_args(path: &syn::Path) -> Vec<&syn::Type> {
2506 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().next().unwrap().arguments {
2507 args.args.iter().map(|gen| if let syn::GenericArgument::Type(t) = gen { t } else { unimplemented!() }).collect()
2508 } else { unimplemented!(); }
2510 fn write_c_mangled_container_path_intern<W: std::io::Write>
2511 (&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 {
2512 let mut mangled_type: Vec<u8> = Vec::new();
2513 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a), generics) {
2514 write!(w, "C{}_", ident).unwrap();
2515 write!(mangled_type, "C{}_", ident).unwrap();
2516 } else { assert_eq!(args.len(), 1); }
2517 for arg in args.iter() {
2518 macro_rules! write_path {
2519 ($p_arg: expr, $extra_write: expr) => {
2520 if let Some(subtype) = self.maybe_resolve_path(&$p_arg.path, generics) {
2521 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a), generics) {
2523 if self.c_type_has_inner_from_path(&subtype) {
2524 if !self.write_c_path_intern(w, &$p_arg.path, generics, is_ref, is_mut, ptr_for_ref, false) { return false; }
2526 if let Some(arr_ty) = self.is_real_type_array(&subtype) {
2527 if !self.write_c_type_intern(w, &arr_ty, generics, false, true, false, false) { return false; }
2529 // Option<T> needs to be converted to a *mut T, ie mut ptr-for-ref
2530 if !self.write_c_path_intern(w, &$p_arg.path, generics, true, true, true, false) { return false; }
2534 write!(w, "{}", $p_arg.path.segments.last().unwrap().ident).unwrap();
2536 } else if self.is_known_container(&subtype, is_ref) || self.is_path_transparent_container(&$p_arg.path, generics, is_ref) {
2537 if !self.write_c_mangled_container_path_intern(w, Self::path_to_generic_args(&$p_arg.path), generics,
2538 &subtype, is_ref, is_mut, ptr_for_ref, true) {
2541 self.write_c_mangled_container_path_intern(&mut mangled_type, Self::path_to_generic_args(&$p_arg.path),
2542 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2543 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2544 self.write_c_mangled_container_path_intern(w2, Self::path_to_generic_args(&$p_arg.path),
2545 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2548 let id = subtype.rsplitn(2, ':').next().unwrap(); // Get the "Base" name of the resolved type
2549 write!(w, "{}", id).unwrap();
2550 write!(mangled_type, "{}", id).unwrap();
2551 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2552 write!(w2, "{}", id).unwrap();
2555 } else { return false; }
2558 match generics.resolve_type(arg) {
2559 syn::Type::Tuple(tuple) => {
2560 if tuple.elems.len() == 0 {
2561 write!(w, "None").unwrap();
2562 write!(mangled_type, "None").unwrap();
2564 let mut mangled_tuple_type: Vec<u8> = Vec::new();
2566 // Figure out what the mangled type should look like. To disambiguate
2567 // ((A, B), C) and (A, B, C) we prefix the generic args with a _ and suffix
2568 // them with a Z. Ideally we wouldn't use Z, but not many special chars are
2569 // available for use in type names.
2570 write!(w, "C{}Tuple_", tuple.elems.len()).unwrap();
2571 write!(mangled_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2572 write!(mangled_tuple_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2573 for elem in tuple.elems.iter() {
2574 if let syn::Type::Path(p) = elem {
2575 write_path!(p, Some(&mut mangled_tuple_type));
2576 } else if let syn::Type::Reference(refelem) = elem {
2577 if let syn::Type::Path(p) = &*refelem.elem {
2578 write_path!(p, Some(&mut mangled_tuple_type));
2579 } else { return false; }
2580 } else { return false; }
2582 write!(w, "Z").unwrap();
2583 write!(mangled_type, "Z").unwrap();
2584 write!(mangled_tuple_type, "Z").unwrap();
2585 if !self.check_create_container(String::from_utf8(mangled_tuple_type).unwrap(),
2586 &format!("{}Tuple", tuple.elems.len()), tuple.elems.iter().collect(), generics, is_ref) {
2591 syn::Type::Path(p_arg) => {
2592 write_path!(p_arg, None);
2594 syn::Type::Reference(refty) => {
2595 if let syn::Type::Path(p_arg) = &*refty.elem {
2596 write_path!(p_arg, None);
2597 } else if let syn::Type::Slice(_) = &*refty.elem {
2598 // write_c_type will actually do exactly what we want here, we just need to
2599 // make it a pointer so that its an option. Note that we cannot always convert
2600 // the Vec-as-slice (ie non-ref types) containers, so sometimes need to be able
2601 // to edit it, hence we use *mut here instead of *const.
2602 if args.len() != 1 { return false; }
2603 write!(w, "*mut ").unwrap();
2604 self.write_c_type(w, arg, None, true);
2605 } else { return false; }
2607 syn::Type::Array(a) => {
2608 if let syn::Type::Path(p_arg) = &*a.elem {
2609 let resolved = self.resolve_path(&p_arg.path, generics);
2610 if !self.is_primitive(&resolved) { return false; }
2611 if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(len), .. }) = &a.len {
2612 if self.c_type_from_path(&format!("[{}; {}]", resolved, len.base10_digits()), is_ref, ptr_for_ref).is_none() { return false; }
2613 write!(w, "_{}{}", resolved, len.base10_digits()).unwrap();
2614 write!(mangled_type, "_{}{}", resolved, len.base10_digits()).unwrap();
2615 } else { return false; }
2616 } else { return false; }
2618 _ => { return false; },
2621 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a), generics) { return true; }
2622 // Push the "end of type" Z
2623 write!(w, "Z").unwrap();
2624 write!(mangled_type, "Z").unwrap();
2626 // Make sure the type is actually defined:
2627 self.check_create_container(String::from_utf8(mangled_type).unwrap(), ident, args, generics, is_ref)
2629 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 {
2630 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a), generics) {
2631 write!(w, "{}::", Self::generated_container_path()).unwrap();
2633 self.write_c_mangled_container_path_intern(w, args, generics, ident, is_ref, is_mut, ptr_for_ref, false)
2635 pub fn get_c_mangled_container_type(&self, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, template_name: &str) -> Option<String> {
2636 let mut out = Vec::new();
2637 if !self.write_c_mangled_container_path(&mut out, args, generics, template_name, false, false, false) {
2640 Some(String::from_utf8(out).unwrap())
2643 // **********************************
2644 // *** C Type Equivalent Printing ***
2645 // **********************************
2647 fn write_c_path_intern<W: std::io::Write>(&self, w: &mut W, path: &syn::Path, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool, with_ref_lifetime: bool) -> bool {
2648 let full_path = match self.maybe_resolve_path(&path, generics) {
2649 Some(path) => path, None => return false };
2650 if let Some(c_type) = self.c_type_from_path(&full_path, is_ref, ptr_for_ref) {
2651 write!(w, "{}", c_type).unwrap();
2653 } else if self.crate_types.traits.get(&full_path).is_some() {
2654 if is_ref && ptr_for_ref {
2655 write!(w, "*{} crate::{}", if is_mut { "mut" } else { "const" }, full_path).unwrap();
2657 if with_ref_lifetime { unimplemented!(); }
2658 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2660 write!(w, "crate::{}", full_path).unwrap();
2663 } else if self.crate_types.opaques.get(&full_path).is_some() || self.crate_types.mirrored_enums.get(&full_path).is_some() {
2664 if is_ref && ptr_for_ref {
2665 // ptr_for_ref implies we're returning the object, which we can't really do for
2666 // opaque or mirrored types without box'ing them, which is quite a waste, so return
2667 // the actual object itself (for opaque types we'll set the pointer to the actual
2668 // type and note that its a reference).
2669 write!(w, "crate::{}", full_path).unwrap();
2670 } else if is_ref && with_ref_lifetime {
2672 // If we're concretizing something with a lifetime parameter, we have to pick a
2673 // lifetime, of which the only real available choice is `static`, obviously.
2674 write!(w, "&'static ").unwrap();
2675 self.write_rust_path(w, generics, path);
2677 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2679 write!(w, "crate::{}", full_path).unwrap();
2686 fn write_c_type_intern<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool, with_ref_lifetime: bool) -> bool {
2687 match generics.resolve_type(t) {
2688 syn::Type::Path(p) => {
2689 if p.qself.is_some() {
2692 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
2693 if self.is_known_container(&full_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
2694 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);
2696 if let Some(aliased_type) = self.crate_types.type_aliases.get(&full_path).cloned() {
2697 return self.write_c_type_intern(w, &aliased_type, None, is_ref, is_mut, ptr_for_ref, with_ref_lifetime);
2700 self.write_c_path_intern(w, &p.path, generics, is_ref, is_mut, ptr_for_ref, with_ref_lifetime)
2702 syn::Type::Reference(r) => {
2703 self.write_c_type_intern(w, &*r.elem, generics, true, r.mutability.is_some(), ptr_for_ref, with_ref_lifetime)
2705 syn::Type::Array(a) => {
2706 if is_ref && is_mut {
2707 write!(w, "*mut [").unwrap();
2708 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref, with_ref_lifetime) { return false; }
2710 write!(w, "*const [").unwrap();
2711 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref, with_ref_lifetime) { return false; }
2713 let mut typecheck = Vec::new();
2714 if !self.write_c_type_intern(&mut typecheck, &a.elem, generics, false, false, ptr_for_ref, with_ref_lifetime) { return false; }
2715 if typecheck[..] != ['u' as u8, '8' as u8] { return false; }
2717 if let syn::Expr::Lit(l) = &a.len {
2718 if let syn::Lit::Int(i) = &l.lit {
2720 if let Some(ty) = self.c_type_from_path(&format!("[u8; {}]", i.base10_digits()), false, ptr_for_ref) {
2721 write!(w, "{}", ty).unwrap();
2725 write!(w, "; {}]", i).unwrap();
2731 syn::Type::Slice(s) => {
2732 if !is_ref || is_mut { return false; }
2733 if let syn::Type::Path(p) = &*s.elem {
2734 let resolved = self.resolve_path(&p.path, generics);
2735 if self.is_primitive(&resolved) {
2736 write!(w, "{}::{}slice", Self::container_templ_path(), resolved).unwrap();
2739 let mut inner_c_ty = Vec::new();
2740 assert!(self.write_c_path_intern(&mut inner_c_ty, &p.path, generics, true, false, ptr_for_ref, with_ref_lifetime));
2741 if self.is_clonable(&String::from_utf8(inner_c_ty).unwrap()) {
2742 if let Some(id) = p.path.get_ident() {
2743 let mangled_container = format!("CVec_{}Z", id);
2744 write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
2745 self.check_create_container(mangled_container, "Vec", vec![&*s.elem], generics, false)
2749 } else if let syn::Type::Reference(r) = &*s.elem {
2750 if let syn::Type::Path(p) = &*r.elem {
2751 // Slices with "real types" inside are mapped as the equivalent non-ref Vec
2752 let resolved = self.resolve_path(&p.path, generics);
2753 let mangled_container = if let Some((ident, _)) = self.crate_types.opaques.get(&resolved) {
2754 format!("CVec_{}Z", ident)
2755 } else if let Some(en) = self.crate_types.mirrored_enums.get(&resolved) {
2756 format!("CVec_{}Z", en.ident)
2757 } else if let Some(id) = p.path.get_ident() {
2758 format!("CVec_{}Z", id)
2759 } else { return false; };
2760 write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
2761 self.check_create_container(mangled_container, "Vec", vec![&*r.elem], generics, false)
2762 } else if let syn::Type::Slice(sl2) = &*r.elem {
2763 if let syn::Type::Reference(r2) = &*sl2.elem {
2764 if let syn::Type::Path(p) = &*r2.elem {
2765 // Slices with slices with opaque types (with is_owned flags) are mapped as non-ref Vecs
2766 let resolved = self.resolve_path(&p.path, generics);
2767 let mangled_container = if let Some((ident, _)) = self.crate_types.opaques.get(&resolved) {
2768 format!("CVec_CVec_{}ZZ", ident)
2769 } else { return false; };
2770 write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
2771 let inner = &r2.elem;
2772 let vec_ty: syn::Type = syn::parse_quote!(Vec<#inner>);
2773 self.check_create_container(mangled_container, "Vec", vec![&vec_ty], generics, false)
2777 } else if let syn::Type::Tuple(_) = &*s.elem {
2778 let mut args = syn::punctuated::Punctuated::<_, syn::token::Comma>::new();
2779 args.push(syn::GenericArgument::Type((*s.elem).clone()));
2780 let mut segments = syn::punctuated::Punctuated::new();
2781 segments.push(parse_quote!(Vec<#args>));
2782 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)
2785 syn::Type::Tuple(t) => {
2786 if t.elems.len() == 0 {
2789 self.write_c_mangled_container_path(w, t.elems.iter().collect(), generics,
2790 &format!("{}Tuple", t.elems.len()), is_ref, is_mut, ptr_for_ref)
2796 pub fn write_c_type<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) {
2797 assert!(self.write_c_type_intern(w, t, generics, false, false, ptr_for_ref, false));
2799 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) {
2800 assert!(self.write_c_type_intern(w, t, generics, false, false, ptr_for_ref, true));
2802 pub fn understood_c_path(&self, p: &syn::Path) -> bool {
2803 if p.leading_colon.is_some() { return false; }
2804 self.write_c_path_intern(&mut std::io::sink(), p, None, false, false, false, false)
2806 pub fn understood_c_type(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
2807 self.write_c_type_intern(&mut std::io::sink(), t, generics, false, false, false, false)