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::collections::{HashMap, HashSet};
16 use proc_macro2::{TokenTree, Span};
18 // The following utils are used purely to build our known types maps - they break down all the
19 // types we need to resolve to include the given object, and no more.
21 pub fn first_seg_self<'a>(t: &'a syn::Type) -> Option<impl Iterator<Item=&syn::PathSegment> + 'a> {
23 syn::Type::Path(p) => {
24 if p.qself.is_some() || p.path.leading_colon.is_some() {
27 let mut segs = p.path.segments.iter();
28 let ty = segs.next().unwrap();
29 if !ty.arguments.is_empty() { return None; }
30 if format!("{}", ty.ident) == "Self" {
38 pub fn get_single_remaining_path_seg<'a, I: Iterator<Item=&'a syn::PathSegment>>(segs: &mut I) -> Option<&'a syn::Ident> {
39 if let Some(ty) = segs.next() {
40 if !ty.arguments.is_empty() { unimplemented!(); }
41 if segs.next().is_some() { return None; }
46 pub fn single_ident_generic_path_to_ident(p: &syn::Path) -> Option<&syn::Ident> {
47 if p.segments.len() == 1 {
48 Some(&p.segments.iter().next().unwrap().ident)
52 pub fn path_matches_nongeneric(p: &syn::Path, exp: &[&str]) -> bool {
53 if p.segments.len() != exp.len() { return false; }
54 for (seg, e) in p.segments.iter().zip(exp.iter()) {
55 if seg.arguments != syn::PathArguments::None { return false; }
56 if &format!("{}", seg.ident) != *e { return false; }
61 #[derive(Debug, PartialEq)]
62 pub enum ExportStatus {
67 /// Gets the ExportStatus of an object (struct, fn, etc) given its attributes.
68 pub fn export_status(attrs: &[syn::Attribute]) -> ExportStatus {
69 for attr in attrs.iter() {
70 let tokens_clone = attr.tokens.clone();
71 let mut token_iter = tokens_clone.into_iter();
72 if let Some(token) = token_iter.next() {
74 TokenTree::Punct(c) if c.as_char() == '=' => {
75 // Really not sure where syn gets '=' from here -
76 // it somehow represents '///' or '//!'
78 TokenTree::Group(g) => {
79 if format!("{}", single_ident_generic_path_to_ident(&attr.path).unwrap()) == "cfg" {
80 let mut iter = g.stream().into_iter();
81 if let TokenTree::Ident(i) = iter.next().unwrap() {
83 // #[cfg(any(test, feature = ""))]
84 if let TokenTree::Group(g) = iter.next().unwrap() {
85 let mut all_test = true;
86 for token in g.stream().into_iter() {
87 if let TokenTree::Ident(i) = token {
88 match format!("{}", i).as_str() {
91 _ => all_test = false,
93 } else if let TokenTree::Literal(lit) = token {
94 if format!("{}", lit) != "fuzztarget" {
99 if all_test { return ExportStatus::TestOnly; }
101 } else if i == "test" || i == "feature" {
102 // If its cfg(feature(...)) we assume its test-only
103 return ExportStatus::TestOnly;
107 continue; // eg #[derive()]
109 _ => unimplemented!(),
112 match token_iter.next().unwrap() {
113 TokenTree::Literal(lit) => {
114 let line = format!("{}", lit);
115 if line.contains("(C-not exported)") {
116 return ExportStatus::NoExport;
119 _ => unimplemented!(),
125 pub fn assert_simple_bound(bound: &syn::TraitBound) {
126 if bound.paren_token.is_some() || bound.lifetimes.is_some() { unimplemented!(); }
127 if let syn::TraitBoundModifier::Maybe(_) = bound.modifier { unimplemented!(); }
130 /// Returns true if the enum will be mapped as an opaue (ie struct with a pointer to the underlying
131 /// type), otherwise it is mapped into a transparent, C-compatible version of itself.
132 pub fn is_enum_opaque(e: &syn::ItemEnum) -> bool {
133 for var in e.variants.iter() {
134 if let syn::Fields::Named(fields) = &var.fields {
135 for field in fields.named.iter() {
136 match export_status(&field.attrs) {
137 ExportStatus::Export|ExportStatus::TestOnly => {},
138 ExportStatus::NoExport => return true,
141 } else if let syn::Fields::Unnamed(fields) = &var.fields {
142 for field in fields.unnamed.iter() {
143 match export_status(&field.attrs) {
144 ExportStatus::Export|ExportStatus::TestOnly => {},
145 ExportStatus::NoExport => return true,
153 /// A stack of sets of generic resolutions.
155 /// This tracks the template parameters for a function, struct, or trait, allowing resolution into
156 /// a concrete type. By pushing a new context onto the stack, this can track a function's template
157 /// parameters inside of a generic struct or trait.
159 /// It maps both direct types as well as Deref<Target = X>, mapping them via the provided
160 /// TypeResolver's resolve_path function (ie traits map to the concrete jump table, structs to the
161 /// concrete C container struct, etc).
162 pub struct GenericTypes<'a> {
163 typed_generics: Vec<HashMap<&'a syn::Ident, (String, Option<&'a syn::Path>)>>,
165 impl<'a> GenericTypes<'a> {
166 pub fn new() -> Self {
167 Self { typed_generics: vec![HashMap::new()], }
170 /// push a new context onto the stack, allowing for a new set of generics to be learned which
171 /// will override any lower contexts, but which will still fall back to resoltion via lower
173 pub fn push_ctx(&mut self) {
174 self.typed_generics.push(HashMap::new());
176 /// pop the latest context off the stack.
177 pub fn pop_ctx(&mut self) {
178 self.typed_generics.pop();
181 /// Learn the generics in generics in the current context, given a TypeResolver.
182 pub fn learn_generics<'b, 'c>(&mut self, generics: &'a syn::Generics, types: &'b TypeResolver<'a, 'c>) -> bool {
183 // First learn simple generics...
184 for generic in generics.params.iter() {
186 syn::GenericParam::Type(type_param) => {
187 let mut non_lifetimes_processed = false;
188 for bound in type_param.bounds.iter() {
189 if let syn::TypeParamBound::Trait(trait_bound) = bound {
190 if let Some(ident) = single_ident_generic_path_to_ident(&trait_bound.path) {
191 match &format!("{}", ident) as &str { "Send" => continue, "Sync" => continue, _ => {} }
193 if path_matches_nongeneric(&trait_bound.path, &["core", "clone", "Clone"]) { continue; }
195 assert_simple_bound(&trait_bound);
196 if let Some(mut path) = types.maybe_resolve_path(&trait_bound.path, None) {
197 if types.skip_path(&path) { continue; }
198 if non_lifetimes_processed { return false; }
199 non_lifetimes_processed = true;
200 let new_ident = if path != "std::ops::Deref" {
201 path = "crate::".to_string() + &path;
202 Some(&trait_bound.path)
204 self.typed_generics.last_mut().unwrap().insert(&type_param.ident, (path, new_ident));
205 } else { return false; }
212 // Then find generics where we are required to pass a Deref<Target=X> and pretend its just X.
213 if let Some(wh) = &generics.where_clause {
214 for pred in wh.predicates.iter() {
215 if let syn::WherePredicate::Type(t) = pred {
216 if let syn::Type::Path(p) = &t.bounded_ty {
217 if p.qself.is_some() { return false; }
218 if p.path.leading_colon.is_some() { return false; }
219 let mut p_iter = p.path.segments.iter();
220 if let Some(gen) = self.typed_generics.last_mut().unwrap().get_mut(&p_iter.next().unwrap().ident) {
221 if gen.0 != "std::ops::Deref" { return false; }
222 if &format!("{}", p_iter.next().unwrap().ident) != "Target" { return false; }
224 let mut non_lifetimes_processed = false;
225 for bound in t.bounds.iter() {
226 if let syn::TypeParamBound::Trait(trait_bound) = bound {
227 if non_lifetimes_processed { return false; }
228 non_lifetimes_processed = true;
229 assert_simple_bound(&trait_bound);
230 *gen = ("crate::".to_string() + &types.resolve_path(&trait_bound.path, None),
231 Some(&trait_bound.path));
234 } else { return false; }
235 } else { return false; }
239 for (_, (_, ident)) in self.typed_generics.last().unwrap().iter() {
240 if ident.is_none() { return false; }
245 /// Learn the associated types from the trait in the current context.
246 pub fn learn_associated_types<'b, 'c>(&mut self, t: &'a syn::ItemTrait, types: &'b TypeResolver<'a, 'c>) {
247 for item in t.items.iter() {
249 &syn::TraitItem::Type(ref t) => {
250 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
251 let mut bounds_iter = t.bounds.iter();
252 match bounds_iter.next().unwrap() {
253 syn::TypeParamBound::Trait(tr) => {
254 assert_simple_bound(&tr);
255 if let Some(mut path) = types.maybe_resolve_path(&tr.path, None) {
256 if types.skip_path(&path) { continue; }
257 // In general we handle Deref<Target=X> as if it were just X (and
258 // implement Deref<Target=Self> for relevant types). We don't
259 // bother to implement it for associated types, however, so we just
260 // ignore such bounds.
261 let new_ident = if path != "std::ops::Deref" {
262 path = "crate::".to_string() + &path;
265 self.typed_generics.last_mut().unwrap().insert(&t.ident, (path, new_ident));
266 } else { unimplemented!(); }
268 _ => unimplemented!(),
270 if bounds_iter.next().is_some() { unimplemented!(); }
277 /// Attempt to resolve an Ident as a generic parameter and return the full path.
278 pub fn maybe_resolve_ident<'b>(&'b self, ident: &syn::Ident) -> Option<&'b String> {
279 for gen in self.typed_generics.iter().rev() {
280 if let Some(res) = gen.get(ident).map(|(a, _)| a) {
286 /// Attempt to resolve a Path as a generic parameter and return the full path. as both a string
288 pub fn maybe_resolve_path<'b>(&'b self, path: &syn::Path) -> Option<(&'b String, &'a syn::Path)> {
289 if let Some(ident) = path.get_ident() {
290 for gen in self.typed_generics.iter().rev() {
291 if let Some(res) = gen.get(ident).map(|(a, b)| (a, b.unwrap())) {
296 // Associated types are usually specified as "Self::Generic", so we check for that
298 let mut it = path.segments.iter();
299 if path.segments.len() == 2 && format!("{}", it.next().unwrap().ident) == "Self" {
300 let ident = &it.next().unwrap().ident;
301 for gen in self.typed_generics.iter().rev() {
302 if let Some(res) = gen.get(ident).map(|(a, b)| (a, b.unwrap())) {
312 #[derive(Clone, PartialEq)]
313 // The type of declaration and the object itself
314 pub enum DeclType<'a> {
316 Trait(&'a syn::ItemTrait),
322 pub struct ImportResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
323 module_path: &'mod_lifetime str,
324 imports: HashMap<syn::Ident, (String, syn::Path)>,
325 declared: HashMap<syn::Ident, DeclType<'crate_lft>>,
326 priv_modules: HashSet<syn::Ident>,
328 impl<'mod_lifetime, 'crate_lft: 'mod_lifetime> ImportResolver<'mod_lifetime, 'crate_lft> {
329 fn process_use_intern(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::UseTree, partial_path: &str, mut path: syn::punctuated::Punctuated<syn::PathSegment, syn::token::Colon2>) {
331 syn::UseTree::Path(p) => {
332 let new_path = format!("{}{}::", partial_path, p.ident);
333 path.push(syn::PathSegment { ident: p.ident.clone(), arguments: syn::PathArguments::None });
334 Self::process_use_intern(imports, &p.tree, &new_path, path);
336 syn::UseTree::Name(n) => {
337 let full_path = format!("{}{}", partial_path, n.ident);
338 path.push(syn::PathSegment { ident: n.ident.clone(), arguments: syn::PathArguments::None });
339 imports.insert(n.ident.clone(), (full_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
341 syn::UseTree::Group(g) => {
342 for i in g.items.iter() {
343 Self::process_use_intern(imports, i, partial_path, path.clone());
346 syn::UseTree::Rename(r) => {
347 let full_path = format!("{}{}", partial_path, r.ident);
348 path.push(syn::PathSegment { ident: r.ident.clone(), arguments: syn::PathArguments::None });
349 imports.insert(r.rename.clone(), (full_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
351 syn::UseTree::Glob(_) => {
352 eprintln!("Ignoring * use for {} - this may result in resolution failures", partial_path);
357 fn process_use(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::ItemUse) {
358 if let syn::Visibility::Public(_) = u.vis {
359 // We actually only use these for #[cfg(fuzztarget)]
360 eprintln!("Ignoring pub(use) tree!");
363 if u.leading_colon.is_some() { eprintln!("Ignoring leading-colon use!"); return; }
364 Self::process_use_intern(imports, &u.tree, "", syn::punctuated::Punctuated::new());
367 fn insert_primitive(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, id: &str) {
368 let ident = syn::Ident::new(id, Span::call_site());
369 let mut path = syn::punctuated::Punctuated::new();
370 path.push(syn::PathSegment { ident: ident.clone(), arguments: syn::PathArguments::None });
371 imports.insert(ident, (id.to_owned(), syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
374 pub fn new(module_path: &'mod_lifetime str, contents: &'crate_lft [syn::Item]) -> Self {
375 let mut imports = HashMap::new();
376 // Add primitives to the "imports" list:
377 Self::insert_primitive(&mut imports, "bool");
378 Self::insert_primitive(&mut imports, "u64");
379 Self::insert_primitive(&mut imports, "u32");
380 Self::insert_primitive(&mut imports, "u16");
381 Self::insert_primitive(&mut imports, "u8");
382 Self::insert_primitive(&mut imports, "usize");
383 Self::insert_primitive(&mut imports, "str");
384 Self::insert_primitive(&mut imports, "String");
386 // These are here to allow us to print native Rust types in trait fn impls even if we don't
388 Self::insert_primitive(&mut imports, "Result");
389 Self::insert_primitive(&mut imports, "Vec");
390 Self::insert_primitive(&mut imports, "Option");
392 let mut declared = HashMap::new();
393 let mut priv_modules = HashSet::new();
395 for item in contents.iter() {
397 syn::Item::Use(u) => Self::process_use(&mut imports, &u),
398 syn::Item::Struct(s) => {
399 if let syn::Visibility::Public(_) = s.vis {
400 match export_status(&s.attrs) {
401 ExportStatus::Export => { declared.insert(s.ident.clone(), DeclType::StructImported); },
402 ExportStatus::NoExport => { declared.insert(s.ident.clone(), DeclType::StructIgnored); },
403 ExportStatus::TestOnly => continue,
407 syn::Item::Type(t) if export_status(&t.attrs) == ExportStatus::Export => {
408 if let syn::Visibility::Public(_) = t.vis {
409 let mut process_alias = true;
410 for tok in t.generics.params.iter() {
411 if let syn::GenericParam::Lifetime(_) = tok {}
412 else { process_alias = false; }
416 syn::Type::Path(_) => { declared.insert(t.ident.clone(), DeclType::StructImported); },
422 syn::Item::Enum(e) => {
423 if let syn::Visibility::Public(_) = e.vis {
424 match export_status(&e.attrs) {
425 ExportStatus::Export if is_enum_opaque(e) => { declared.insert(e.ident.clone(), DeclType::EnumIgnored); },
426 ExportStatus::Export => { declared.insert(e.ident.clone(), DeclType::MirroredEnum); },
431 syn::Item::Trait(t) if export_status(&t.attrs) == ExportStatus::Export => {
432 if let syn::Visibility::Public(_) = t.vis {
433 declared.insert(t.ident.clone(), DeclType::Trait(t));
436 syn::Item::Mod(m) => {
437 priv_modules.insert(m.ident.clone());
443 Self { module_path, imports, declared, priv_modules }
446 pub fn get_declared_type(&self, ident: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
447 self.declared.get(ident)
450 pub fn maybe_resolve_declared(&self, id: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
451 self.declared.get(id)
454 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
455 if let Some((imp, _)) = self.imports.get(id) {
457 } else if self.declared.get(id).is_some() {
458 Some(self.module_path.to_string() + "::" + &format!("{}", id))
462 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
463 if let Some((imp, _)) = self.imports.get(id) {
465 } else if let Some(decl_type) = self.declared.get(id) {
467 DeclType::StructIgnored => None,
468 _ => Some(self.module_path.to_string() + "::" + &format!("{}", id)),
473 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
474 let p = if let Some(gen_types) = generics {
475 if let Some((_, synpath)) = gen_types.maybe_resolve_path(p_arg) {
480 if p.leading_colon.is_some() {
481 Some(p.segments.iter().enumerate().map(|(idx, seg)| {
482 format!("{}{}", if idx == 0 { "" } else { "::" }, seg.ident)
484 } else if let Some(id) = p.get_ident() {
485 self.maybe_resolve_ident(id)
487 if p.segments.len() == 1 {
488 let seg = p.segments.iter().next().unwrap();
489 return self.maybe_resolve_ident(&seg.ident);
491 let mut seg_iter = p.segments.iter();
492 let first_seg = seg_iter.next().unwrap();
493 let remaining: String = seg_iter.map(|seg| {
494 format!("::{}", seg.ident)
496 if let Some((imp, _)) = self.imports.get(&first_seg.ident) {
498 Some(imp.clone() + &remaining)
502 } else if let Some(_) = self.priv_modules.get(&first_seg.ident) {
503 Some(format!("{}::{}{}", self.module_path, first_seg.ident, remaining))
508 /// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern)
509 pub fn resolve_imported_refs(&self, mut ty: syn::Type) -> syn::Type {
511 syn::Type::Path(p) => {
512 if let Some(ident) = p.path.get_ident() {
513 if let Some((_, newpath)) = self.imports.get(ident) {
514 p.path = newpath.clone();
516 } else { unimplemented!(); }
518 syn::Type::Reference(r) => {
519 r.elem = Box::new(self.resolve_imported_refs((*r.elem).clone()));
521 syn::Type::Slice(s) => {
522 s.elem = Box::new(self.resolve_imported_refs((*s.elem).clone()));
524 syn::Type::Tuple(t) => {
525 for e in t.elems.iter_mut() {
526 *e = self.resolve_imported_refs(e.clone());
529 _ => unimplemented!(),
535 // templates_defined is walked to write the C++ header, so if we use the default hashing it get
536 // reordered on each genbindings run. Instead, we use SipHasher (which defaults to 0-keys) so that
537 // the sorting is stable across runs. It is deprecated, but the "replacement" doesn't actually
538 // accomplish the same goals, so we just ignore it.
540 pub type NonRandomHash = hash::BuildHasherDefault<hash::SipHasher>;
542 /// Top-level struct tracking everything which has been defined while walking the crate.
543 pub struct CrateTypes<'a> {
544 /// This may contain structs or enums, but only when either is mapped as
545 /// struct X { inner: *mut originalX, .. }
546 pub opaques: HashMap<String, &'a syn::Ident>,
547 /// Enums which are mapped as C enums with conversion functions
548 pub mirrored_enums: HashMap<String, &'a syn::ItemEnum>,
549 /// Traits which are mapped as a pointer + jump table
550 pub traits: HashMap<String, &'a syn::ItemTrait>,
551 /// Aliases from paths to some other Type
552 pub type_aliases: HashMap<String, syn::Type>,
553 /// Value is an alias to Key (maybe with some generics)
554 pub reverse_alias_map: HashMap<String, Vec<(syn::Path, syn::PathArguments)>>,
555 /// Template continer types defined, map from mangled type name -> whether a destructor fn
558 /// This is used at the end of processing to make C++ wrapper classes
559 pub templates_defined: HashMap<String, bool, NonRandomHash>,
560 /// The output file for any created template container types, written to as we find new
561 /// template containers which need to be defined.
562 pub template_file: &'a mut File,
563 /// Set of containers which are clonable
564 pub clonable_types: HashSet<String>,
566 pub trait_impls: HashMap<String, Vec<String>>,
569 /// A struct which tracks resolving rust types into C-mapped equivalents, exists for one specific
570 /// module but contains a reference to the overall CrateTypes tracking.
571 pub struct TypeResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
572 pub orig_crate: &'mod_lifetime str,
573 pub module_path: &'mod_lifetime str,
574 pub crate_types: &'mod_lifetime mut CrateTypes<'crate_lft>,
575 types: ImportResolver<'mod_lifetime, 'crate_lft>,
578 /// Returned by write_empty_rust_val_check_suffix to indicate what type of dereferencing needs to
579 /// happen to get the inner value of a generic.
580 enum EmptyValExpectedTy {
581 /// A type which has a flag for being empty (eg an array where we treat all-0s as empty).
583 /// A pointer that we want to dereference and move out of.
585 /// A pointer which we want to convert to a reference.
590 /// Describes the appropriate place to print a general type-conversion string when converting a
592 enum ContainerPrefixLocation {
593 /// Prints a general type-conversion string prefix and suffix outside of the
594 /// container-conversion strings.
596 /// Prints a general type-conversion string prefix and suffix inside of the
597 /// container-conversion strings.
599 /// Does not print the usual type-conversion string prefix and suffix.
603 impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
604 pub fn new(orig_crate: &'a str, module_path: &'a str, types: ImportResolver<'a, 'c>, crate_types: &'a mut CrateTypes<'c>) -> Self {
605 Self { orig_crate, module_path, types, crate_types }
608 // *************************************************
609 // *** Well know type and conversion definitions ***
610 // *************************************************
612 /// Returns true we if can just skip passing this to C entirely
613 fn skip_path(&self, full_path: &str) -> bool {
614 full_path == "bitcoin::secp256k1::Secp256k1" ||
615 full_path == "bitcoin::secp256k1::Signing" ||
616 full_path == "bitcoin::secp256k1::Verification"
618 /// Returns true we if can just skip passing this to C entirely
619 fn no_arg_path_to_rust(&self, full_path: &str) -> &str {
620 if full_path == "bitcoin::secp256k1::Secp256k1" {
621 "secp256k1::SECP256K1"
622 } else { unimplemented!(); }
625 /// Returns true if the object is a primitive and is mapped as-is with no conversion
627 pub fn is_primitive(&self, full_path: &str) -> bool {
638 pub fn is_clonable(&self, ty: &str) -> bool {
639 if self.crate_types.clonable_types.contains(ty) { return true; }
640 if self.is_primitive(ty) { return true; }
643 "crate::c_types::Signature" => true,
644 "crate::c_types::TxOut" => true,
648 /// Gets the C-mapped type for types which are outside of the crate, or which are manually
649 /// ignored by for some reason need mapping anyway.
650 fn c_type_from_path<'b>(&self, full_path: &'b str, is_ref: bool, _ptr_for_ref: bool) -> Option<&'b str> {
651 if self.is_primitive(full_path) {
652 return Some(full_path);
655 "Result" => Some("crate::c_types::derived::CResult"),
656 "Vec" if !is_ref => Some("crate::c_types::derived::CVec"),
657 "Option" => Some(""),
659 // Note that no !is_ref types can map to an array because Rust and C's call semantics
660 // for arrays are different (https://github.com/eqrion/cbindgen/issues/528)
662 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
663 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes"),
664 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes"),
665 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes"),
666 "[u8; 3]" if !is_ref => Some("crate::c_types::ThreeBytes"), // Used for RGB values
668 "str" if is_ref => Some("crate::c_types::Str"),
669 "String" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
670 "String" if is_ref => Some("crate::c_types::Str"),
672 "std::time::Duration" => Some("u64"),
674 "bitcoin::secp256k1::key::PublicKey" => Some("crate::c_types::PublicKey"),
675 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature"),
676 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some("*const [u8; 32]"),
677 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some("crate::c_types::SecretKey"),
678 "bitcoin::secp256k1::Error" if !is_ref => Some("crate::c_types::Secp256k1Error"),
679 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice"),
680 "bitcoin::blockdata::script::Script" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
681 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::chain::transaction::OutPoint"),
682 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction"),
683 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut"),
684 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network"),
685 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("*const [u8; 80]"),
686 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice"),
688 // Newtypes that we just expose in their original form.
689 "bitcoin::hash_types::Txid" if is_ref => Some("*const [u8; 32]"),
690 "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
691 "bitcoin::hash_types::BlockHash" if is_ref => Some("*const [u8; 32]"),
692 "bitcoin::hash_types::BlockHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
693 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
694 "ln::channelmanager::PaymentHash" if is_ref => Some("*const [u8; 32]"),
695 "ln::channelmanager::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
696 "ln::channelmanager::PaymentPreimage" if is_ref => Some("*const [u8; 32]"),
697 "ln::channelmanager::PaymentPreimage" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
698 "ln::channelmanager::PaymentSecret" if is_ref => Some("crate::c_types::ThirtyTwoBytes"),
699 "ln::channelmanager::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
701 // Override the default since Records contain an fmt with a lifetime:
702 "util::logger::Record" => Some("*const std::os::raw::c_char"),
708 fn from_c_conversion_new_var_from_path<'b>(&self, _full_path: &str, _is_ref: bool) -> Option<(&'b str, &'b str)> {
711 fn from_c_conversion_prefix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
712 if self.is_primitive(full_path) {
713 return Some("".to_owned());
716 "Vec" if !is_ref => Some("local_"),
717 "Result" if !is_ref => Some("local_"),
718 "Option" if is_ref => Some("&local_"),
719 "Option" => Some("local_"),
721 "[u8; 32]" if is_ref => Some("unsafe { &*"),
722 "[u8; 32]" if !is_ref => Some(""),
723 "[u8; 16]" if !is_ref => Some(""),
724 "[u8; 10]" if !is_ref => Some(""),
725 "[u8; 4]" if !is_ref => Some(""),
726 "[u8; 3]" if !is_ref => Some(""),
728 "[u8]" if is_ref => Some(""),
729 "[usize]" if is_ref => Some(""),
731 "str" if is_ref => Some(""),
732 "String" if !is_ref => Some("String::from_utf8("),
733 // Note that we'll panic for String if is_ref, as we only have non-owned memory, we
734 // cannot create a &String.
736 "std::time::Duration" => Some("std::time::Duration::from_secs("),
738 "bitcoin::secp256k1::key::PublicKey" if is_ref => Some("&"),
739 "bitcoin::secp256k1::key::PublicKey" => Some(""),
740 "bitcoin::secp256k1::Signature" if is_ref => Some("&"),
741 "bitcoin::secp256k1::Signature" => Some(""),
742 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some("&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *"),
743 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some(""),
744 "bitcoin::blockdata::script::Script" if is_ref => Some("&::bitcoin::blockdata::script::Script::from(Vec::from("),
745 "bitcoin::blockdata::script::Script" if !is_ref => Some("::bitcoin::blockdata::script::Script::from("),
746 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some("&"),
747 "bitcoin::blockdata::transaction::Transaction" => Some(""),
748 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(""),
749 "bitcoin::network::constants::Network" => Some(""),
750 "bitcoin::blockdata::block::BlockHeader" => Some("&::bitcoin::consensus::encode::deserialize(unsafe { &*"),
751 "bitcoin::blockdata::block::Block" if is_ref => Some("&::bitcoin::consensus::encode::deserialize("),
753 // Newtypes that we just expose in their original form.
754 "bitcoin::hash_types::Txid" if is_ref => Some("&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*"),
755 "bitcoin::hash_types::Txid" if !is_ref => Some("::bitcoin::hash_types::Txid::from_slice(&"),
756 "bitcoin::hash_types::BlockHash" => Some("::bitcoin::hash_types::BlockHash::from_slice(&"),
757 "ln::channelmanager::PaymentHash" if !is_ref => Some("::lightning::ln::channelmanager::PaymentHash("),
758 "ln::channelmanager::PaymentHash" if is_ref => Some("&::lightning::ln::channelmanager::PaymentHash(unsafe { *"),
759 "ln::channelmanager::PaymentPreimage" if !is_ref => Some("::lightning::ln::channelmanager::PaymentPreimage("),
760 "ln::channelmanager::PaymentPreimage" if is_ref => Some("&::lightning::ln::channelmanager::PaymentPreimage(unsafe { *"),
761 "ln::channelmanager::PaymentSecret" => Some("::lightning::ln::channelmanager::PaymentSecret("),
763 // List of traits we map (possibly during processing of other files):
764 "crate::util::logger::Logger" => Some(""),
767 }.map(|s| s.to_owned())
769 fn from_c_conversion_suffix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
770 if self.is_primitive(full_path) {
771 return Some("".to_owned());
774 "Vec" if !is_ref => Some(""),
775 "Option" => Some(""),
776 "Result" if !is_ref => Some(""),
778 "[u8; 32]" if is_ref => Some("}"),
779 "[u8; 32]" if !is_ref => Some(".data"),
780 "[u8; 16]" if !is_ref => Some(".data"),
781 "[u8; 10]" if !is_ref => Some(".data"),
782 "[u8; 4]" if !is_ref => Some(".data"),
783 "[u8; 3]" if !is_ref => Some(".data"),
785 "[u8]" if is_ref => Some(".to_slice()"),
786 "[usize]" if is_ref => Some(".to_slice()"),
788 "str" if is_ref => Some(".into()"),
789 "String" if !is_ref => Some(".into_rust()).unwrap()"),
791 "std::time::Duration" => Some(")"),
793 "bitcoin::secp256k1::key::PublicKey" => Some(".into_rust()"),
794 "bitcoin::secp256k1::Signature" => Some(".into_rust()"),
795 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some(".into_rust()"),
796 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some("}[..]).unwrap()"),
797 "bitcoin::blockdata::script::Script" if is_ref => Some(".to_slice()))"),
798 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_rust())"),
799 "bitcoin::blockdata::transaction::Transaction" => Some(".into_bitcoin()"),
800 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(".into_rust()"),
801 "bitcoin::network::constants::Network" => Some(".into_bitcoin()"),
802 "bitcoin::blockdata::block::BlockHeader" => Some(" }).unwrap()"),
803 "bitcoin::blockdata::block::Block" => Some(".to_slice()).unwrap()"),
805 // Newtypes that we just expose in their original form.
806 "bitcoin::hash_types::Txid" if is_ref => Some(" }[..]).unwrap()"),
807 "bitcoin::hash_types::Txid" => Some(".data[..]).unwrap()"),
808 "bitcoin::hash_types::BlockHash" if !is_ref => Some(".data[..]).unwrap()"),
809 "ln::channelmanager::PaymentHash" if !is_ref => Some(".data)"),
810 "ln::channelmanager::PaymentHash" if is_ref => Some(" })"),
811 "ln::channelmanager::PaymentPreimage" if !is_ref => Some(".data)"),
812 "ln::channelmanager::PaymentPreimage" if is_ref => Some(" })"),
813 "ln::channelmanager::PaymentSecret" => Some(".data)"),
815 // List of traits we map (possibly during processing of other files):
816 "crate::util::logger::Logger" => Some(""),
819 }.map(|s| s.to_owned())
822 fn to_c_conversion_new_var_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<(&'b str, &'b str)> {
823 if self.is_primitive(full_path) {
827 "[u8]" if is_ref => Some(("crate::c_types::u8slice::from_slice(", ")")),
828 "[usize]" if is_ref => Some(("crate::c_types::usizeslice::from_slice(", ")")),
830 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
831 "bitcoin::blockdata::transaction::Transaction" if !is_ref => Some(("::bitcoin::consensus::encode::serialize(&", ")")),
832 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(("{ let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(", ")); s }")),
833 "bitcoin::blockdata::block::Block" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
834 "bitcoin::hash_types::Txid" => None,
836 // Override the default since Records contain an fmt with a lifetime:
837 // TODO: We should include the other record fields
838 "util::logger::Record" => Some(("std::ffi::CString::new(format!(\"{}\", ", ".args)).unwrap()")),
840 }.map(|s| s.to_owned())
842 fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
843 if self.is_primitive(full_path) {
844 return Some("".to_owned());
847 "Result" if !is_ref => Some("local_"),
848 "Vec" if !is_ref => Some("local_"),
849 "Option" => Some("local_"),
851 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
852 "[u8; 32]" if is_ref => Some("&"),
853 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes { data: "),
854 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes { data: "),
855 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes { data: "),
856 "[u8; 3]" if is_ref => Some("&"),
858 "[u8]" if is_ref => Some("local_"),
859 "[usize]" if is_ref => Some("local_"),
861 "str" if is_ref => Some(""),
862 "String" => Some(""),
864 "std::time::Duration" => Some(""),
866 "bitcoin::secp256k1::key::PublicKey" => Some("crate::c_types::PublicKey::from_rust(&"),
867 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature::from_rust(&"),
868 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some(""),
869 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some("crate::c_types::SecretKey::from_rust("),
870 "bitcoin::secp256k1::Error" if !is_ref => Some("crate::c_types::Secp256k1Error::from_rust("),
871 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice::from_slice(&"),
872 "bitcoin::blockdata::script::Script" if !is_ref => Some(""),
873 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction::from_vec(local_"),
874 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::c_types::bitcoin_to_C_outpoint("),
875 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut::from_rust("),
876 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network::from_bitcoin("),
877 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("&local_"),
878 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice::from_slice(&local_"),
880 "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
882 // Newtypes that we just expose in their original form.
883 "bitcoin::hash_types::Txid" if is_ref => Some(""),
884 "bitcoin::hash_types::BlockHash" if is_ref => Some(""),
885 "bitcoin::hash_types::BlockHash" => Some("crate::c_types::ThirtyTwoBytes { data: "),
886 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
887 "ln::channelmanager::PaymentHash" if is_ref => Some("&"),
888 "ln::channelmanager::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
889 "ln::channelmanager::PaymentPreimage" if is_ref => Some("&"),
890 "ln::channelmanager::PaymentPreimage" => Some("crate::c_types::ThirtyTwoBytes { data: "),
891 "ln::channelmanager::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
893 // Override the default since Records contain an fmt with a lifetime:
894 "util::logger::Record" => Some("local_"),
897 }.map(|s| s.to_owned())
899 fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
900 if self.is_primitive(full_path) {
901 return Some("".to_owned());
904 "Result" if !is_ref => Some(""),
905 "Vec" if !is_ref => Some(".into()"),
906 "Option" => Some(""),
908 "[u8; 32]" if !is_ref => Some(" }"),
909 "[u8; 32]" if is_ref => Some(""),
910 "[u8; 16]" if !is_ref => Some(" }"),
911 "[u8; 10]" if !is_ref => Some(" }"),
912 "[u8; 4]" if !is_ref => Some(" }"),
913 "[u8; 3]" if is_ref => Some(""),
915 "[u8]" if is_ref => Some(""),
916 "[usize]" if is_ref => Some(""),
918 "str" if is_ref => Some(".into()"),
919 "String" if !is_ref => Some(".into_bytes().into()"),
920 "String" if is_ref => Some(".as_str().into()"),
922 "std::time::Duration" => Some(".as_secs()"),
924 "bitcoin::secp256k1::key::PublicKey" => Some(")"),
925 "bitcoin::secp256k1::Signature" => Some(")"),
926 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some(")"),
927 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some(".as_ref()"),
928 "bitcoin::secp256k1::Error" if !is_ref => Some(")"),
929 "bitcoin::blockdata::script::Script" if is_ref => Some("[..])"),
930 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_bytes().into()"),
931 "bitcoin::blockdata::transaction::Transaction" => Some(")"),
932 "bitcoin::blockdata::transaction::OutPoint" => Some(")"),
933 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(")"),
934 "bitcoin::network::constants::Network" => Some(")"),
935 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(""),
936 "bitcoin::blockdata::block::Block" if is_ref => Some(")"),
938 "bitcoin::hash_types::Txid" if !is_ref => Some(".into_inner() }"),
940 // Newtypes that we just expose in their original form.
941 "bitcoin::hash_types::Txid" if is_ref => Some(".as_inner()"),
942 "bitcoin::hash_types::BlockHash" if is_ref => Some(".as_inner()"),
943 "bitcoin::hash_types::BlockHash" => Some(".into_inner() }"),
944 "bitcoin::secp256k1::Message" if !is_ref => Some(".as_ref().clone() }"),
945 "ln::channelmanager::PaymentHash" if is_ref => Some(".0"),
946 "ln::channelmanager::PaymentHash" => Some(".0 }"),
947 "ln::channelmanager::PaymentPreimage" if is_ref => Some(".0"),
948 "ln::channelmanager::PaymentPreimage" => Some(".0 }"),
949 "ln::channelmanager::PaymentSecret" if !is_ref => Some(".0 }"),
951 // Override the default since Records contain an fmt with a lifetime:
952 "util::logger::Record" => Some(".as_ptr()"),
955 }.map(|s| s.to_owned())
958 fn empty_val_check_suffix_from_path(&self, full_path: &str) -> Option<&str> {
960 "ln::channelmanager::PaymentSecret" => Some(".data == [0; 32]"),
961 "bitcoin::secp256k1::key::PublicKey" => Some(".is_null()"),
962 "bitcoin::secp256k1::Signature" => Some(".is_null()"),
967 // ****************************
968 // *** Container Processing ***
969 // ****************************
971 /// Returns the module path in the generated mapping crate to the containers which we generate
972 /// when writing to CrateTypes::template_file.
973 pub fn generated_container_path() -> &'static str {
974 "crate::c_types::derived"
976 /// Returns the module path in the generated mapping crate to the container templates, which
977 /// are then concretized and put in the generated container path/template_file.
978 fn container_templ_path() -> &'static str {
982 /// Returns true if the path containing the given args is a "transparent" container, ie an
983 /// Option or a container which does not require a generated continer class.
984 fn is_transparent_container<'i, I: Iterator<Item=&'i syn::Type>>(&self, full_path: &str, _is_ref: bool, mut args: I) -> bool {
985 if full_path == "Option" {
986 let inner = args.next().unwrap();
987 assert!(args.next().is_none());
989 syn::Type::Reference(_) => true,
990 syn::Type::Path(p) => {
991 if let Some(resolved) = self.maybe_resolve_path(&p.path, None) {
992 if self.is_primitive(&resolved) { false } else { true }
995 syn::Type::Tuple(_) => false,
996 _ => unimplemented!(),
1000 /// Returns true if the path is a "transparent" container, ie an Option or a container which does
1001 /// not require a generated continer class.
1002 fn is_path_transparent_container(&self, full_path: &syn::Path, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
1003 let inner_iter = match &full_path.segments.last().unwrap().arguments {
1004 syn::PathArguments::None => return false,
1005 syn::PathArguments::AngleBracketed(args) => args.args.iter().map(|arg| {
1006 if let syn::GenericArgument::Type(ref ty) = arg {
1008 } else { unimplemented!() }
1010 syn::PathArguments::Parenthesized(_) => unimplemented!(),
1012 self.is_transparent_container(&self.resolve_path(full_path, generics), is_ref, inner_iter)
1014 /// Returns true if this is a known, supported, non-transparent container.
1015 fn is_known_container(&self, full_path: &str, is_ref: bool) -> bool {
1016 (full_path == "Result" && !is_ref) || (full_path == "Vec" && !is_ref) || full_path.ends_with("Tuple") || full_path == "Option"
1018 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)
1019 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1020 // expecting one element in the vec per generic type, each of which is inline-converted
1021 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1023 "Result" if !is_ref => {
1025 vec![(" { Ok(mut o) => crate::c_types::CResultTempl::ok(".to_string(), "o".to_string()),
1026 (").into(), Err(mut e) => crate::c_types::CResultTempl::err(".to_string(), "e".to_string())],
1027 ").into() }", ContainerPrefixLocation::PerConv))
1029 "Vec" if !is_ref => {
1030 Some(("Vec::new(); for mut item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1033 Some(("Vec::new(); for item in ", vec![(format!(".iter() {{ local_{}.push(", var_name), "**item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1036 if let Some(syn::Type::Path(p)) = single_contained {
1037 let inner_path = self.resolve_path(&p.path, generics);
1038 if self.is_primitive(&inner_path) {
1039 return Some(("if ", vec![
1040 (format!(".is_none() {{ {}::COption_{}Z::None }} else {{ ", Self::generated_container_path(), inner_path),
1041 format!("{}::COption_{}Z::Some({}.unwrap())", Self::generated_container_path(), inner_path, var_access))
1042 ], " }", ContainerPrefixLocation::NoPrefix));
1043 } else if self.c_type_has_inner_from_path(&inner_path) {
1045 return Some(("if ", vec![
1046 (".is_none() { std::ptr::null() } else { ".to_owned(), format!("({}.as_ref().unwrap())", var_access))
1047 ], " }", ContainerPrefixLocation::OutsideConv));
1049 return Some(("if ", vec![
1050 (".is_none() { std::ptr::null_mut() } else { ".to_owned(), format!("({}.unwrap())", var_access))
1051 ], " }", ContainerPrefixLocation::OutsideConv));
1055 if let Some(t) = single_contained {
1056 let mut v = Vec::new();
1057 self.write_empty_rust_val(generics, &mut v, t);
1058 let s = String::from_utf8(v).unwrap();
1059 return Some(("if ", vec![
1060 (format!(".is_none() {{ {} }} else {{ ", s), format!("({}.unwrap())", var_access))
1061 ], " }", ContainerPrefixLocation::PerConv));
1062 } else { unreachable!(); }
1068 /// only_contained_has_inner implies that there is only one contained element in the container
1069 /// and it has an inner field (ie is an "opaque" type we've defined).
1070 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)
1071 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1072 // expecting one element in the vec per generic type, each of which is inline-converted
1073 -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)> {
1075 "Result" if !is_ref => {
1077 vec![(".result_ok { true => Ok(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.result)) }})", var_access)),
1078 ("), false => Err(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.err)) }})", var_access))],
1079 ")}", ContainerPrefixLocation::PerConv))
1081 "Slice" if is_ref => {
1082 Some(("Vec::new(); for mut item in ", vec![(format!(".as_slice().iter() {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1085 Some(("Vec::new(); for mut item in ", vec![(format!(".into_rust().drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }", ContainerPrefixLocation::PerConv))
1088 if let Some(syn::Type::Path(p)) = single_contained {
1089 let inner_path = self.resolve_path(&p.path, generics);
1090 if self.is_primitive(&inner_path) {
1091 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::NoPrefix))
1092 } else if self.c_type_has_inner_from_path(&inner_path) {
1094 return Some(("if ", vec![(".inner.is_null() { None } else { Some((*".to_string(), format!("{}", var_access))], ").clone()) }", ContainerPrefixLocation::PerConv))
1096 return Some(("if ", vec![(".inner.is_null() { None } else { Some(".to_string(), format!("{}", var_access))], ") }", ContainerPrefixLocation::PerConv));
1101 if let Some(t) = single_contained {
1103 syn::Type::Reference(_)|syn::Type::Path(_)|syn::Type::Slice(_) => {
1104 let mut v = Vec::new();
1105 let ret_ref = self.write_empty_rust_val_check_suffix(generics, &mut v, t);
1106 let s = String::from_utf8(v).unwrap();
1108 EmptyValExpectedTy::ReferenceAsPointer =>
1109 return Some(("if ", vec![
1110 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ &mut *{} }}", var_access))
1111 ], ") }", ContainerPrefixLocation::NoPrefix)),
1112 EmptyValExpectedTy::OwnedPointer => {
1113 if let syn::Type::Slice(_) = t {
1116 return Some(("if ", vec![
1117 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ *Box::from_raw({}) }}", var_access))
1118 ], ") }", ContainerPrefixLocation::NoPrefix));
1120 EmptyValExpectedTy::NonPointer =>
1121 return Some(("if ", vec![
1122 (format!("{} {{ None }} else {{ Some(", s), format!("{}", var_access))
1123 ], ") }", ContainerPrefixLocation::PerConv)),
1126 syn::Type::Tuple(_) => {
1127 return Some(("if ", vec![(".is_some() { Some(".to_string(), format!("{}.take()", var_access))], ") } else { None }", ContainerPrefixLocation::PerConv))
1129 _ => unimplemented!(),
1131 } else { unreachable!(); }
1137 // *************************************************
1138 // *** Type definition during main.rs processing ***
1139 // *************************************************
1141 pub fn get_declared_type(&'a self, ident: &syn::Ident) -> Option<&'a DeclType<'c>> {
1142 self.types.get_declared_type(ident)
1144 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1145 pub fn c_type_has_inner_from_path(&self, full_path: &str) -> bool{
1146 self.crate_types.opaques.get(full_path).is_some()
1149 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
1150 self.types.maybe_resolve_ident(id)
1153 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
1154 self.types.maybe_resolve_non_ignored_ident(id)
1157 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
1158 self.types.maybe_resolve_path(p_arg, generics)
1160 pub fn resolve_path(&self, p: &syn::Path, generics: Option<&GenericTypes>) -> String {
1161 self.maybe_resolve_path(p, generics).unwrap()
1164 // ***********************************
1165 // *** Original Rust Type Printing ***
1166 // ***********************************
1168 fn in_rust_prelude(resolved_path: &str) -> bool {
1169 match resolved_path {
1177 fn write_rust_path<W: std::io::Write>(&self, w: &mut W, generics_resolver: Option<&GenericTypes>, path: &syn::Path) {
1178 if let Some(resolved) = self.maybe_resolve_path(&path, generics_resolver) {
1179 if self.is_primitive(&resolved) {
1180 write!(w, "{}", path.get_ident().unwrap()).unwrap();
1182 // TODO: We should have a generic "is from a dependency" check here instead of
1183 // checking for "bitcoin" explicitly.
1184 if resolved.starts_with("bitcoin::") || Self::in_rust_prelude(&resolved) {
1185 write!(w, "{}", resolved).unwrap();
1186 // If we're printing a generic argument, it needs to reference the crate, otherwise
1187 // the original crate:
1188 } else if self.maybe_resolve_path(&path, None).as_ref() == Some(&resolved) {
1189 write!(w, "{}::{}", self.orig_crate, resolved).unwrap();
1191 write!(w, "crate::{}", resolved).unwrap();
1194 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().last().unwrap().arguments {
1195 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1198 if path.leading_colon.is_some() {
1199 write!(w, "::").unwrap();
1201 for (idx, seg) in path.segments.iter().enumerate() {
1202 if idx != 0 { write!(w, "::").unwrap(); }
1203 write!(w, "{}", seg.ident).unwrap();
1204 if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
1205 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1210 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>) {
1211 let mut had_params = false;
1212 for (idx, arg) in generics.enumerate() {
1213 if idx != 0 { write!(w, ", ").unwrap(); } else { write!(w, "<").unwrap(); }
1216 syn::GenericParam::Lifetime(lt) => write!(w, "'{}", lt.lifetime.ident).unwrap(),
1217 syn::GenericParam::Type(t) => {
1218 write!(w, "{}", t.ident).unwrap();
1219 if t.colon_token.is_some() { write!(w, ":").unwrap(); }
1220 for (idx, bound) in t.bounds.iter().enumerate() {
1221 if idx != 0 { write!(w, " + ").unwrap(); }
1223 syn::TypeParamBound::Trait(tb) => {
1224 if tb.paren_token.is_some() || tb.lifetimes.is_some() { unimplemented!(); }
1225 self.write_rust_path(w, generics_resolver, &tb.path);
1227 _ => unimplemented!(),
1230 if t.eq_token.is_some() || t.default.is_some() { unimplemented!(); }
1232 _ => unimplemented!(),
1235 if had_params { write!(w, ">").unwrap(); }
1238 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>) {
1239 write!(w, "<").unwrap();
1240 for (idx, arg) in generics.enumerate() {
1241 if idx != 0 { write!(w, ", ").unwrap(); }
1243 syn::GenericArgument::Type(t) => self.write_rust_type(w, generics_resolver, t),
1244 _ => unimplemented!(),
1247 write!(w, ">").unwrap();
1249 pub fn write_rust_type<W: std::io::Write>(&self, w: &mut W, generics: Option<&GenericTypes>, t: &syn::Type) {
1251 syn::Type::Path(p) => {
1252 if p.qself.is_some() {
1255 self.write_rust_path(w, generics, &p.path);
1257 syn::Type::Reference(r) => {
1258 write!(w, "&").unwrap();
1259 if let Some(lft) = &r.lifetime {
1260 write!(w, "'{} ", lft.ident).unwrap();
1262 if r.mutability.is_some() {
1263 write!(w, "mut ").unwrap();
1265 self.write_rust_type(w, generics, &*r.elem);
1267 syn::Type::Array(a) => {
1268 write!(w, "[").unwrap();
1269 self.write_rust_type(w, generics, &a.elem);
1270 if let syn::Expr::Lit(l) = &a.len {
1271 if let syn::Lit::Int(i) = &l.lit {
1272 write!(w, "; {}]", i).unwrap();
1273 } else { unimplemented!(); }
1274 } else { unimplemented!(); }
1276 syn::Type::Slice(s) => {
1277 write!(w, "[").unwrap();
1278 self.write_rust_type(w, generics, &s.elem);
1279 write!(w, "]").unwrap();
1281 syn::Type::Tuple(s) => {
1282 write!(w, "(").unwrap();
1283 for (idx, t) in s.elems.iter().enumerate() {
1284 if idx != 0 { write!(w, ", ").unwrap(); }
1285 self.write_rust_type(w, generics, &t);
1287 write!(w, ")").unwrap();
1289 _ => unimplemented!(),
1293 /// Prints a constructor for something which is "uninitialized" (but obviously not actually
1294 /// unint'd memory).
1295 pub fn write_empty_rust_val<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) {
1297 syn::Type::Path(p) => {
1298 let resolved = self.resolve_path(&p.path, generics);
1299 if self.crate_types.opaques.get(&resolved).is_some() {
1300 write!(w, "crate::{} {{ inner: std::ptr::null_mut(), is_owned: true }}", resolved).unwrap();
1302 // Assume its a manually-mapped C type, where we can just define an null() fn
1303 write!(w, "{}::null()", self.c_type_from_path(&resolved, false, false).unwrap()).unwrap();
1306 syn::Type::Array(a) => {
1307 if let syn::Expr::Lit(l) = &a.len {
1308 if let syn::Lit::Int(i) = &l.lit {
1309 if i.base10_digits().parse::<usize>().unwrap() < 32 {
1310 // Blindly assume that if we're trying to create an empty value for an
1311 // array < 32 entries that all-0s may be a valid state.
1314 let arrty = format!("[u8; {}]", i.base10_digits());
1315 write!(w, "{}", self.to_c_conversion_inline_prefix_from_path(&arrty, false, false).unwrap()).unwrap();
1316 write!(w, "[0; {}]", i.base10_digits()).unwrap();
1317 write!(w, "{}", self.to_c_conversion_inline_suffix_from_path(&arrty, false, false).unwrap()).unwrap();
1318 } else { unimplemented!(); }
1319 } else { unimplemented!(); }
1321 _ => unimplemented!(),
1325 fn is_real_type_array(&self, resolved_type: &str) -> Option<syn::Type> {
1326 if let Some(real_ty) = self.c_type_from_path(&resolved_type, true, false) {
1327 if real_ty.ends_with("]") && real_ty.starts_with("*const [u8; ") {
1328 let mut split = real_ty.split("; ");
1329 split.next().unwrap();
1330 let tail_str = split.next().unwrap();
1331 assert!(split.next().is_none());
1332 let len = &tail_str[..tail_str.len() - 1];
1333 Some(syn::Type::Array(syn::TypeArray {
1334 bracket_token: syn::token::Bracket { span: Span::call_site() },
1335 elem: Box::new(syn::Type::Path(syn::TypePath {
1337 path: syn::Path::from(syn::PathSegment::from(syn::Ident::new("u8", Span::call_site()))),
1339 semi_token: syn::Token!(;)(Span::call_site()),
1340 len: syn::Expr::Lit(syn::ExprLit { attrs: Vec::new(), lit: syn::Lit::Int(syn::LitInt::new(len, Span::call_site())) }),
1346 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1347 /// See EmptyValExpectedTy for information on return types.
1348 fn write_empty_rust_val_check_suffix<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) -> EmptyValExpectedTy {
1350 syn::Type::Path(p) => {
1351 let resolved = self.resolve_path(&p.path, generics);
1352 if let Some(arr_ty) = self.is_real_type_array(&resolved) {
1353 write!(w, ".data").unwrap();
1354 return self.write_empty_rust_val_check_suffix(generics, w, &arr_ty);
1356 if self.crate_types.opaques.get(&resolved).is_some() {
1357 write!(w, ".inner.is_null()").unwrap();
1358 EmptyValExpectedTy::NonPointer
1360 if let Some(suffix) = self.empty_val_check_suffix_from_path(&resolved) {
1361 write!(w, "{}", suffix).unwrap();
1362 // We may eventually need to allow empty_val_check_suffix_from_path to specify if we need a deref or not
1363 EmptyValExpectedTy::NonPointer
1365 write!(w, " == std::ptr::null_mut()").unwrap();
1366 EmptyValExpectedTy::OwnedPointer
1370 syn::Type::Array(a) => {
1371 if let syn::Expr::Lit(l) = &a.len {
1372 if let syn::Lit::Int(i) = &l.lit {
1373 write!(w, " == [0; {}]", i.base10_digits()).unwrap();
1374 EmptyValExpectedTy::NonPointer
1375 } else { unimplemented!(); }
1376 } else { unimplemented!(); }
1378 syn::Type::Slice(_) => {
1379 // Option<[]> always implies that we want to treat len() == 0 differently from
1380 // None, so we always map an Option<[]> into a pointer.
1381 write!(w, " == std::ptr::null_mut()").unwrap();
1382 EmptyValExpectedTy::ReferenceAsPointer
1384 _ => unimplemented!(),
1388 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1389 pub fn write_empty_rust_val_check<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type, var_access: &str) {
1391 syn::Type::Path(_) => {
1392 write!(w, "{}", var_access).unwrap();
1393 self.write_empty_rust_val_check_suffix(generics, w, t);
1395 syn::Type::Array(a) => {
1396 if let syn::Expr::Lit(l) = &a.len {
1397 if let syn::Lit::Int(i) = &l.lit {
1398 let arrty = format!("[u8; {}]", i.base10_digits());
1399 // We don't (yet) support a new-var conversion here.
1400 assert!(self.from_c_conversion_new_var_from_path(&arrty, false).is_none());
1402 self.from_c_conversion_prefix_from_path(&arrty, false).unwrap(),
1404 self.from_c_conversion_suffix_from_path(&arrty, false).unwrap()).unwrap();
1405 self.write_empty_rust_val_check_suffix(generics, w, t);
1406 } else { unimplemented!(); }
1407 } else { unimplemented!(); }
1409 _ => unimplemented!(),
1413 // ********************************
1414 // *** Type conversion printing ***
1415 // ********************************
1417 /// Returns true we if can just skip passing this to C entirely
1418 pub fn skip_arg(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
1420 syn::Type::Path(p) => {
1421 if p.qself.is_some() { unimplemented!(); }
1422 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1423 self.skip_path(&full_path)
1426 syn::Type::Reference(r) => {
1427 self.skip_arg(&*r.elem, generics)
1432 pub fn no_arg_to_rust<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1434 syn::Type::Path(p) => {
1435 if p.qself.is_some() { unimplemented!(); }
1436 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1437 write!(w, "{}", self.no_arg_path_to_rust(&full_path)).unwrap();
1440 syn::Type::Reference(r) => {
1441 self.no_arg_to_rust(w, &*r.elem, generics);
1447 fn write_conversion_inline_intern<W: std::io::Write,
1448 LP: Fn(&str, bool, bool) -> Option<String>, DL: Fn(&mut W, &DeclType, &str, bool, bool), SC: Fn(bool) -> &'static str>
1449 (&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool,
1450 tupleconv: &str, prefix: bool, sliceconv: SC, path_lookup: LP, decl_lookup: DL) {
1452 syn::Type::Reference(r) => {
1453 self.write_conversion_inline_intern(w, &*r.elem, generics, true, r.mutability.is_some(),
1454 ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1456 syn::Type::Path(p) => {
1457 if p.qself.is_some() {
1461 let resolved_path = self.resolve_path(&p.path, generics);
1462 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1463 return self.write_conversion_inline_intern(w, aliased_type, None, is_ref, is_mut, ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1464 } else if let Some(c_type) = path_lookup(&resolved_path, is_ref, ptr_for_ref) {
1465 write!(w, "{}", c_type).unwrap();
1466 } else if self.crate_types.opaques.get(&resolved_path).is_some() {
1467 decl_lookup(w, &DeclType::StructImported, &resolved_path, is_ref, is_mut);
1468 } else if self.crate_types.mirrored_enums.get(&resolved_path).is_some() {
1469 decl_lookup(w, &DeclType::MirroredEnum, &resolved_path, is_ref, is_mut);
1470 } else if let Some(t) = self.crate_types.traits.get(&resolved_path) {
1471 decl_lookup(w, &DeclType::Trait(t), &resolved_path, is_ref, is_mut);
1472 } else if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
1473 if let Some(decl_type) = self.types.maybe_resolve_declared(ident) {
1474 decl_lookup(w, decl_type, &self.maybe_resolve_ident(ident).unwrap(), is_ref, is_mut);
1475 } else { unimplemented!(); }
1476 } else { unimplemented!(); }
1478 syn::Type::Array(a) => {
1479 // We assume all arrays contain only [int_literal; X]s.
1480 // This may result in some outputs not compiling.
1481 if let syn::Expr::Lit(l) = &a.len {
1482 if let syn::Lit::Int(i) = &l.lit {
1483 write!(w, "{}", path_lookup(&format!("[u8; {}]", i.base10_digits()), is_ref, ptr_for_ref).unwrap()).unwrap();
1484 } else { unimplemented!(); }
1485 } else { unimplemented!(); }
1487 syn::Type::Slice(s) => {
1488 // We assume all slices contain only literals or references.
1489 // This may result in some outputs not compiling.
1490 if let syn::Type::Path(p) = &*s.elem {
1491 let resolved = self.resolve_path(&p.path, generics);
1492 assert!(self.is_primitive(&resolved));
1493 write!(w, "{}", path_lookup("[u8]", is_ref, ptr_for_ref).unwrap()).unwrap();
1494 } else if let syn::Type::Reference(r) = &*s.elem {
1495 if let syn::Type::Path(p) = &*r.elem {
1496 write!(w, "{}", sliceconv(self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)))).unwrap();
1497 } else { unimplemented!(); }
1498 } else if let syn::Type::Tuple(t) = &*s.elem {
1499 assert!(!t.elems.is_empty());
1501 write!(w, "&local_").unwrap();
1503 let mut needs_map = false;
1504 for e in t.elems.iter() {
1505 if let syn::Type::Reference(_) = e {
1510 write!(w, ".iter().map(|(").unwrap();
1511 for i in 0..t.elems.len() {
1512 write!(w, "{}{}", if i != 0 { ", " } else { "" }, ('a' as u8 + i as u8) as char).unwrap();
1514 write!(w, ")| (").unwrap();
1515 for (idx, e) in t.elems.iter().enumerate() {
1516 if let syn::Type::Reference(_) = e {
1517 write!(w, "{}{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1518 } else if let syn::Type::Path(_) = e {
1519 write!(w, "{}*{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1520 } else { unimplemented!(); }
1522 write!(w, ")).collect::<Vec<_>>()[..]").unwrap();
1525 } else { unimplemented!(); }
1527 syn::Type::Tuple(t) => {
1528 if t.elems.is_empty() {
1529 // cbindgen has poor support for (), see, eg https://github.com/eqrion/cbindgen/issues/527
1530 // so work around it by just pretending its a 0u8
1531 write!(w, "{}", tupleconv).unwrap();
1533 if prefix { write!(w, "local_").unwrap(); }
1536 _ => unimplemented!(),
1540 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) {
1541 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "0u8 /*", true, |_| "local_",
1542 |a, b, c| self.to_c_conversion_inline_prefix_from_path(a, b, c),
1543 |w, decl_type, decl_path, is_ref, _is_mut| {
1545 DeclType::MirroredEnum if is_ref && ptr_for_ref => write!(w, "crate::{}::from_native(&", decl_path).unwrap(),
1546 DeclType::MirroredEnum if is_ref => write!(w, "&crate::{}::from_native(&", decl_path).unwrap(),
1547 DeclType::MirroredEnum => write!(w, "crate::{}::native_into(", decl_path).unwrap(),
1548 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1549 write!(w, "crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1550 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1551 write!(w, "crate::{} {{ inner: unsafe {{ ( (&(", decl_path).unwrap(),
1552 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1553 write!(w, "&crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1554 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1555 write!(w, "crate::{} {{ inner: ", decl_path).unwrap(),
1556 DeclType::EnumIgnored|DeclType::StructImported if !is_ref =>
1557 write!(w, "crate::{} {{ inner: Box::into_raw(Box::new(", decl_path).unwrap(),
1558 DeclType::Trait(_) if is_ref => write!(w, "&").unwrap(),
1559 DeclType::Trait(_) if !is_ref => {},
1560 _ => panic!("{:?}", decl_path),
1564 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) {
1565 self.write_to_c_conversion_inline_prefix_inner(w, t, generics, false, ptr_for_ref, false);
1567 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) {
1568 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "*/", false, |_| ".into()",
1569 |a, b, c| self.to_c_conversion_inline_suffix_from_path(a, b, c),
1570 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1571 DeclType::MirroredEnum => write!(w, ")").unwrap(),
1572 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1573 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1574 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1575 write!(w, ") as *const _) as *mut _) }}, is_owned: false }}").unwrap(),
1576 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1577 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1578 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1579 write!(w, ", is_owned: true }}").unwrap(),
1580 DeclType::EnumIgnored|DeclType::StructImported if !is_ref => write!(w, ")), is_owned: true }}").unwrap(),
1581 DeclType::Trait(_) if is_ref => {},
1582 DeclType::Trait(_) => {
1583 // This is used when we're converting a concrete Rust type into a C trait
1584 // for use when a Rust trait method returns an associated type.
1585 // Because all of our C traits implement From<RustTypesImplementingTraits>
1586 // we can just call .into() here and be done.
1587 write!(w, ".into()").unwrap()
1589 _ => unimplemented!(),
1592 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) {
1593 self.write_to_c_conversion_inline_suffix_inner(w, t, generics, false, ptr_for_ref, false);
1596 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) {
1597 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "() /*", true, |_| "&local_",
1598 |a, b, _c| self.from_c_conversion_prefix_from_path(a, b),
1599 |w, decl_type, _full_path, is_ref, is_mut| match decl_type {
1600 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, "unsafe {{ &*(*").unwrap(),
1601 DeclType::StructImported if is_mut && is_ref => write!(w, "unsafe {{ &mut *").unwrap(),
1602 DeclType::StructImported if is_ref => write!(w, "unsafe {{ &*").unwrap(),
1603 DeclType::StructImported if !is_ref => write!(w, "*unsafe {{ Box::from_raw(").unwrap(),
1604 DeclType::MirroredEnum if is_ref => write!(w, "&").unwrap(),
1605 DeclType::MirroredEnum => {},
1606 DeclType::Trait(_) => {},
1607 _ => unimplemented!(),
1610 pub fn write_from_c_conversion_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1611 self.write_from_c_conversion_prefix_inner(w, t, generics, false, false);
1613 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) {
1614 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "*/", false,
1615 |has_inner| match has_inner {
1616 false => ".iter().collect::<Vec<_>>()[..]",
1619 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1620 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1621 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, ").inner }}").unwrap(),
1622 DeclType::StructImported if is_ref => write!(w, ".inner }}").unwrap(),
1623 DeclType::StructImported if !is_ref => write!(w, ".take_inner()) }}").unwrap(),
1624 DeclType::MirroredEnum if is_ref => write!(w, ".to_native()").unwrap(),
1625 DeclType::MirroredEnum => write!(w, ".into_native()").unwrap(),
1626 DeclType::Trait(_) => {},
1627 _ => unimplemented!(),
1630 pub fn write_from_c_conversion_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1631 self.write_from_c_conversion_suffix_inner(w, t, generics, false, false);
1633 // Note that compared to the above conversion functions, the following two are generally
1634 // significantly undertested:
1635 pub fn write_from_c_conversion_to_ref_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1636 self.write_conversion_inline_intern(w, t, generics, false, false, false, "() /*", true, |_| "&local_",
1638 if let Some(conv) = self.from_c_conversion_prefix_from_path(a, b) {
1639 Some(format!("&{}", conv))
1642 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1643 DeclType::StructImported if !is_ref => write!(w, "unsafe {{ &*").unwrap(),
1644 _ => unimplemented!(),
1647 pub fn write_from_c_conversion_to_ref_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1648 self.write_conversion_inline_intern(w, t, generics, false, false, false, "*/", false,
1649 |has_inner| match has_inner {
1650 false => ".iter().collect::<Vec<_>>()[..]",
1653 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1654 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1655 DeclType::StructImported if !is_ref => write!(w, ".inner }}").unwrap(),
1656 _ => unimplemented!(),
1660 fn write_conversion_new_var_intern<'b, W: std::io::Write,
1661 LP: Fn(&str, bool) -> Option<(&str, &str)>,
1662 LC: Fn(&str, bool, Option<&syn::Type>, &syn::Ident, &str) -> Option<(&'b str, Vec<(String, String)>, &'b str, ContainerPrefixLocation)>,
1663 VP: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool),
1664 VS: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool)>
1665 (&self, w: &mut W, ident: &syn::Ident, var: &str, t: &syn::Type, generics: Option<&GenericTypes>,
1666 mut is_ref: bool, mut ptr_for_ref: bool, to_c: bool,
1667 path_lookup: &LP, container_lookup: &LC, var_prefix: &VP, var_suffix: &VS) -> bool {
1669 macro_rules! convert_container {
1670 ($container_type: expr, $args_len: expr, $args_iter: expr) => { {
1671 // For slices (and Options), we refuse to directly map them as is_ref when they
1672 // aren't opaque types containing an inner pointer. This is due to the fact that,
1673 // in both cases, the actual higher-level type is non-is_ref.
1674 let ty_has_inner = if $args_len == 1 {
1675 let ty = $args_iter().next().unwrap();
1676 if $container_type == "Slice" && to_c {
1677 // "To C ptr_for_ref" means "return the regular object with is_owned
1678 // set to false", which is totally what we want in a slice if we're about to
1679 // set ty_has_inner.
1682 if let syn::Type::Reference(t) = ty {
1683 if let syn::Type::Path(p) = &*t.elem {
1684 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1686 } else if let syn::Type::Path(p) = ty {
1687 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1691 // Options get a bunch of special handling, since in general we map Option<>al
1692 // types into the same C type as non-Option-wrapped types. This ends up being
1693 // pretty manual here and most of the below special-cases are for Options.
1694 let mut needs_ref_map = false;
1695 let mut only_contained_type = None;
1696 let mut only_contained_has_inner = false;
1697 let mut contains_slice = false;
1699 only_contained_has_inner = ty_has_inner;
1700 let arg = $args_iter().next().unwrap();
1701 if let syn::Type::Reference(t) = arg {
1702 only_contained_type = Some(&*t.elem);
1703 if let syn::Type::Path(_) = &*t.elem {
1705 } else if let syn::Type::Slice(_) = &*t.elem {
1706 contains_slice = true;
1707 } else { return false; }
1708 // If the inner element contains an inner pointer, we will just use that,
1709 // avoiding the need to map elements to references. Otherwise we'll need to
1710 // do an extra mapping step.
1711 needs_ref_map = !only_contained_has_inner;
1713 only_contained_type = Some(&arg);
1717 if let Some((prefix, conversions, suffix, prefix_location)) = container_lookup(&$container_type, is_ref && ty_has_inner, only_contained_type, ident, var) {
1718 assert_eq!(conversions.len(), $args_len);
1719 write!(w, "let mut local_{}{} = ", ident, if !to_c && needs_ref_map {"_base"} else { "" }).unwrap();
1720 if prefix_location == ContainerPrefixLocation::OutsideConv {
1721 var_prefix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
1723 write!(w, "{}{}", prefix, var).unwrap();
1725 for ((pfx, var_name), (idx, ty)) in conversions.iter().zip($args_iter().enumerate()) {
1726 let mut var = std::io::Cursor::new(Vec::new());
1727 write!(&mut var, "{}", var_name).unwrap();
1728 let var_access = String::from_utf8(var.into_inner()).unwrap();
1730 let conv_ty = if needs_ref_map { only_contained_type.as_ref().unwrap() } else { ty };
1732 write!(w, "{} {{ ", pfx).unwrap();
1733 let new_var_name = format!("{}_{}", ident, idx);
1734 let new_var = self.write_conversion_new_var_intern(w, &syn::Ident::new(&new_var_name, Span::call_site()),
1735 &var_access, conv_ty, generics, contains_slice || (is_ref && ty_has_inner), ptr_for_ref, to_c, path_lookup, container_lookup, var_prefix, var_suffix);
1736 if new_var { write!(w, " ").unwrap(); }
1738 if prefix_location == ContainerPrefixLocation::PerConv {
1739 var_prefix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1740 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
1741 write!(w, "Box::into_raw(Box::new(").unwrap();
1744 write!(w, "{}{}", if contains_slice { "local_" } else { "" }, if new_var { new_var_name } else { var_access }).unwrap();
1745 if prefix_location == ContainerPrefixLocation::PerConv {
1746 var_suffix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1747 } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
1748 write!(w, "))").unwrap();
1750 write!(w, " }}").unwrap();
1752 write!(w, "{}", suffix).unwrap();
1753 if prefix_location == ContainerPrefixLocation::OutsideConv {
1754 var_suffix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
1756 write!(w, ";").unwrap();
1757 if !to_c && needs_ref_map {
1758 write!(w, " let mut local_{} = local_{}_base.as_ref()", ident, ident).unwrap();
1760 write!(w, ".map(|a| &a[..])").unwrap();
1762 write!(w, ";").unwrap();
1770 syn::Type::Reference(r) => {
1771 if let syn::Type::Slice(_) = &*r.elem {
1772 self.write_conversion_new_var_intern(w, ident, var, &*r.elem, generics, is_ref, ptr_for_ref, to_c, path_lookup, container_lookup, var_prefix, var_suffix)
1774 self.write_conversion_new_var_intern(w, ident, var, &*r.elem, generics, true, ptr_for_ref, to_c, path_lookup, container_lookup, var_prefix, var_suffix)
1777 syn::Type::Path(p) => {
1778 if p.qself.is_some() {
1781 let resolved_path = self.resolve_path(&p.path, generics);
1782 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1783 return self.write_conversion_new_var_intern(w, ident, var, aliased_type, None, is_ref, ptr_for_ref, to_c, path_lookup, container_lookup, var_prefix, var_suffix);
1785 if self.is_known_container(&resolved_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
1786 if let syn::PathArguments::AngleBracketed(args) = &p.path.segments.iter().next().unwrap().arguments {
1787 convert_container!(resolved_path, args.args.len(), || args.args.iter().map(|arg| {
1788 if let syn::GenericArgument::Type(ty) = arg {
1790 } else { unimplemented!(); }
1792 } else { unimplemented!(); }
1794 if self.is_primitive(&resolved_path) {
1796 } else if let Some(ty_ident) = single_ident_generic_path_to_ident(&p.path) {
1797 if let Some((prefix, suffix)) = path_lookup(&resolved_path, is_ref) {
1798 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
1800 } else if self.types.maybe_resolve_declared(ty_ident).is_some() {
1805 syn::Type::Array(_) => {
1806 // We assume all arrays contain only primitive types.
1807 // This may result in some outputs not compiling.
1810 syn::Type::Slice(s) => {
1811 if let syn::Type::Path(p) = &*s.elem {
1812 let resolved = self.resolve_path(&p.path, generics);
1813 assert!(self.is_primitive(&resolved));
1814 let slice_path = format!("[{}]", resolved);
1815 if let Some((prefix, suffix)) = path_lookup(&slice_path, true) {
1816 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
1819 } else if let syn::Type::Reference(ty) = &*s.elem {
1820 let tyref = [&*ty.elem];
1822 convert_container!("Slice", 1, || tyref.iter().map(|t| *t));
1823 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
1824 } else if let syn::Type::Tuple(t) = &*s.elem {
1825 // When mapping into a temporary new var, we need to own all the underlying objects.
1826 // Thus, we drop any references inside the tuple and convert with non-reference types.
1827 let mut elems = syn::punctuated::Punctuated::new();
1828 for elem in t.elems.iter() {
1829 if let syn::Type::Reference(r) = elem {
1830 elems.push((*r.elem).clone());
1832 elems.push(elem.clone());
1835 let ty = [syn::Type::Tuple(syn::TypeTuple {
1836 paren_token: t.paren_token, elems
1840 convert_container!("Slice", 1, || ty.iter());
1841 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
1842 } else { unimplemented!() }
1844 syn::Type::Tuple(t) => {
1845 if !t.elems.is_empty() {
1846 // We don't (yet) support tuple elements which cannot be converted inline
1847 write!(w, "let (").unwrap();
1848 for idx in 0..t.elems.len() {
1849 if idx != 0 { write!(w, ", ").unwrap(); }
1850 write!(w, "{} orig_{}_{}", if is_ref { "ref" } else { "mut" }, ident, idx).unwrap();
1852 write!(w, ") = {}{}; ", var, if !to_c { ".to_rust()" } else { "" }).unwrap();
1853 // Like other template types, tuples are always mapped as their non-ref
1854 // versions for types which have different ref mappings. Thus, we convert to
1855 // non-ref versions and handle opaque types with inner pointers manually.
1856 for (idx, elem) in t.elems.iter().enumerate() {
1857 if let syn::Type::Path(p) = elem {
1858 let v_name = format!("orig_{}_{}", ident, idx);
1859 let tuple_elem_ident = syn::Ident::new(&v_name, Span::call_site());
1860 if self.write_conversion_new_var_intern(w, &tuple_elem_ident, &v_name, elem, generics,
1861 false, ptr_for_ref, to_c,
1862 path_lookup, container_lookup, var_prefix, var_suffix) {
1863 write!(w, " ").unwrap();
1864 // Opaque types with inner pointers shouldn't ever create new stack
1865 // variables, so we don't handle it and just assert that it doesn't
1867 assert!(!self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)));
1871 write!(w, "let mut local_{} = (", ident).unwrap();
1872 for (idx, elem) in t.elems.iter().enumerate() {
1873 let ty_has_inner = {
1875 // "To C ptr_for_ref" means "return the regular object with
1876 // is_owned set to false", which is totally what we want
1877 // if we're about to set ty_has_inner.
1880 if let syn::Type::Reference(t) = elem {
1881 if let syn::Type::Path(p) = &*t.elem {
1882 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1884 } else if let syn::Type::Path(p) = elem {
1885 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1888 if idx != 0 { write!(w, ", ").unwrap(); }
1889 var_prefix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1890 if is_ref && ty_has_inner {
1891 // For ty_has_inner, the regular var_prefix mapping will take a
1892 // reference, so deref once here to make sure we keep the original ref.
1893 write!(w, "*").unwrap();
1895 write!(w, "orig_{}_{}", ident, idx).unwrap();
1896 if is_ref && !ty_has_inner {
1897 // If we don't have an inner variable's reference to maintain, just
1898 // hope the type is Clonable and use that.
1899 write!(w, ".clone()").unwrap();
1901 var_suffix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1903 write!(w, "){};", if to_c { ".into()" } else { "" }).unwrap();
1907 _ => unimplemented!(),
1911 pub fn write_to_c_conversion_new_var_inner<W: std::io::Write>(&self, w: &mut W, ident: &syn::Ident, var_access: &str, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) -> bool {
1912 self.write_conversion_new_var_intern(w, ident, var_access, t, generics, false, ptr_for_ref, true,
1913 &|a, b| self.to_c_conversion_new_var_from_path(a, b),
1914 &|a, b, c, d, e| self.to_c_conversion_container_new_var(generics, a, b, c, d, e),
1915 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
1916 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_prefix_inner(a, b, c, d, e, f),
1917 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_suffix_inner(a, b, c, d, e, f))
1919 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 {
1920 self.write_to_c_conversion_new_var_inner(w, ident, &format!("{}", ident), t, generics, ptr_for_ref)
1922 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 {
1923 self.write_conversion_new_var_intern(w, ident, &format!("{}", ident), t, generics, false, false, false,
1924 &|a, b| self.from_c_conversion_new_var_from_path(a, b),
1925 &|a, b, c, d, e| self.from_c_conversion_container_new_var(generics, a, b, c, d, e),
1926 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
1927 &|a, b, c, d, e, _f| self.write_from_c_conversion_prefix_inner(a, b, c, d, e),
1928 &|a, b, c, d, e, _f| self.write_from_c_conversion_suffix_inner(a, b, c, d, e))
1931 // ******************************************************
1932 // *** C Container Type Equivalent and alias Printing ***
1933 // ******************************************************
1935 fn write_template_generics<'b, W: std::io::Write>(&mut self, w: &mut W, args: &mut dyn Iterator<Item=&'b syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
1936 for (idx, t) in args.enumerate() {
1938 write!(w, ", ").unwrap();
1940 if let syn::Type::Reference(r_arg) = t {
1941 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
1943 if !self.write_c_type_intern(w, &*r_arg.elem, generics, false, false, false) { return false; }
1945 // While write_c_type_intern, above is correct, we don't want to blindly convert a
1946 // reference to something stupid, so check that the container is either opaque or a
1947 // predefined type (currently only Transaction).
1948 if let syn::Type::Path(p_arg) = &*r_arg.elem {
1949 let resolved = self.resolve_path(&p_arg.path, generics);
1950 assert!(self.crate_types.opaques.get(&resolved).is_some() ||
1951 self.c_type_from_path(&resolved, true, true).is_some(), "Template generics should be opaque or have a predefined mapping");
1952 } else { unimplemented!(); }
1953 } else if let syn::Type::Path(p_arg) = t {
1954 if let Some(resolved) = self.maybe_resolve_path(&p_arg.path, generics) {
1955 if !self.is_primitive(&resolved) {
1956 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
1959 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
1961 if !self.write_c_type_intern(w, t, generics, false, false, false) { return false; }
1963 assert!(!is_ref); // We don't currently support outer reference types for non-primitive inners
1964 if !self.write_c_type_intern(w, t, generics, false, false, false) { return false; }
1969 fn check_create_container(&mut self, mangled_container: String, container_type: &str, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
1970 if !self.crate_types.templates_defined.get(&mangled_container).is_some() {
1971 let mut created_container: Vec<u8> = Vec::new();
1973 if container_type == "Result" {
1974 let mut a_ty: Vec<u8> = Vec::new();
1975 if let syn::Type::Tuple(tup) = args.iter().next().unwrap() {
1976 if tup.elems.is_empty() {
1977 write!(&mut a_ty, "()").unwrap();
1979 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
1982 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
1985 let mut b_ty: Vec<u8> = Vec::new();
1986 if let syn::Type::Tuple(tup) = args.iter().skip(1).next().unwrap() {
1987 if tup.elems.is_empty() {
1988 write!(&mut b_ty, "()").unwrap();
1990 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
1993 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
1996 let ok_str = String::from_utf8(a_ty).unwrap();
1997 let err_str = String::from_utf8(b_ty).unwrap();
1998 let is_clonable = self.is_clonable(&ok_str) && self.is_clonable(&err_str);
1999 write_result_block(&mut created_container, &mangled_container, &ok_str, &err_str, is_clonable);
2001 self.crate_types.clonable_types.insert(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2003 } else if container_type == "Vec" {
2004 let mut a_ty: Vec<u8> = Vec::new();
2005 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2006 let ty = String::from_utf8(a_ty).unwrap();
2007 let is_clonable = self.is_clonable(&ty);
2008 write_vec_block(&mut created_container, &mangled_container, &ty, is_clonable);
2010 self.crate_types.clonable_types.insert(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2012 } else if container_type.ends_with("Tuple") {
2013 let mut tuple_args = Vec::new();
2014 let mut is_clonable = true;
2015 for arg in args.iter() {
2016 let mut ty: Vec<u8> = Vec::new();
2017 if !self.write_template_generics(&mut ty, &mut [arg].iter().map(|t| **t), generics, is_ref) { return false; }
2018 let ty_str = String::from_utf8(ty).unwrap();
2019 if !self.is_clonable(&ty_str) {
2020 is_clonable = false;
2022 tuple_args.push(ty_str);
2024 write_tuple_block(&mut created_container, &mangled_container, &tuple_args, is_clonable);
2026 self.crate_types.clonable_types.insert(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2028 } else if container_type == "Option" {
2029 let mut a_ty: Vec<u8> = Vec::new();
2030 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
2031 let ty = String::from_utf8(a_ty).unwrap();
2032 let is_clonable = self.is_clonable(&ty);
2033 write_option_block(&mut created_container, &mangled_container, &ty, is_clonable);
2035 self.crate_types.clonable_types.insert(Self::generated_container_path().to_owned() + "::" + &mangled_container);
2040 self.crate_types.templates_defined.insert(mangled_container.clone(), true);
2042 self.crate_types.template_file.write(&created_container).unwrap();
2046 fn path_to_generic_args(path: &syn::Path) -> Vec<&syn::Type> {
2047 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().next().unwrap().arguments {
2048 args.args.iter().map(|gen| if let syn::GenericArgument::Type(t) = gen { t } else { unimplemented!() }).collect()
2049 } else { unimplemented!(); }
2051 fn write_c_mangled_container_path_intern<W: std::io::Write>
2052 (&mut 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 {
2053 let mut mangled_type: Vec<u8> = Vec::new();
2054 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2055 write!(w, "C{}_", ident).unwrap();
2056 write!(mangled_type, "C{}_", ident).unwrap();
2057 } else { assert_eq!(args.len(), 1); }
2058 for arg in args.iter() {
2059 macro_rules! write_path {
2060 ($p_arg: expr, $extra_write: expr) => {
2061 if let Some(subtype) = self.maybe_resolve_path(&$p_arg.path, generics) {
2062 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2064 if self.c_type_has_inner_from_path(&subtype) {
2065 if !self.write_c_path_intern(w, &$p_arg.path, generics, is_ref, is_mut, ptr_for_ref) { return false; }
2067 if let Some(arr_ty) = self.is_real_type_array(&subtype) {
2068 if !self.write_c_type_intern(w, &arr_ty, generics, false, true, false) { return false; }
2070 // Option<T> needs to be converted to a *mut T, ie mut ptr-for-ref
2071 if !self.write_c_path_intern(w, &$p_arg.path, generics, true, true, true) { return false; }
2075 write!(w, "{}", $p_arg.path.segments.last().unwrap().ident).unwrap();
2077 } else if self.is_known_container(&subtype, is_ref) || self.is_path_transparent_container(&$p_arg.path, generics, is_ref) {
2078 if !self.write_c_mangled_container_path_intern(w, Self::path_to_generic_args(&$p_arg.path), generics,
2079 &subtype, is_ref, is_mut, ptr_for_ref, true) {
2082 self.write_c_mangled_container_path_intern(&mut mangled_type, Self::path_to_generic_args(&$p_arg.path),
2083 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2084 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2085 self.write_c_mangled_container_path_intern(w2, Self::path_to_generic_args(&$p_arg.path),
2086 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
2089 let id = subtype.rsplitn(2, ':').next().unwrap(); // Get the "Base" name of the resolved type
2090 write!(w, "{}", id).unwrap();
2091 write!(mangled_type, "{}", id).unwrap();
2092 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
2093 write!(w2, "{}", id).unwrap();
2096 } else { return false; }
2099 if let syn::Type::Tuple(tuple) = arg {
2100 if tuple.elems.len() == 0 {
2101 write!(w, "None").unwrap();
2102 write!(mangled_type, "None").unwrap();
2104 let mut mangled_tuple_type: Vec<u8> = Vec::new();
2106 // Figure out what the mangled type should look like. To disambiguate
2107 // ((A, B), C) and (A, B, C) we prefix the generic args with a _ and suffix
2108 // them with a Z. Ideally we wouldn't use Z, but not many special chars are
2109 // available for use in type names.
2110 write!(w, "C{}Tuple_", tuple.elems.len()).unwrap();
2111 write!(mangled_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2112 write!(mangled_tuple_type, "C{}Tuple_", tuple.elems.len()).unwrap();
2113 for elem in tuple.elems.iter() {
2114 if let syn::Type::Path(p) = elem {
2115 write_path!(p, Some(&mut mangled_tuple_type));
2116 } else if let syn::Type::Reference(refelem) = elem {
2117 if let syn::Type::Path(p) = &*refelem.elem {
2118 write_path!(p, Some(&mut mangled_tuple_type));
2119 } else { return false; }
2120 } else { return false; }
2122 write!(w, "Z").unwrap();
2123 write!(mangled_type, "Z").unwrap();
2124 write!(mangled_tuple_type, "Z").unwrap();
2125 if !self.check_create_container(String::from_utf8(mangled_tuple_type).unwrap(),
2126 &format!("{}Tuple", tuple.elems.len()), tuple.elems.iter().collect(), generics, is_ref) {
2130 } else if let syn::Type::Path(p_arg) = arg {
2131 write_path!(p_arg, None);
2132 } else if let syn::Type::Reference(refty) = arg {
2133 if let syn::Type::Path(p_arg) = &*refty.elem {
2134 write_path!(p_arg, None);
2135 } else if let syn::Type::Slice(_) = &*refty.elem {
2136 // write_c_type will actually do exactly what we want here, we just need to
2137 // make it a pointer so that its an option. Note that we cannot always convert
2138 // the Vec-as-slice (ie non-ref types) containers, so sometimes need to be able
2139 // to edit it, hence we use *mut here instead of *const.
2140 if args.len() != 1 { return false; }
2141 write!(w, "*mut ").unwrap();
2142 self.write_c_type(w, arg, None, true);
2143 } else { return false; }
2144 } else if let syn::Type::Array(a) = arg {
2145 if let syn::Type::Path(p_arg) = &*a.elem {
2146 let resolved = self.resolve_path(&p_arg.path, generics);
2147 if !self.is_primitive(&resolved) { return false; }
2148 if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(len), .. }) = &a.len {
2149 if self.c_type_from_path(&format!("[{}; {}]", resolved, len.base10_digits()), is_ref, ptr_for_ref).is_none() { return false; }
2150 write!(w, "_{}{}", resolved, len.base10_digits()).unwrap();
2151 write!(mangled_type, "_{}{}", resolved, len.base10_digits()).unwrap();
2152 } else { return false; }
2153 } else { return false; }
2154 } else { return false; }
2156 if self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) { return true; }
2157 // Push the "end of type" Z
2158 write!(w, "Z").unwrap();
2159 write!(mangled_type, "Z").unwrap();
2161 // Make sure the type is actually defined:
2162 self.check_create_container(String::from_utf8(mangled_type).unwrap(), ident, args, generics, is_ref)
2164 fn write_c_mangled_container_path<W: std::io::Write>(&mut self, w: &mut W, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, ident: &str, is_ref: bool, is_mut: bool, ptr_for_ref: bool) -> bool {
2165 if !self.is_transparent_container(ident, is_ref, args.iter().map(|a| *a)) {
2166 write!(w, "{}::", Self::generated_container_path()).unwrap();
2168 self.write_c_mangled_container_path_intern(w, args, generics, ident, is_ref, is_mut, ptr_for_ref, false)
2171 // **********************************
2172 // *** C Type Equivalent Printing ***
2173 // **********************************
2175 fn write_c_path_intern<W: std::io::Write>(&self, w: &mut W, path: &syn::Path, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool) -> bool {
2176 let full_path = match self.maybe_resolve_path(&path, generics) {
2177 Some(path) => path, None => return false };
2178 if let Some(c_type) = self.c_type_from_path(&full_path, is_ref, ptr_for_ref) {
2179 write!(w, "{}", c_type).unwrap();
2181 } else if self.crate_types.traits.get(&full_path).is_some() {
2182 if is_ref && ptr_for_ref {
2183 write!(w, "*{} crate::{}", if is_mut { "mut" } else { "const" }, full_path).unwrap();
2185 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2187 write!(w, "crate::{}", full_path).unwrap();
2190 } else if self.crate_types.opaques.get(&full_path).is_some() || self.crate_types.mirrored_enums.get(&full_path).is_some() {
2191 if is_ref && ptr_for_ref {
2192 // ptr_for_ref implies we're returning the object, which we can't really do for
2193 // opaque or mirrored types without box'ing them, which is quite a waste, so return
2194 // the actual object itself (for opaque types we'll set the pointer to the actual
2195 // type and note that its a reference).
2196 write!(w, "crate::{}", full_path).unwrap();
2198 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2200 write!(w, "crate::{}", full_path).unwrap();
2207 fn write_c_type_intern<W: std::io::Write>(&mut self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool) -> bool {
2209 syn::Type::Path(p) => {
2210 if p.qself.is_some() {
2213 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
2214 if self.is_known_container(&full_path, is_ref) || self.is_path_transparent_container(&p.path, generics, is_ref) {
2215 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);
2217 if let Some(aliased_type) = self.crate_types.type_aliases.get(&full_path).cloned() {
2218 return self.write_c_type_intern(w, &aliased_type, None, is_ref, is_mut, ptr_for_ref);
2221 self.write_c_path_intern(w, &p.path, generics, is_ref, is_mut, ptr_for_ref)
2223 syn::Type::Reference(r) => {
2224 self.write_c_type_intern(w, &*r.elem, generics, true, r.mutability.is_some(), ptr_for_ref)
2226 syn::Type::Array(a) => {
2227 if is_ref && is_mut {
2228 write!(w, "*mut [").unwrap();
2229 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2231 write!(w, "*const [").unwrap();
2232 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2234 let mut typecheck = Vec::new();
2235 if !self.write_c_type_intern(&mut typecheck, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2236 if typecheck[..] != ['u' as u8, '8' as u8] { return false; }
2238 if let syn::Expr::Lit(l) = &a.len {
2239 if let syn::Lit::Int(i) = &l.lit {
2241 if let Some(ty) = self.c_type_from_path(&format!("[u8; {}]", i.base10_digits()), false, ptr_for_ref) {
2242 write!(w, "{}", ty).unwrap();
2246 write!(w, "; {}]", i).unwrap();
2252 syn::Type::Slice(s) => {
2253 if !is_ref || is_mut { return false; }
2254 if let syn::Type::Path(p) = &*s.elem {
2255 let resolved = self.resolve_path(&p.path, generics);
2256 if self.is_primitive(&resolved) {
2257 write!(w, "{}::{}slice", Self::container_templ_path(), resolved).unwrap();
2260 } else if let syn::Type::Reference(r) = &*s.elem {
2261 if let syn::Type::Path(p) = &*r.elem {
2262 // Slices with "real types" inside are mapped as the equivalent non-ref Vec
2263 let resolved = self.resolve_path(&p.path, generics);
2264 let mangled_container = if let Some(ident) = self.crate_types.opaques.get(&resolved) {
2265 format!("CVec_{}Z", ident)
2266 } else if let Some(en) = self.crate_types.mirrored_enums.get(&resolved) {
2267 format!("CVec_{}Z", en.ident)
2268 } else if let Some(id) = p.path.get_ident() {
2269 format!("CVec_{}Z", id)
2270 } else { return false; };
2271 write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
2272 self.check_create_container(mangled_container, "Vec", vec![&*r.elem], generics, false)
2274 } else if let syn::Type::Tuple(_) = &*s.elem {
2275 let mut args = syn::punctuated::Punctuated::new();
2276 args.push(syn::GenericArgument::Type((*s.elem).clone()));
2277 let mut segments = syn::punctuated::Punctuated::new();
2278 segments.push(syn::PathSegment {
2279 ident: syn::Ident::new("Vec", Span::call_site()),
2280 arguments: syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
2281 colon2_token: None, lt_token: syn::Token![<](Span::call_site()), args, gt_token: syn::Token![>](Span::call_site()),
2284 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)
2287 syn::Type::Tuple(t) => {
2288 if t.elems.len() == 0 {
2291 self.write_c_mangled_container_path(w, t.elems.iter().collect(), generics,
2292 &format!("{}Tuple", t.elems.len()), is_ref, is_mut, ptr_for_ref)
2298 pub fn write_c_type<W: std::io::Write>(&mut self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) {
2299 assert!(self.write_c_type_intern(w, t, generics, false, false, ptr_for_ref));
2301 pub fn understood_c_path(&mut self, p: &syn::Path) -> bool {
2302 if p.leading_colon.is_some() { return false; }
2303 self.write_c_path_intern(&mut std::io::sink(), p, None, false, false, false)
2305 pub fn understood_c_type(&mut self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
2306 self.write_c_type_intern(&mut std::io::sink(), t, generics, false, false, false)