1 use std::collections::{HashMap, HashSet};
8 use proc_macro2::{TokenTree, Span};
10 // The following utils are used purely to build our known types maps - they break down all the
11 // types we need to resolve to include the given object, and no more.
13 pub fn first_seg_self<'a>(t: &'a syn::Type) -> Option<impl Iterator<Item=&syn::PathSegment> + 'a> {
15 syn::Type::Path(p) => {
16 if p.qself.is_some() || p.path.leading_colon.is_some() {
19 let mut segs = p.path.segments.iter();
20 let ty = segs.next().unwrap();
21 if !ty.arguments.is_empty() { return None; }
22 if format!("{}", ty.ident) == "Self" {
30 pub fn get_single_remaining_path_seg<'a, I: Iterator<Item=&'a syn::PathSegment>>(segs: &mut I) -> Option<&'a syn::Ident> {
31 if let Some(ty) = segs.next() {
32 if !ty.arguments.is_empty() { unimplemented!(); }
33 if segs.next().is_some() { return None; }
38 pub fn single_ident_generic_path_to_ident(p: &syn::Path) -> Option<&syn::Ident> {
39 if p.segments.len() == 1 {
40 Some(&p.segments.iter().next().unwrap().ident)
44 pub fn path_matches_nongeneric(p: &syn::Path, exp: &[&str]) -> bool {
45 if p.segments.len() != exp.len() { return false; }
46 for (seg, e) in p.segments.iter().zip(exp.iter()) {
47 if seg.arguments != syn::PathArguments::None { return false; }
48 if &format!("{}", seg.ident) != *e { return false; }
53 #[derive(Debug, PartialEq)]
54 pub enum ExportStatus {
59 /// Gets the ExportStatus of an object (struct, fn, etc) given its attributes.
60 pub fn export_status(attrs: &[syn::Attribute]) -> ExportStatus {
61 for attr in attrs.iter() {
62 let tokens_clone = attr.tokens.clone();
63 let mut token_iter = tokens_clone.into_iter();
64 if let Some(token) = token_iter.next() {
66 TokenTree::Punct(c) if c.as_char() == '=' => {
67 // Really not sure where syn gets '=' from here -
68 // it somehow represents '///' or '//!'
70 TokenTree::Group(g) => {
71 if format!("{}", single_ident_generic_path_to_ident(&attr.path).unwrap()) == "cfg" {
72 let mut iter = g.stream().into_iter();
73 if let TokenTree::Ident(i) = iter.next().unwrap() {
75 // #[cfg(any(test, feature = ""))]
76 if let TokenTree::Group(g) = iter.next().unwrap() {
77 if let TokenTree::Ident(i) = g.stream().into_iter().next().unwrap() {
78 if i == "test" || i == "feature" {
79 // If its cfg(feature(...)) we assume its test-only
80 return ExportStatus::TestOnly;
84 } else if i == "test" || i == "feature" {
85 // If its cfg(feature(...)) we assume its test-only
86 return ExportStatus::TestOnly;
90 continue; // eg #[derive()]
92 _ => unimplemented!(),
95 match token_iter.next().unwrap() {
96 TokenTree::Literal(lit) => {
97 let line = format!("{}", lit);
98 if line.contains("(C-not exported)") {
99 return ExportStatus::NoExport;
102 _ => unimplemented!(),
108 pub fn assert_simple_bound(bound: &syn::TraitBound) {
109 if bound.paren_token.is_some() || bound.lifetimes.is_some() { unimplemented!(); }
110 if let syn::TraitBoundModifier::Maybe(_) = bound.modifier { unimplemented!(); }
113 /// Returns true if the enum will be mapped as an opaue (ie struct with a pointer to the underlying
114 /// type), otherwise it is mapped into a transparent, C-compatible version of itself.
115 pub fn is_enum_opaque(e: &syn::ItemEnum) -> bool {
116 for var in e.variants.iter() {
117 if let syn::Fields::Unit = var.fields {
118 } else if let syn::Fields::Named(fields) = &var.fields {
119 for field in fields.named.iter() {
120 match export_status(&field.attrs) {
121 ExportStatus::Export|ExportStatus::TestOnly => {},
122 ExportStatus::NoExport => return true,
132 /// A stack of sets of generic resolutions.
134 /// This tracks the template parameters for a function, struct, or trait, allowing resolution into
135 /// a concrete type. By pushing a new context onto the stack, this can track a function's template
136 /// parameters inside of a generic struct or trait.
138 /// It maps both direct types as well as Deref<Target = X>, mapping them via the provided
139 /// TypeResolver's resolve_path function (ie traits map to the concrete jump table, structs to the
140 /// concrete C container struct, etc).
141 pub struct GenericTypes<'a> {
142 typed_generics: Vec<HashMap<&'a syn::Ident, (String, Option<&'a syn::Path>)>>,
144 impl<'a> GenericTypes<'a> {
145 pub fn new() -> Self {
146 Self { typed_generics: vec![HashMap::new()], }
149 /// push a new context onto the stack, allowing for a new set of generics to be learned which
150 /// will override any lower contexts, but which will still fall back to resoltion via lower
152 pub fn push_ctx(&mut self) {
153 self.typed_generics.push(HashMap::new());
155 /// pop the latest context off the stack.
156 pub fn pop_ctx(&mut self) {
157 self.typed_generics.pop();
160 /// Learn the generics in generics in the current context, given a TypeResolver.
161 pub fn learn_generics<'b, 'c>(&mut self, generics: &'a syn::Generics, types: &'b TypeResolver<'a, 'c>) -> bool {
162 // First learn simple generics...
163 for generic in generics.params.iter() {
165 syn::GenericParam::Type(type_param) => {
166 let mut non_lifetimes_processed = false;
167 for bound in type_param.bounds.iter() {
168 if let syn::TypeParamBound::Trait(trait_bound) = bound {
169 if let Some(ident) = single_ident_generic_path_to_ident(&trait_bound.path) {
170 match &format!("{}", ident) as &str { "Send" => continue, "Sync" => continue, _ => {} }
172 if path_matches_nongeneric(&trait_bound.path, &["core", "clone", "Clone"]) { continue; }
174 assert_simple_bound(&trait_bound);
175 if let Some(mut path) = types.maybe_resolve_path(&trait_bound.path, None) {
176 if types.skip_path(&path) { continue; }
177 if non_lifetimes_processed { return false; }
178 non_lifetimes_processed = true;
179 let new_ident = if path != "std::ops::Deref" {
180 path = "crate::".to_string() + &path;
181 Some(&trait_bound.path)
183 self.typed_generics.last_mut().unwrap().insert(&type_param.ident, (path, new_ident));
184 } else { return false; }
191 // Then find generics where we are required to pass a Deref<Target=X> and pretend its just X.
192 if let Some(wh) = &generics.where_clause {
193 for pred in wh.predicates.iter() {
194 if let syn::WherePredicate::Type(t) = pred {
195 if let syn::Type::Path(p) = &t.bounded_ty {
196 if p.qself.is_some() { return false; }
197 if p.path.leading_colon.is_some() { return false; }
198 let mut p_iter = p.path.segments.iter();
199 if let Some(gen) = self.typed_generics.last_mut().unwrap().get_mut(&p_iter.next().unwrap().ident) {
200 if gen.0 != "std::ops::Deref" { return false; }
201 if &format!("{}", p_iter.next().unwrap().ident) != "Target" { return false; }
203 let mut non_lifetimes_processed = false;
204 for bound in t.bounds.iter() {
205 if let syn::TypeParamBound::Trait(trait_bound) = bound {
206 if non_lifetimes_processed { return false; }
207 non_lifetimes_processed = true;
208 assert_simple_bound(&trait_bound);
209 *gen = ("crate::".to_string() + &types.resolve_path(&trait_bound.path, None),
210 Some(&trait_bound.path));
213 } else { return false; }
214 } else { return false; }
218 for (_, (_, ident)) in self.typed_generics.last().unwrap().iter() {
219 if ident.is_none() { return false; }
224 /// Learn the associated types from the trait in the current context.
225 pub fn learn_associated_types<'b, 'c>(&mut self, t: &'a syn::ItemTrait, types: &'b TypeResolver<'a, 'c>) {
226 for item in t.items.iter() {
228 &syn::TraitItem::Type(ref t) => {
229 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
230 let mut bounds_iter = t.bounds.iter();
231 match bounds_iter.next().unwrap() {
232 syn::TypeParamBound::Trait(tr) => {
233 assert_simple_bound(&tr);
234 if let Some(mut path) = types.maybe_resolve_path(&tr.path, None) {
235 if types.skip_path(&path) { continue; }
236 // In general we handle Deref<Target=X> as if it were just X (and
237 // implement Deref<Target=Self> for relevant types). We don't
238 // bother to implement it for associated types, however, so we just
239 // ignore such bounds.
240 let new_ident = if path != "std::ops::Deref" {
241 path = "crate::".to_string() + &path;
244 self.typed_generics.last_mut().unwrap().insert(&t.ident, (path, new_ident));
245 } else { unimplemented!(); }
247 _ => unimplemented!(),
249 if bounds_iter.next().is_some() { unimplemented!(); }
256 /// Attempt to resolve an Ident as a generic parameter and return the full path.
257 pub fn maybe_resolve_ident<'b>(&'b self, ident: &syn::Ident) -> Option<&'b String> {
258 for gen in self.typed_generics.iter().rev() {
259 if let Some(res) = gen.get(ident).map(|(a, _)| a) {
265 /// Attempt to resolve a Path as a generic parameter and return the full path. as both a string
267 pub fn maybe_resolve_path<'b>(&'b self, path: &syn::Path) -> Option<(&'b String, &'a syn::Path)> {
268 if let Some(ident) = path.get_ident() {
269 for gen in self.typed_generics.iter().rev() {
270 if let Some(res) = gen.get(ident).map(|(a, b)| (a, b.unwrap())) {
275 // Associated types are usually specified as "Self::Generic", so we check for that
277 let mut it = path.segments.iter();
278 if path.segments.len() == 2 && format!("{}", it.next().unwrap().ident) == "Self" {
279 let ident = &it.next().unwrap().ident;
280 for gen in self.typed_generics.iter().rev() {
281 if let Some(res) = gen.get(ident).map(|(a, b)| (a, b.unwrap())) {
291 #[derive(Clone, PartialEq)]
292 // The type of declaration and the object itself
293 pub enum DeclType<'a> {
295 Trait(&'a syn::ItemTrait),
301 pub struct ImportResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
302 module_path: &'mod_lifetime str,
303 imports: HashMap<syn::Ident, (String, syn::Path)>,
304 declared: HashMap<syn::Ident, DeclType<'crate_lft>>,
305 priv_modules: HashSet<syn::Ident>,
307 impl<'mod_lifetime, 'crate_lft: 'mod_lifetime> ImportResolver<'mod_lifetime, 'crate_lft> {
308 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>) {
310 syn::UseTree::Path(p) => {
311 let new_path = format!("{}{}::", partial_path, p.ident);
312 path.push(syn::PathSegment { ident: p.ident.clone(), arguments: syn::PathArguments::None });
313 Self::process_use_intern(imports, &p.tree, &new_path, path);
315 syn::UseTree::Name(n) => {
316 let full_path = format!("{}{}", partial_path, n.ident);
317 path.push(syn::PathSegment { ident: n.ident.clone(), arguments: syn::PathArguments::None });
318 imports.insert(n.ident.clone(), (full_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
320 syn::UseTree::Group(g) => {
321 for i in g.items.iter() {
322 Self::process_use_intern(imports, i, partial_path, path.clone());
325 syn::UseTree::Rename(r) => {
326 let full_path = format!("{}{}", partial_path, r.ident);
327 path.push(syn::PathSegment { ident: r.ident.clone(), arguments: syn::PathArguments::None });
328 imports.insert(r.rename.clone(), (full_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
330 syn::UseTree::Glob(_) => {
331 eprintln!("Ignoring * use for {} - this may result in resolution failures", partial_path);
336 fn process_use(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::ItemUse) {
337 if let syn::Visibility::Public(_) = u.vis {
338 // We actually only use these for #[cfg(fuzztarget)]
339 eprintln!("Ignoring pub(use) tree!");
342 if u.leading_colon.is_some() { eprintln!("Ignoring leading-colon use!"); return; }
343 Self::process_use_intern(imports, &u.tree, "", syn::punctuated::Punctuated::new());
346 fn insert_primitive(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, id: &str) {
347 let ident = syn::Ident::new(id, Span::call_site());
348 let mut path = syn::punctuated::Punctuated::new();
349 path.push(syn::PathSegment { ident: ident.clone(), arguments: syn::PathArguments::None });
350 imports.insert(ident, (id.to_owned(), syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
353 pub fn new(module_path: &'mod_lifetime str, contents: &'crate_lft [syn::Item]) -> Self {
354 let mut imports = HashMap::new();
355 // Add primitives to the "imports" list:
356 Self::insert_primitive(&mut imports, "bool");
357 Self::insert_primitive(&mut imports, "u64");
358 Self::insert_primitive(&mut imports, "u32");
359 Self::insert_primitive(&mut imports, "u16");
360 Self::insert_primitive(&mut imports, "u8");
361 Self::insert_primitive(&mut imports, "usize");
362 Self::insert_primitive(&mut imports, "str");
363 Self::insert_primitive(&mut imports, "String");
365 // These are here to allow us to print native Rust types in trait fn impls even if we don't
367 Self::insert_primitive(&mut imports, "Result");
368 Self::insert_primitive(&mut imports, "Vec");
369 Self::insert_primitive(&mut imports, "Option");
371 let mut declared = HashMap::new();
372 let mut priv_modules = HashSet::new();
374 for item in contents.iter() {
376 syn::Item::Use(u) => Self::process_use(&mut imports, &u),
377 syn::Item::Struct(s) => {
378 if let syn::Visibility::Public(_) = s.vis {
379 match export_status(&s.attrs) {
380 ExportStatus::Export => { declared.insert(s.ident.clone(), DeclType::StructImported); },
381 ExportStatus::NoExport => { declared.insert(s.ident.clone(), DeclType::StructIgnored); },
382 ExportStatus::TestOnly => continue,
386 syn::Item::Type(t) if export_status(&t.attrs) == ExportStatus::Export => {
387 if let syn::Visibility::Public(_) = t.vis {
388 let mut process_alias = true;
389 for tok in t.generics.params.iter() {
390 if let syn::GenericParam::Lifetime(_) = tok {}
391 else { process_alias = false; }
395 syn::Type::Path(_) => { declared.insert(t.ident.clone(), DeclType::StructImported); },
401 syn::Item::Enum(e) => {
402 if let syn::Visibility::Public(_) = e.vis {
403 match export_status(&e.attrs) {
404 ExportStatus::Export if is_enum_opaque(e) => { declared.insert(e.ident.clone(), DeclType::EnumIgnored); },
405 ExportStatus::Export => { declared.insert(e.ident.clone(), DeclType::MirroredEnum); },
410 syn::Item::Trait(t) if export_status(&t.attrs) == ExportStatus::Export => {
411 if let syn::Visibility::Public(_) = t.vis {
412 declared.insert(t.ident.clone(), DeclType::Trait(t));
415 syn::Item::Mod(m) => {
416 priv_modules.insert(m.ident.clone());
422 Self { module_path, imports, declared, priv_modules }
425 pub fn get_declared_type(&self, ident: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
426 self.declared.get(ident)
429 pub fn maybe_resolve_declared(&self, id: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
430 self.declared.get(id)
433 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
434 if let Some((imp, _)) = self.imports.get(id) {
436 } else if self.declared.get(id).is_some() {
437 Some(self.module_path.to_string() + "::" + &format!("{}", id))
441 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
442 if let Some((imp, _)) = self.imports.get(id) {
444 } else if let Some(decl_type) = self.declared.get(id) {
446 DeclType::StructIgnored => None,
447 _ => Some(self.module_path.to_string() + "::" + &format!("{}", id)),
452 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
453 let p = if let Some(gen_types) = generics {
454 if let Some((_, synpath)) = gen_types.maybe_resolve_path(p_arg) {
459 if p.leading_colon.is_some() {
460 Some(p.segments.iter().enumerate().map(|(idx, seg)| {
461 format!("{}{}", if idx == 0 { "" } else { "::" }, seg.ident)
463 } else if let Some(id) = p.get_ident() {
464 self.maybe_resolve_ident(id)
466 if p.segments.len() == 1 {
467 let seg = p.segments.iter().next().unwrap();
468 return self.maybe_resolve_ident(&seg.ident);
470 let mut seg_iter = p.segments.iter();
471 let first_seg = seg_iter.next().unwrap();
472 let remaining: String = seg_iter.map(|seg| {
473 format!("::{}", seg.ident)
475 if let Some((imp, _)) = self.imports.get(&first_seg.ident) {
477 Some(imp.clone() + &remaining)
481 } else if let Some(_) = self.priv_modules.get(&first_seg.ident) {
482 Some(format!("{}::{}{}", self.module_path, first_seg.ident, remaining))
487 /// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern)
488 pub fn resolve_imported_refs(&self, mut ty: syn::Type) -> syn::Type {
490 syn::Type::Path(p) => {
491 if let Some(ident) = p.path.get_ident() {
492 if let Some((_, newpath)) = self.imports.get(ident) {
493 p.path = newpath.clone();
495 } else { unimplemented!(); }
497 syn::Type::Reference(r) => {
498 r.elem = Box::new(self.resolve_imported_refs((*r.elem).clone()));
500 syn::Type::Slice(s) => {
501 s.elem = Box::new(self.resolve_imported_refs((*s.elem).clone()));
503 syn::Type::Tuple(t) => {
504 for e in t.elems.iter_mut() {
505 *e = self.resolve_imported_refs(e.clone());
508 _ => unimplemented!(),
514 // templates_defined is walked to write the C++ header, so if we use the default hashing it get
515 // reordered on each genbindings run. Instead, we use SipHasher (which defaults to 0-keys) so that
516 // the sorting is stable across runs. It is deprecated, but the "replacement" doesn't actually
517 // accomplish the same goals, so we just ignore it.
519 pub type NonRandomHash = hash::BuildHasherDefault<hash::SipHasher>;
521 /// Top-level struct tracking everything which has been defined while walking the crate.
522 pub struct CrateTypes<'a> {
523 /// This may contain structs or enums, but only when either is mapped as
524 /// struct X { inner: *mut originalX, .. }
525 pub opaques: HashMap<String, &'a syn::Ident>,
526 /// Enums which are mapped as C enums with conversion functions
527 pub mirrored_enums: HashMap<String, &'a syn::ItemEnum>,
528 /// Traits which are mapped as a pointer + jump table
529 pub traits: HashMap<String, &'a syn::ItemTrait>,
530 /// Aliases from paths to some other Type
531 pub type_aliases: HashMap<String, syn::Type>,
532 /// Value is an alias to Key (maybe with some generics)
533 pub reverse_alias_map: HashMap<String, Vec<(syn::Path, syn::PathArguments)>>,
534 /// Template continer types defined, map from mangled type name -> whether a destructor fn
537 /// This is used at the end of processing to make C++ wrapper classes
538 pub templates_defined: HashMap<String, bool, NonRandomHash>,
539 /// The output file for any created template container types, written to as we find new
540 /// template containers which need to be defined.
541 pub template_file: &'a mut File,
542 /// Set of containers which are clonable
543 pub clonable_types: HashSet<String>,
545 pub trait_impls: HashMap<String, Vec<String>>,
548 /// A struct which tracks resolving rust types into C-mapped equivalents, exists for one specific
549 /// module but contains a reference to the overall CrateTypes tracking.
550 pub struct TypeResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
551 pub orig_crate: &'mod_lifetime str,
552 pub module_path: &'mod_lifetime str,
553 pub crate_types: &'mod_lifetime mut CrateTypes<'crate_lft>,
554 types: ImportResolver<'mod_lifetime, 'crate_lft>,
557 /// Returned by write_empty_rust_val_check_suffix to indicate what type of dereferencing needs to
558 /// happen to get the inner value of a generic.
559 enum EmptyValExpectedTy {
560 /// A type which has a flag for being empty (eg an array where we treat all-0s as empty).
562 /// A pointer that we want to dereference and move out of.
564 /// A pointer which we want to convert to a reference.
568 impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
569 pub fn new(orig_crate: &'a str, module_path: &'a str, types: ImportResolver<'a, 'c>, crate_types: &'a mut CrateTypes<'c>) -> Self {
570 Self { orig_crate, module_path, types, crate_types }
573 // *************************************************
574 // *** Well know type and conversion definitions ***
575 // *************************************************
577 /// Returns true we if can just skip passing this to C entirely
578 fn skip_path(&self, full_path: &str) -> bool {
579 full_path == "bitcoin::secp256k1::Secp256k1" ||
580 full_path == "bitcoin::secp256k1::Signing" ||
581 full_path == "bitcoin::secp256k1::Verification"
583 /// Returns true we if can just skip passing this to C entirely
584 fn no_arg_path_to_rust(&self, full_path: &str) -> &str {
585 if full_path == "bitcoin::secp256k1::Secp256k1" {
586 "&bitcoin::secp256k1::Secp256k1::new()"
587 } else { unimplemented!(); }
590 /// Returns true if the object is a primitive and is mapped as-is with no conversion
592 pub fn is_primitive(&self, full_path: &str) -> bool {
603 pub fn is_clonable(&self, ty: &str) -> bool {
604 if self.crate_types.clonable_types.contains(ty) { return true; }
605 if self.is_primitive(ty) { return true; }
608 "crate::c_types::Signature" => true,
609 "crate::c_types::TxOut" => true,
613 /// Gets the C-mapped type for types which are outside of the crate, or which are manually
614 /// ignored by for some reason need mapping anyway.
615 fn c_type_from_path<'b>(&self, full_path: &'b str, is_ref: bool, _ptr_for_ref: bool) -> Option<&'b str> {
616 if self.is_primitive(full_path) {
617 return Some(full_path);
620 "Result" => Some("crate::c_types::derived::CResult"),
621 "Vec" if !is_ref => Some("crate::c_types::derived::CVec"),
622 "Option" => Some(""),
624 // Note that no !is_ref types can map to an array because Rust and C's call semantics
625 // for arrays are different (https://github.com/eqrion/cbindgen/issues/528)
627 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
628 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes"),
629 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes"),
630 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes"),
631 "[u8; 3]" if !is_ref => Some("crate::c_types::ThreeBytes"), // Used for RGB values
633 "str" if is_ref => Some("crate::c_types::Str"),
634 "String" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
635 "String" if is_ref => Some("crate::c_types::Str"),
637 "std::time::Duration" => Some("u64"),
639 "bitcoin::secp256k1::key::PublicKey" => Some("crate::c_types::PublicKey"),
640 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature"),
641 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some("*const [u8; 32]"),
642 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some("crate::c_types::SecretKey"),
643 "bitcoin::secp256k1::Error" if !is_ref => Some("crate::c_types::Secp256k1Error"),
644 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice"),
645 "bitcoin::blockdata::script::Script" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
646 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::chain::transaction::OutPoint"),
647 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction"),
648 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut"),
649 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network"),
650 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("*const [u8; 80]"),
651 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice"),
653 // Newtypes that we just expose in their original form.
654 "bitcoin::hash_types::Txid" if is_ref => Some("*const [u8; 32]"),
655 "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
656 "bitcoin::hash_types::BlockHash" if is_ref => Some("*const [u8; 32]"),
657 "bitcoin::hash_types::BlockHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
658 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
659 "ln::channelmanager::PaymentHash" if is_ref => Some("*const [u8; 32]"),
660 "ln::channelmanager::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
661 "ln::channelmanager::PaymentPreimage" if is_ref => Some("*const [u8; 32]"),
662 "ln::channelmanager::PaymentPreimage" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
663 "ln::channelmanager::PaymentSecret" if is_ref => Some("crate::c_types::ThirtyTwoBytes"),
664 "ln::channelmanager::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
666 // Override the default since Records contain an fmt with a lifetime:
667 "util::logger::Record" => Some("*const std::os::raw::c_char"),
673 fn from_c_conversion_new_var_from_path<'b>(&self, _full_path: &str, _is_ref: bool) -> Option<(&'b str, &'b str)> {
676 fn from_c_conversion_prefix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
677 if self.is_primitive(full_path) {
678 return Some("".to_owned());
681 "Vec" if !is_ref => Some("local_"),
682 "Result" if !is_ref => Some("local_"),
683 "Option" if is_ref => Some("&local_"),
684 "Option" => Some("local_"),
686 "[u8; 32]" if is_ref => Some("unsafe { &*"),
687 "[u8; 32]" if !is_ref => Some(""),
688 "[u8; 16]" if !is_ref => Some(""),
689 "[u8; 10]" if !is_ref => Some(""),
690 "[u8; 4]" if !is_ref => Some(""),
691 "[u8; 3]" if !is_ref => Some(""),
693 "[u8]" if is_ref => Some(""),
694 "[usize]" if is_ref => Some(""),
696 "str" if is_ref => Some(""),
697 "String" if !is_ref => Some("String::from_utf8("),
698 // Note that we'll panic for String if is_ref, as we only have non-owned memory, we
699 // cannot create a &String.
701 "std::time::Duration" => Some("std::time::Duration::from_secs("),
703 "bitcoin::secp256k1::key::PublicKey" if is_ref => Some("&"),
704 "bitcoin::secp256k1::key::PublicKey" => Some(""),
705 "bitcoin::secp256k1::Signature" if is_ref => Some("&"),
706 "bitcoin::secp256k1::Signature" => Some(""),
707 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some("&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *"),
708 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some(""),
709 "bitcoin::blockdata::script::Script" if is_ref => Some("&::bitcoin::blockdata::script::Script::from(Vec::from("),
710 "bitcoin::blockdata::script::Script" if !is_ref => Some("::bitcoin::blockdata::script::Script::from("),
711 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some("&"),
712 "bitcoin::blockdata::transaction::Transaction" => Some(""),
713 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(""),
714 "bitcoin::network::constants::Network" => Some(""),
715 "bitcoin::blockdata::block::BlockHeader" => Some("&::bitcoin::consensus::encode::deserialize(unsafe { &*"),
716 "bitcoin::blockdata::block::Block" if is_ref => Some("&::bitcoin::consensus::encode::deserialize("),
718 // Newtypes that we just expose in their original form.
719 "bitcoin::hash_types::Txid" if is_ref => Some("&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*"),
720 "bitcoin::hash_types::Txid" if !is_ref => Some("::bitcoin::hash_types::Txid::from_slice(&"),
721 "bitcoin::hash_types::BlockHash" => Some("::bitcoin::hash_types::BlockHash::from_slice(&"),
722 "ln::channelmanager::PaymentHash" if !is_ref => Some("::lightning::ln::channelmanager::PaymentHash("),
723 "ln::channelmanager::PaymentHash" if is_ref => Some("&::lightning::ln::channelmanager::PaymentHash(unsafe { *"),
724 "ln::channelmanager::PaymentPreimage" if !is_ref => Some("::lightning::ln::channelmanager::PaymentPreimage("),
725 "ln::channelmanager::PaymentPreimage" if is_ref => Some("&::lightning::ln::channelmanager::PaymentPreimage(unsafe { *"),
726 "ln::channelmanager::PaymentSecret" => Some("::lightning::ln::channelmanager::PaymentSecret("),
728 // List of traits we map (possibly during processing of other files):
729 "crate::util::logger::Logger" => Some(""),
732 }.map(|s| s.to_owned())
734 fn from_c_conversion_suffix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
735 if self.is_primitive(full_path) {
736 return Some("".to_owned());
739 "Vec" if !is_ref => Some(""),
740 "Option" => Some(""),
741 "Result" if !is_ref => Some(""),
743 "[u8; 32]" if is_ref => Some("}"),
744 "[u8; 32]" if !is_ref => Some(".data"),
745 "[u8; 16]" if !is_ref => Some(".data"),
746 "[u8; 10]" if !is_ref => Some(".data"),
747 "[u8; 4]" if !is_ref => Some(".data"),
748 "[u8; 3]" if !is_ref => Some(".data"),
750 "[u8]" if is_ref => Some(".to_slice()"),
751 "[usize]" if is_ref => Some(".to_slice()"),
753 "str" if is_ref => Some(".into()"),
754 "String" if !is_ref => Some(".into_rust()).unwrap()"),
756 "std::time::Duration" => Some(")"),
758 "bitcoin::secp256k1::key::PublicKey" => Some(".into_rust()"),
759 "bitcoin::secp256k1::Signature" => Some(".into_rust()"),
760 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some(".into_rust()"),
761 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some("}[..]).unwrap()"),
762 "bitcoin::blockdata::script::Script" if is_ref => Some(".to_slice()))"),
763 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_rust())"),
764 "bitcoin::blockdata::transaction::Transaction" => Some(".into_bitcoin()"),
765 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(".into_rust()"),
766 "bitcoin::network::constants::Network" => Some(".into_bitcoin()"),
767 "bitcoin::blockdata::block::BlockHeader" => Some(" }).unwrap()"),
768 "bitcoin::blockdata::block::Block" => Some(".to_slice()).unwrap()"),
770 // Newtypes that we just expose in their original form.
771 "bitcoin::hash_types::Txid" if is_ref => Some(" }[..]).unwrap()"),
772 "bitcoin::hash_types::Txid" => Some(".data[..]).unwrap()"),
773 "bitcoin::hash_types::BlockHash" if !is_ref => Some(".data[..]).unwrap()"),
774 "ln::channelmanager::PaymentHash" if !is_ref => Some(".data)"),
775 "ln::channelmanager::PaymentHash" if is_ref => Some(" })"),
776 "ln::channelmanager::PaymentPreimage" if !is_ref => Some(".data)"),
777 "ln::channelmanager::PaymentPreimage" if is_ref => Some(" })"),
778 "ln::channelmanager::PaymentSecret" => Some(".data)"),
780 // List of traits we map (possibly during processing of other files):
781 "crate::util::logger::Logger" => Some(""),
784 }.map(|s| s.to_owned())
787 fn to_c_conversion_new_var_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<(&'b str, &'b str)> {
788 if self.is_primitive(full_path) {
792 "[u8]" if is_ref => Some(("crate::c_types::u8slice::from_slice(", ")")),
793 "[usize]" if is_ref => Some(("crate::c_types::usizeslice::from_slice(", ")")),
795 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
796 "bitcoin::blockdata::transaction::Transaction" if !is_ref => Some(("::bitcoin::consensus::encode::serialize(&", ")")),
797 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(("{ let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(", ")); s }")),
798 "bitcoin::blockdata::block::Block" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
799 "bitcoin::hash_types::Txid" => None,
801 // Override the default since Records contain an fmt with a lifetime:
802 // TODO: We should include the other record fields
803 "util::logger::Record" => Some(("std::ffi::CString::new(format!(\"{}\", ", ".args)).unwrap()")),
805 }.map(|s| s.to_owned())
807 fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
808 if self.is_primitive(full_path) {
809 return Some("".to_owned());
812 "Result" if !is_ref => Some("local_"),
813 "Vec" if !is_ref => Some("local_"),
814 "Option" => Some("local_"),
816 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
817 "[u8; 32]" if is_ref => Some("&"),
818 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes { data: "),
819 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes { data: "),
820 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes { data: "),
821 "[u8; 3]" if is_ref => Some("&"),
823 "[u8]" if is_ref => Some("local_"),
824 "[usize]" if is_ref => Some("local_"),
826 "str" if is_ref => Some(""),
827 "String" => Some(""),
829 "std::time::Duration" => Some(""),
831 "bitcoin::secp256k1::key::PublicKey" => Some("crate::c_types::PublicKey::from_rust(&"),
832 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature::from_rust(&"),
833 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some(""),
834 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some("crate::c_types::SecretKey::from_rust("),
835 "bitcoin::secp256k1::Error" if !is_ref => Some("crate::c_types::Secp256k1Error::from_rust("),
836 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice::from_slice(&"),
837 "bitcoin::blockdata::script::Script" if !is_ref => Some(""),
838 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction::from_vec(local_"),
839 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::c_types::bitcoin_to_C_outpoint("),
840 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut::from_rust("),
841 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("&local_"),
842 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice::from_slice(&local_"),
844 "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
846 // Newtypes that we just expose in their original form.
847 "bitcoin::hash_types::Txid" if is_ref => Some(""),
848 "bitcoin::hash_types::BlockHash" if is_ref => Some(""),
849 "bitcoin::hash_types::BlockHash" => Some("crate::c_types::ThirtyTwoBytes { data: "),
850 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
851 "ln::channelmanager::PaymentHash" if is_ref => Some("&"),
852 "ln::channelmanager::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
853 "ln::channelmanager::PaymentPreimage" if is_ref => Some("&"),
854 "ln::channelmanager::PaymentPreimage" => Some("crate::c_types::ThirtyTwoBytes { data: "),
855 "ln::channelmanager::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
857 // Override the default since Records contain an fmt with a lifetime:
858 "util::logger::Record" => Some("local_"),
861 }.map(|s| s.to_owned())
863 fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
864 if self.is_primitive(full_path) {
865 return Some("".to_owned());
868 "Result" if !is_ref => Some(""),
869 "Vec" if !is_ref => Some(".into()"),
870 "Option" => Some(""),
872 "[u8; 32]" if !is_ref => Some(" }"),
873 "[u8; 32]" if is_ref => Some(""),
874 "[u8; 16]" if !is_ref => Some(" }"),
875 "[u8; 10]" if !is_ref => Some(" }"),
876 "[u8; 4]" if !is_ref => Some(" }"),
877 "[u8; 3]" if is_ref => Some(""),
879 "[u8]" if is_ref => Some(""),
880 "[usize]" if is_ref => Some(""),
882 "str" if is_ref => Some(".into()"),
883 "String" if !is_ref => Some(".into_bytes().into()"),
884 "String" if is_ref => Some(".as_str().into()"),
886 "std::time::Duration" => Some(".as_secs()"),
888 "bitcoin::secp256k1::key::PublicKey" => Some(")"),
889 "bitcoin::secp256k1::Signature" => Some(")"),
890 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some(")"),
891 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some(".as_ref()"),
892 "bitcoin::secp256k1::Error" if !is_ref => Some(")"),
893 "bitcoin::blockdata::script::Script" if is_ref => Some("[..])"),
894 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_bytes().into()"),
895 "bitcoin::blockdata::transaction::Transaction" => Some(")"),
896 "bitcoin::blockdata::transaction::OutPoint" => Some(")"),
897 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(")"),
898 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(""),
899 "bitcoin::blockdata::block::Block" if is_ref => Some(")"),
901 "bitcoin::hash_types::Txid" if !is_ref => Some(".into_inner() }"),
903 // Newtypes that we just expose in their original form.
904 "bitcoin::hash_types::Txid" if is_ref => Some(".as_inner()"),
905 "bitcoin::hash_types::BlockHash" if is_ref => Some(".as_inner()"),
906 "bitcoin::hash_types::BlockHash" => Some(".into_inner() }"),
907 "bitcoin::secp256k1::Message" if !is_ref => Some(".as_ref().clone() }"),
908 "ln::channelmanager::PaymentHash" if is_ref => Some(".0"),
909 "ln::channelmanager::PaymentHash" => Some(".0 }"),
910 "ln::channelmanager::PaymentPreimage" if is_ref => Some(".0"),
911 "ln::channelmanager::PaymentPreimage" => Some(".0 }"),
912 "ln::channelmanager::PaymentSecret" if !is_ref => Some(".0 }"),
914 // Override the default since Records contain an fmt with a lifetime:
915 "util::logger::Record" => Some(".as_ptr()"),
918 }.map(|s| s.to_owned())
921 fn empty_val_check_suffix_from_path(&self, full_path: &str) -> Option<&str> {
923 "ln::channelmanager::PaymentSecret" => Some(".data == [0; 32]"),
924 "bitcoin::secp256k1::key::PublicKey" => Some(".is_null()"),
925 "bitcoin::secp256k1::Signature" => Some(".is_null()"),
930 // ****************************
931 // *** Container Processing ***
932 // ****************************
934 /// Returns the module path in the generated mapping crate to the containers which we generate
935 /// when writing to CrateTypes::template_file.
936 pub fn generated_container_path() -> &'static str {
937 "crate::c_types::derived"
939 /// Returns the module path in the generated mapping crate to the container templates, which
940 /// are then concretized and put in the generated container path/template_file.
941 fn container_templ_path() -> &'static str {
945 /// Returns true if this is a "transparent" container, ie an Option or a container which does
946 /// not require a generated continer class.
947 fn is_transparent_container(&self, full_path: &str, _is_ref: bool) -> bool {
948 full_path == "Option"
950 /// Returns true if this is a known, supported, non-transparent container.
951 fn is_known_container(&self, full_path: &str, is_ref: bool) -> bool {
952 (full_path == "Result" && !is_ref) || (full_path == "Vec" && !is_ref) || full_path.ends_with("Tuple")
954 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)
955 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
956 // expecting one element in the vec per generic type, each of which is inline-converted
957 -> Option<(&'b str, Vec<(String, String)>, &'b str)> {
959 "Result" if !is_ref => {
961 vec![(" { Ok(mut o) => crate::c_types::CResultTempl::ok(".to_string(), "o".to_string()),
962 (").into(), Err(mut e) => crate::c_types::CResultTempl::err(".to_string(), "e".to_string())],
965 "Vec" if !is_ref => {
966 Some(("Vec::new(); for item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }"))
969 Some(("Vec::new(); for item in ", vec![(format!(".iter() {{ local_{}.push(", var_name), "**item".to_string())], "); }"))
972 if let Some(syn::Type::Path(p)) = single_contained {
973 if self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)) {
975 return Some(("if ", vec![
976 (".is_none() { std::ptr::null() } else { ".to_owned(), format!("({}.as_ref().unwrap())", var_access))
979 return Some(("if ", vec![
980 (".is_none() { std::ptr::null_mut() } else { ".to_owned(), format!("({}.unwrap())", var_access))
985 if let Some(t) = single_contained {
986 let mut v = Vec::new();
987 self.write_empty_rust_val(generics, &mut v, t);
988 let s = String::from_utf8(v).unwrap();
989 return Some(("if ", vec![
990 (format!(".is_none() {{ {} }} else {{ ", s), format!("({}.unwrap())", var_access))
992 } else { unreachable!(); }
998 /// only_contained_has_inner implies that there is only one contained element in the container
999 /// and it has an inner field (ie is an "opaque" type we've defined).
1000 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)
1001 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1002 // expecting one element in the vec per generic type, each of which is inline-converted
1003 -> Option<(&'b str, Vec<(String, String)>, &'b str)> {
1005 "Result" if !is_ref => {
1007 vec![(".result_ok { true => Ok(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.result)) }})", var_name)),
1008 ("), false => Err(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.err)) }})", var_name))],
1011 "Vec"|"Slice" if !is_ref => {
1012 Some(("Vec::new(); for mut item in ", vec![(format!(".into_rust().drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }"))
1014 "Slice" if is_ref => {
1015 Some(("Vec::new(); for mut item in ", vec![(format!(".as_slice().iter() {{ local_{}.push(", var_name), "item".to_string())], "); }"))
1018 if let Some(syn::Type::Path(p)) = single_contained {
1019 if self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)) {
1021 return Some(("if ", vec![(".inner.is_null() { None } else { Some((*".to_string(), format!("{}", var_name))], ").clone()) }"))
1023 return Some(("if ", vec![(".inner.is_null() { None } else { Some(".to_string(), format!("{}", var_name))], ") }"));
1028 if let Some(t) = single_contained {
1029 let mut v = Vec::new();
1030 let ret_ref = self.write_empty_rust_val_check_suffix(generics, &mut v, t);
1031 let s = String::from_utf8(v).unwrap();
1033 EmptyValExpectedTy::ReferenceAsPointer =>
1034 return Some(("if ", vec![
1035 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ &mut *{} }}", var_access))
1037 EmptyValExpectedTy::OwnedPointer =>
1038 return Some(("if ", vec![
1039 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ *Box::from_raw({}) }}", var_access))
1041 EmptyValExpectedTy::NonPointer =>
1042 return Some(("if ", vec![
1043 (format!("{} {{ None }} else {{ Some(", s), format!("{}", var_access))
1046 } else { unreachable!(); }
1052 // *************************************************
1053 // *** Type definition during main.rs processing ***
1054 // *************************************************
1056 pub fn get_declared_type(&'a self, ident: &syn::Ident) -> Option<&'a DeclType<'c>> {
1057 self.types.get_declared_type(ident)
1059 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1060 pub fn c_type_has_inner_from_path(&self, full_path: &str) -> bool{
1061 self.crate_types.opaques.get(full_path).is_some()
1064 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
1065 self.types.maybe_resolve_ident(id)
1068 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
1069 self.types.maybe_resolve_non_ignored_ident(id)
1072 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
1073 self.types.maybe_resolve_path(p_arg, generics)
1075 pub fn resolve_path(&self, p: &syn::Path, generics: Option<&GenericTypes>) -> String {
1076 self.maybe_resolve_path(p, generics).unwrap()
1079 // ***********************************
1080 // *** Original Rust Type Printing ***
1081 // ***********************************
1083 fn in_rust_prelude(resolved_path: &str) -> bool {
1084 match resolved_path {
1092 fn write_rust_path<W: std::io::Write>(&self, w: &mut W, generics_resolver: Option<&GenericTypes>, path: &syn::Path) {
1093 if let Some(resolved) = self.maybe_resolve_path(&path, generics_resolver) {
1094 if self.is_primitive(&resolved) {
1095 write!(w, "{}", path.get_ident().unwrap()).unwrap();
1097 // TODO: We should have a generic "is from a dependency" check here instead of
1098 // checking for "bitcoin" explicitly.
1099 if resolved.starts_with("bitcoin::") || Self::in_rust_prelude(&resolved) {
1100 write!(w, "{}", resolved).unwrap();
1101 // If we're printing a generic argument, it needs to reference the crate, otherwise
1102 // the original crate:
1103 } else if self.maybe_resolve_path(&path, None).as_ref() == Some(&resolved) {
1104 write!(w, "{}::{}", self.orig_crate, resolved).unwrap();
1106 write!(w, "crate::{}", resolved).unwrap();
1109 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().last().unwrap().arguments {
1110 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1113 if path.leading_colon.is_some() {
1114 write!(w, "::").unwrap();
1116 for (idx, seg) in path.segments.iter().enumerate() {
1117 if idx != 0 { write!(w, "::").unwrap(); }
1118 write!(w, "{}", seg.ident).unwrap();
1119 if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
1120 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1125 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>) {
1126 let mut had_params = false;
1127 for (idx, arg) in generics.enumerate() {
1128 if idx != 0 { write!(w, ", ").unwrap(); } else { write!(w, "<").unwrap(); }
1131 syn::GenericParam::Lifetime(lt) => write!(w, "'{}", lt.lifetime.ident).unwrap(),
1132 syn::GenericParam::Type(t) => {
1133 write!(w, "{}", t.ident).unwrap();
1134 if t.colon_token.is_some() { write!(w, ":").unwrap(); }
1135 for (idx, bound) in t.bounds.iter().enumerate() {
1136 if idx != 0 { write!(w, " + ").unwrap(); }
1138 syn::TypeParamBound::Trait(tb) => {
1139 if tb.paren_token.is_some() || tb.lifetimes.is_some() { unimplemented!(); }
1140 self.write_rust_path(w, generics_resolver, &tb.path);
1142 _ => unimplemented!(),
1145 if t.eq_token.is_some() || t.default.is_some() { unimplemented!(); }
1147 _ => unimplemented!(),
1150 if had_params { write!(w, ">").unwrap(); }
1153 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>) {
1154 write!(w, "<").unwrap();
1155 for (idx, arg) in generics.enumerate() {
1156 if idx != 0 { write!(w, ", ").unwrap(); }
1158 syn::GenericArgument::Type(t) => self.write_rust_type(w, generics_resolver, t),
1159 _ => unimplemented!(),
1162 write!(w, ">").unwrap();
1164 pub fn write_rust_type<W: std::io::Write>(&self, w: &mut W, generics: Option<&GenericTypes>, t: &syn::Type) {
1166 syn::Type::Path(p) => {
1167 if p.qself.is_some() {
1170 self.write_rust_path(w, generics, &p.path);
1172 syn::Type::Reference(r) => {
1173 write!(w, "&").unwrap();
1174 if let Some(lft) = &r.lifetime {
1175 write!(w, "'{} ", lft.ident).unwrap();
1177 if r.mutability.is_some() {
1178 write!(w, "mut ").unwrap();
1180 self.write_rust_type(w, generics, &*r.elem);
1182 syn::Type::Array(a) => {
1183 write!(w, "[").unwrap();
1184 self.write_rust_type(w, generics, &a.elem);
1185 if let syn::Expr::Lit(l) = &a.len {
1186 if let syn::Lit::Int(i) = &l.lit {
1187 write!(w, "; {}]", i).unwrap();
1188 } else { unimplemented!(); }
1189 } else { unimplemented!(); }
1191 syn::Type::Slice(s) => {
1192 write!(w, "[").unwrap();
1193 self.write_rust_type(w, generics, &s.elem);
1194 write!(w, "]").unwrap();
1196 syn::Type::Tuple(s) => {
1197 write!(w, "(").unwrap();
1198 for (idx, t) in s.elems.iter().enumerate() {
1199 if idx != 0 { write!(w, ", ").unwrap(); }
1200 self.write_rust_type(w, generics, &t);
1202 write!(w, ")").unwrap();
1204 _ => unimplemented!(),
1208 /// Prints a constructor for something which is "uninitialized" (but obviously not actually
1209 /// unint'd memory).
1210 pub fn write_empty_rust_val<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) {
1212 syn::Type::Path(p) => {
1213 let resolved = self.resolve_path(&p.path, generics);
1214 if self.crate_types.opaques.get(&resolved).is_some() {
1215 write!(w, "crate::{} {{ inner: std::ptr::null_mut(), is_owned: true }}", resolved).unwrap();
1217 // Assume its a manually-mapped C type, where we can just define an null() fn
1218 write!(w, "{}::null()", self.c_type_from_path(&resolved, false, false).unwrap()).unwrap();
1221 syn::Type::Array(a) => {
1222 if let syn::Expr::Lit(l) = &a.len {
1223 if let syn::Lit::Int(i) = &l.lit {
1224 if i.base10_digits().parse::<usize>().unwrap() < 32 {
1225 // Blindly assume that if we're trying to create an empty value for an
1226 // array < 32 entries that all-0s may be a valid state.
1229 let arrty = format!("[u8; {}]", i.base10_digits());
1230 write!(w, "{}", self.to_c_conversion_inline_prefix_from_path(&arrty, false, false).unwrap()).unwrap();
1231 write!(w, "[0; {}]", i.base10_digits()).unwrap();
1232 write!(w, "{}", self.to_c_conversion_inline_suffix_from_path(&arrty, false, false).unwrap()).unwrap();
1233 } else { unimplemented!(); }
1234 } else { unimplemented!(); }
1236 _ => unimplemented!(),
1240 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1241 /// See EmptyValExpectedTy for information on return types.
1242 fn write_empty_rust_val_check_suffix<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) -> EmptyValExpectedTy {
1244 syn::Type::Path(p) => {
1245 let resolved = self.resolve_path(&p.path, generics);
1246 if self.crate_types.opaques.get(&resolved).is_some() {
1247 write!(w, ".inner.is_null()").unwrap();
1248 EmptyValExpectedTy::NonPointer
1250 if let Some(suffix) = self.empty_val_check_suffix_from_path(&resolved) {
1251 write!(w, "{}", suffix).unwrap();
1252 // We may eventually need to allow empty_val_check_suffix_from_path to specify if we need a deref or not
1253 EmptyValExpectedTy::NonPointer
1255 write!(w, " == std::ptr::null_mut()").unwrap();
1256 EmptyValExpectedTy::OwnedPointer
1260 syn::Type::Array(a) => {
1261 if let syn::Expr::Lit(l) = &a.len {
1262 if let syn::Lit::Int(i) = &l.lit {
1263 write!(w, " == [0; {}]", i.base10_digits()).unwrap();
1264 EmptyValExpectedTy::NonPointer
1265 } else { unimplemented!(); }
1266 } else { unimplemented!(); }
1268 syn::Type::Slice(_) => {
1269 // Option<[]> always implies that we want to treat len() == 0 differently from
1270 // None, so we always map an Option<[]> into a pointer.
1271 write!(w, " == std::ptr::null_mut()").unwrap();
1272 EmptyValExpectedTy::ReferenceAsPointer
1274 _ => unimplemented!(),
1278 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1279 pub fn write_empty_rust_val_check<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type, var_access: &str) {
1281 syn::Type::Path(_) => {
1282 write!(w, "{}", var_access).unwrap();
1283 self.write_empty_rust_val_check_suffix(generics, w, t);
1285 syn::Type::Array(a) => {
1286 if let syn::Expr::Lit(l) = &a.len {
1287 if let syn::Lit::Int(i) = &l.lit {
1288 let arrty = format!("[u8; {}]", i.base10_digits());
1289 // We don't (yet) support a new-var conversion here.
1290 assert!(self.from_c_conversion_new_var_from_path(&arrty, false).is_none());
1292 self.from_c_conversion_prefix_from_path(&arrty, false).unwrap(),
1294 self.from_c_conversion_suffix_from_path(&arrty, false).unwrap()).unwrap();
1295 self.write_empty_rust_val_check_suffix(generics, w, t);
1296 } else { unimplemented!(); }
1297 } else { unimplemented!(); }
1299 _ => unimplemented!(),
1303 // ********************************
1304 // *** Type conversion printing ***
1305 // ********************************
1307 /// Returns true we if can just skip passing this to C entirely
1308 pub fn skip_arg(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
1310 syn::Type::Path(p) => {
1311 if p.qself.is_some() { unimplemented!(); }
1312 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1313 self.skip_path(&full_path)
1316 syn::Type::Reference(r) => {
1317 self.skip_arg(&*r.elem, generics)
1322 pub fn no_arg_to_rust<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1324 syn::Type::Path(p) => {
1325 if p.qself.is_some() { unimplemented!(); }
1326 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1327 write!(w, "{}", self.no_arg_path_to_rust(&full_path)).unwrap();
1330 syn::Type::Reference(r) => {
1331 self.no_arg_to_rust(w, &*r.elem, generics);
1337 fn write_conversion_inline_intern<W: std::io::Write,
1338 LP: Fn(&str, bool, bool) -> Option<String>, DL: Fn(&mut W, &DeclType, &str, bool, bool), SC: Fn(bool) -> &'static str>
1339 (&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool,
1340 tupleconv: &str, prefix: bool, sliceconv: SC, path_lookup: LP, decl_lookup: DL) {
1342 syn::Type::Reference(r) => {
1343 self.write_conversion_inline_intern(w, &*r.elem, generics, true, r.mutability.is_some(),
1344 ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1346 syn::Type::Path(p) => {
1347 if p.qself.is_some() {
1351 let resolved_path = self.resolve_path(&p.path, generics);
1352 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1353 return self.write_conversion_inline_intern(w, aliased_type, None, is_ref, is_mut, ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1354 } else if let Some(c_type) = path_lookup(&resolved_path, is_ref, ptr_for_ref) {
1355 write!(w, "{}", c_type).unwrap();
1356 } else if self.crate_types.opaques.get(&resolved_path).is_some() {
1357 decl_lookup(w, &DeclType::StructImported, &resolved_path, is_ref, is_mut);
1358 } else if self.crate_types.mirrored_enums.get(&resolved_path).is_some() {
1359 decl_lookup(w, &DeclType::MirroredEnum, &resolved_path, is_ref, is_mut);
1360 } else if let Some(t) = self.crate_types.traits.get(&resolved_path) {
1361 decl_lookup(w, &DeclType::Trait(t), &resolved_path, is_ref, is_mut);
1362 } else if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
1363 if let Some(decl_type) = self.types.maybe_resolve_declared(ident) {
1364 decl_lookup(w, decl_type, &self.maybe_resolve_ident(ident).unwrap(), is_ref, is_mut);
1365 } else { unimplemented!(); }
1366 } else { unimplemented!(); }
1368 syn::Type::Array(a) => {
1369 // We assume all arrays contain only [int_literal; X]s.
1370 // This may result in some outputs not compiling.
1371 if let syn::Expr::Lit(l) = &a.len {
1372 if let syn::Lit::Int(i) = &l.lit {
1373 write!(w, "{}", path_lookup(&format!("[u8; {}]", i.base10_digits()), is_ref, ptr_for_ref).unwrap()).unwrap();
1374 } else { unimplemented!(); }
1375 } else { unimplemented!(); }
1377 syn::Type::Slice(s) => {
1378 // We assume all slices contain only literals or references.
1379 // This may result in some outputs not compiling.
1380 if let syn::Type::Path(p) = &*s.elem {
1381 let resolved = self.resolve_path(&p.path, generics);
1382 assert!(self.is_primitive(&resolved));
1383 write!(w, "{}", path_lookup("[u8]", is_ref, ptr_for_ref).unwrap()).unwrap();
1384 } else if let syn::Type::Reference(r) = &*s.elem {
1385 if let syn::Type::Path(p) = &*r.elem {
1386 write!(w, "{}", sliceconv(self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)))).unwrap();
1387 } else { unimplemented!(); }
1388 } else if let syn::Type::Tuple(t) = &*s.elem {
1389 assert!(!t.elems.is_empty());
1391 write!(w, "&local_").unwrap();
1393 let mut needs_map = false;
1394 for e in t.elems.iter() {
1395 if let syn::Type::Reference(_) = e {
1400 write!(w, ".iter().map(|(").unwrap();
1401 for i in 0..t.elems.len() {
1402 write!(w, "{}{}", if i != 0 { ", " } else { "" }, ('a' as u8 + i as u8) as char).unwrap();
1404 write!(w, ")| (").unwrap();
1405 for (idx, e) in t.elems.iter().enumerate() {
1406 if let syn::Type::Reference(_) = e {
1407 write!(w, "{}{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1408 } else if let syn::Type::Path(_) = e {
1409 write!(w, "{}*{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1410 } else { unimplemented!(); }
1412 write!(w, ")).collect::<Vec<_>>()[..]").unwrap();
1415 } else { unimplemented!(); }
1417 syn::Type::Tuple(t) => {
1418 if t.elems.is_empty() {
1419 // cbindgen has poor support for (), see, eg https://github.com/eqrion/cbindgen/issues/527
1420 // so work around it by just pretending its a 0u8
1421 write!(w, "{}", tupleconv).unwrap();
1423 if prefix { write!(w, "local_").unwrap(); }
1426 _ => unimplemented!(),
1430 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) {
1431 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "0u8 /*", true, |_| "local_",
1432 |a, b, c| self.to_c_conversion_inline_prefix_from_path(a, b, c),
1433 |w, decl_type, decl_path, is_ref, _is_mut| {
1435 DeclType::MirroredEnum if is_ref && ptr_for_ref => write!(w, "crate::{}::from_native(&", decl_path).unwrap(),
1436 DeclType::MirroredEnum if is_ref => write!(w, "&crate::{}::from_native(&", decl_path).unwrap(),
1437 DeclType::MirroredEnum => write!(w, "crate::{}::native_into(", decl_path).unwrap(),
1438 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1439 write!(w, "crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1440 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1441 write!(w, "crate::{} {{ inner: unsafe {{ ( (&(", decl_path).unwrap(),
1442 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1443 write!(w, "&crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1444 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1445 write!(w, "crate::{} {{ inner: ", decl_path).unwrap(),
1446 DeclType::EnumIgnored|DeclType::StructImported if !is_ref =>
1447 write!(w, "crate::{} {{ inner: Box::into_raw(Box::new(", decl_path).unwrap(),
1448 DeclType::Trait(_) if is_ref => write!(w, "&").unwrap(),
1449 DeclType::Trait(_) if !is_ref => {},
1450 _ => panic!("{:?}", decl_path),
1454 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) {
1455 self.write_to_c_conversion_inline_prefix_inner(w, t, generics, false, ptr_for_ref, false);
1457 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) {
1458 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "*/", false, |_| ".into()",
1459 |a, b, c| self.to_c_conversion_inline_suffix_from_path(a, b, c),
1460 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1461 DeclType::MirroredEnum => write!(w, ")").unwrap(),
1462 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1463 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1464 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1465 write!(w, ") as *const _) as *mut _) }}, is_owned: false }}").unwrap(),
1466 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1467 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1468 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1469 write!(w, ", is_owned: true }}").unwrap(),
1470 DeclType::EnumIgnored|DeclType::StructImported if !is_ref => write!(w, ")), is_owned: true }}").unwrap(),
1471 DeclType::Trait(_) if is_ref => {},
1472 DeclType::Trait(_) => {
1473 // This is used when we're converting a concrete Rust type into a C trait
1474 // for use when a Rust trait method returns an associated type.
1475 // Because all of our C traits implement From<RustTypesImplementingTraits>
1476 // we can just call .into() here and be done.
1477 write!(w, ".into()").unwrap()
1479 _ => unimplemented!(),
1482 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) {
1483 self.write_to_c_conversion_inline_suffix_inner(w, t, generics, false, ptr_for_ref, false);
1486 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) {
1487 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "() /*", true, |_| "&local_",
1488 |a, b, _c| self.from_c_conversion_prefix_from_path(a, b),
1489 |w, decl_type, _full_path, is_ref, is_mut| match decl_type {
1490 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, "unsafe {{ &*(*").unwrap(),
1491 DeclType::StructImported if is_mut && is_ref => write!(w, "unsafe {{ &mut *").unwrap(),
1492 DeclType::StructImported if is_ref => write!(w, "unsafe {{ &*").unwrap(),
1493 DeclType::StructImported if !is_ref => write!(w, "*unsafe {{ Box::from_raw(").unwrap(),
1494 DeclType::MirroredEnum if is_ref => write!(w, "&").unwrap(),
1495 DeclType::MirroredEnum => {},
1496 DeclType::Trait(_) => {},
1497 _ => unimplemented!(),
1500 pub fn write_from_c_conversion_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1501 self.write_from_c_conversion_prefix_inner(w, t, generics, false, false);
1503 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) {
1504 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "*/", false,
1505 |has_inner| match has_inner {
1506 false => ".iter().collect::<Vec<_>>()[..]",
1509 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1510 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1511 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, ").inner }}").unwrap(),
1512 DeclType::StructImported if is_ref => write!(w, ".inner }}").unwrap(),
1513 DeclType::StructImported if !is_ref => write!(w, ".take_inner()) }}").unwrap(),
1514 DeclType::MirroredEnum if is_ref => write!(w, ".to_native()").unwrap(),
1515 DeclType::MirroredEnum => write!(w, ".into_native()").unwrap(),
1516 DeclType::Trait(_) => {},
1517 _ => unimplemented!(),
1520 pub fn write_from_c_conversion_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1521 self.write_from_c_conversion_suffix_inner(w, t, generics, false, false);
1523 // Note that compared to the above conversion functions, the following two are generally
1524 // significantly undertested:
1525 pub fn write_from_c_conversion_to_ref_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1526 self.write_conversion_inline_intern(w, t, generics, false, false, false, "() /*", true, |_| "&local_",
1528 if let Some(conv) = self.from_c_conversion_prefix_from_path(a, b) {
1529 Some(format!("&{}", conv))
1532 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1533 DeclType::StructImported if !is_ref => write!(w, "unsafe {{ &*").unwrap(),
1534 _ => unimplemented!(),
1537 pub fn write_from_c_conversion_to_ref_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1538 self.write_conversion_inline_intern(w, t, generics, false, false, false, "*/", false,
1539 |has_inner| match has_inner {
1540 false => ".iter().collect::<Vec<_>>()[..]",
1543 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1544 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1545 DeclType::StructImported if !is_ref => write!(w, ".inner }}").unwrap(),
1546 _ => unimplemented!(),
1550 fn write_conversion_new_var_intern<'b, W: std::io::Write,
1551 LP: Fn(&str, bool) -> Option<(&str, &str)>,
1552 LC: Fn(&str, bool, Option<&syn::Type>, &syn::Ident, &str) -> Option<(&'b str, Vec<(String, String)>, &'b str)>,
1553 VP: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool),
1554 VS: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool)>
1555 (&self, w: &mut W, ident: &syn::Ident, var: &str, t: &syn::Type, generics: Option<&GenericTypes>,
1556 mut is_ref: bool, mut ptr_for_ref: bool, to_c: bool,
1557 path_lookup: &LP, container_lookup: &LC, var_prefix: &VP, var_suffix: &VS) -> bool {
1559 macro_rules! convert_container {
1560 ($container_type: expr, $args_len: expr, $args_iter: expr) => { {
1561 // For slices (and Options), we refuse to directly map them as is_ref when they
1562 // aren't opaque types containing an inner pointer. This is due to the fact that,
1563 // in both cases, the actual higher-level type is non-is_ref.
1564 let ty_has_inner = if self.is_transparent_container(&$container_type, is_ref) || $container_type == "Slice" {
1565 let ty = $args_iter().next().unwrap();
1566 if $container_type == "Slice" && to_c {
1567 // "To C ptr_for_ref" means "return the regular object with is_owned
1568 // set to false", which is totally what we want in a slice if we're about to
1569 // set ty_has_inner.
1572 if let syn::Type::Reference(t) = ty {
1573 if let syn::Type::Path(p) = &*t.elem {
1574 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1576 } else if let syn::Type::Path(p) = ty {
1577 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1581 // Options get a bunch of special handling, since in general we map Option<>al
1582 // types into the same C type as non-Option-wrapped types. This ends up being
1583 // pretty manual here and most of the below special-cases are for Options.
1584 let mut needs_ref_map = false;
1585 let mut only_contained_type = None;
1586 let mut only_contained_has_inner = false;
1587 let mut contains_slice = false;
1588 if $args_len == 1 && self.is_transparent_container(&$container_type, is_ref) {
1589 only_contained_has_inner = ty_has_inner;
1590 let arg = $args_iter().next().unwrap();
1591 if let syn::Type::Reference(t) = arg {
1592 only_contained_type = Some(&*t.elem);
1593 if let syn::Type::Path(_) = &*t.elem {
1595 } else if let syn::Type::Slice(_) = &*t.elem {
1596 contains_slice = true;
1597 } else { return false; }
1598 needs_ref_map = true;
1599 } else if let syn::Type::Path(_) = arg {
1600 only_contained_type = Some(&arg);
1601 } else { unimplemented!(); }
1604 if let Some((prefix, conversions, suffix)) = container_lookup(&$container_type, is_ref && ty_has_inner, only_contained_type, ident, var) {
1605 assert_eq!(conversions.len(), $args_len);
1606 write!(w, "let mut local_{}{} = ", ident, if !to_c && needs_ref_map {"_base"} else { "" }).unwrap();
1607 if only_contained_has_inner && to_c {
1608 var_prefix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
1610 write!(w, "{}{}", prefix, var).unwrap();
1612 for ((pfx, var_name), (idx, ty)) in conversions.iter().zip($args_iter().enumerate()) {
1613 let mut var = std::io::Cursor::new(Vec::new());
1614 write!(&mut var, "{}", var_name).unwrap();
1615 let var_access = String::from_utf8(var.into_inner()).unwrap();
1617 let conv_ty = if needs_ref_map { only_contained_type.as_ref().unwrap() } else { ty };
1619 write!(w, "{} {{ ", pfx).unwrap();
1620 let new_var_name = format!("{}_{}", ident, idx);
1621 let new_var = self.write_conversion_new_var_intern(w, &syn::Ident::new(&new_var_name, Span::call_site()),
1622 &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);
1623 if new_var { write!(w, " ").unwrap(); }
1624 if (!only_contained_has_inner || !to_c) && !contains_slice {
1625 var_prefix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1628 if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
1629 write!(w, "Box::into_raw(Box::new(").unwrap();
1631 write!(w, "{}{}", if contains_slice { "local_" } else { "" }, if new_var { new_var_name } else { var_access }).unwrap();
1632 if (!only_contained_has_inner || !to_c) && !contains_slice {
1633 var_suffix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1635 if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
1636 write!(w, "))").unwrap();
1638 write!(w, " }}").unwrap();
1640 write!(w, "{}", suffix).unwrap();
1641 if only_contained_has_inner && to_c {
1642 var_suffix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
1644 write!(w, ";").unwrap();
1645 if !to_c && needs_ref_map {
1646 write!(w, " let mut local_{} = local_{}_base.as_ref()", ident, ident).unwrap();
1648 write!(w, ".map(|a| &a[..])").unwrap();
1650 write!(w, ";").unwrap();
1658 syn::Type::Reference(r) => {
1659 if let syn::Type::Slice(_) = &*r.elem {
1660 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)
1662 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)
1665 syn::Type::Path(p) => {
1666 if p.qself.is_some() {
1669 let resolved_path = self.resolve_path(&p.path, generics);
1670 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1671 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);
1673 if self.is_known_container(&resolved_path, is_ref) || self.is_transparent_container(&resolved_path, is_ref) {
1674 if let syn::PathArguments::AngleBracketed(args) = &p.path.segments.iter().next().unwrap().arguments {
1675 convert_container!(resolved_path, args.args.len(), || args.args.iter().map(|arg| {
1676 if let syn::GenericArgument::Type(ty) = arg {
1678 } else { unimplemented!(); }
1680 } else { unimplemented!(); }
1682 if self.is_primitive(&resolved_path) {
1684 } else if let Some(ty_ident) = single_ident_generic_path_to_ident(&p.path) {
1685 if let Some((prefix, suffix)) = path_lookup(&resolved_path, is_ref) {
1686 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
1688 } else if self.types.maybe_resolve_declared(ty_ident).is_some() {
1693 syn::Type::Array(_) => {
1694 // We assume all arrays contain only primitive types.
1695 // This may result in some outputs not compiling.
1698 syn::Type::Slice(s) => {
1699 if let syn::Type::Path(p) = &*s.elem {
1700 let resolved = self.resolve_path(&p.path, generics);
1701 assert!(self.is_primitive(&resolved));
1702 let slice_path = format!("[{}]", resolved);
1703 if let Some((prefix, suffix)) = path_lookup(&slice_path, true) {
1704 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
1707 } else if let syn::Type::Reference(ty) = &*s.elem {
1708 let tyref = [&*ty.elem];
1710 convert_container!("Slice", 1, || tyref.iter());
1711 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
1712 } else if let syn::Type::Tuple(t) = &*s.elem {
1713 // When mapping into a temporary new var, we need to own all the underlying objects.
1714 // Thus, we drop any references inside the tuple and convert with non-reference types.
1715 let mut elems = syn::punctuated::Punctuated::new();
1716 for elem in t.elems.iter() {
1717 if let syn::Type::Reference(r) = elem {
1718 elems.push((*r.elem).clone());
1720 elems.push(elem.clone());
1723 let ty = [syn::Type::Tuple(syn::TypeTuple {
1724 paren_token: t.paren_token, elems
1728 convert_container!("Slice", 1, || ty.iter());
1729 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
1730 } else { unimplemented!() }
1732 syn::Type::Tuple(t) => {
1733 if !t.elems.is_empty() {
1734 // We don't (yet) support tuple elements which cannot be converted inline
1735 write!(w, "let (").unwrap();
1736 for idx in 0..t.elems.len() {
1737 if idx != 0 { write!(w, ", ").unwrap(); }
1738 write!(w, "{} orig_{}_{}", if is_ref { "ref" } else { "mut" }, ident, idx).unwrap();
1740 write!(w, ") = {}{}; ", var, if !to_c { ".to_rust()" } else { "" }).unwrap();
1741 // Like other template types, tuples are always mapped as their non-ref
1742 // versions for types which have different ref mappings. Thus, we convert to
1743 // non-ref versions and handle opaque types with inner pointers manually.
1744 for (idx, elem) in t.elems.iter().enumerate() {
1745 if let syn::Type::Path(p) = elem {
1746 let v_name = format!("orig_{}_{}", ident, idx);
1747 let tuple_elem_ident = syn::Ident::new(&v_name, Span::call_site());
1748 if self.write_conversion_new_var_intern(w, &tuple_elem_ident, &v_name, elem, generics,
1749 false, ptr_for_ref, to_c,
1750 path_lookup, container_lookup, var_prefix, var_suffix) {
1751 write!(w, " ").unwrap();
1752 // Opaque types with inner pointers shouldn't ever create new stack
1753 // variables, so we don't handle it and just assert that it doesn't
1755 assert!(!self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)));
1759 write!(w, "let mut local_{} = (", ident).unwrap();
1760 for (idx, elem) in t.elems.iter().enumerate() {
1761 let ty_has_inner = {
1763 // "To C ptr_for_ref" means "return the regular object with
1764 // is_owned set to false", which is totally what we want
1765 // if we're about to set ty_has_inner.
1768 if let syn::Type::Reference(t) = elem {
1769 if let syn::Type::Path(p) = &*t.elem {
1770 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1772 } else if let syn::Type::Path(p) = elem {
1773 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1776 if idx != 0 { write!(w, ", ").unwrap(); }
1777 var_prefix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1778 if is_ref && ty_has_inner {
1779 // For ty_has_inner, the regular var_prefix mapping will take a
1780 // reference, so deref once here to make sure we keep the original ref.
1781 write!(w, "*").unwrap();
1783 write!(w, "orig_{}_{}", ident, idx).unwrap();
1784 if is_ref && !ty_has_inner {
1785 // If we don't have an inner variable's reference to maintain, just
1786 // hope the type is Clonable and use that.
1787 write!(w, ".clone()").unwrap();
1789 var_suffix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1791 write!(w, "){};", if to_c { ".into()" } else { "" }).unwrap();
1795 _ => unimplemented!(),
1799 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 {
1800 self.write_conversion_new_var_intern(w, ident, var_access, t, generics, false, ptr_for_ref, true,
1801 &|a, b| self.to_c_conversion_new_var_from_path(a, b),
1802 &|a, b, c, d, e| self.to_c_conversion_container_new_var(generics, a, b, c, d, e),
1803 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
1804 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_prefix_inner(a, b, c, d, e, f),
1805 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_suffix_inner(a, b, c, d, e, f))
1807 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 {
1808 self.write_to_c_conversion_new_var_inner(w, ident, &format!("{}", ident), t, generics, ptr_for_ref)
1810 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 {
1811 self.write_conversion_new_var_intern(w, ident, &format!("{}", ident), t, generics, false, false, false,
1812 &|a, b| self.from_c_conversion_new_var_from_path(a, b),
1813 &|a, b, c, d, e| self.from_c_conversion_container_new_var(generics, a, b, c, d, e),
1814 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
1815 &|a, b, c, d, e, _f| self.write_from_c_conversion_prefix_inner(a, b, c, d, e),
1816 &|a, b, c, d, e, _f| self.write_from_c_conversion_suffix_inner(a, b, c, d, e))
1819 // ******************************************************
1820 // *** C Container Type Equivalent and alias Printing ***
1821 // ******************************************************
1823 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 {
1824 assert!(!is_ref); // We don't currently support outer reference types
1825 for (idx, t) in args.enumerate() {
1827 write!(w, ", ").unwrap();
1829 if let syn::Type::Reference(r_arg) = t {
1830 if !self.write_c_type_intern(w, &*r_arg.elem, generics, false, false, false) { return false; }
1832 // While write_c_type_intern, above is correct, we don't want to blindly convert a
1833 // reference to something stupid, so check that the container is either opaque or a
1834 // predefined type (currently only Transaction).
1835 if let syn::Type::Path(p_arg) = &*r_arg.elem {
1836 let resolved = self.resolve_path(&p_arg.path, generics);
1837 assert!(self.crate_types.opaques.get(&resolved).is_some() ||
1838 self.c_type_from_path(&resolved, true, true).is_some(), "Template generics should be opaque or have a predefined mapping");
1839 } else { unimplemented!(); }
1841 if !self.write_c_type_intern(w, t, generics, false, false, false) { return false; }
1846 fn check_create_container(&mut self, mangled_container: String, container_type: &str, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
1847 if !self.crate_types.templates_defined.get(&mangled_container).is_some() {
1848 let mut created_container: Vec<u8> = Vec::new();
1850 if container_type == "Result" {
1851 let mut a_ty: Vec<u8> = Vec::new();
1852 if let syn::Type::Tuple(tup) = args.iter().next().unwrap() {
1853 if tup.elems.is_empty() {
1854 write!(&mut a_ty, "()").unwrap();
1856 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
1859 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
1862 let mut b_ty: Vec<u8> = Vec::new();
1863 if let syn::Type::Tuple(tup) = args.iter().skip(1).next().unwrap() {
1864 if tup.elems.is_empty() {
1865 write!(&mut b_ty, "()").unwrap();
1867 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
1870 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
1873 let ok_str = String::from_utf8(a_ty).unwrap();
1874 let err_str = String::from_utf8(b_ty).unwrap();
1875 let is_clonable = self.is_clonable(&ok_str) && self.is_clonable(&err_str);
1876 write_result_block(&mut created_container, &mangled_container, &ok_str, &err_str, is_clonable);
1878 self.crate_types.clonable_types.insert(Self::generated_container_path().to_owned() + "::" + &mangled_container);
1880 } else if container_type == "Vec" {
1881 let mut a_ty: Vec<u8> = Vec::new();
1882 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
1883 let ty = String::from_utf8(a_ty).unwrap();
1884 let is_clonable = self.is_clonable(&ty);
1885 write_vec_block(&mut created_container, &mangled_container, &ty, is_clonable);
1887 self.crate_types.clonable_types.insert(Self::generated_container_path().to_owned() + "::" + &mangled_container);
1889 } else if container_type.ends_with("Tuple") {
1890 let mut tuple_args = Vec::new();
1891 let mut is_clonable = true;
1892 for arg in args.iter() {
1893 let mut ty: Vec<u8> = Vec::new();
1894 if !self.write_template_generics(&mut ty, &mut [arg].iter().map(|t| **t), generics, is_ref) { return false; }
1895 let ty_str = String::from_utf8(ty).unwrap();
1896 if !self.is_clonable(&ty_str) {
1897 is_clonable = false;
1899 tuple_args.push(ty_str);
1901 write_tuple_block(&mut created_container, &mangled_container, &tuple_args, is_clonable);
1903 self.crate_types.clonable_types.insert(Self::generated_container_path().to_owned() + "::" + &mangled_container);
1908 self.crate_types.templates_defined.insert(mangled_container.clone(), true);
1910 self.crate_types.template_file.write(&created_container).unwrap();
1914 fn path_to_generic_args(path: &syn::Path) -> Vec<&syn::Type> {
1915 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().next().unwrap().arguments {
1916 args.args.iter().map(|gen| if let syn::GenericArgument::Type(t) = gen { t } else { unimplemented!() }).collect()
1917 } else { unimplemented!(); }
1919 fn write_c_mangled_container_path_intern<W: std::io::Write>
1920 (&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 {
1921 let mut mangled_type: Vec<u8> = Vec::new();
1922 if !self.is_transparent_container(ident, is_ref) {
1923 write!(w, "C{}_", ident).unwrap();
1924 write!(mangled_type, "C{}_", ident).unwrap();
1925 } else { assert_eq!(args.len(), 1); }
1926 for arg in args.iter() {
1927 macro_rules! write_path {
1928 ($p_arg: expr, $extra_write: expr) => {
1929 if let Some(subtype) = self.maybe_resolve_path(&$p_arg.path, generics) {
1930 if self.is_transparent_container(ident, is_ref) {
1931 // We dont (yet) support primitives or containers inside transparent
1932 // containers, so check for that first:
1933 if self.is_primitive(&subtype) { return false; }
1934 if self.is_known_container(&subtype, is_ref) { return false; }
1936 if self.c_type_has_inner_from_path(&subtype) {
1937 if !self.write_c_path_intern(w, &$p_arg.path, generics, is_ref, is_mut, ptr_for_ref) { return false; }
1939 // Option<T> needs to be converted to a *mut T, ie mut ptr-for-ref
1940 if !self.write_c_path_intern(w, &$p_arg.path, generics, true, true, true) { return false; }
1943 if $p_arg.path.segments.len() == 1 {
1944 write!(w, "{}", $p_arg.path.segments.iter().next().unwrap().ident).unwrap();
1949 } else if self.is_known_container(&subtype, is_ref) || self.is_transparent_container(&subtype, is_ref) {
1950 if !self.write_c_mangled_container_path_intern(w, Self::path_to_generic_args(&$p_arg.path), generics,
1951 &subtype, is_ref, is_mut, ptr_for_ref, true) {
1954 self.write_c_mangled_container_path_intern(&mut mangled_type, Self::path_to_generic_args(&$p_arg.path),
1955 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
1956 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
1957 self.write_c_mangled_container_path_intern(w2, Self::path_to_generic_args(&$p_arg.path),
1958 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
1961 let id = subtype.rsplitn(2, ':').next().unwrap(); // Get the "Base" name of the resolved type
1962 write!(w, "{}", id).unwrap();
1963 write!(mangled_type, "{}", id).unwrap();
1964 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
1965 write!(w2, "{}", id).unwrap();
1968 } else { return false; }
1971 if let syn::Type::Tuple(tuple) = arg {
1972 if tuple.elems.len() == 0 {
1973 write!(w, "None").unwrap();
1974 write!(mangled_type, "None").unwrap();
1976 let mut mangled_tuple_type: Vec<u8> = Vec::new();
1978 // Figure out what the mangled type should look like. To disambiguate
1979 // ((A, B), C) and (A, B, C) we prefix the generic args with a _ and suffix
1980 // them with a Z. Ideally we wouldn't use Z, but not many special chars are
1981 // available for use in type names.
1982 write!(w, "C{}Tuple_", tuple.elems.len()).unwrap();
1983 write!(mangled_type, "C{}Tuple_", tuple.elems.len()).unwrap();
1984 write!(mangled_tuple_type, "C{}Tuple_", tuple.elems.len()).unwrap();
1985 for elem in tuple.elems.iter() {
1986 if let syn::Type::Path(p) = elem {
1987 write_path!(p, Some(&mut mangled_tuple_type));
1988 } else if let syn::Type::Reference(refelem) = elem {
1989 if let syn::Type::Path(p) = &*refelem.elem {
1990 write_path!(p, Some(&mut mangled_tuple_type));
1991 } else { return false; }
1992 } else { return false; }
1994 write!(w, "Z").unwrap();
1995 write!(mangled_type, "Z").unwrap();
1996 write!(mangled_tuple_type, "Z").unwrap();
1997 if !self.check_create_container(String::from_utf8(mangled_tuple_type).unwrap(),
1998 &format!("{}Tuple", tuple.elems.len()), tuple.elems.iter().collect(), generics, is_ref) {
2002 } else if let syn::Type::Path(p_arg) = arg {
2003 write_path!(p_arg, None);
2004 } else if let syn::Type::Reference(refty) = arg {
2005 if let syn::Type::Path(p_arg) = &*refty.elem {
2006 write_path!(p_arg, None);
2007 } else if let syn::Type::Slice(_) = &*refty.elem {
2008 // write_c_type will actually do exactly what we want here, we just need to
2009 // make it a pointer so that its an option. Note that we cannot always convert
2010 // the Vec-as-slice (ie non-ref types) containers, so sometimes need to be able
2011 // to edit it, hence we use *mut here instead of *const.
2012 if args.len() != 1 { return false; }
2013 write!(w, "*mut ").unwrap();
2014 self.write_c_type(w, arg, None, true);
2015 } else { return false; }
2016 } else if let syn::Type::Array(a) = arg {
2017 if let syn::Type::Path(p_arg) = &*a.elem {
2018 let resolved = self.resolve_path(&p_arg.path, generics);
2019 if !self.is_primitive(&resolved) { return false; }
2020 if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(len), .. }) = &a.len {
2021 if self.c_type_from_path(&format!("[{}; {}]", resolved, len.base10_digits()), is_ref, ptr_for_ref).is_none() { return false; }
2022 write!(w, "_{}{}", resolved, len.base10_digits()).unwrap();
2023 write!(mangled_type, "_{}{}", resolved, len.base10_digits()).unwrap();
2024 } else { return false; }
2025 } else { return false; }
2026 } else { return false; }
2028 if self.is_transparent_container(ident, is_ref) { return true; }
2029 // Push the "end of type" Z
2030 write!(w, "Z").unwrap();
2031 write!(mangled_type, "Z").unwrap();
2033 // Make sure the type is actually defined:
2034 self.check_create_container(String::from_utf8(mangled_type).unwrap(), ident, args, generics, is_ref)
2036 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 {
2037 if !self.is_transparent_container(ident, is_ref) {
2038 write!(w, "{}::", Self::generated_container_path()).unwrap();
2040 self.write_c_mangled_container_path_intern(w, args, generics, ident, is_ref, is_mut, ptr_for_ref, false)
2043 // **********************************
2044 // *** C Type Equivalent Printing ***
2045 // **********************************
2047 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 {
2048 let full_path = match self.maybe_resolve_path(&path, generics) {
2049 Some(path) => path, None => return false };
2050 if let Some(c_type) = self.c_type_from_path(&full_path, is_ref, ptr_for_ref) {
2051 write!(w, "{}", c_type).unwrap();
2053 } else if self.crate_types.traits.get(&full_path).is_some() {
2054 if is_ref && ptr_for_ref {
2055 write!(w, "*{} crate::{}", if is_mut { "mut" } else { "const" }, full_path).unwrap();
2057 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2059 write!(w, "crate::{}", full_path).unwrap();
2062 } else if self.crate_types.opaques.get(&full_path).is_some() || self.crate_types.mirrored_enums.get(&full_path).is_some() {
2063 if is_ref && ptr_for_ref {
2064 // ptr_for_ref implies we're returning the object, which we can't really do for
2065 // opaque or mirrored types without box'ing them, which is quite a waste, so return
2066 // the actual object itself (for opaque types we'll set the pointer to the actual
2067 // type and note that its a reference).
2068 write!(w, "crate::{}", full_path).unwrap();
2070 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2072 write!(w, "crate::{}", full_path).unwrap();
2079 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 {
2081 syn::Type::Path(p) => {
2082 if p.qself.is_some() {
2085 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
2086 if self.is_known_container(&full_path, is_ref) || self.is_transparent_container(&full_path, is_ref) {
2087 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);
2089 if let Some(aliased_type) = self.crate_types.type_aliases.get(&full_path).cloned() {
2090 return self.write_c_type_intern(w, &aliased_type, None, is_ref, is_mut, ptr_for_ref);
2093 self.write_c_path_intern(w, &p.path, generics, is_ref, is_mut, ptr_for_ref)
2095 syn::Type::Reference(r) => {
2096 self.write_c_type_intern(w, &*r.elem, generics, true, r.mutability.is_some(), ptr_for_ref)
2098 syn::Type::Array(a) => {
2099 if is_ref && is_mut {
2100 write!(w, "*mut [").unwrap();
2101 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2103 write!(w, "*const [").unwrap();
2104 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2106 let mut typecheck = Vec::new();
2107 if !self.write_c_type_intern(&mut typecheck, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2108 if typecheck[..] != ['u' as u8, '8' as u8] { return false; }
2110 if let syn::Expr::Lit(l) = &a.len {
2111 if let syn::Lit::Int(i) = &l.lit {
2113 if let Some(ty) = self.c_type_from_path(&format!("[u8; {}]", i.base10_digits()), false, ptr_for_ref) {
2114 write!(w, "{}", ty).unwrap();
2118 write!(w, "; {}]", i).unwrap();
2124 syn::Type::Slice(s) => {
2125 if !is_ref || is_mut { return false; }
2126 if let syn::Type::Path(p) = &*s.elem {
2127 let resolved = self.resolve_path(&p.path, generics);
2128 if self.is_primitive(&resolved) {
2129 write!(w, "{}::{}slice", Self::container_templ_path(), resolved).unwrap();
2132 } else if let syn::Type::Reference(r) = &*s.elem {
2133 if let syn::Type::Path(p) = &*r.elem {
2134 // Slices with "real types" inside are mapped as the equivalent non-ref Vec
2135 let resolved = self.resolve_path(&p.path, generics);
2136 let mangled_container = if let Some(ident) = self.crate_types.opaques.get(&resolved) {
2137 format!("CVec_{}Z", ident)
2138 } else if let Some(en) = self.crate_types.mirrored_enums.get(&resolved) {
2139 format!("CVec_{}Z", en.ident)
2140 } else if let Some(id) = p.path.get_ident() {
2141 format!("CVec_{}Z", id)
2142 } else { return false; };
2143 write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
2144 self.check_create_container(mangled_container, "Vec", vec![&*r.elem], generics, false)
2146 } else if let syn::Type::Tuple(_) = &*s.elem {
2147 let mut args = syn::punctuated::Punctuated::new();
2148 args.push(syn::GenericArgument::Type((*s.elem).clone()));
2149 let mut segments = syn::punctuated::Punctuated::new();
2150 segments.push(syn::PathSegment {
2151 ident: syn::Ident::new("Vec", Span::call_site()),
2152 arguments: syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
2153 colon2_token: None, lt_token: syn::Token![<](Span::call_site()), args, gt_token: syn::Token![>](Span::call_site()),
2156 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)
2159 syn::Type::Tuple(t) => {
2160 if t.elems.len() == 0 {
2163 self.write_c_mangled_container_path(w, t.elems.iter().collect(), generics,
2164 &format!("{}Tuple", t.elems.len()), is_ref, is_mut, ptr_for_ref)
2170 pub fn write_c_type<W: std::io::Write>(&mut self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) {
2171 assert!(self.write_c_type_intern(w, t, generics, false, false, ptr_for_ref));
2173 pub fn understood_c_path(&mut self, p: &syn::Path) -> bool {
2174 if p.leading_colon.is_some() { return false; }
2175 self.write_c_path_intern(&mut std::io::sink(), p, None, false, false, false)
2177 pub fn understood_c_type(&mut self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
2178 self.write_c_type_intern(&mut std::io::sink(), t, generics, false, false, false)