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::Named(fields) = &var.fields {
118 for field in fields.named.iter() {
119 match export_status(&field.attrs) {
120 ExportStatus::Export|ExportStatus::TestOnly => {},
121 ExportStatus::NoExport => return true,
124 } else if let syn::Fields::Unnamed(fields) = &var.fields {
125 for field in fields.unnamed.iter() {
126 match export_status(&field.attrs) {
127 ExportStatus::Export|ExportStatus::TestOnly => {},
128 ExportStatus::NoExport => return true,
136 /// A stack of sets of generic resolutions.
138 /// This tracks the template parameters for a function, struct, or trait, allowing resolution into
139 /// a concrete type. By pushing a new context onto the stack, this can track a function's template
140 /// parameters inside of a generic struct or trait.
142 /// It maps both direct types as well as Deref<Target = X>, mapping them via the provided
143 /// TypeResolver's resolve_path function (ie traits map to the concrete jump table, structs to the
144 /// concrete C container struct, etc).
145 pub struct GenericTypes<'a> {
146 typed_generics: Vec<HashMap<&'a syn::Ident, (String, Option<&'a syn::Path>)>>,
148 impl<'a> GenericTypes<'a> {
149 pub fn new() -> Self {
150 Self { typed_generics: vec![HashMap::new()], }
153 /// push a new context onto the stack, allowing for a new set of generics to be learned which
154 /// will override any lower contexts, but which will still fall back to resoltion via lower
156 pub fn push_ctx(&mut self) {
157 self.typed_generics.push(HashMap::new());
159 /// pop the latest context off the stack.
160 pub fn pop_ctx(&mut self) {
161 self.typed_generics.pop();
164 /// Learn the generics in generics in the current context, given a TypeResolver.
165 pub fn learn_generics<'b, 'c>(&mut self, generics: &'a syn::Generics, types: &'b TypeResolver<'a, 'c>) -> bool {
166 // First learn simple generics...
167 for generic in generics.params.iter() {
169 syn::GenericParam::Type(type_param) => {
170 let mut non_lifetimes_processed = false;
171 for bound in type_param.bounds.iter() {
172 if let syn::TypeParamBound::Trait(trait_bound) = bound {
173 if let Some(ident) = single_ident_generic_path_to_ident(&trait_bound.path) {
174 match &format!("{}", ident) as &str { "Send" => continue, "Sync" => continue, _ => {} }
176 if path_matches_nongeneric(&trait_bound.path, &["core", "clone", "Clone"]) { continue; }
178 assert_simple_bound(&trait_bound);
179 if let Some(mut path) = types.maybe_resolve_path(&trait_bound.path, None) {
180 if types.skip_path(&path) { continue; }
181 if non_lifetimes_processed { return false; }
182 non_lifetimes_processed = true;
183 let new_ident = if path != "std::ops::Deref" {
184 path = "crate::".to_string() + &path;
185 Some(&trait_bound.path)
187 self.typed_generics.last_mut().unwrap().insert(&type_param.ident, (path, new_ident));
188 } else { return false; }
195 // Then find generics where we are required to pass a Deref<Target=X> and pretend its just X.
196 if let Some(wh) = &generics.where_clause {
197 for pred in wh.predicates.iter() {
198 if let syn::WherePredicate::Type(t) = pred {
199 if let syn::Type::Path(p) = &t.bounded_ty {
200 if p.qself.is_some() { return false; }
201 if p.path.leading_colon.is_some() { return false; }
202 let mut p_iter = p.path.segments.iter();
203 if let Some(gen) = self.typed_generics.last_mut().unwrap().get_mut(&p_iter.next().unwrap().ident) {
204 if gen.0 != "std::ops::Deref" { return false; }
205 if &format!("{}", p_iter.next().unwrap().ident) != "Target" { return false; }
207 let mut non_lifetimes_processed = false;
208 for bound in t.bounds.iter() {
209 if let syn::TypeParamBound::Trait(trait_bound) = bound {
210 if non_lifetimes_processed { return false; }
211 non_lifetimes_processed = true;
212 assert_simple_bound(&trait_bound);
213 *gen = ("crate::".to_string() + &types.resolve_path(&trait_bound.path, None),
214 Some(&trait_bound.path));
217 } else { return false; }
218 } else { return false; }
222 for (_, (_, ident)) in self.typed_generics.last().unwrap().iter() {
223 if ident.is_none() { return false; }
228 /// Learn the associated types from the trait in the current context.
229 pub fn learn_associated_types<'b, 'c>(&mut self, t: &'a syn::ItemTrait, types: &'b TypeResolver<'a, 'c>) {
230 for item in t.items.iter() {
232 &syn::TraitItem::Type(ref t) => {
233 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
234 let mut bounds_iter = t.bounds.iter();
235 match bounds_iter.next().unwrap() {
236 syn::TypeParamBound::Trait(tr) => {
237 assert_simple_bound(&tr);
238 if let Some(mut path) = types.maybe_resolve_path(&tr.path, None) {
239 if types.skip_path(&path) { continue; }
240 // In general we handle Deref<Target=X> as if it were just X (and
241 // implement Deref<Target=Self> for relevant types). We don't
242 // bother to implement it for associated types, however, so we just
243 // ignore such bounds.
244 let new_ident = if path != "std::ops::Deref" {
245 path = "crate::".to_string() + &path;
248 self.typed_generics.last_mut().unwrap().insert(&t.ident, (path, new_ident));
249 } else { unimplemented!(); }
251 _ => unimplemented!(),
253 if bounds_iter.next().is_some() { unimplemented!(); }
260 /// Attempt to resolve an Ident as a generic parameter and return the full path.
261 pub fn maybe_resolve_ident<'b>(&'b self, ident: &syn::Ident) -> Option<&'b String> {
262 for gen in self.typed_generics.iter().rev() {
263 if let Some(res) = gen.get(ident).map(|(a, _)| a) {
269 /// Attempt to resolve a Path as a generic parameter and return the full path. as both a string
271 pub fn maybe_resolve_path<'b>(&'b self, path: &syn::Path) -> Option<(&'b String, &'a syn::Path)> {
272 if let Some(ident) = path.get_ident() {
273 for gen in self.typed_generics.iter().rev() {
274 if let Some(res) = gen.get(ident).map(|(a, b)| (a, b.unwrap())) {
279 // Associated types are usually specified as "Self::Generic", so we check for that
281 let mut it = path.segments.iter();
282 if path.segments.len() == 2 && format!("{}", it.next().unwrap().ident) == "Self" {
283 let ident = &it.next().unwrap().ident;
284 for gen in self.typed_generics.iter().rev() {
285 if let Some(res) = gen.get(ident).map(|(a, b)| (a, b.unwrap())) {
295 #[derive(Clone, PartialEq)]
296 // The type of declaration and the object itself
297 pub enum DeclType<'a> {
299 Trait(&'a syn::ItemTrait),
305 pub struct ImportResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
306 module_path: &'mod_lifetime str,
307 imports: HashMap<syn::Ident, (String, syn::Path)>,
308 declared: HashMap<syn::Ident, DeclType<'crate_lft>>,
309 priv_modules: HashSet<syn::Ident>,
311 impl<'mod_lifetime, 'crate_lft: 'mod_lifetime> ImportResolver<'mod_lifetime, 'crate_lft> {
312 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>) {
314 syn::UseTree::Path(p) => {
315 let new_path = format!("{}{}::", partial_path, p.ident);
316 path.push(syn::PathSegment { ident: p.ident.clone(), arguments: syn::PathArguments::None });
317 Self::process_use_intern(imports, &p.tree, &new_path, path);
319 syn::UseTree::Name(n) => {
320 let full_path = format!("{}{}", partial_path, n.ident);
321 path.push(syn::PathSegment { ident: n.ident.clone(), arguments: syn::PathArguments::None });
322 imports.insert(n.ident.clone(), (full_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
324 syn::UseTree::Group(g) => {
325 for i in g.items.iter() {
326 Self::process_use_intern(imports, i, partial_path, path.clone());
329 syn::UseTree::Rename(r) => {
330 let full_path = format!("{}{}", partial_path, r.ident);
331 path.push(syn::PathSegment { ident: r.ident.clone(), arguments: syn::PathArguments::None });
332 imports.insert(r.rename.clone(), (full_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
334 syn::UseTree::Glob(_) => {
335 eprintln!("Ignoring * use for {} - this may result in resolution failures", partial_path);
340 fn process_use(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::ItemUse) {
341 if let syn::Visibility::Public(_) = u.vis {
342 // We actually only use these for #[cfg(fuzztarget)]
343 eprintln!("Ignoring pub(use) tree!");
346 if u.leading_colon.is_some() { eprintln!("Ignoring leading-colon use!"); return; }
347 Self::process_use_intern(imports, &u.tree, "", syn::punctuated::Punctuated::new());
350 fn insert_primitive(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, id: &str) {
351 let ident = syn::Ident::new(id, Span::call_site());
352 let mut path = syn::punctuated::Punctuated::new();
353 path.push(syn::PathSegment { ident: ident.clone(), arguments: syn::PathArguments::None });
354 imports.insert(ident, (id.to_owned(), syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
357 pub fn new(module_path: &'mod_lifetime str, contents: &'crate_lft [syn::Item]) -> Self {
358 let mut imports = HashMap::new();
359 // Add primitives to the "imports" list:
360 Self::insert_primitive(&mut imports, "bool");
361 Self::insert_primitive(&mut imports, "u64");
362 Self::insert_primitive(&mut imports, "u32");
363 Self::insert_primitive(&mut imports, "u16");
364 Self::insert_primitive(&mut imports, "u8");
365 Self::insert_primitive(&mut imports, "usize");
366 Self::insert_primitive(&mut imports, "str");
367 Self::insert_primitive(&mut imports, "String");
369 // These are here to allow us to print native Rust types in trait fn impls even if we don't
371 Self::insert_primitive(&mut imports, "Result");
372 Self::insert_primitive(&mut imports, "Vec");
373 Self::insert_primitive(&mut imports, "Option");
375 let mut declared = HashMap::new();
376 let mut priv_modules = HashSet::new();
378 for item in contents.iter() {
380 syn::Item::Use(u) => Self::process_use(&mut imports, &u),
381 syn::Item::Struct(s) => {
382 if let syn::Visibility::Public(_) = s.vis {
383 match export_status(&s.attrs) {
384 ExportStatus::Export => { declared.insert(s.ident.clone(), DeclType::StructImported); },
385 ExportStatus::NoExport => { declared.insert(s.ident.clone(), DeclType::StructIgnored); },
386 ExportStatus::TestOnly => continue,
390 syn::Item::Type(t) if export_status(&t.attrs) == ExportStatus::Export => {
391 if let syn::Visibility::Public(_) = t.vis {
392 let mut process_alias = true;
393 for tok in t.generics.params.iter() {
394 if let syn::GenericParam::Lifetime(_) = tok {}
395 else { process_alias = false; }
399 syn::Type::Path(_) => { declared.insert(t.ident.clone(), DeclType::StructImported); },
405 syn::Item::Enum(e) => {
406 if let syn::Visibility::Public(_) = e.vis {
407 match export_status(&e.attrs) {
408 ExportStatus::Export if is_enum_opaque(e) => { declared.insert(e.ident.clone(), DeclType::EnumIgnored); },
409 ExportStatus::Export => { declared.insert(e.ident.clone(), DeclType::MirroredEnum); },
414 syn::Item::Trait(t) if export_status(&t.attrs) == ExportStatus::Export => {
415 if let syn::Visibility::Public(_) = t.vis {
416 declared.insert(t.ident.clone(), DeclType::Trait(t));
419 syn::Item::Mod(m) => {
420 priv_modules.insert(m.ident.clone());
426 Self { module_path, imports, declared, priv_modules }
429 pub fn get_declared_type(&self, ident: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
430 self.declared.get(ident)
433 pub fn maybe_resolve_declared(&self, id: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
434 self.declared.get(id)
437 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
438 if let Some((imp, _)) = self.imports.get(id) {
440 } else if self.declared.get(id).is_some() {
441 Some(self.module_path.to_string() + "::" + &format!("{}", id))
445 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
446 if let Some((imp, _)) = self.imports.get(id) {
448 } else if let Some(decl_type) = self.declared.get(id) {
450 DeclType::StructIgnored => None,
451 _ => Some(self.module_path.to_string() + "::" + &format!("{}", id)),
456 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
457 let p = if let Some(gen_types) = generics {
458 if let Some((_, synpath)) = gen_types.maybe_resolve_path(p_arg) {
463 if p.leading_colon.is_some() {
464 Some(p.segments.iter().enumerate().map(|(idx, seg)| {
465 format!("{}{}", if idx == 0 { "" } else { "::" }, seg.ident)
467 } else if let Some(id) = p.get_ident() {
468 self.maybe_resolve_ident(id)
470 if p.segments.len() == 1 {
471 let seg = p.segments.iter().next().unwrap();
472 return self.maybe_resolve_ident(&seg.ident);
474 let mut seg_iter = p.segments.iter();
475 let first_seg = seg_iter.next().unwrap();
476 let remaining: String = seg_iter.map(|seg| {
477 format!("::{}", seg.ident)
479 if let Some((imp, _)) = self.imports.get(&first_seg.ident) {
481 Some(imp.clone() + &remaining)
485 } else if let Some(_) = self.priv_modules.get(&first_seg.ident) {
486 Some(format!("{}::{}{}", self.module_path, first_seg.ident, remaining))
491 /// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern)
492 pub fn resolve_imported_refs(&self, mut ty: syn::Type) -> syn::Type {
494 syn::Type::Path(p) => {
495 if let Some(ident) = p.path.get_ident() {
496 if let Some((_, newpath)) = self.imports.get(ident) {
497 p.path = newpath.clone();
499 } else { unimplemented!(); }
501 syn::Type::Reference(r) => {
502 r.elem = Box::new(self.resolve_imported_refs((*r.elem).clone()));
504 syn::Type::Slice(s) => {
505 s.elem = Box::new(self.resolve_imported_refs((*s.elem).clone()));
507 syn::Type::Tuple(t) => {
508 for e in t.elems.iter_mut() {
509 *e = self.resolve_imported_refs(e.clone());
512 _ => unimplemented!(),
518 // templates_defined is walked to write the C++ header, so if we use the default hashing it get
519 // reordered on each genbindings run. Instead, we use SipHasher (which defaults to 0-keys) so that
520 // the sorting is stable across runs. It is deprecated, but the "replacement" doesn't actually
521 // accomplish the same goals, so we just ignore it.
523 pub type NonRandomHash = hash::BuildHasherDefault<hash::SipHasher>;
525 /// Top-level struct tracking everything which has been defined while walking the crate.
526 pub struct CrateTypes<'a> {
527 /// This may contain structs or enums, but only when either is mapped as
528 /// struct X { inner: *mut originalX, .. }
529 pub opaques: HashMap<String, &'a syn::Ident>,
530 /// Enums which are mapped as C enums with conversion functions
531 pub mirrored_enums: HashMap<String, &'a syn::ItemEnum>,
532 /// Traits which are mapped as a pointer + jump table
533 pub traits: HashMap<String, &'a syn::ItemTrait>,
534 /// Aliases from paths to some other Type
535 pub type_aliases: HashMap<String, syn::Type>,
536 /// Value is an alias to Key (maybe with some generics)
537 pub reverse_alias_map: HashMap<String, Vec<(syn::Path, syn::PathArguments)>>,
538 /// Template continer types defined, map from mangled type name -> whether a destructor fn
541 /// This is used at the end of processing to make C++ wrapper classes
542 pub templates_defined: HashMap<String, bool, NonRandomHash>,
543 /// The output file for any created template container types, written to as we find new
544 /// template containers which need to be defined.
545 pub template_file: &'a mut File,
546 /// Set of containers which are clonable
547 pub clonable_types: HashSet<String>,
549 pub trait_impls: HashMap<String, Vec<String>>,
552 /// A struct which tracks resolving rust types into C-mapped equivalents, exists for one specific
553 /// module but contains a reference to the overall CrateTypes tracking.
554 pub struct TypeResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
555 pub orig_crate: &'mod_lifetime str,
556 pub module_path: &'mod_lifetime str,
557 pub crate_types: &'mod_lifetime mut CrateTypes<'crate_lft>,
558 types: ImportResolver<'mod_lifetime, 'crate_lft>,
561 /// Returned by write_empty_rust_val_check_suffix to indicate what type of dereferencing needs to
562 /// happen to get the inner value of a generic.
563 enum EmptyValExpectedTy {
564 /// A type which has a flag for being empty (eg an array where we treat all-0s as empty).
566 /// A pointer that we want to dereference and move out of.
568 /// A pointer which we want to convert to a reference.
572 impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
573 pub fn new(orig_crate: &'a str, module_path: &'a str, types: ImportResolver<'a, 'c>, crate_types: &'a mut CrateTypes<'c>) -> Self {
574 Self { orig_crate, module_path, types, crate_types }
577 // *************************************************
578 // *** Well know type and conversion definitions ***
579 // *************************************************
581 /// Returns true we if can just skip passing this to C entirely
582 fn skip_path(&self, full_path: &str) -> bool {
583 full_path == "bitcoin::secp256k1::Secp256k1" ||
584 full_path == "bitcoin::secp256k1::Signing" ||
585 full_path == "bitcoin::secp256k1::Verification"
587 /// Returns true we if can just skip passing this to C entirely
588 fn no_arg_path_to_rust(&self, full_path: &str) -> &str {
589 if full_path == "bitcoin::secp256k1::Secp256k1" {
590 "&bitcoin::secp256k1::Secp256k1::new()"
591 } else { unimplemented!(); }
594 /// Returns true if the object is a primitive and is mapped as-is with no conversion
596 pub fn is_primitive(&self, full_path: &str) -> bool {
607 pub fn is_clonable(&self, ty: &str) -> bool {
608 if self.crate_types.clonable_types.contains(ty) { return true; }
609 if self.is_primitive(ty) { return true; }
612 "crate::c_types::Signature" => true,
613 "crate::c_types::TxOut" => true,
617 /// Gets the C-mapped type for types which are outside of the crate, or which are manually
618 /// ignored by for some reason need mapping anyway.
619 fn c_type_from_path<'b>(&self, full_path: &'b str, is_ref: bool, _ptr_for_ref: bool) -> Option<&'b str> {
620 if self.is_primitive(full_path) {
621 return Some(full_path);
624 "Result" => Some("crate::c_types::derived::CResult"),
625 "Vec" if !is_ref => Some("crate::c_types::derived::CVec"),
626 "Option" => Some(""),
628 // Note that no !is_ref types can map to an array because Rust and C's call semantics
629 // for arrays are different (https://github.com/eqrion/cbindgen/issues/528)
631 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
632 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes"),
633 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes"),
634 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes"),
635 "[u8; 3]" if !is_ref => Some("crate::c_types::ThreeBytes"), // Used for RGB values
637 "str" if is_ref => Some("crate::c_types::Str"),
638 "String" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
639 "String" if is_ref => Some("crate::c_types::Str"),
641 "std::time::Duration" => Some("u64"),
643 "bitcoin::secp256k1::key::PublicKey" => Some("crate::c_types::PublicKey"),
644 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature"),
645 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some("*const [u8; 32]"),
646 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some("crate::c_types::SecretKey"),
647 "bitcoin::secp256k1::Error" if !is_ref => Some("crate::c_types::Secp256k1Error"),
648 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice"),
649 "bitcoin::blockdata::script::Script" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
650 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::chain::transaction::OutPoint"),
651 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction"),
652 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut"),
653 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network"),
654 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("*const [u8; 80]"),
655 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice"),
657 // Newtypes that we just expose in their original form.
658 "bitcoin::hash_types::Txid" if is_ref => Some("*const [u8; 32]"),
659 "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
660 "bitcoin::hash_types::BlockHash" if is_ref => Some("*const [u8; 32]"),
661 "bitcoin::hash_types::BlockHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
662 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
663 "ln::channelmanager::PaymentHash" if is_ref => Some("*const [u8; 32]"),
664 "ln::channelmanager::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
665 "ln::channelmanager::PaymentPreimage" if is_ref => Some("*const [u8; 32]"),
666 "ln::channelmanager::PaymentPreimage" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
667 "ln::channelmanager::PaymentSecret" if is_ref => Some("crate::c_types::ThirtyTwoBytes"),
668 "ln::channelmanager::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
670 // Override the default since Records contain an fmt with a lifetime:
671 "util::logger::Record" => Some("*const std::os::raw::c_char"),
677 fn from_c_conversion_new_var_from_path<'b>(&self, _full_path: &str, _is_ref: bool) -> Option<(&'b str, &'b str)> {
680 fn from_c_conversion_prefix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
681 if self.is_primitive(full_path) {
682 return Some("".to_owned());
685 "Vec" if !is_ref => Some("local_"),
686 "Result" if !is_ref => Some("local_"),
687 "Option" if is_ref => Some("&local_"),
688 "Option" => Some("local_"),
690 "[u8; 32]" if is_ref => Some("unsafe { &*"),
691 "[u8; 32]" if !is_ref => Some(""),
692 "[u8; 16]" if !is_ref => Some(""),
693 "[u8; 10]" if !is_ref => Some(""),
694 "[u8; 4]" if !is_ref => Some(""),
695 "[u8; 3]" if !is_ref => Some(""),
697 "[u8]" if is_ref => Some(""),
698 "[usize]" if is_ref => Some(""),
700 "str" if is_ref => Some(""),
701 "String" if !is_ref => Some("String::from_utf8("),
702 // Note that we'll panic for String if is_ref, as we only have non-owned memory, we
703 // cannot create a &String.
705 "std::time::Duration" => Some("std::time::Duration::from_secs("),
707 "bitcoin::secp256k1::key::PublicKey" if is_ref => Some("&"),
708 "bitcoin::secp256k1::key::PublicKey" => Some(""),
709 "bitcoin::secp256k1::Signature" if is_ref => Some("&"),
710 "bitcoin::secp256k1::Signature" => Some(""),
711 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some("&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *"),
712 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some(""),
713 "bitcoin::blockdata::script::Script" if is_ref => Some("&::bitcoin::blockdata::script::Script::from(Vec::from("),
714 "bitcoin::blockdata::script::Script" if !is_ref => Some("::bitcoin::blockdata::script::Script::from("),
715 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some("&"),
716 "bitcoin::blockdata::transaction::Transaction" => Some(""),
717 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(""),
718 "bitcoin::network::constants::Network" => Some(""),
719 "bitcoin::blockdata::block::BlockHeader" => Some("&::bitcoin::consensus::encode::deserialize(unsafe { &*"),
720 "bitcoin::blockdata::block::Block" if is_ref => Some("&::bitcoin::consensus::encode::deserialize("),
722 // Newtypes that we just expose in their original form.
723 "bitcoin::hash_types::Txid" if is_ref => Some("&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*"),
724 "bitcoin::hash_types::Txid" if !is_ref => Some("::bitcoin::hash_types::Txid::from_slice(&"),
725 "bitcoin::hash_types::BlockHash" => Some("::bitcoin::hash_types::BlockHash::from_slice(&"),
726 "ln::channelmanager::PaymentHash" if !is_ref => Some("::lightning::ln::channelmanager::PaymentHash("),
727 "ln::channelmanager::PaymentHash" if is_ref => Some("&::lightning::ln::channelmanager::PaymentHash(unsafe { *"),
728 "ln::channelmanager::PaymentPreimage" if !is_ref => Some("::lightning::ln::channelmanager::PaymentPreimage("),
729 "ln::channelmanager::PaymentPreimage" if is_ref => Some("&::lightning::ln::channelmanager::PaymentPreimage(unsafe { *"),
730 "ln::channelmanager::PaymentSecret" => Some("::lightning::ln::channelmanager::PaymentSecret("),
732 // List of traits we map (possibly during processing of other files):
733 "crate::util::logger::Logger" => Some(""),
736 }.map(|s| s.to_owned())
738 fn from_c_conversion_suffix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
739 if self.is_primitive(full_path) {
740 return Some("".to_owned());
743 "Vec" if !is_ref => Some(""),
744 "Option" => Some(""),
745 "Result" if !is_ref => Some(""),
747 "[u8; 32]" if is_ref => Some("}"),
748 "[u8; 32]" if !is_ref => Some(".data"),
749 "[u8; 16]" if !is_ref => Some(".data"),
750 "[u8; 10]" if !is_ref => Some(".data"),
751 "[u8; 4]" if !is_ref => Some(".data"),
752 "[u8; 3]" if !is_ref => Some(".data"),
754 "[u8]" if is_ref => Some(".to_slice()"),
755 "[usize]" if is_ref => Some(".to_slice()"),
757 "str" if is_ref => Some(".into()"),
758 "String" if !is_ref => Some(".into_rust()).unwrap()"),
760 "std::time::Duration" => Some(")"),
762 "bitcoin::secp256k1::key::PublicKey" => Some(".into_rust()"),
763 "bitcoin::secp256k1::Signature" => Some(".into_rust()"),
764 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some(".into_rust()"),
765 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some("}[..]).unwrap()"),
766 "bitcoin::blockdata::script::Script" if is_ref => Some(".to_slice()))"),
767 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_rust())"),
768 "bitcoin::blockdata::transaction::Transaction" => Some(".into_bitcoin()"),
769 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(".into_rust()"),
770 "bitcoin::network::constants::Network" => Some(".into_bitcoin()"),
771 "bitcoin::blockdata::block::BlockHeader" => Some(" }).unwrap()"),
772 "bitcoin::blockdata::block::Block" => Some(".to_slice()).unwrap()"),
774 // Newtypes that we just expose in their original form.
775 "bitcoin::hash_types::Txid" if is_ref => Some(" }[..]).unwrap()"),
776 "bitcoin::hash_types::Txid" => Some(".data[..]).unwrap()"),
777 "bitcoin::hash_types::BlockHash" if !is_ref => Some(".data[..]).unwrap()"),
778 "ln::channelmanager::PaymentHash" if !is_ref => Some(".data)"),
779 "ln::channelmanager::PaymentHash" if is_ref => Some(" })"),
780 "ln::channelmanager::PaymentPreimage" if !is_ref => Some(".data)"),
781 "ln::channelmanager::PaymentPreimage" if is_ref => Some(" })"),
782 "ln::channelmanager::PaymentSecret" => Some(".data)"),
784 // List of traits we map (possibly during processing of other files):
785 "crate::util::logger::Logger" => Some(""),
788 }.map(|s| s.to_owned())
791 fn to_c_conversion_new_var_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<(&'b str, &'b str)> {
792 if self.is_primitive(full_path) {
796 "[u8]" if is_ref => Some(("crate::c_types::u8slice::from_slice(", ")")),
797 "[usize]" if is_ref => Some(("crate::c_types::usizeslice::from_slice(", ")")),
799 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
800 "bitcoin::blockdata::transaction::Transaction" if !is_ref => Some(("::bitcoin::consensus::encode::serialize(&", ")")),
801 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(("{ let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(", ")); s }")),
802 "bitcoin::blockdata::block::Block" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
803 "bitcoin::hash_types::Txid" => None,
805 // Override the default since Records contain an fmt with a lifetime:
806 // TODO: We should include the other record fields
807 "util::logger::Record" => Some(("std::ffi::CString::new(format!(\"{}\", ", ".args)).unwrap()")),
809 }.map(|s| s.to_owned())
811 fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
812 if self.is_primitive(full_path) {
813 return Some("".to_owned());
816 "Result" if !is_ref => Some("local_"),
817 "Vec" if !is_ref => Some("local_"),
818 "Option" => Some("local_"),
820 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
821 "[u8; 32]" if is_ref => Some("&"),
822 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes { data: "),
823 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes { data: "),
824 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes { data: "),
825 "[u8; 3]" if is_ref => Some("&"),
827 "[u8]" if is_ref => Some("local_"),
828 "[usize]" if is_ref => Some("local_"),
830 "str" if is_ref => Some(""),
831 "String" => Some(""),
833 "std::time::Duration" => Some(""),
835 "bitcoin::secp256k1::key::PublicKey" => Some("crate::c_types::PublicKey::from_rust(&"),
836 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature::from_rust(&"),
837 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some(""),
838 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some("crate::c_types::SecretKey::from_rust("),
839 "bitcoin::secp256k1::Error" if !is_ref => Some("crate::c_types::Secp256k1Error::from_rust("),
840 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice::from_slice(&"),
841 "bitcoin::blockdata::script::Script" if !is_ref => Some(""),
842 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction::from_vec(local_"),
843 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::c_types::bitcoin_to_C_outpoint("),
844 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut::from_rust("),
845 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("&local_"),
846 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice::from_slice(&local_"),
848 "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
850 // Newtypes that we just expose in their original form.
851 "bitcoin::hash_types::Txid" if is_ref => Some(""),
852 "bitcoin::hash_types::BlockHash" if is_ref => Some(""),
853 "bitcoin::hash_types::BlockHash" => Some("crate::c_types::ThirtyTwoBytes { data: "),
854 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
855 "ln::channelmanager::PaymentHash" if is_ref => Some("&"),
856 "ln::channelmanager::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
857 "ln::channelmanager::PaymentPreimage" if is_ref => Some("&"),
858 "ln::channelmanager::PaymentPreimage" => Some("crate::c_types::ThirtyTwoBytes { data: "),
859 "ln::channelmanager::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
861 // Override the default since Records contain an fmt with a lifetime:
862 "util::logger::Record" => Some("local_"),
865 }.map(|s| s.to_owned())
867 fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
868 if self.is_primitive(full_path) {
869 return Some("".to_owned());
872 "Result" if !is_ref => Some(""),
873 "Vec" if !is_ref => Some(".into()"),
874 "Option" => Some(""),
876 "[u8; 32]" if !is_ref => Some(" }"),
877 "[u8; 32]" if is_ref => Some(""),
878 "[u8; 16]" if !is_ref => Some(" }"),
879 "[u8; 10]" if !is_ref => Some(" }"),
880 "[u8; 4]" if !is_ref => Some(" }"),
881 "[u8; 3]" if is_ref => Some(""),
883 "[u8]" if is_ref => Some(""),
884 "[usize]" if is_ref => Some(""),
886 "str" if is_ref => Some(".into()"),
887 "String" if !is_ref => Some(".into_bytes().into()"),
888 "String" if is_ref => Some(".as_str().into()"),
890 "std::time::Duration" => Some(".as_secs()"),
892 "bitcoin::secp256k1::key::PublicKey" => Some(")"),
893 "bitcoin::secp256k1::Signature" => Some(")"),
894 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some(")"),
895 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some(".as_ref()"),
896 "bitcoin::secp256k1::Error" if !is_ref => Some(")"),
897 "bitcoin::blockdata::script::Script" if is_ref => Some("[..])"),
898 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_bytes().into()"),
899 "bitcoin::blockdata::transaction::Transaction" => Some(")"),
900 "bitcoin::blockdata::transaction::OutPoint" => Some(")"),
901 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(")"),
902 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(""),
903 "bitcoin::blockdata::block::Block" if is_ref => Some(")"),
905 "bitcoin::hash_types::Txid" if !is_ref => Some(".into_inner() }"),
907 // Newtypes that we just expose in their original form.
908 "bitcoin::hash_types::Txid" if is_ref => Some(".as_inner()"),
909 "bitcoin::hash_types::BlockHash" if is_ref => Some(".as_inner()"),
910 "bitcoin::hash_types::BlockHash" => Some(".into_inner() }"),
911 "bitcoin::secp256k1::Message" if !is_ref => Some(".as_ref().clone() }"),
912 "ln::channelmanager::PaymentHash" if is_ref => Some(".0"),
913 "ln::channelmanager::PaymentHash" => Some(".0 }"),
914 "ln::channelmanager::PaymentPreimage" if is_ref => Some(".0"),
915 "ln::channelmanager::PaymentPreimage" => Some(".0 }"),
916 "ln::channelmanager::PaymentSecret" if !is_ref => Some(".0 }"),
918 // Override the default since Records contain an fmt with a lifetime:
919 "util::logger::Record" => Some(".as_ptr()"),
922 }.map(|s| s.to_owned())
925 fn empty_val_check_suffix_from_path(&self, full_path: &str) -> Option<&str> {
927 "ln::channelmanager::PaymentSecret" => Some(".data == [0; 32]"),
928 "bitcoin::secp256k1::key::PublicKey" => Some(".is_null()"),
929 "bitcoin::secp256k1::Signature" => Some(".is_null()"),
934 // ****************************
935 // *** Container Processing ***
936 // ****************************
938 /// Returns the module path in the generated mapping crate to the containers which we generate
939 /// when writing to CrateTypes::template_file.
940 pub fn generated_container_path() -> &'static str {
941 "crate::c_types::derived"
943 /// Returns the module path in the generated mapping crate to the container templates, which
944 /// are then concretized and put in the generated container path/template_file.
945 fn container_templ_path() -> &'static str {
949 /// Returns true if this is a "transparent" container, ie an Option or a container which does
950 /// not require a generated continer class.
951 fn is_transparent_container(&self, full_path: &str, _is_ref: bool) -> bool {
952 full_path == "Option"
954 /// Returns true if this is a known, supported, non-transparent container.
955 fn is_known_container(&self, full_path: &str, is_ref: bool) -> bool {
956 (full_path == "Result" && !is_ref) || (full_path == "Vec" && !is_ref) || full_path.ends_with("Tuple")
958 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)
959 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
960 // expecting one element in the vec per generic type, each of which is inline-converted
961 -> Option<(&'b str, Vec<(String, String)>, &'b str)> {
963 "Result" if !is_ref => {
965 vec![(" { Ok(mut o) => crate::c_types::CResultTempl::ok(".to_string(), "o".to_string()),
966 (").into(), Err(mut e) => crate::c_types::CResultTempl::err(".to_string(), "e".to_string())],
969 "Vec" if !is_ref => {
970 Some(("Vec::new(); for mut item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }"))
973 Some(("Vec::new(); for item in ", vec![(format!(".iter() {{ local_{}.push(", var_name), "**item".to_string())], "); }"))
976 if let Some(syn::Type::Path(p)) = single_contained {
977 if self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)) {
979 return Some(("if ", vec![
980 (".is_none() { std::ptr::null() } else { ".to_owned(), format!("({}.as_ref().unwrap())", var_access))
983 return Some(("if ", vec![
984 (".is_none() { std::ptr::null_mut() } else { ".to_owned(), format!("({}.unwrap())", var_access))
989 if let Some(t) = single_contained {
990 let mut v = Vec::new();
991 self.write_empty_rust_val(generics, &mut v, t);
992 let s = String::from_utf8(v).unwrap();
993 return Some(("if ", vec![
994 (format!(".is_none() {{ {} }} else {{ ", s), format!("({}.unwrap())", var_access))
996 } else { unreachable!(); }
1002 /// only_contained_has_inner implies that there is only one contained element in the container
1003 /// and it has an inner field (ie is an "opaque" type we've defined).
1004 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)
1005 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1006 // expecting one element in the vec per generic type, each of which is inline-converted
1007 -> Option<(&'b str, Vec<(String, String)>, &'b str)> {
1009 "Result" if !is_ref => {
1011 vec![(".result_ok { true => Ok(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.result)) }})", var_access)),
1012 ("), false => Err(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.err)) }})", var_access))],
1015 "Vec"|"Slice" if !is_ref => {
1016 Some(("Vec::new(); for mut item in ", vec![(format!(".into_rust().drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }"))
1018 "Slice" if is_ref => {
1019 Some(("Vec::new(); for mut item in ", vec![(format!(".as_slice().iter() {{ local_{}.push(", var_name), "item".to_string())], "); }"))
1022 if let Some(syn::Type::Path(p)) = single_contained {
1023 if self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)) {
1025 return Some(("if ", vec![(".inner.is_null() { None } else { Some((*".to_string(), format!("{}", var_access))], ").clone()) }"))
1027 return Some(("if ", vec![(".inner.is_null() { None } else { Some(".to_string(), format!("{}", var_access))], ") }"));
1032 if let Some(t) = single_contained {
1033 let mut v = Vec::new();
1034 let ret_ref = self.write_empty_rust_val_check_suffix(generics, &mut v, t);
1035 let s = String::from_utf8(v).unwrap();
1037 EmptyValExpectedTy::ReferenceAsPointer =>
1038 return Some(("if ", vec![
1039 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ &mut *{} }}", var_access))
1041 EmptyValExpectedTy::OwnedPointer =>
1042 return Some(("if ", vec![
1043 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ *Box::from_raw({}) }}", var_access))
1045 EmptyValExpectedTy::NonPointer =>
1046 return Some(("if ", vec![
1047 (format!("{} {{ None }} else {{ Some(", s), format!("{}", var_access))
1050 } else { unreachable!(); }
1056 // *************************************************
1057 // *** Type definition during main.rs processing ***
1058 // *************************************************
1060 pub fn get_declared_type(&'a self, ident: &syn::Ident) -> Option<&'a DeclType<'c>> {
1061 self.types.get_declared_type(ident)
1063 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1064 pub fn c_type_has_inner_from_path(&self, full_path: &str) -> bool{
1065 self.crate_types.opaques.get(full_path).is_some()
1068 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
1069 self.types.maybe_resolve_ident(id)
1072 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
1073 self.types.maybe_resolve_non_ignored_ident(id)
1076 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
1077 self.types.maybe_resolve_path(p_arg, generics)
1079 pub fn resolve_path(&self, p: &syn::Path, generics: Option<&GenericTypes>) -> String {
1080 self.maybe_resolve_path(p, generics).unwrap()
1083 // ***********************************
1084 // *** Original Rust Type Printing ***
1085 // ***********************************
1087 fn in_rust_prelude(resolved_path: &str) -> bool {
1088 match resolved_path {
1096 fn write_rust_path<W: std::io::Write>(&self, w: &mut W, generics_resolver: Option<&GenericTypes>, path: &syn::Path) {
1097 if let Some(resolved) = self.maybe_resolve_path(&path, generics_resolver) {
1098 if self.is_primitive(&resolved) {
1099 write!(w, "{}", path.get_ident().unwrap()).unwrap();
1101 // TODO: We should have a generic "is from a dependency" check here instead of
1102 // checking for "bitcoin" explicitly.
1103 if resolved.starts_with("bitcoin::") || Self::in_rust_prelude(&resolved) {
1104 write!(w, "{}", resolved).unwrap();
1105 // If we're printing a generic argument, it needs to reference the crate, otherwise
1106 // the original crate:
1107 } else if self.maybe_resolve_path(&path, None).as_ref() == Some(&resolved) {
1108 write!(w, "{}::{}", self.orig_crate, resolved).unwrap();
1110 write!(w, "crate::{}", resolved).unwrap();
1113 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().last().unwrap().arguments {
1114 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1117 if path.leading_colon.is_some() {
1118 write!(w, "::").unwrap();
1120 for (idx, seg) in path.segments.iter().enumerate() {
1121 if idx != 0 { write!(w, "::").unwrap(); }
1122 write!(w, "{}", seg.ident).unwrap();
1123 if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
1124 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1129 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>) {
1130 let mut had_params = false;
1131 for (idx, arg) in generics.enumerate() {
1132 if idx != 0 { write!(w, ", ").unwrap(); } else { write!(w, "<").unwrap(); }
1135 syn::GenericParam::Lifetime(lt) => write!(w, "'{}", lt.lifetime.ident).unwrap(),
1136 syn::GenericParam::Type(t) => {
1137 write!(w, "{}", t.ident).unwrap();
1138 if t.colon_token.is_some() { write!(w, ":").unwrap(); }
1139 for (idx, bound) in t.bounds.iter().enumerate() {
1140 if idx != 0 { write!(w, " + ").unwrap(); }
1142 syn::TypeParamBound::Trait(tb) => {
1143 if tb.paren_token.is_some() || tb.lifetimes.is_some() { unimplemented!(); }
1144 self.write_rust_path(w, generics_resolver, &tb.path);
1146 _ => unimplemented!(),
1149 if t.eq_token.is_some() || t.default.is_some() { unimplemented!(); }
1151 _ => unimplemented!(),
1154 if had_params { write!(w, ">").unwrap(); }
1157 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>) {
1158 write!(w, "<").unwrap();
1159 for (idx, arg) in generics.enumerate() {
1160 if idx != 0 { write!(w, ", ").unwrap(); }
1162 syn::GenericArgument::Type(t) => self.write_rust_type(w, generics_resolver, t),
1163 _ => unimplemented!(),
1166 write!(w, ">").unwrap();
1168 pub fn write_rust_type<W: std::io::Write>(&self, w: &mut W, generics: Option<&GenericTypes>, t: &syn::Type) {
1170 syn::Type::Path(p) => {
1171 if p.qself.is_some() {
1174 self.write_rust_path(w, generics, &p.path);
1176 syn::Type::Reference(r) => {
1177 write!(w, "&").unwrap();
1178 if let Some(lft) = &r.lifetime {
1179 write!(w, "'{} ", lft.ident).unwrap();
1181 if r.mutability.is_some() {
1182 write!(w, "mut ").unwrap();
1184 self.write_rust_type(w, generics, &*r.elem);
1186 syn::Type::Array(a) => {
1187 write!(w, "[").unwrap();
1188 self.write_rust_type(w, generics, &a.elem);
1189 if let syn::Expr::Lit(l) = &a.len {
1190 if let syn::Lit::Int(i) = &l.lit {
1191 write!(w, "; {}]", i).unwrap();
1192 } else { unimplemented!(); }
1193 } else { unimplemented!(); }
1195 syn::Type::Slice(s) => {
1196 write!(w, "[").unwrap();
1197 self.write_rust_type(w, generics, &s.elem);
1198 write!(w, "]").unwrap();
1200 syn::Type::Tuple(s) => {
1201 write!(w, "(").unwrap();
1202 for (idx, t) in s.elems.iter().enumerate() {
1203 if idx != 0 { write!(w, ", ").unwrap(); }
1204 self.write_rust_type(w, generics, &t);
1206 write!(w, ")").unwrap();
1208 _ => unimplemented!(),
1212 /// Prints a constructor for something which is "uninitialized" (but obviously not actually
1213 /// unint'd memory).
1214 pub fn write_empty_rust_val<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) {
1216 syn::Type::Path(p) => {
1217 let resolved = self.resolve_path(&p.path, generics);
1218 if self.crate_types.opaques.get(&resolved).is_some() {
1219 write!(w, "crate::{} {{ inner: std::ptr::null_mut(), is_owned: true }}", resolved).unwrap();
1221 // Assume its a manually-mapped C type, where we can just define an null() fn
1222 write!(w, "{}::null()", self.c_type_from_path(&resolved, false, false).unwrap()).unwrap();
1225 syn::Type::Array(a) => {
1226 if let syn::Expr::Lit(l) = &a.len {
1227 if let syn::Lit::Int(i) = &l.lit {
1228 if i.base10_digits().parse::<usize>().unwrap() < 32 {
1229 // Blindly assume that if we're trying to create an empty value for an
1230 // array < 32 entries that all-0s may be a valid state.
1233 let arrty = format!("[u8; {}]", i.base10_digits());
1234 write!(w, "{}", self.to_c_conversion_inline_prefix_from_path(&arrty, false, false).unwrap()).unwrap();
1235 write!(w, "[0; {}]", i.base10_digits()).unwrap();
1236 write!(w, "{}", self.to_c_conversion_inline_suffix_from_path(&arrty, false, false).unwrap()).unwrap();
1237 } else { unimplemented!(); }
1238 } else { unimplemented!(); }
1240 _ => unimplemented!(),
1244 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1245 /// See EmptyValExpectedTy for information on return types.
1246 fn write_empty_rust_val_check_suffix<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) -> EmptyValExpectedTy {
1248 syn::Type::Path(p) => {
1249 let resolved = self.resolve_path(&p.path, generics);
1250 if self.crate_types.opaques.get(&resolved).is_some() {
1251 write!(w, ".inner.is_null()").unwrap();
1252 EmptyValExpectedTy::NonPointer
1254 if let Some(suffix) = self.empty_val_check_suffix_from_path(&resolved) {
1255 write!(w, "{}", suffix).unwrap();
1256 // We may eventually need to allow empty_val_check_suffix_from_path to specify if we need a deref or not
1257 EmptyValExpectedTy::NonPointer
1259 write!(w, " == std::ptr::null_mut()").unwrap();
1260 EmptyValExpectedTy::OwnedPointer
1264 syn::Type::Array(a) => {
1265 if let syn::Expr::Lit(l) = &a.len {
1266 if let syn::Lit::Int(i) = &l.lit {
1267 write!(w, " == [0; {}]", i.base10_digits()).unwrap();
1268 EmptyValExpectedTy::NonPointer
1269 } else { unimplemented!(); }
1270 } else { unimplemented!(); }
1272 syn::Type::Slice(_) => {
1273 // Option<[]> always implies that we want to treat len() == 0 differently from
1274 // None, so we always map an Option<[]> into a pointer.
1275 write!(w, " == std::ptr::null_mut()").unwrap();
1276 EmptyValExpectedTy::ReferenceAsPointer
1278 _ => unimplemented!(),
1282 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1283 pub fn write_empty_rust_val_check<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type, var_access: &str) {
1285 syn::Type::Path(_) => {
1286 write!(w, "{}", var_access).unwrap();
1287 self.write_empty_rust_val_check_suffix(generics, w, t);
1289 syn::Type::Array(a) => {
1290 if let syn::Expr::Lit(l) = &a.len {
1291 if let syn::Lit::Int(i) = &l.lit {
1292 let arrty = format!("[u8; {}]", i.base10_digits());
1293 // We don't (yet) support a new-var conversion here.
1294 assert!(self.from_c_conversion_new_var_from_path(&arrty, false).is_none());
1296 self.from_c_conversion_prefix_from_path(&arrty, false).unwrap(),
1298 self.from_c_conversion_suffix_from_path(&arrty, false).unwrap()).unwrap();
1299 self.write_empty_rust_val_check_suffix(generics, w, t);
1300 } else { unimplemented!(); }
1301 } else { unimplemented!(); }
1303 _ => unimplemented!(),
1307 // ********************************
1308 // *** Type conversion printing ***
1309 // ********************************
1311 /// Returns true we if can just skip passing this to C entirely
1312 pub fn skip_arg(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
1314 syn::Type::Path(p) => {
1315 if p.qself.is_some() { unimplemented!(); }
1316 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1317 self.skip_path(&full_path)
1320 syn::Type::Reference(r) => {
1321 self.skip_arg(&*r.elem, generics)
1326 pub fn no_arg_to_rust<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1328 syn::Type::Path(p) => {
1329 if p.qself.is_some() { unimplemented!(); }
1330 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1331 write!(w, "{}", self.no_arg_path_to_rust(&full_path)).unwrap();
1334 syn::Type::Reference(r) => {
1335 self.no_arg_to_rust(w, &*r.elem, generics);
1341 fn write_conversion_inline_intern<W: std::io::Write,
1342 LP: Fn(&str, bool, bool) -> Option<String>, DL: Fn(&mut W, &DeclType, &str, bool, bool), SC: Fn(bool) -> &'static str>
1343 (&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool,
1344 tupleconv: &str, prefix: bool, sliceconv: SC, path_lookup: LP, decl_lookup: DL) {
1346 syn::Type::Reference(r) => {
1347 self.write_conversion_inline_intern(w, &*r.elem, generics, true, r.mutability.is_some(),
1348 ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1350 syn::Type::Path(p) => {
1351 if p.qself.is_some() {
1355 let resolved_path = self.resolve_path(&p.path, generics);
1356 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1357 return self.write_conversion_inline_intern(w, aliased_type, None, is_ref, is_mut, ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1358 } else if let Some(c_type) = path_lookup(&resolved_path, is_ref, ptr_for_ref) {
1359 write!(w, "{}", c_type).unwrap();
1360 } else if self.crate_types.opaques.get(&resolved_path).is_some() {
1361 decl_lookup(w, &DeclType::StructImported, &resolved_path, is_ref, is_mut);
1362 } else if self.crate_types.mirrored_enums.get(&resolved_path).is_some() {
1363 decl_lookup(w, &DeclType::MirroredEnum, &resolved_path, is_ref, is_mut);
1364 } else if let Some(t) = self.crate_types.traits.get(&resolved_path) {
1365 decl_lookup(w, &DeclType::Trait(t), &resolved_path, is_ref, is_mut);
1366 } else if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
1367 if let Some(decl_type) = self.types.maybe_resolve_declared(ident) {
1368 decl_lookup(w, decl_type, &self.maybe_resolve_ident(ident).unwrap(), is_ref, is_mut);
1369 } else { unimplemented!(); }
1370 } else { unimplemented!(); }
1372 syn::Type::Array(a) => {
1373 // We assume all arrays contain only [int_literal; X]s.
1374 // This may result in some outputs not compiling.
1375 if let syn::Expr::Lit(l) = &a.len {
1376 if let syn::Lit::Int(i) = &l.lit {
1377 write!(w, "{}", path_lookup(&format!("[u8; {}]", i.base10_digits()), is_ref, ptr_for_ref).unwrap()).unwrap();
1378 } else { unimplemented!(); }
1379 } else { unimplemented!(); }
1381 syn::Type::Slice(s) => {
1382 // We assume all slices contain only literals or references.
1383 // This may result in some outputs not compiling.
1384 if let syn::Type::Path(p) = &*s.elem {
1385 let resolved = self.resolve_path(&p.path, generics);
1386 assert!(self.is_primitive(&resolved));
1387 write!(w, "{}", path_lookup("[u8]", is_ref, ptr_for_ref).unwrap()).unwrap();
1388 } else if let syn::Type::Reference(r) = &*s.elem {
1389 if let syn::Type::Path(p) = &*r.elem {
1390 write!(w, "{}", sliceconv(self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)))).unwrap();
1391 } else { unimplemented!(); }
1392 } else if let syn::Type::Tuple(t) = &*s.elem {
1393 assert!(!t.elems.is_empty());
1395 write!(w, "&local_").unwrap();
1397 let mut needs_map = false;
1398 for e in t.elems.iter() {
1399 if let syn::Type::Reference(_) = e {
1404 write!(w, ".iter().map(|(").unwrap();
1405 for i in 0..t.elems.len() {
1406 write!(w, "{}{}", if i != 0 { ", " } else { "" }, ('a' as u8 + i as u8) as char).unwrap();
1408 write!(w, ")| (").unwrap();
1409 for (idx, e) in t.elems.iter().enumerate() {
1410 if let syn::Type::Reference(_) = e {
1411 write!(w, "{}{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1412 } else if let syn::Type::Path(_) = e {
1413 write!(w, "{}*{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1414 } else { unimplemented!(); }
1416 write!(w, ")).collect::<Vec<_>>()[..]").unwrap();
1419 } else { unimplemented!(); }
1421 syn::Type::Tuple(t) => {
1422 if t.elems.is_empty() {
1423 // cbindgen has poor support for (), see, eg https://github.com/eqrion/cbindgen/issues/527
1424 // so work around it by just pretending its a 0u8
1425 write!(w, "{}", tupleconv).unwrap();
1427 if prefix { write!(w, "local_").unwrap(); }
1430 _ => unimplemented!(),
1434 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) {
1435 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "0u8 /*", true, |_| "local_",
1436 |a, b, c| self.to_c_conversion_inline_prefix_from_path(a, b, c),
1437 |w, decl_type, decl_path, is_ref, _is_mut| {
1439 DeclType::MirroredEnum if is_ref && ptr_for_ref => write!(w, "crate::{}::from_native(&", decl_path).unwrap(),
1440 DeclType::MirroredEnum if is_ref => write!(w, "&crate::{}::from_native(&", decl_path).unwrap(),
1441 DeclType::MirroredEnum => write!(w, "crate::{}::native_into(", decl_path).unwrap(),
1442 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1443 write!(w, "crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1444 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1445 write!(w, "crate::{} {{ inner: unsafe {{ ( (&(", decl_path).unwrap(),
1446 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1447 write!(w, "&crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1448 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1449 write!(w, "crate::{} {{ inner: ", decl_path).unwrap(),
1450 DeclType::EnumIgnored|DeclType::StructImported if !is_ref =>
1451 write!(w, "crate::{} {{ inner: Box::into_raw(Box::new(", decl_path).unwrap(),
1452 DeclType::Trait(_) if is_ref => write!(w, "&").unwrap(),
1453 DeclType::Trait(_) if !is_ref => {},
1454 _ => panic!("{:?}", decl_path),
1458 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) {
1459 self.write_to_c_conversion_inline_prefix_inner(w, t, generics, false, ptr_for_ref, false);
1461 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) {
1462 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "*/", false, |_| ".into()",
1463 |a, b, c| self.to_c_conversion_inline_suffix_from_path(a, b, c),
1464 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1465 DeclType::MirroredEnum => write!(w, ")").unwrap(),
1466 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1467 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1468 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1469 write!(w, ") as *const _) as *mut _) }}, is_owned: false }}").unwrap(),
1470 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1471 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1472 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1473 write!(w, ", is_owned: true }}").unwrap(),
1474 DeclType::EnumIgnored|DeclType::StructImported if !is_ref => write!(w, ")), is_owned: true }}").unwrap(),
1475 DeclType::Trait(_) if is_ref => {},
1476 DeclType::Trait(_) => {
1477 // This is used when we're converting a concrete Rust type into a C trait
1478 // for use when a Rust trait method returns an associated type.
1479 // Because all of our C traits implement From<RustTypesImplementingTraits>
1480 // we can just call .into() here and be done.
1481 write!(w, ".into()").unwrap()
1483 _ => unimplemented!(),
1486 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) {
1487 self.write_to_c_conversion_inline_suffix_inner(w, t, generics, false, ptr_for_ref, false);
1490 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) {
1491 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "() /*", true, |_| "&local_",
1492 |a, b, _c| self.from_c_conversion_prefix_from_path(a, b),
1493 |w, decl_type, _full_path, is_ref, is_mut| match decl_type {
1494 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, "unsafe {{ &*(*").unwrap(),
1495 DeclType::StructImported if is_mut && is_ref => write!(w, "unsafe {{ &mut *").unwrap(),
1496 DeclType::StructImported if is_ref => write!(w, "unsafe {{ &*").unwrap(),
1497 DeclType::StructImported if !is_ref => write!(w, "*unsafe {{ Box::from_raw(").unwrap(),
1498 DeclType::MirroredEnum if is_ref => write!(w, "&").unwrap(),
1499 DeclType::MirroredEnum => {},
1500 DeclType::Trait(_) => {},
1501 _ => unimplemented!(),
1504 pub fn write_from_c_conversion_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1505 self.write_from_c_conversion_prefix_inner(w, t, generics, false, false);
1507 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) {
1508 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "*/", false,
1509 |has_inner| match has_inner {
1510 false => ".iter().collect::<Vec<_>>()[..]",
1513 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1514 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1515 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, ").inner }}").unwrap(),
1516 DeclType::StructImported if is_ref => write!(w, ".inner }}").unwrap(),
1517 DeclType::StructImported if !is_ref => write!(w, ".take_inner()) }}").unwrap(),
1518 DeclType::MirroredEnum if is_ref => write!(w, ".to_native()").unwrap(),
1519 DeclType::MirroredEnum => write!(w, ".into_native()").unwrap(),
1520 DeclType::Trait(_) => {},
1521 _ => unimplemented!(),
1524 pub fn write_from_c_conversion_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1525 self.write_from_c_conversion_suffix_inner(w, t, generics, false, false);
1527 // Note that compared to the above conversion functions, the following two are generally
1528 // significantly undertested:
1529 pub fn write_from_c_conversion_to_ref_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1530 self.write_conversion_inline_intern(w, t, generics, false, false, false, "() /*", true, |_| "&local_",
1532 if let Some(conv) = self.from_c_conversion_prefix_from_path(a, b) {
1533 Some(format!("&{}", conv))
1536 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1537 DeclType::StructImported if !is_ref => write!(w, "unsafe {{ &*").unwrap(),
1538 _ => unimplemented!(),
1541 pub fn write_from_c_conversion_to_ref_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1542 self.write_conversion_inline_intern(w, t, generics, false, false, false, "*/", false,
1543 |has_inner| match has_inner {
1544 false => ".iter().collect::<Vec<_>>()[..]",
1547 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1548 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1549 DeclType::StructImported if !is_ref => write!(w, ".inner }}").unwrap(),
1550 _ => unimplemented!(),
1554 fn write_conversion_new_var_intern<'b, W: std::io::Write,
1555 LP: Fn(&str, bool) -> Option<(&str, &str)>,
1556 LC: Fn(&str, bool, Option<&syn::Type>, &syn::Ident, &str) -> Option<(&'b str, Vec<(String, String)>, &'b str)>,
1557 VP: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool),
1558 VS: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool)>
1559 (&self, w: &mut W, ident: &syn::Ident, var: &str, t: &syn::Type, generics: Option<&GenericTypes>,
1560 mut is_ref: bool, mut ptr_for_ref: bool, to_c: bool,
1561 path_lookup: &LP, container_lookup: &LC, var_prefix: &VP, var_suffix: &VS) -> bool {
1563 macro_rules! convert_container {
1564 ($container_type: expr, $args_len: expr, $args_iter: expr) => { {
1565 // For slices (and Options), we refuse to directly map them as is_ref when they
1566 // aren't opaque types containing an inner pointer. This is due to the fact that,
1567 // in both cases, the actual higher-level type is non-is_ref.
1568 let ty_has_inner = if self.is_transparent_container(&$container_type, is_ref) || $container_type == "Slice" {
1569 let ty = $args_iter().next().unwrap();
1570 if $container_type == "Slice" && to_c {
1571 // "To C ptr_for_ref" means "return the regular object with is_owned
1572 // set to false", which is totally what we want in a slice if we're about to
1573 // set ty_has_inner.
1576 if let syn::Type::Reference(t) = ty {
1577 if let syn::Type::Path(p) = &*t.elem {
1578 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1580 } else if let syn::Type::Path(p) = ty {
1581 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1585 // Options get a bunch of special handling, since in general we map Option<>al
1586 // types into the same C type as non-Option-wrapped types. This ends up being
1587 // pretty manual here and most of the below special-cases are for Options.
1588 let mut needs_ref_map = false;
1589 let mut only_contained_type = None;
1590 let mut only_contained_has_inner = false;
1591 let mut contains_slice = false;
1592 if $args_len == 1 && self.is_transparent_container(&$container_type, is_ref) {
1593 only_contained_has_inner = ty_has_inner;
1594 let arg = $args_iter().next().unwrap();
1595 if let syn::Type::Reference(t) = arg {
1596 only_contained_type = Some(&*t.elem);
1597 if let syn::Type::Path(_) = &*t.elem {
1599 } else if let syn::Type::Slice(_) = &*t.elem {
1600 contains_slice = true;
1601 } else { return false; }
1602 needs_ref_map = true;
1603 } else if let syn::Type::Path(_) = arg {
1604 only_contained_type = Some(&arg);
1605 } else { unimplemented!(); }
1608 if let Some((prefix, conversions, suffix)) = container_lookup(&$container_type, is_ref && ty_has_inner, only_contained_type, ident, var) {
1609 assert_eq!(conversions.len(), $args_len);
1610 write!(w, "let mut local_{}{} = ", ident, if !to_c && needs_ref_map {"_base"} else { "" }).unwrap();
1611 if only_contained_has_inner && to_c {
1612 var_prefix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
1614 write!(w, "{}{}", prefix, var).unwrap();
1616 for ((pfx, var_name), (idx, ty)) in conversions.iter().zip($args_iter().enumerate()) {
1617 let mut var = std::io::Cursor::new(Vec::new());
1618 write!(&mut var, "{}", var_name).unwrap();
1619 let var_access = String::from_utf8(var.into_inner()).unwrap();
1621 let conv_ty = if needs_ref_map { only_contained_type.as_ref().unwrap() } else { ty };
1623 write!(w, "{} {{ ", pfx).unwrap();
1624 let new_var_name = format!("{}_{}", ident, idx);
1625 let new_var = self.write_conversion_new_var_intern(w, &syn::Ident::new(&new_var_name, Span::call_site()),
1626 &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);
1627 if new_var { write!(w, " ").unwrap(); }
1628 if (!only_contained_has_inner || !to_c) && !contains_slice {
1629 var_prefix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1632 if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
1633 write!(w, "Box::into_raw(Box::new(").unwrap();
1635 write!(w, "{}{}", if contains_slice { "local_" } else { "" }, if new_var { new_var_name } else { var_access }).unwrap();
1636 if (!only_contained_has_inner || !to_c) && !contains_slice {
1637 var_suffix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1639 if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
1640 write!(w, "))").unwrap();
1642 write!(w, " }}").unwrap();
1644 write!(w, "{}", suffix).unwrap();
1645 if only_contained_has_inner && to_c {
1646 var_suffix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
1648 write!(w, ";").unwrap();
1649 if !to_c && needs_ref_map {
1650 write!(w, " let mut local_{} = local_{}_base.as_ref()", ident, ident).unwrap();
1652 write!(w, ".map(|a| &a[..])").unwrap();
1654 write!(w, ";").unwrap();
1662 syn::Type::Reference(r) => {
1663 if let syn::Type::Slice(_) = &*r.elem {
1664 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)
1666 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)
1669 syn::Type::Path(p) => {
1670 if p.qself.is_some() {
1673 let resolved_path = self.resolve_path(&p.path, generics);
1674 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1675 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);
1677 if self.is_known_container(&resolved_path, is_ref) || self.is_transparent_container(&resolved_path, is_ref) {
1678 if let syn::PathArguments::AngleBracketed(args) = &p.path.segments.iter().next().unwrap().arguments {
1679 convert_container!(resolved_path, args.args.len(), || args.args.iter().map(|arg| {
1680 if let syn::GenericArgument::Type(ty) = arg {
1682 } else { unimplemented!(); }
1684 } else { unimplemented!(); }
1686 if self.is_primitive(&resolved_path) {
1688 } else if let Some(ty_ident) = single_ident_generic_path_to_ident(&p.path) {
1689 if let Some((prefix, suffix)) = path_lookup(&resolved_path, is_ref) {
1690 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
1692 } else if self.types.maybe_resolve_declared(ty_ident).is_some() {
1697 syn::Type::Array(_) => {
1698 // We assume all arrays contain only primitive types.
1699 // This may result in some outputs not compiling.
1702 syn::Type::Slice(s) => {
1703 if let syn::Type::Path(p) = &*s.elem {
1704 let resolved = self.resolve_path(&p.path, generics);
1705 assert!(self.is_primitive(&resolved));
1706 let slice_path = format!("[{}]", resolved);
1707 if let Some((prefix, suffix)) = path_lookup(&slice_path, true) {
1708 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
1711 } else if let syn::Type::Reference(ty) = &*s.elem {
1712 let tyref = [&*ty.elem];
1714 convert_container!("Slice", 1, || tyref.iter());
1715 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
1716 } else if let syn::Type::Tuple(t) = &*s.elem {
1717 // When mapping into a temporary new var, we need to own all the underlying objects.
1718 // Thus, we drop any references inside the tuple and convert with non-reference types.
1719 let mut elems = syn::punctuated::Punctuated::new();
1720 for elem in t.elems.iter() {
1721 if let syn::Type::Reference(r) = elem {
1722 elems.push((*r.elem).clone());
1724 elems.push(elem.clone());
1727 let ty = [syn::Type::Tuple(syn::TypeTuple {
1728 paren_token: t.paren_token, elems
1732 convert_container!("Slice", 1, || ty.iter());
1733 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
1734 } else { unimplemented!() }
1736 syn::Type::Tuple(t) => {
1737 if !t.elems.is_empty() {
1738 // We don't (yet) support tuple elements which cannot be converted inline
1739 write!(w, "let (").unwrap();
1740 for idx in 0..t.elems.len() {
1741 if idx != 0 { write!(w, ", ").unwrap(); }
1742 write!(w, "{} orig_{}_{}", if is_ref { "ref" } else { "mut" }, ident, idx).unwrap();
1744 write!(w, ") = {}{}; ", var, if !to_c { ".to_rust()" } else { "" }).unwrap();
1745 // Like other template types, tuples are always mapped as their non-ref
1746 // versions for types which have different ref mappings. Thus, we convert to
1747 // non-ref versions and handle opaque types with inner pointers manually.
1748 for (idx, elem) in t.elems.iter().enumerate() {
1749 if let syn::Type::Path(p) = elem {
1750 let v_name = format!("orig_{}_{}", ident, idx);
1751 let tuple_elem_ident = syn::Ident::new(&v_name, Span::call_site());
1752 if self.write_conversion_new_var_intern(w, &tuple_elem_ident, &v_name, elem, generics,
1753 false, ptr_for_ref, to_c,
1754 path_lookup, container_lookup, var_prefix, var_suffix) {
1755 write!(w, " ").unwrap();
1756 // Opaque types with inner pointers shouldn't ever create new stack
1757 // variables, so we don't handle it and just assert that it doesn't
1759 assert!(!self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)));
1763 write!(w, "let mut local_{} = (", ident).unwrap();
1764 for (idx, elem) in t.elems.iter().enumerate() {
1765 let ty_has_inner = {
1767 // "To C ptr_for_ref" means "return the regular object with
1768 // is_owned set to false", which is totally what we want
1769 // if we're about to set ty_has_inner.
1772 if let syn::Type::Reference(t) = elem {
1773 if let syn::Type::Path(p) = &*t.elem {
1774 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1776 } else if let syn::Type::Path(p) = elem {
1777 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1780 if idx != 0 { write!(w, ", ").unwrap(); }
1781 var_prefix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1782 if is_ref && ty_has_inner {
1783 // For ty_has_inner, the regular var_prefix mapping will take a
1784 // reference, so deref once here to make sure we keep the original ref.
1785 write!(w, "*").unwrap();
1787 write!(w, "orig_{}_{}", ident, idx).unwrap();
1788 if is_ref && !ty_has_inner {
1789 // If we don't have an inner variable's reference to maintain, just
1790 // hope the type is Clonable and use that.
1791 write!(w, ".clone()").unwrap();
1793 var_suffix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1795 write!(w, "){};", if to_c { ".into()" } else { "" }).unwrap();
1799 _ => unimplemented!(),
1803 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 {
1804 self.write_conversion_new_var_intern(w, ident, var_access, t, generics, false, ptr_for_ref, true,
1805 &|a, b| self.to_c_conversion_new_var_from_path(a, b),
1806 &|a, b, c, d, e| self.to_c_conversion_container_new_var(generics, a, b, c, d, e),
1807 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
1808 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_prefix_inner(a, b, c, d, e, f),
1809 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_suffix_inner(a, b, c, d, e, f))
1811 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 {
1812 self.write_to_c_conversion_new_var_inner(w, ident, &format!("{}", ident), t, generics, ptr_for_ref)
1814 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 {
1815 self.write_conversion_new_var_intern(w, ident, &format!("{}", ident), t, generics, false, false, false,
1816 &|a, b| self.from_c_conversion_new_var_from_path(a, b),
1817 &|a, b, c, d, e| self.from_c_conversion_container_new_var(generics, a, b, c, d, e),
1818 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
1819 &|a, b, c, d, e, _f| self.write_from_c_conversion_prefix_inner(a, b, c, d, e),
1820 &|a, b, c, d, e, _f| self.write_from_c_conversion_suffix_inner(a, b, c, d, e))
1823 // ******************************************************
1824 // *** C Container Type Equivalent and alias Printing ***
1825 // ******************************************************
1827 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 {
1828 assert!(!is_ref); // We don't currently support outer reference types
1829 for (idx, t) in args.enumerate() {
1831 write!(w, ", ").unwrap();
1833 if let syn::Type::Reference(r_arg) = t {
1834 if !self.write_c_type_intern(w, &*r_arg.elem, generics, false, false, false) { return false; }
1836 // While write_c_type_intern, above is correct, we don't want to blindly convert a
1837 // reference to something stupid, so check that the container is either opaque or a
1838 // predefined type (currently only Transaction).
1839 if let syn::Type::Path(p_arg) = &*r_arg.elem {
1840 let resolved = self.resolve_path(&p_arg.path, generics);
1841 assert!(self.crate_types.opaques.get(&resolved).is_some() ||
1842 self.c_type_from_path(&resolved, true, true).is_some(), "Template generics should be opaque or have a predefined mapping");
1843 } else { unimplemented!(); }
1845 if !self.write_c_type_intern(w, t, generics, false, false, false) { return false; }
1850 fn check_create_container(&mut self, mangled_container: String, container_type: &str, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
1851 if !self.crate_types.templates_defined.get(&mangled_container).is_some() {
1852 let mut created_container: Vec<u8> = Vec::new();
1854 if container_type == "Result" {
1855 let mut a_ty: Vec<u8> = Vec::new();
1856 if let syn::Type::Tuple(tup) = args.iter().next().unwrap() {
1857 if tup.elems.is_empty() {
1858 write!(&mut a_ty, "()").unwrap();
1860 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
1863 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
1866 let mut b_ty: Vec<u8> = Vec::new();
1867 if let syn::Type::Tuple(tup) = args.iter().skip(1).next().unwrap() {
1868 if tup.elems.is_empty() {
1869 write!(&mut b_ty, "()").unwrap();
1871 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
1874 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
1877 let ok_str = String::from_utf8(a_ty).unwrap();
1878 let err_str = String::from_utf8(b_ty).unwrap();
1879 let is_clonable = self.is_clonable(&ok_str) && self.is_clonable(&err_str);
1880 write_result_block(&mut created_container, &mangled_container, &ok_str, &err_str, is_clonable);
1882 self.crate_types.clonable_types.insert(Self::generated_container_path().to_owned() + "::" + &mangled_container);
1884 } else if container_type == "Vec" {
1885 let mut a_ty: Vec<u8> = Vec::new();
1886 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
1887 let ty = String::from_utf8(a_ty).unwrap();
1888 let is_clonable = self.is_clonable(&ty);
1889 write_vec_block(&mut created_container, &mangled_container, &ty, is_clonable);
1891 self.crate_types.clonable_types.insert(Self::generated_container_path().to_owned() + "::" + &mangled_container);
1893 } else if container_type.ends_with("Tuple") {
1894 let mut tuple_args = Vec::new();
1895 let mut is_clonable = true;
1896 for arg in args.iter() {
1897 let mut ty: Vec<u8> = Vec::new();
1898 if !self.write_template_generics(&mut ty, &mut [arg].iter().map(|t| **t), generics, is_ref) { return false; }
1899 let ty_str = String::from_utf8(ty).unwrap();
1900 if !self.is_clonable(&ty_str) {
1901 is_clonable = false;
1903 tuple_args.push(ty_str);
1905 write_tuple_block(&mut created_container, &mangled_container, &tuple_args, is_clonable);
1907 self.crate_types.clonable_types.insert(Self::generated_container_path().to_owned() + "::" + &mangled_container);
1912 self.crate_types.templates_defined.insert(mangled_container.clone(), true);
1914 self.crate_types.template_file.write(&created_container).unwrap();
1918 fn path_to_generic_args(path: &syn::Path) -> Vec<&syn::Type> {
1919 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().next().unwrap().arguments {
1920 args.args.iter().map(|gen| if let syn::GenericArgument::Type(t) = gen { t } else { unimplemented!() }).collect()
1921 } else { unimplemented!(); }
1923 fn write_c_mangled_container_path_intern<W: std::io::Write>
1924 (&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 {
1925 let mut mangled_type: Vec<u8> = Vec::new();
1926 if !self.is_transparent_container(ident, is_ref) {
1927 write!(w, "C{}_", ident).unwrap();
1928 write!(mangled_type, "C{}_", ident).unwrap();
1929 } else { assert_eq!(args.len(), 1); }
1930 for arg in args.iter() {
1931 macro_rules! write_path {
1932 ($p_arg: expr, $extra_write: expr) => {
1933 if let Some(subtype) = self.maybe_resolve_path(&$p_arg.path, generics) {
1934 if self.is_transparent_container(ident, is_ref) {
1935 // We dont (yet) support primitives or containers inside transparent
1936 // containers, so check for that first:
1937 if self.is_primitive(&subtype) { return false; }
1938 if self.is_known_container(&subtype, is_ref) { return false; }
1940 if self.c_type_has_inner_from_path(&subtype) {
1941 if !self.write_c_path_intern(w, &$p_arg.path, generics, is_ref, is_mut, ptr_for_ref) { return false; }
1943 // Option<T> needs to be converted to a *mut T, ie mut ptr-for-ref
1944 if !self.write_c_path_intern(w, &$p_arg.path, generics, true, true, true) { return false; }
1947 if $p_arg.path.segments.len() == 1 {
1948 write!(w, "{}", $p_arg.path.segments.iter().next().unwrap().ident).unwrap();
1953 } else if self.is_known_container(&subtype, is_ref) || self.is_transparent_container(&subtype, is_ref) {
1954 if !self.write_c_mangled_container_path_intern(w, Self::path_to_generic_args(&$p_arg.path), generics,
1955 &subtype, is_ref, is_mut, ptr_for_ref, true) {
1958 self.write_c_mangled_container_path_intern(&mut mangled_type, Self::path_to_generic_args(&$p_arg.path),
1959 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
1960 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
1961 self.write_c_mangled_container_path_intern(w2, Self::path_to_generic_args(&$p_arg.path),
1962 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
1965 let id = subtype.rsplitn(2, ':').next().unwrap(); // Get the "Base" name of the resolved type
1966 write!(w, "{}", id).unwrap();
1967 write!(mangled_type, "{}", id).unwrap();
1968 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
1969 write!(w2, "{}", id).unwrap();
1972 } else { return false; }
1975 if let syn::Type::Tuple(tuple) = arg {
1976 if tuple.elems.len() == 0 {
1977 write!(w, "None").unwrap();
1978 write!(mangled_type, "None").unwrap();
1980 let mut mangled_tuple_type: Vec<u8> = Vec::new();
1982 // Figure out what the mangled type should look like. To disambiguate
1983 // ((A, B), C) and (A, B, C) we prefix the generic args with a _ and suffix
1984 // them with a Z. Ideally we wouldn't use Z, but not many special chars are
1985 // available for use in type names.
1986 write!(w, "C{}Tuple_", tuple.elems.len()).unwrap();
1987 write!(mangled_type, "C{}Tuple_", tuple.elems.len()).unwrap();
1988 write!(mangled_tuple_type, "C{}Tuple_", tuple.elems.len()).unwrap();
1989 for elem in tuple.elems.iter() {
1990 if let syn::Type::Path(p) = elem {
1991 write_path!(p, Some(&mut mangled_tuple_type));
1992 } else if let syn::Type::Reference(refelem) = elem {
1993 if let syn::Type::Path(p) = &*refelem.elem {
1994 write_path!(p, Some(&mut mangled_tuple_type));
1995 } else { return false; }
1996 } else { return false; }
1998 write!(w, "Z").unwrap();
1999 write!(mangled_type, "Z").unwrap();
2000 write!(mangled_tuple_type, "Z").unwrap();
2001 if !self.check_create_container(String::from_utf8(mangled_tuple_type).unwrap(),
2002 &format!("{}Tuple", tuple.elems.len()), tuple.elems.iter().collect(), generics, is_ref) {
2006 } else if let syn::Type::Path(p_arg) = arg {
2007 write_path!(p_arg, None);
2008 } else if let syn::Type::Reference(refty) = arg {
2009 if let syn::Type::Path(p_arg) = &*refty.elem {
2010 write_path!(p_arg, None);
2011 } else if let syn::Type::Slice(_) = &*refty.elem {
2012 // write_c_type will actually do exactly what we want here, we just need to
2013 // make it a pointer so that its an option. Note that we cannot always convert
2014 // the Vec-as-slice (ie non-ref types) containers, so sometimes need to be able
2015 // to edit it, hence we use *mut here instead of *const.
2016 if args.len() != 1 { return false; }
2017 write!(w, "*mut ").unwrap();
2018 self.write_c_type(w, arg, None, true);
2019 } else { return false; }
2020 } else if let syn::Type::Array(a) = arg {
2021 if let syn::Type::Path(p_arg) = &*a.elem {
2022 let resolved = self.resolve_path(&p_arg.path, generics);
2023 if !self.is_primitive(&resolved) { return false; }
2024 if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(len), .. }) = &a.len {
2025 if self.c_type_from_path(&format!("[{}; {}]", resolved, len.base10_digits()), is_ref, ptr_for_ref).is_none() { return false; }
2026 write!(w, "_{}{}", resolved, len.base10_digits()).unwrap();
2027 write!(mangled_type, "_{}{}", resolved, len.base10_digits()).unwrap();
2028 } else { return false; }
2029 } else { return false; }
2030 } else { return false; }
2032 if self.is_transparent_container(ident, is_ref) { return true; }
2033 // Push the "end of type" Z
2034 write!(w, "Z").unwrap();
2035 write!(mangled_type, "Z").unwrap();
2037 // Make sure the type is actually defined:
2038 self.check_create_container(String::from_utf8(mangled_type).unwrap(), ident, args, generics, is_ref)
2040 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 {
2041 if !self.is_transparent_container(ident, is_ref) {
2042 write!(w, "{}::", Self::generated_container_path()).unwrap();
2044 self.write_c_mangled_container_path_intern(w, args, generics, ident, is_ref, is_mut, ptr_for_ref, false)
2047 // **********************************
2048 // *** C Type Equivalent Printing ***
2049 // **********************************
2051 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 {
2052 let full_path = match self.maybe_resolve_path(&path, generics) {
2053 Some(path) => path, None => return false };
2054 if let Some(c_type) = self.c_type_from_path(&full_path, is_ref, ptr_for_ref) {
2055 write!(w, "{}", c_type).unwrap();
2057 } else if self.crate_types.traits.get(&full_path).is_some() {
2058 if is_ref && ptr_for_ref {
2059 write!(w, "*{} crate::{}", if is_mut { "mut" } else { "const" }, full_path).unwrap();
2061 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2063 write!(w, "crate::{}", full_path).unwrap();
2066 } else if self.crate_types.opaques.get(&full_path).is_some() || self.crate_types.mirrored_enums.get(&full_path).is_some() {
2067 if is_ref && ptr_for_ref {
2068 // ptr_for_ref implies we're returning the object, which we can't really do for
2069 // opaque or mirrored types without box'ing them, which is quite a waste, so return
2070 // the actual object itself (for opaque types we'll set the pointer to the actual
2071 // type and note that its a reference).
2072 write!(w, "crate::{}", full_path).unwrap();
2074 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2076 write!(w, "crate::{}", full_path).unwrap();
2083 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 {
2085 syn::Type::Path(p) => {
2086 if p.qself.is_some() {
2089 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
2090 if self.is_known_container(&full_path, is_ref) || self.is_transparent_container(&full_path, is_ref) {
2091 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);
2093 if let Some(aliased_type) = self.crate_types.type_aliases.get(&full_path).cloned() {
2094 return self.write_c_type_intern(w, &aliased_type, None, is_ref, is_mut, ptr_for_ref);
2097 self.write_c_path_intern(w, &p.path, generics, is_ref, is_mut, ptr_for_ref)
2099 syn::Type::Reference(r) => {
2100 self.write_c_type_intern(w, &*r.elem, generics, true, r.mutability.is_some(), ptr_for_ref)
2102 syn::Type::Array(a) => {
2103 if is_ref && is_mut {
2104 write!(w, "*mut [").unwrap();
2105 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2107 write!(w, "*const [").unwrap();
2108 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2110 let mut typecheck = Vec::new();
2111 if !self.write_c_type_intern(&mut typecheck, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2112 if typecheck[..] != ['u' as u8, '8' as u8] { return false; }
2114 if let syn::Expr::Lit(l) = &a.len {
2115 if let syn::Lit::Int(i) = &l.lit {
2117 if let Some(ty) = self.c_type_from_path(&format!("[u8; {}]", i.base10_digits()), false, ptr_for_ref) {
2118 write!(w, "{}", ty).unwrap();
2122 write!(w, "; {}]", i).unwrap();
2128 syn::Type::Slice(s) => {
2129 if !is_ref || is_mut { return false; }
2130 if let syn::Type::Path(p) = &*s.elem {
2131 let resolved = self.resolve_path(&p.path, generics);
2132 if self.is_primitive(&resolved) {
2133 write!(w, "{}::{}slice", Self::container_templ_path(), resolved).unwrap();
2136 } else if let syn::Type::Reference(r) = &*s.elem {
2137 if let syn::Type::Path(p) = &*r.elem {
2138 // Slices with "real types" inside are mapped as the equivalent non-ref Vec
2139 let resolved = self.resolve_path(&p.path, generics);
2140 let mangled_container = if let Some(ident) = self.crate_types.opaques.get(&resolved) {
2141 format!("CVec_{}Z", ident)
2142 } else if let Some(en) = self.crate_types.mirrored_enums.get(&resolved) {
2143 format!("CVec_{}Z", en.ident)
2144 } else if let Some(id) = p.path.get_ident() {
2145 format!("CVec_{}Z", id)
2146 } else { return false; };
2147 write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
2148 self.check_create_container(mangled_container, "Vec", vec![&*r.elem], generics, false)
2150 } else if let syn::Type::Tuple(_) = &*s.elem {
2151 let mut args = syn::punctuated::Punctuated::new();
2152 args.push(syn::GenericArgument::Type((*s.elem).clone()));
2153 let mut segments = syn::punctuated::Punctuated::new();
2154 segments.push(syn::PathSegment {
2155 ident: syn::Ident::new("Vec", Span::call_site()),
2156 arguments: syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
2157 colon2_token: None, lt_token: syn::Token![<](Span::call_site()), args, gt_token: syn::Token![>](Span::call_site()),
2160 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)
2163 syn::Type::Tuple(t) => {
2164 if t.elems.len() == 0 {
2167 self.write_c_mangled_container_path(w, t.elems.iter().collect(), generics,
2168 &format!("{}Tuple", t.elems.len()), is_ref, is_mut, ptr_for_ref)
2174 pub fn write_c_type<W: std::io::Write>(&mut self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) {
2175 assert!(self.write_c_type_intern(w, t, generics, false, false, ptr_for_ref));
2177 pub fn understood_c_path(&mut self, p: &syn::Path) -> bool {
2178 if p.leading_colon.is_some() { return false; }
2179 self.write_c_path_intern(&mut std::io::sink(), p, None, false, false, false)
2181 pub fn understood_c_type(&mut self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
2182 self.write_c_type_intern(&mut std::io::sink(), t, generics, false, false, false)