1 use std::collections::{HashMap, HashSet};
6 use proc_macro2::{TokenTree, Span};
8 // The following utils are used purely to build our known types maps - they break down all the
9 // types we need to resolve to include the given object, and no more.
11 pub fn first_seg_self<'a>(t: &'a syn::Type) -> Option<impl Iterator<Item=&syn::PathSegment> + 'a> {
13 syn::Type::Path(p) => {
14 if p.qself.is_some() || p.path.leading_colon.is_some() {
17 let mut segs = p.path.segments.iter();
18 let ty = segs.next().unwrap();
19 if !ty.arguments.is_empty() { return None; }
20 if format!("{}", ty.ident) == "Self" {
28 pub fn get_single_remaining_path_seg<'a, I: Iterator<Item=&'a syn::PathSegment>>(segs: &mut I) -> Option<&'a syn::Ident> {
29 if let Some(ty) = segs.next() {
30 if !ty.arguments.is_empty() { unimplemented!(); }
31 if segs.next().is_some() { return None; }
36 pub fn single_ident_generic_path_to_ident(p: &syn::Path) -> Option<&syn::Ident> {
37 if p.segments.len() == 1 {
38 Some(&p.segments.iter().next().unwrap().ident)
42 pub fn attrs_derives_clone(attrs: &[syn::Attribute]) -> bool {
43 for attr in attrs.iter() {
44 let tokens_clone = attr.tokens.clone();
45 let mut token_iter = tokens_clone.into_iter();
46 if let Some(token) = token_iter.next() {
48 TokenTree::Group(g) => {
49 if format!("{}", single_ident_generic_path_to_ident(&attr.path).unwrap()) == "derive" {
50 for id in g.stream().into_iter() {
51 if let TokenTree::Ident(i) = id {
66 #[derive(Debug, PartialEq)]
67 pub enum ExportStatus {
72 /// Gets the ExportStatus of an object (struct, fn, etc) given its attributes.
73 pub fn export_status(attrs: &[syn::Attribute]) -> ExportStatus {
74 for attr in attrs.iter() {
75 let tokens_clone = attr.tokens.clone();
76 let mut token_iter = tokens_clone.into_iter();
77 if let Some(token) = token_iter.next() {
79 TokenTree::Punct(c) if c.as_char() == '=' => {
80 // Really not sure where syn gets '=' from here -
81 // it somehow represents '///' or '//!'
83 TokenTree::Group(g) => {
84 if format!("{}", single_ident_generic_path_to_ident(&attr.path).unwrap()) == "cfg" {
85 let mut iter = g.stream().into_iter();
86 if let TokenTree::Ident(i) = iter.next().unwrap() {
88 // #[cfg(any(test, feature = ""))]
89 if let TokenTree::Group(g) = iter.next().unwrap() {
90 if let TokenTree::Ident(i) = g.stream().into_iter().next().unwrap() {
91 if i == "test" || i == "feature" {
92 // If its cfg(feature(...)) we assume its test-only
93 return ExportStatus::TestOnly;
97 } else if i == "test" || i == "feature" {
98 // If its cfg(feature(...)) we assume its test-only
99 return ExportStatus::TestOnly;
103 continue; // eg #[derive()]
105 _ => unimplemented!(),
108 match token_iter.next().unwrap() {
109 TokenTree::Literal(lit) => {
110 let line = format!("{}", lit);
111 if line.contains("(C-not exported)") {
112 return ExportStatus::NoExport;
115 _ => unimplemented!(),
121 pub fn assert_simple_bound(bound: &syn::TraitBound) {
122 if bound.paren_token.is_some() || bound.lifetimes.is_some() { unimplemented!(); }
123 if let syn::TraitBoundModifier::Maybe(_) = bound.modifier { unimplemented!(); }
126 /// A stack of sets of generic resolutions.
128 /// This tracks the template parameters for a function, struct, or trait, allowing resolution into
129 /// a concrete type. By pushing a new context onto the stack, this can track a function's template
130 /// parameters inside of a generic struct or trait.
132 /// It maps both direct types as well as Deref<Target = X>, mapping them via the provided
133 /// TypeResolver's resolve_path function (ie traits map to the concrete jump table, structs to the
134 /// concrete C container struct, etc).
135 pub struct GenericTypes<'a> {
136 typed_generics: Vec<HashMap<&'a syn::Ident, (String, Option<&'a syn::Path>)>>,
138 impl<'a> GenericTypes<'a> {
139 pub fn new() -> Self {
140 Self { typed_generics: vec![HashMap::new()], }
143 /// push a new context onto the stack, allowing for a new set of generics to be learned which
144 /// will override any lower contexts, but which will still fall back to resoltion via lower
146 pub fn push_ctx(&mut self) {
147 self.typed_generics.push(HashMap::new());
149 /// pop the latest context off the stack.
150 pub fn pop_ctx(&mut self) {
151 self.typed_generics.pop();
154 /// Learn the generics in generics in the current context, given a TypeResolver.
155 pub fn learn_generics<'b, 'c>(&mut self, generics: &'a syn::Generics, types: &'b TypeResolver<'a, 'c>) -> bool {
156 // First learn simple generics...
157 for generic in generics.params.iter() {
159 syn::GenericParam::Type(type_param) => {
160 let mut non_lifetimes_processed = false;
161 for bound in type_param.bounds.iter() {
162 if let syn::TypeParamBound::Trait(trait_bound) = bound {
163 if let Some(ident) = single_ident_generic_path_to_ident(&trait_bound.path) {
164 match &format!("{}", ident) as &str { "Send" => continue, "Sync" => continue, _ => {} }
167 assert_simple_bound(&trait_bound);
168 if let Some(mut path) = types.maybe_resolve_path(&trait_bound.path, None) {
169 if types.skip_path(&path) { continue; }
170 if non_lifetimes_processed { return false; }
171 non_lifetimes_processed = true;
172 let new_ident = if path != "std::ops::Deref" {
173 path = "crate::".to_string() + &path;
174 Some(&trait_bound.path)
176 self.typed_generics.last_mut().unwrap().insert(&type_param.ident, (path, new_ident));
177 } else { return false; }
184 // Then find generics where we are required to pass a Deref<Target=X> and pretend its just X.
185 if let Some(wh) = &generics.where_clause {
186 for pred in wh.predicates.iter() {
187 if let syn::WherePredicate::Type(t) = pred {
188 if let syn::Type::Path(p) = &t.bounded_ty {
189 if p.qself.is_some() { return false; }
190 if p.path.leading_colon.is_some() { return false; }
191 let mut p_iter = p.path.segments.iter();
192 if let Some(gen) = self.typed_generics.last_mut().unwrap().get_mut(&p_iter.next().unwrap().ident) {
193 if gen.0 != "std::ops::Deref" { return false; }
194 if &format!("{}", p_iter.next().unwrap().ident) != "Target" { return false; }
196 let mut non_lifetimes_processed = false;
197 for bound in t.bounds.iter() {
198 if let syn::TypeParamBound::Trait(trait_bound) = bound {
199 if non_lifetimes_processed { return false; }
200 non_lifetimes_processed = true;
201 assert_simple_bound(&trait_bound);
202 *gen = ("crate::".to_string() + &types.resolve_path(&trait_bound.path, None),
203 Some(&trait_bound.path));
206 } else { return false; }
207 } else { return false; }
211 for (_, (_, ident)) in self.typed_generics.last().unwrap().iter() {
212 if ident.is_none() { return false; }
217 /// Learn the associated types from the trait in the current context.
218 pub fn learn_associated_types<'b, 'c>(&mut self, t: &'a syn::ItemTrait, types: &'b TypeResolver<'a, 'c>) {
219 for item in t.items.iter() {
221 &syn::TraitItem::Type(ref t) => {
222 if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
223 let mut bounds_iter = t.bounds.iter();
224 match bounds_iter.next().unwrap() {
225 syn::TypeParamBound::Trait(tr) => {
226 assert_simple_bound(&tr);
227 if let Some(mut path) = types.maybe_resolve_path(&tr.path, None) {
228 if types.skip_path(&path) { continue; }
229 // In general we handle Deref<Target=X> as if it were just X (and
230 // implement Deref<Target=Self> for relevant types). We don't
231 // bother to implement it for associated types, however, so we just
232 // ignore such bounds.
233 let new_ident = if path != "std::ops::Deref" {
234 path = "crate::".to_string() + &path;
237 self.typed_generics.last_mut().unwrap().insert(&t.ident, (path, new_ident));
238 } else { unimplemented!(); }
240 _ => unimplemented!(),
242 if bounds_iter.next().is_some() { unimplemented!(); }
249 /// Attempt to resolve an Ident as a generic parameter and return the full path.
250 pub fn maybe_resolve_ident<'b>(&'b self, ident: &syn::Ident) -> Option<&'b String> {
251 for gen in self.typed_generics.iter().rev() {
252 if let Some(res) = gen.get(ident).map(|(a, _)| a) {
258 /// Attempt to resolve a Path as a generic parameter and return the full path. as both a string
260 pub fn maybe_resolve_path<'b>(&'b self, path: &syn::Path) -> Option<(&'b String, &'a syn::Path)> {
261 if let Some(ident) = path.get_ident() {
262 for gen in self.typed_generics.iter().rev() {
263 if let Some(res) = gen.get(ident).map(|(a, b)| (a, b.unwrap())) {
268 // Associated types are usually specified as "Self::Generic", so we check for that
270 let mut it = path.segments.iter();
271 if path.segments.len() == 2 && format!("{}", it.next().unwrap().ident) == "Self" {
272 let ident = &it.next().unwrap().ident;
273 for gen in self.typed_generics.iter().rev() {
274 if let Some(res) = gen.get(ident).map(|(a, b)| (a, b.unwrap())) {
284 #[derive(Clone, PartialEq)]
285 // The type of declaration and the object itself
286 pub enum DeclType<'a> {
288 Trait(&'a syn::ItemTrait),
294 // templates_defined is walked to write the C++ header, so if we use the default hashing it get
295 // reordered on each genbindings run. Instead, we use SipHasher (which defaults to 0-keys) so that
296 // the sorting is stable across runs. It is deprecated, but the "replacement" doesn't actually
297 // accomplish the same goals, so we just ignore it.
299 type NonRandomHash = hash::BuildHasherDefault<hash::SipHasher>;
301 /// Top-level struct tracking everything which has been defined while walking the crate.
302 pub struct CrateTypes<'a> {
303 /// This may contain structs or enums, but only when either is mapped as
304 /// struct X { inner: *mut originalX, .. }
305 pub opaques: HashMap<String, &'a syn::Ident>,
306 /// Enums which are mapped as C enums with conversion functions
307 pub mirrored_enums: HashMap<String, &'a syn::ItemEnum>,
308 /// Traits which are mapped as a pointer + jump table
309 pub traits: HashMap<String, &'a syn::ItemTrait>,
310 /// Aliases from paths to some other Type
311 pub type_aliases: HashMap<String, syn::Type>,
312 /// Template continer types defined, map from mangled type name -> whether a destructor fn
315 /// This is used at the end of processing to make C++ wrapper classes
316 pub templates_defined: HashMap<String, bool, NonRandomHash>,
317 /// The output file for any created template container types, written to as we find new
318 /// template containers which need to be defined.
319 pub template_file: &'a mut File,
320 /// Set of containers which are clonable
321 pub clonable_types: HashSet<String>,
324 /// A struct which tracks resolving rust types into C-mapped equivalents, exists for one specific
325 /// module but contains a reference to the overall CrateTypes tracking.
326 pub struct TypeResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
327 pub orig_crate: &'mod_lifetime str,
328 pub module_path: &'mod_lifetime str,
329 imports: HashMap<syn::Ident, String>,
330 // ident -> is-mirrored-enum
331 declared: HashMap<syn::Ident, DeclType<'crate_lft>>,
332 pub crate_types: &'mod_lifetime mut CrateTypes<'crate_lft>,
335 /// Returned by write_empty_rust_val_check_suffix to indicate what type of dereferencing needs to
336 /// happen to get the inner value of a generic.
337 enum EmptyValExpectedTy {
338 /// A type which has a flag for being empty (eg an array where we treat all-0s as empty).
340 /// A pointer that we want to dereference and move out of.
342 /// A pointer which we want to convert to a reference.
346 impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
347 pub fn new(orig_crate: &'a str, module_path: &'a str, crate_types: &'a mut CrateTypes<'c>) -> Self {
348 let mut imports = HashMap::new();
349 // Add primitives to the "imports" list:
350 imports.insert(syn::Ident::new("bool", Span::call_site()), "bool".to_string());
351 imports.insert(syn::Ident::new("u64", Span::call_site()), "u64".to_string());
352 imports.insert(syn::Ident::new("u32", Span::call_site()), "u32".to_string());
353 imports.insert(syn::Ident::new("u16", Span::call_site()), "u16".to_string());
354 imports.insert(syn::Ident::new("u8", Span::call_site()), "u8".to_string());
355 imports.insert(syn::Ident::new("usize", Span::call_site()), "usize".to_string());
356 imports.insert(syn::Ident::new("str", Span::call_site()), "str".to_string());
357 imports.insert(syn::Ident::new("String", Span::call_site()), "String".to_string());
359 // These are here to allow us to print native Rust types in trait fn impls even if we don't
361 imports.insert(syn::Ident::new("Result", Span::call_site()), "Result".to_string());
362 imports.insert(syn::Ident::new("Vec", Span::call_site()), "Vec".to_string());
363 imports.insert(syn::Ident::new("Option", Span::call_site()), "Option".to_string());
364 Self { orig_crate, module_path, imports, declared: HashMap::new(), crate_types }
367 // *************************************************
368 // *** Well know type and conversion definitions ***
369 // *************************************************
371 /// Returns true we if can just skip passing this to C entirely
372 fn skip_path(&self, full_path: &str) -> bool {
373 full_path == "bitcoin::secp256k1::Secp256k1" ||
374 full_path == "bitcoin::secp256k1::Signing" ||
375 full_path == "bitcoin::secp256k1::Verification"
377 /// Returns true we if can just skip passing this to C entirely
378 fn no_arg_path_to_rust(&self, full_path: &str) -> &str {
379 if full_path == "bitcoin::secp256k1::Secp256k1" {
380 "&bitcoin::secp256k1::Secp256k1::new()"
381 } else { unimplemented!(); }
384 /// Returns true if the object is a primitive and is mapped as-is with no conversion
386 pub fn is_primitive(&self, full_path: &str) -> bool {
397 pub fn is_clonable(&self, ty: &str) -> bool {
398 if self.crate_types.clonable_types.contains(ty) { return true; }
399 if self.is_primitive(ty) { return true; }
402 "crate::c_types::Signature" => true,
403 "crate::c_types::TxOut" => true,
407 /// Gets the C-mapped type for types which are outside of the crate, or which are manually
408 /// ignored by for some reason need mapping anyway.
409 fn c_type_from_path<'b>(&self, full_path: &'b str, is_ref: bool, ptr_for_ref: bool) -> Option<&'b str> {
410 if self.is_primitive(full_path) {
411 return Some(full_path);
414 "Result" => Some("crate::c_types::derived::CResult"),
415 "Vec" if !is_ref => Some("crate::c_types::derived::CVec"),
416 "Option" => Some(""),
418 // Note that no !is_ref types can map to an array because Rust and C's call semantics
419 // for arrays are different (https://github.com/eqrion/cbindgen/issues/528)
421 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
422 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes"),
423 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes"),
424 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes"),
425 "[u8; 3]" if !is_ref => Some("crate::c_types::ThreeBytes"), // Used for RGB values
427 "str" if is_ref => Some("crate::c_types::Str"),
428 "String" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
429 "String" if is_ref => Some("crate::c_types::Str"),
431 "std::time::Duration" => Some("u64"),
433 "bitcoin::secp256k1::key::PublicKey" => Some("crate::c_types::PublicKey"),
434 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature"),
435 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some("*const [u8; 32]"),
436 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some("crate::c_types::SecretKey"),
437 "bitcoin::secp256k1::Error" if !is_ref => Some("crate::c_types::Secp256k1Error"),
438 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice"),
439 "bitcoin::blockdata::script::Script" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
440 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::chain::transaction::OutPoint"),
441 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction"),
442 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut"),
443 "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network"),
444 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("*const [u8; 80]"),
445 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice"),
447 // Newtypes that we just expose in their original form.
448 "bitcoin::hash_types::Txid" if is_ref => Some("*const [u8; 32]"),
449 "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
450 "bitcoin::hash_types::BlockHash" if is_ref => Some("*const [u8; 32]"),
451 "bitcoin::hash_types::BlockHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
452 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
453 "ln::channelmanager::PaymentHash" if is_ref => Some("*const [u8; 32]"),
454 "ln::channelmanager::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
455 "ln::channelmanager::PaymentPreimage" if is_ref => Some("*const [u8; 32]"),
456 "ln::channelmanager::PaymentPreimage" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
457 "ln::channelmanager::PaymentSecret" if is_ref => Some("crate::c_types::ThirtyTwoBytes"),
458 "ln::channelmanager::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
460 // Override the default since Records contain an fmt with a lifetime:
461 "util::logger::Record" => Some("*const std::os::raw::c_char"),
463 // List of structs we map that aren't detected:
464 "ln::features::InitFeatures" if is_ref && ptr_for_ref => Some("crate::ln::features::InitFeatures"),
465 "ln::features::InitFeatures" if is_ref => Some("*const crate::ln::features::InitFeatures"),
466 "ln::features::InitFeatures" => Some("crate::ln::features::InitFeatures"),
468 eprintln!(" Type {} (ref: {}) unresolvable in C", full_path, is_ref);
474 fn from_c_conversion_new_var_from_path<'b>(&self, _full_path: &str, _is_ref: bool) -> Option<(&'b str, &'b str)> {
477 fn from_c_conversion_prefix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
478 if self.is_primitive(full_path) {
479 return Some("".to_owned());
482 "Vec" if !is_ref => Some("local_"),
483 "Result" if !is_ref => Some("local_"),
484 "Option" if is_ref => Some("&local_"),
485 "Option" => Some("local_"),
487 "[u8; 32]" if is_ref => Some("unsafe { &*"),
488 "[u8; 32]" if !is_ref => Some(""),
489 "[u8; 16]" if !is_ref => Some(""),
490 "[u8; 10]" if !is_ref => Some(""),
491 "[u8; 4]" if !is_ref => Some(""),
492 "[u8; 3]" if !is_ref => Some(""),
494 "[u8]" if is_ref => Some(""),
495 "[usize]" if is_ref => Some(""),
497 "str" if is_ref => Some(""),
498 "String" if !is_ref => Some("String::from_utf8("),
499 // Note that we'll panic for String if is_ref, as we only have non-owned memory, we
500 // cannot create a &String.
502 "std::time::Duration" => Some("std::time::Duration::from_secs("),
504 "bitcoin::secp256k1::key::PublicKey" if is_ref => Some("&"),
505 "bitcoin::secp256k1::key::PublicKey" => Some(""),
506 "bitcoin::secp256k1::Signature" if is_ref => Some("&"),
507 "bitcoin::secp256k1::Signature" => Some(""),
508 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some("&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *"),
509 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some(""),
510 "bitcoin::blockdata::script::Script" if is_ref => Some("&::bitcoin::blockdata::script::Script::from(Vec::from("),
511 "bitcoin::blockdata::script::Script" if !is_ref => Some("::bitcoin::blockdata::script::Script::from("),
512 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some("&"),
513 "bitcoin::blockdata::transaction::Transaction" => Some(""),
514 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(""),
515 "bitcoin::network::constants::Network" => Some(""),
516 "bitcoin::blockdata::block::BlockHeader" => Some("&::bitcoin::consensus::encode::deserialize(unsafe { &*"),
517 "bitcoin::blockdata::block::Block" if is_ref => Some("&::bitcoin::consensus::encode::deserialize("),
519 // Newtypes that we just expose in their original form.
520 "bitcoin::hash_types::Txid" if is_ref => Some("&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*"),
521 "bitcoin::hash_types::Txid" if !is_ref => Some("::bitcoin::hash_types::Txid::from_slice(&"),
522 "bitcoin::hash_types::BlockHash" => Some("::bitcoin::hash_types::BlockHash::from_slice(&"),
523 "ln::channelmanager::PaymentHash" if !is_ref => Some("::lightning::ln::channelmanager::PaymentHash("),
524 "ln::channelmanager::PaymentHash" if is_ref => Some("&::lightning::ln::channelmanager::PaymentHash(unsafe { *"),
525 "ln::channelmanager::PaymentPreimage" if !is_ref => Some("::lightning::ln::channelmanager::PaymentPreimage("),
526 "ln::channelmanager::PaymentPreimage" if is_ref => Some("&::lightning::ln::channelmanager::PaymentPreimage(unsafe { *"),
527 "ln::channelmanager::PaymentSecret" => Some("::lightning::ln::channelmanager::PaymentSecret("),
529 // List of structs we map (possibly during processing of other files):
530 "ln::features::InitFeatures" if !is_ref => Some("*unsafe { Box::from_raw("),
532 // List of traits we map (possibly during processing of other files):
533 "crate::util::logger::Logger" => Some(""),
536 eprintln!(" Type {} unconvertable from C", full_path);
539 }.map(|s| s.to_owned())
541 fn from_c_conversion_suffix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
542 if self.is_primitive(full_path) {
543 return Some("".to_owned());
546 "Vec" if !is_ref => Some(""),
547 "Option" => Some(""),
548 "Result" if !is_ref => Some(""),
550 "[u8; 32]" if is_ref => Some("}"),
551 "[u8; 32]" if !is_ref => Some(".data"),
552 "[u8; 16]" if !is_ref => Some(".data"),
553 "[u8; 10]" if !is_ref => Some(".data"),
554 "[u8; 4]" if !is_ref => Some(".data"),
555 "[u8; 3]" if !is_ref => Some(".data"),
557 "[u8]" if is_ref => Some(".to_slice()"),
558 "[usize]" if is_ref => Some(".to_slice()"),
560 "str" if is_ref => Some(".into()"),
561 "String" if !is_ref => Some(".into_rust()).unwrap()"),
563 "std::time::Duration" => Some(")"),
565 "bitcoin::secp256k1::key::PublicKey" => Some(".into_rust()"),
566 "bitcoin::secp256k1::Signature" => Some(".into_rust()"),
567 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some(".into_rust()"),
568 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some("}[..]).unwrap()"),
569 "bitcoin::blockdata::script::Script" if is_ref => Some(".to_slice()))"),
570 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_rust())"),
571 "bitcoin::blockdata::transaction::Transaction" => Some(".into_bitcoin()"),
572 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(".into_rust()"),
573 "bitcoin::network::constants::Network" => Some(".into_bitcoin()"),
574 "bitcoin::blockdata::block::BlockHeader" => Some(" }).unwrap()"),
575 "bitcoin::blockdata::block::Block" => Some(".to_slice()).unwrap()"),
577 // Newtypes that we just expose in their original form.
578 "bitcoin::hash_types::Txid" if is_ref => Some(" }[..]).unwrap()"),
579 "bitcoin::hash_types::Txid" => Some(".data[..]).unwrap()"),
580 "bitcoin::hash_types::BlockHash" if !is_ref => Some(".data[..]).unwrap()"),
581 "ln::channelmanager::PaymentHash" if !is_ref => Some(".data)"),
582 "ln::channelmanager::PaymentHash" if is_ref => Some(" })"),
583 "ln::channelmanager::PaymentPreimage" if !is_ref => Some(".data)"),
584 "ln::channelmanager::PaymentPreimage" if is_ref => Some(" })"),
585 "ln::channelmanager::PaymentSecret" => Some(".data)"),
587 // List of structs we map (possibly during processing of other files):
588 "ln::features::InitFeatures" if is_ref => Some(".inner) }"),
589 "ln::features::InitFeatures" if !is_ref => Some(".take_inner()) }"),
591 // List of traits we map (possibly during processing of other files):
592 "crate::util::logger::Logger" => Some(""),
595 eprintln!(" Type {} unconvertable from C", full_path);
598 }.map(|s| s.to_owned())
601 fn to_c_conversion_new_var_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<(&'b str, &'b str)> {
602 if self.is_primitive(full_path) {
606 "[u8]" if is_ref => Some(("crate::c_types::u8slice::from_slice(", ")")),
607 "[usize]" if is_ref => Some(("crate::c_types::usizeslice::from_slice(", ")")),
609 "bitcoin::blockdata::transaction::Transaction" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
610 "bitcoin::blockdata::transaction::Transaction" if !is_ref => Some(("::bitcoin::consensus::encode::serialize(&", ")")),
611 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(("{ let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(", ")); s }")),
612 "bitcoin::blockdata::block::Block" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
613 "bitcoin::hash_types::Txid" => None,
615 // Override the default since Records contain an fmt with a lifetime:
616 // TODO: We should include the other record fields
617 "util::logger::Record" => Some(("std::ffi::CString::new(format!(\"{}\", ", ".args)).unwrap()")),
619 }.map(|s| s.to_owned())
621 fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, ptr_for_ref: bool) -> Option<String> {
622 if self.is_primitive(full_path) {
623 return Some("".to_owned());
626 "Result" if !is_ref => Some("local_"),
627 "Vec" if !is_ref => Some("local_"),
628 "Option" => Some("local_"),
630 "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
631 "[u8; 32]" if is_ref => Some("&"),
632 "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes { data: "),
633 "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes { data: "),
634 "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes { data: "),
635 "[u8; 3]" if is_ref => Some("&"),
637 "[u8]" if is_ref => Some("local_"),
638 "[usize]" if is_ref => Some("local_"),
640 "str" if is_ref => Some(""),
641 "String" => Some(""),
643 "std::time::Duration" => Some(""),
645 "bitcoin::secp256k1::key::PublicKey" => Some("crate::c_types::PublicKey::from_rust(&"),
646 "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature::from_rust(&"),
647 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some(""),
648 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some("crate::c_types::SecretKey::from_rust("),
649 "bitcoin::secp256k1::Error" if !is_ref => Some("crate::c_types::Secp256k1Error::from_rust("),
650 "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice::from_slice(&"),
651 "bitcoin::blockdata::script::Script" if !is_ref => Some(""),
652 "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction::from_vec(local_"),
653 "bitcoin::blockdata::transaction::OutPoint" => Some("crate::c_types::bitcoin_to_C_outpoint("),
654 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut::from_rust("),
655 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("&local_"),
656 "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice::from_slice(&local_"),
658 "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
660 // Newtypes that we just expose in their original form.
661 "bitcoin::hash_types::Txid" if is_ref => Some(""),
662 "bitcoin::hash_types::BlockHash" if is_ref => Some(""),
663 "bitcoin::hash_types::BlockHash" => Some("crate::c_types::ThirtyTwoBytes { data: "),
664 "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
665 "ln::channelmanager::PaymentHash" if is_ref => Some("&"),
666 "ln::channelmanager::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
667 "ln::channelmanager::PaymentPreimage" if is_ref => Some("&"),
668 "ln::channelmanager::PaymentPreimage" => Some("crate::c_types::ThirtyTwoBytes { data: "),
669 "ln::channelmanager::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
671 // Override the default since Records contain an fmt with a lifetime:
672 "util::logger::Record" => Some("local_"),
674 // List of structs we map (possibly during processing of other files):
675 "ln::features::InitFeatures" if is_ref && ptr_for_ref => Some("crate::ln::features::InitFeatures { inner: &mut "),
676 "ln::features::InitFeatures" if is_ref => Some("Box::into_raw(Box::new(crate::ln::features::InitFeatures { inner: &mut "),
677 "ln::features::InitFeatures" if !is_ref => Some("crate::ln::features::InitFeatures { inner: Box::into_raw(Box::new("),
680 eprintln!(" Type {} (is_ref: {}) unconvertable to C", full_path, is_ref);
683 }.map(|s| s.to_owned())
685 fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, ptr_for_ref: bool) -> Option<String> {
686 if self.is_primitive(full_path) {
687 return Some("".to_owned());
690 "Result" if !is_ref => Some(""),
691 "Vec" if !is_ref => Some(".into()"),
692 "Option" => Some(""),
694 "[u8; 32]" if !is_ref => Some(" }"),
695 "[u8; 32]" if is_ref => Some(""),
696 "[u8; 16]" if !is_ref => Some(" }"),
697 "[u8; 10]" if !is_ref => Some(" }"),
698 "[u8; 4]" if !is_ref => Some(" }"),
699 "[u8; 3]" if is_ref => Some(""),
701 "[u8]" if is_ref => Some(""),
702 "[usize]" if is_ref => Some(""),
704 "str" if is_ref => Some(".into()"),
705 "String" if !is_ref => Some(".into_bytes().into()"),
706 "String" if is_ref => Some(".as_str().into()"),
708 "std::time::Duration" => Some(".as_secs()"),
710 "bitcoin::secp256k1::key::PublicKey" => Some(")"),
711 "bitcoin::secp256k1::Signature" => Some(")"),
712 "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some(")"),
713 "bitcoin::secp256k1::key::SecretKey" if is_ref => Some(".as_ref()"),
714 "bitcoin::secp256k1::Error" if !is_ref => Some(")"),
715 "bitcoin::blockdata::script::Script" if is_ref => Some("[..])"),
716 "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_bytes().into()"),
717 "bitcoin::blockdata::transaction::Transaction" => Some(")"),
718 "bitcoin::blockdata::transaction::OutPoint" => Some(")"),
719 "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(")"),
720 "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(""),
721 "bitcoin::blockdata::block::Block" if is_ref => Some(")"),
723 "bitcoin::hash_types::Txid" if !is_ref => Some(".into_inner() }"),
725 // Newtypes that we just expose in their original form.
726 "bitcoin::hash_types::Txid" if is_ref => Some(".as_inner()"),
727 "bitcoin::hash_types::BlockHash" if is_ref => Some(".as_inner()"),
728 "bitcoin::hash_types::BlockHash" => Some(".into_inner() }"),
729 "bitcoin::secp256k1::Message" if !is_ref => Some(".as_ref().clone() }"),
730 "ln::channelmanager::PaymentHash" if is_ref => Some(".0"),
731 "ln::channelmanager::PaymentHash" => Some(".0 }"),
732 "ln::channelmanager::PaymentPreimage" if is_ref => Some(".0"),
733 "ln::channelmanager::PaymentPreimage" => Some(".0 }"),
734 "ln::channelmanager::PaymentSecret" if !is_ref => Some(".0 }"),
736 // Override the default since Records contain an fmt with a lifetime:
737 "util::logger::Record" => Some(".as_ptr()"),
739 // List of structs we map (possibly during processing of other files):
740 "ln::features::InitFeatures" if is_ref && ptr_for_ref => Some(", is_owned: false }"),
741 "ln::features::InitFeatures" if is_ref => Some(", is_owned: false }))"),
742 "ln::features::InitFeatures" => Some(")), is_owned: true }"),
745 eprintln!(" Type {} unconvertable to C", full_path);
748 }.map(|s| s.to_owned())
751 fn empty_val_check_suffix_from_path(&self, full_path: &str) -> Option<&str> {
753 "ln::channelmanager::PaymentSecret" => Some(".data == [0; 32]"),
754 "bitcoin::secp256k1::key::PublicKey" => Some(".is_null()"),
755 "bitcoin::secp256k1::Signature" => Some(".is_null()"),
760 // ****************************
761 // *** Container Processing ***
762 // ****************************
764 /// Returns the module path in the generated mapping crate to the containers which we generate
765 /// when writing to CrateTypes::template_file.
766 pub fn generated_container_path() -> &'static str {
767 "crate::c_types::derived"
769 /// Returns the module path in the generated mapping crate to the container templates, which
770 /// are then concretized and put in the generated container path/template_file.
771 fn container_templ_path() -> &'static str {
775 /// Returns true if this is a "transparent" container, ie an Option or a container which does
776 /// not require a generated continer class.
777 fn is_transparent_container(&self, full_path: &str, _is_ref: bool) -> bool {
778 full_path == "Option"
780 /// Returns true if this is a known, supported, non-transparent container.
781 fn is_known_container(&self, full_path: &str, is_ref: bool) -> bool {
782 (full_path == "Result" && !is_ref) || (full_path == "Vec" && !is_ref) || full_path.ends_with("Tuple")
784 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)
785 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
786 // expecting one element in the vec per generic type, each of which is inline-converted
787 -> Option<(&'b str, Vec<(String, String)>, &'b str)> {
789 "Result" if !is_ref => {
791 vec![(" { Ok(mut o) => crate::c_types::CResultTempl::ok(".to_string(), "o".to_string()),
792 ("), Err(mut e) => crate::c_types::CResultTempl::err(".to_string(), "e".to_string())],
795 "Vec" if !is_ref => {
796 Some(("Vec::new(); for item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }"))
799 Some(("Vec::new(); for item in ", vec![(format!(".iter() {{ local_{}.push(", var_name), "**item".to_string())], "); }"))
802 if let Some(syn::Type::Path(p)) = single_contained {
803 if self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)) {
805 return Some(("if ", vec![
806 (".is_none() { std::ptr::null() } else { ".to_owned(), format!("({}.as_ref().unwrap())", var_access))
809 return Some(("if ", vec![
810 (".is_none() { std::ptr::null_mut() } else { ".to_owned(), format!("({}.unwrap())", var_access))
815 if let Some(t) = single_contained {
816 let mut v = Vec::new();
817 self.write_empty_rust_val(generics, &mut v, t);
818 let s = String::from_utf8(v).unwrap();
819 return Some(("if ", vec![
820 (format!(".is_none() {{ {} }} else {{ ", s), format!("({}.unwrap())", var_access))
822 } else { unreachable!(); }
828 /// only_contained_has_inner implies that there is only one contained element in the container
829 /// and it has an inner field (ie is an "opaque" type we've defined).
830 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)
831 // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
832 // expecting one element in the vec per generic type, each of which is inline-converted
833 -> Option<(&'b str, Vec<(String, String)>, &'b str)> {
835 "Result" if !is_ref => {
837 vec![(".result_ok { true => Ok(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.result)) }})", var_name)),
838 ("), false => Err(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.err)) }})", var_name))],
841 "Vec"|"Slice" if !is_ref => {
842 Some(("Vec::new(); for mut item in ", vec![(format!(".into_rust().drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }"))
844 "Slice" if is_ref => {
845 Some(("Vec::new(); for mut item in ", vec![(format!(".as_slice().iter() {{ local_{}.push(", var_name), "item".to_string())], "); }"))
848 if let Some(syn::Type::Path(p)) = single_contained {
849 if self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)) {
851 return Some(("if ", vec![(".inner.is_null() { None } else { Some((*".to_string(), format!("{}", var_name))], ").clone()) }"))
853 return Some(("if ", vec![(".inner.is_null() { None } else { Some(".to_string(), format!("{}", var_name))], ") }"));
858 if let Some(t) = single_contained {
859 let mut v = Vec::new();
860 let ret_ref = self.write_empty_rust_val_check_suffix(generics, &mut v, t);
861 let s = String::from_utf8(v).unwrap();
863 EmptyValExpectedTy::ReferenceAsPointer =>
864 return Some(("if ", vec![
865 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ &mut *{} }}", var_access))
867 EmptyValExpectedTy::OwnedPointer =>
868 return Some(("if ", vec![
869 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ *Box::from_raw({}) }}", var_access))
871 EmptyValExpectedTy::NonPointer =>
872 return Some(("if ", vec![
873 (format!("{} {{ None }} else {{ Some(", s), format!("{}", var_access))
876 } else { unreachable!(); }
882 // *************************************************
883 // *** Type definition during main.rs processing ***
884 // *************************************************
886 fn process_use_intern<W: std::io::Write>(&mut self, w: &mut W, u: &syn::UseTree, partial_path: &str) {
888 syn::UseTree::Path(p) => {
889 let new_path = format!("{}::{}", partial_path, p.ident);
890 self.process_use_intern(w, &p.tree, &new_path);
892 syn::UseTree::Name(n) => {
893 let full_path = format!("{}::{}", partial_path, n.ident);
894 self.imports.insert(n.ident.clone(), full_path);
896 syn::UseTree::Group(g) => {
897 for i in g.items.iter() {
898 self.process_use_intern(w, i, partial_path);
901 syn::UseTree::Rename(r) => {
902 let full_path = format!("{}::{}", partial_path, r.ident);
903 self.imports.insert(r.rename.clone(), full_path);
905 syn::UseTree::Glob(_) => {
906 eprintln!("Ignoring * use for {} - this may result in resolution failures", partial_path);
910 pub fn process_use<W: std::io::Write>(&mut self, w: &mut W, u: &syn::ItemUse) {
911 if let syn::Visibility::Public(_) = u.vis {
912 // We actually only use these for #[cfg(fuzztarget)]
913 eprintln!("Ignoring pub(use) tree!");
917 syn::UseTree::Path(p) => {
918 let new_path = format!("{}", p.ident);
919 self.process_use_intern(w, &p.tree, &new_path);
921 syn::UseTree::Name(n) => {
922 let full_path = format!("{}", n.ident);
923 self.imports.insert(n.ident.clone(), full_path);
925 _ => unimplemented!(),
927 if u.leading_colon.is_some() { unimplemented!() }
930 pub fn mirrored_enum_declared(&mut self, ident: &syn::Ident) {
931 eprintln!("{} mirrored", ident);
932 self.declared.insert(ident.clone(), DeclType::MirroredEnum);
934 pub fn enum_ignored(&mut self, ident: &'c syn::Ident) {
935 self.declared.insert(ident.clone(), DeclType::EnumIgnored);
937 pub fn struct_imported(&mut self, ident: &'c syn::Ident, named: String) {
938 eprintln!("Imported {} as {}", ident, named);
939 self.declared.insert(ident.clone(), DeclType::StructImported);
941 pub fn struct_ignored(&mut self, ident: &syn::Ident) {
942 eprintln!("Not importing {}", ident);
943 self.declared.insert(ident.clone(), DeclType::StructIgnored);
945 pub fn trait_declared(&mut self, ident: &syn::Ident, t: &'c syn::ItemTrait) {
946 eprintln!("Trait {} created", ident);
947 self.declared.insert(ident.clone(), DeclType::Trait(t));
949 pub fn get_declared_type(&'a self, ident: &syn::Ident) -> Option<&'a DeclType<'c>> {
950 self.declared.get(ident)
952 /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
953 pub fn c_type_has_inner_from_path(&self, full_path: &str) -> bool{
954 self.crate_types.opaques.get(full_path).is_some()
957 pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
958 if let Some(imp) = self.imports.get(id) {
960 } else if self.declared.get(id).is_some() {
961 Some(self.module_path.to_string() + "::" + &format!("{}", id))
965 pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
966 if let Some(imp) = self.imports.get(id) {
968 } else if let Some(decl_type) = self.declared.get(id) {
970 DeclType::StructIgnored => None,
971 _ => Some(self.module_path.to_string() + "::" + &format!("{}", id)),
976 pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
977 let p = if let Some(gen_types) = generics {
978 if let Some((_, synpath)) = gen_types.maybe_resolve_path(p_arg) {
983 if p.leading_colon.is_some() {
984 Some(p.segments.iter().enumerate().map(|(idx, seg)| {
985 format!("{}{}", if idx == 0 { "" } else { "::" }, seg.ident)
987 } else if let Some(id) = p.get_ident() {
988 self.maybe_resolve_ident(id)
990 if p.segments.len() == 1 {
991 let seg = p.segments.iter().next().unwrap();
992 return self.maybe_resolve_ident(&seg.ident);
994 let mut seg_iter = p.segments.iter();
995 let first_seg = seg_iter.next().unwrap();
996 let remaining: String = seg_iter.map(|seg| {
997 format!("::{}", seg.ident)
999 if let Some(imp) = self.imports.get(&first_seg.ident) {
1000 if remaining != "" {
1001 Some(imp.clone() + &remaining)
1008 pub fn resolve_path(&self, p: &syn::Path, generics: Option<&GenericTypes>) -> String {
1009 self.maybe_resolve_path(p, generics).unwrap()
1012 // ***********************************
1013 // *** Original Rust Type Printing ***
1014 // ***********************************
1016 fn in_rust_prelude(resolved_path: &str) -> bool {
1017 match resolved_path {
1025 fn write_rust_path<W: std::io::Write>(&self, w: &mut W, generics_resolver: Option<&GenericTypes>, path: &syn::Path) {
1026 if let Some(resolved) = self.maybe_resolve_path(&path, generics_resolver) {
1027 if self.is_primitive(&resolved) {
1028 write!(w, "{}", path.get_ident().unwrap()).unwrap();
1030 // TODO: We should have a generic "is from a dependency" check here instead of
1031 // checking for "bitcoin" explicitly.
1032 if resolved.starts_with("bitcoin::") || Self::in_rust_prelude(&resolved) {
1033 write!(w, "{}", resolved).unwrap();
1034 // If we're printing a generic argument, it needs to reference the crate, otherwise
1035 // the original crate:
1036 } else if self.maybe_resolve_path(&path, None).as_ref() == Some(&resolved) {
1037 write!(w, "{}::{}", self.orig_crate, resolved).unwrap();
1039 write!(w, "crate::{}", resolved).unwrap();
1042 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().last().unwrap().arguments {
1043 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1046 if path.leading_colon.is_some() {
1047 write!(w, "::").unwrap();
1049 for (idx, seg) in path.segments.iter().enumerate() {
1050 if idx != 0 { write!(w, "::").unwrap(); }
1051 write!(w, "{}", seg.ident).unwrap();
1052 if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
1053 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1058 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>) {
1059 let mut had_params = false;
1060 for (idx, arg) in generics.enumerate() {
1061 if idx != 0 { write!(w, ", ").unwrap(); } else { write!(w, "<").unwrap(); }
1064 syn::GenericParam::Lifetime(lt) => write!(w, "'{}", lt.lifetime.ident).unwrap(),
1065 syn::GenericParam::Type(t) => {
1066 write!(w, "{}", t.ident).unwrap();
1067 if t.colon_token.is_some() { write!(w, ":").unwrap(); }
1068 for (idx, bound) in t.bounds.iter().enumerate() {
1069 if idx != 0 { write!(w, " + ").unwrap(); }
1071 syn::TypeParamBound::Trait(tb) => {
1072 if tb.paren_token.is_some() || tb.lifetimes.is_some() { unimplemented!(); }
1073 self.write_rust_path(w, generics_resolver, &tb.path);
1075 _ => unimplemented!(),
1078 if t.eq_token.is_some() || t.default.is_some() { unimplemented!(); }
1080 _ => unimplemented!(),
1083 if had_params { write!(w, ">").unwrap(); }
1086 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>) {
1087 write!(w, "<").unwrap();
1088 for (idx, arg) in generics.enumerate() {
1089 if idx != 0 { write!(w, ", ").unwrap(); }
1091 syn::GenericArgument::Type(t) => self.write_rust_type(w, generics_resolver, t),
1092 _ => unimplemented!(),
1095 write!(w, ">").unwrap();
1097 pub fn write_rust_type<W: std::io::Write>(&self, w: &mut W, generics: Option<&GenericTypes>, t: &syn::Type) {
1099 syn::Type::Path(p) => {
1100 if p.qself.is_some() {
1103 self.write_rust_path(w, generics, &p.path);
1105 syn::Type::Reference(r) => {
1106 write!(w, "&").unwrap();
1107 if let Some(lft) = &r.lifetime {
1108 write!(w, "'{} ", lft.ident).unwrap();
1110 if r.mutability.is_some() {
1111 write!(w, "mut ").unwrap();
1113 self.write_rust_type(w, generics, &*r.elem);
1115 syn::Type::Array(a) => {
1116 write!(w, "[").unwrap();
1117 self.write_rust_type(w, generics, &a.elem);
1118 if let syn::Expr::Lit(l) = &a.len {
1119 if let syn::Lit::Int(i) = &l.lit {
1120 write!(w, "; {}]", i).unwrap();
1121 } else { unimplemented!(); }
1122 } else { unimplemented!(); }
1124 syn::Type::Slice(s) => {
1125 write!(w, "[").unwrap();
1126 self.write_rust_type(w, generics, &s.elem);
1127 write!(w, "]").unwrap();
1129 syn::Type::Tuple(s) => {
1130 write!(w, "(").unwrap();
1131 for (idx, t) in s.elems.iter().enumerate() {
1132 if idx != 0 { write!(w, ", ").unwrap(); }
1133 self.write_rust_type(w, generics, &t);
1135 write!(w, ")").unwrap();
1137 _ => unimplemented!(),
1141 /// Prints a constructor for something which is "uninitialized" (but obviously not actually
1142 /// unint'd memory).
1143 pub fn write_empty_rust_val<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) {
1145 syn::Type::Path(p) => {
1146 let resolved = self.resolve_path(&p.path, generics);
1147 if self.crate_types.opaques.get(&resolved).is_some() {
1148 write!(w, "crate::{} {{ inner: std::ptr::null_mut(), is_owned: true }}", resolved).unwrap();
1150 // Assume its a manually-mapped C type, where we can just define an null() fn
1151 write!(w, "{}::null()", self.c_type_from_path(&resolved, false, false).unwrap()).unwrap();
1154 syn::Type::Array(a) => {
1155 if let syn::Expr::Lit(l) = &a.len {
1156 if let syn::Lit::Int(i) = &l.lit {
1157 if i.base10_digits().parse::<usize>().unwrap() < 32 {
1158 // Blindly assume that if we're trying to create an empty value for an
1159 // array < 32 entries that all-0s may be a valid state.
1162 let arrty = format!("[u8; {}]", i.base10_digits());
1163 write!(w, "{}", self.to_c_conversion_inline_prefix_from_path(&arrty, false, false).unwrap()).unwrap();
1164 write!(w, "[0; {}]", i.base10_digits()).unwrap();
1165 write!(w, "{}", self.to_c_conversion_inline_suffix_from_path(&arrty, false, false).unwrap()).unwrap();
1166 } else { unimplemented!(); }
1167 } else { unimplemented!(); }
1169 _ => unimplemented!(),
1173 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1174 /// See EmptyValExpectedTy for information on return types.
1175 fn write_empty_rust_val_check_suffix<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) -> EmptyValExpectedTy {
1177 syn::Type::Path(p) => {
1178 let resolved = self.resolve_path(&p.path, generics);
1179 if self.crate_types.opaques.get(&resolved).is_some() {
1180 write!(w, ".inner.is_null()").unwrap();
1181 EmptyValExpectedTy::NonPointer
1183 if let Some(suffix) = self.empty_val_check_suffix_from_path(&resolved) {
1184 write!(w, "{}", suffix).unwrap();
1185 // We may eventually need to allow empty_val_check_suffix_from_path to specify if we need a deref or not
1186 EmptyValExpectedTy::NonPointer
1188 write!(w, " == std::ptr::null_mut()").unwrap();
1189 EmptyValExpectedTy::OwnedPointer
1193 syn::Type::Array(a) => {
1194 if let syn::Expr::Lit(l) = &a.len {
1195 if let syn::Lit::Int(i) = &l.lit {
1196 write!(w, " == [0; {}]", i.base10_digits()).unwrap();
1197 EmptyValExpectedTy::NonPointer
1198 } else { unimplemented!(); }
1199 } else { unimplemented!(); }
1201 syn::Type::Slice(_) => {
1202 // Option<[]> always implies that we want to treat len() == 0 differently from
1203 // None, so we always map an Option<[]> into a pointer.
1204 write!(w, " == std::ptr::null_mut()").unwrap();
1205 EmptyValExpectedTy::ReferenceAsPointer
1207 _ => unimplemented!(),
1211 /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1212 pub fn write_empty_rust_val_check<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type, var_access: &str) {
1214 syn::Type::Path(_) => {
1215 write!(w, "{}", var_access).unwrap();
1216 self.write_empty_rust_val_check_suffix(generics, w, t);
1218 syn::Type::Array(a) => {
1219 if let syn::Expr::Lit(l) = &a.len {
1220 if let syn::Lit::Int(i) = &l.lit {
1221 let arrty = format!("[u8; {}]", i.base10_digits());
1222 // We don't (yet) support a new-var conversion here.
1223 assert!(self.from_c_conversion_new_var_from_path(&arrty, false).is_none());
1225 self.from_c_conversion_prefix_from_path(&arrty, false).unwrap(),
1227 self.from_c_conversion_suffix_from_path(&arrty, false).unwrap()).unwrap();
1228 self.write_empty_rust_val_check_suffix(generics, w, t);
1229 } else { unimplemented!(); }
1230 } else { unimplemented!(); }
1232 _ => unimplemented!(),
1236 // ********************************
1237 // *** Type conversion printing ***
1238 // ********************************
1240 /// Returns true we if can just skip passing this to C entirely
1241 pub fn skip_arg(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
1243 syn::Type::Path(p) => {
1244 if p.qself.is_some() { unimplemented!(); }
1245 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1246 self.skip_path(&full_path)
1249 syn::Type::Reference(r) => {
1250 self.skip_arg(&*r.elem, generics)
1255 pub fn no_arg_to_rust<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1257 syn::Type::Path(p) => {
1258 if p.qself.is_some() { unimplemented!(); }
1259 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1260 write!(w, "{}", self.no_arg_path_to_rust(&full_path)).unwrap();
1263 syn::Type::Reference(r) => {
1264 self.no_arg_to_rust(w, &*r.elem, generics);
1270 fn write_conversion_inline_intern<W: std::io::Write,
1271 LP: Fn(&str, bool, bool) -> Option<String>, DL: Fn(&mut W, &DeclType, &str, bool, bool), SC: Fn(bool) -> &'static str>
1272 (&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool,
1273 tupleconv: &str, prefix: bool, sliceconv: SC, path_lookup: LP, decl_lookup: DL) {
1275 syn::Type::Reference(r) => {
1276 self.write_conversion_inline_intern(w, &*r.elem, generics, true, r.mutability.is_some(),
1277 ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1279 syn::Type::Path(p) => {
1280 if p.qself.is_some() {
1284 let resolved_path = self.resolve_path(&p.path, generics);
1285 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1286 return self.write_conversion_inline_intern(w, aliased_type, None, is_ref, is_mut, ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1287 } else if let Some(c_type) = path_lookup(&resolved_path, is_ref, ptr_for_ref) {
1288 write!(w, "{}", c_type).unwrap();
1289 } else if self.crate_types.opaques.get(&resolved_path).is_some() {
1290 decl_lookup(w, &DeclType::StructImported, &resolved_path, is_ref, is_mut);
1291 } else if self.crate_types.mirrored_enums.get(&resolved_path).is_some() {
1292 decl_lookup(w, &DeclType::MirroredEnum, &resolved_path, is_ref, is_mut);
1293 } else if let Some(t) = self.crate_types.traits.get(&resolved_path) {
1294 decl_lookup(w, &DeclType::Trait(t), &resolved_path, is_ref, is_mut);
1295 } else if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
1296 if let Some(_) = self.imports.get(ident) {
1297 // crate_types lookup has to have succeeded:
1298 panic!("Failed to print inline conversion for {}", ident);
1299 } else if let Some(decl_type) = self.declared.get(ident) {
1300 decl_lookup(w, decl_type, &self.maybe_resolve_ident(ident).unwrap(), is_ref, is_mut);
1301 } else { unimplemented!(); }
1302 } else { unimplemented!(); }
1304 syn::Type::Array(a) => {
1305 // We assume all arrays contain only [int_literal; X]s.
1306 // This may result in some outputs not compiling.
1307 if let syn::Expr::Lit(l) = &a.len {
1308 if let syn::Lit::Int(i) = &l.lit {
1309 write!(w, "{}", path_lookup(&format!("[u8; {}]", i.base10_digits()), is_ref, ptr_for_ref).unwrap()).unwrap();
1310 } else { unimplemented!(); }
1311 } else { unimplemented!(); }
1313 syn::Type::Slice(s) => {
1314 // We assume all slices contain only literals or references.
1315 // This may result in some outputs not compiling.
1316 if let syn::Type::Path(p) = &*s.elem {
1317 let resolved = self.resolve_path(&p.path, generics);
1318 assert!(self.is_primitive(&resolved));
1319 write!(w, "{}", path_lookup("[u8]", is_ref, ptr_for_ref).unwrap()).unwrap();
1320 } else if let syn::Type::Reference(r) = &*s.elem {
1321 if let syn::Type::Path(p) = &*r.elem {
1322 write!(w, "{}", sliceconv(self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)))).unwrap();
1323 } else { unimplemented!(); }
1324 } else if let syn::Type::Tuple(t) = &*s.elem {
1325 assert!(!t.elems.is_empty());
1327 write!(w, "&local_").unwrap();
1329 let mut needs_map = false;
1330 for e in t.elems.iter() {
1331 if let syn::Type::Reference(_) = e {
1336 write!(w, ".iter().map(|(").unwrap();
1337 for i in 0..t.elems.len() {
1338 write!(w, "{}{}", if i != 0 { ", " } else { "" }, ('a' as u8 + i as u8) as char).unwrap();
1340 write!(w, ")| (").unwrap();
1341 for (idx, e) in t.elems.iter().enumerate() {
1342 if let syn::Type::Reference(_) = e {
1343 write!(w, "{}{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1344 } else if let syn::Type::Path(_) = e {
1345 write!(w, "{}*{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1346 } else { unimplemented!(); }
1348 write!(w, ")).collect::<Vec<_>>()[..]").unwrap();
1351 } else { unimplemented!(); }
1353 syn::Type::Tuple(t) => {
1354 if t.elems.is_empty() {
1355 // cbindgen has poor support for (), see, eg https://github.com/eqrion/cbindgen/issues/527
1356 // so work around it by just pretending its a 0u8
1357 write!(w, "{}", tupleconv).unwrap();
1359 if prefix { write!(w, "local_").unwrap(); }
1362 _ => unimplemented!(),
1366 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) {
1367 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "0u8 /*", true, |_| "local_",
1368 |a, b, c| self.to_c_conversion_inline_prefix_from_path(a, b, c),
1369 |w, decl_type, decl_path, is_ref, _is_mut| {
1371 DeclType::MirroredEnum if is_ref && ptr_for_ref => write!(w, "crate::{}::from_native(&", decl_path).unwrap(),
1372 DeclType::MirroredEnum if is_ref => write!(w, "&crate::{}::from_native(&", decl_path).unwrap(),
1373 DeclType::MirroredEnum => write!(w, "crate::{}::native_into(", decl_path).unwrap(),
1374 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1375 write!(w, "crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1376 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1377 write!(w, "crate::{} {{ inner: unsafe {{ ( (&(", decl_path).unwrap(),
1378 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1379 write!(w, "&crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1380 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1381 write!(w, "crate::{} {{ inner: ", decl_path).unwrap(),
1382 DeclType::EnumIgnored|DeclType::StructImported if !is_ref =>
1383 write!(w, "crate::{} {{ inner: Box::into_raw(Box::new(", decl_path).unwrap(),
1384 DeclType::Trait(_) if is_ref => write!(w, "&").unwrap(),
1385 DeclType::Trait(_) if !is_ref => {},
1386 _ => panic!("{:?}", decl_path),
1390 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) {
1391 self.write_to_c_conversion_inline_prefix_inner(w, t, generics, false, ptr_for_ref, false);
1393 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) {
1394 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "*/", false, |_| ".into()",
1395 |a, b, c| self.to_c_conversion_inline_suffix_from_path(a, b, c),
1396 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1397 DeclType::MirroredEnum => write!(w, ")").unwrap(),
1398 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1399 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1400 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1401 write!(w, ") as *const _) as *mut _) }}, is_owned: false }}").unwrap(),
1402 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1403 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1404 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1405 write!(w, ", is_owned: true }}").unwrap(),
1406 DeclType::EnumIgnored|DeclType::StructImported if !is_ref => write!(w, ")), is_owned: true }}").unwrap(),
1407 DeclType::Trait(_) if is_ref => {},
1408 DeclType::Trait(_) => {
1409 // This is used when we're converting a concrete Rust type into a C trait
1410 // for use when a Rust trait method returns an associated type.
1411 // Because all of our C traits implement From<RustTypesImplementingTraits>
1412 // we can just call .into() here and be done.
1413 write!(w, ".into()").unwrap()
1415 _ => unimplemented!(),
1418 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) {
1419 self.write_to_c_conversion_inline_suffix_inner(w, t, generics, false, ptr_for_ref, false);
1422 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) {
1423 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "() /*", true, |_| "&local_",
1424 |a, b, _c| self.from_c_conversion_prefix_from_path(a, b),
1425 |w, decl_type, _full_path, is_ref, is_mut| match decl_type {
1426 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, "unsafe {{ &*(*").unwrap(),
1427 DeclType::StructImported if is_mut && is_ref => write!(w, "unsafe {{ &mut *").unwrap(),
1428 DeclType::StructImported if is_ref => write!(w, "unsafe {{ &*").unwrap(),
1429 DeclType::StructImported if !is_ref => write!(w, "*unsafe {{ Box::from_raw(").unwrap(),
1430 DeclType::MirroredEnum if is_ref => write!(w, "&").unwrap(),
1431 DeclType::MirroredEnum => {},
1432 DeclType::Trait(_) => {},
1433 _ => unimplemented!(),
1436 pub fn write_from_c_conversion_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1437 self.write_from_c_conversion_prefix_inner(w, t, generics, false, false);
1439 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) {
1440 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "*/", false,
1441 |has_inner| match has_inner {
1442 false => ".iter().collect::<Vec<_>>()[..]",
1445 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1446 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1447 DeclType::StructImported if is_ref && ptr_for_ref => write!(w, ").inner }}").unwrap(),
1448 DeclType::StructImported if is_ref => write!(w, ".inner }}").unwrap(),
1449 DeclType::StructImported if !is_ref => write!(w, ".take_inner()) }}").unwrap(),
1450 DeclType::MirroredEnum if is_ref => write!(w, ".to_native()").unwrap(),
1451 DeclType::MirroredEnum => write!(w, ".into_native()").unwrap(),
1452 DeclType::Trait(_) => {},
1453 _ => unimplemented!(),
1456 pub fn write_from_c_conversion_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1457 self.write_from_c_conversion_suffix_inner(w, t, generics, false, false);
1459 // Note that compared to the above conversion functions, the following two are generally
1460 // significantly undertested:
1461 pub fn write_from_c_conversion_to_ref_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1462 self.write_conversion_inline_intern(w, t, generics, false, false, false, "() /*", true, |_| "&local_",
1464 if let Some(conv) = self.from_c_conversion_prefix_from_path(a, b) {
1465 Some(format!("&{}", conv))
1468 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1469 DeclType::StructImported if !is_ref => write!(w, "unsafe {{ &*").unwrap(),
1470 _ => unimplemented!(),
1473 pub fn write_from_c_conversion_to_ref_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1474 self.write_conversion_inline_intern(w, t, generics, false, false, false, "*/", false,
1475 |has_inner| match has_inner {
1476 false => ".iter().collect::<Vec<_>>()[..]",
1479 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1480 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1481 DeclType::StructImported if !is_ref => write!(w, ".inner }}").unwrap(),
1482 _ => unimplemented!(),
1486 fn write_conversion_new_var_intern<'b, W: std::io::Write,
1487 LP: Fn(&str, bool) -> Option<(&str, &str)>,
1488 LC: Fn(&str, bool, Option<&syn::Type>, &syn::Ident, &str) -> Option<(&'b str, Vec<(String, String)>, &'b str)>,
1489 VP: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool),
1490 VS: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool)>
1491 (&self, w: &mut W, ident: &syn::Ident, var: &str, t: &syn::Type, generics: Option<&GenericTypes>,
1492 mut is_ref: bool, mut ptr_for_ref: bool, to_c: bool,
1493 path_lookup: &LP, container_lookup: &LC, var_prefix: &VP, var_suffix: &VS) -> bool {
1495 macro_rules! convert_container {
1496 ($container_type: expr, $args_len: expr, $args_iter: expr) => { {
1497 // For slices (and Options), we refuse to directly map them as is_ref when they
1498 // aren't opaque types containing an inner pointer. This is due to the fact that,
1499 // in both cases, the actual higher-level type is non-is_ref.
1500 let ty_has_inner = if self.is_transparent_container(&$container_type, is_ref) || $container_type == "Slice" {
1501 let ty = $args_iter().next().unwrap();
1502 if $container_type == "Slice" && to_c {
1503 // "To C ptr_for_ref" means "return the regular object with is_owned
1504 // set to false", which is totally what we want in a slice if we're about to
1505 // set ty_has_inner.
1508 if let syn::Type::Reference(t) = ty {
1509 if let syn::Type::Path(p) = &*t.elem {
1510 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1512 } else if let syn::Type::Path(p) = ty {
1513 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1517 // Options get a bunch of special handling, since in general we map Option<>al
1518 // types into the same C type as non-Option-wrapped types. This ends up being
1519 // pretty manual here and most of the below special-cases are for Options.
1520 let mut needs_ref_map = false;
1521 let mut only_contained_type = None;
1522 let mut only_contained_has_inner = false;
1523 let mut contains_slice = false;
1524 if $args_len == 1 && self.is_transparent_container(&$container_type, is_ref) {
1525 only_contained_has_inner = ty_has_inner;
1526 let arg = $args_iter().next().unwrap();
1527 if let syn::Type::Reference(t) = arg {
1528 only_contained_type = Some(&*t.elem);
1529 if let syn::Type::Path(_) = &*t.elem {
1531 } else if let syn::Type::Slice(_) = &*t.elem {
1532 contains_slice = true;
1533 } else { return false; }
1534 needs_ref_map = true;
1535 } else if let syn::Type::Path(_) = arg {
1536 only_contained_type = Some(&arg);
1537 } else { unimplemented!(); }
1540 if let Some((prefix, conversions, suffix)) = container_lookup(&$container_type, is_ref && ty_has_inner, only_contained_type, ident, var) {
1541 assert_eq!(conversions.len(), $args_len);
1542 write!(w, "let mut local_{}{} = ", ident, if !to_c && needs_ref_map {"_base"} else { "" }).unwrap();
1543 if only_contained_has_inner && to_c {
1544 var_prefix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
1546 write!(w, "{}{}", prefix, var).unwrap();
1548 for ((pfx, var_name), (idx, ty)) in conversions.iter().zip($args_iter().enumerate()) {
1549 let mut var = std::io::Cursor::new(Vec::new());
1550 write!(&mut var, "{}", var_name).unwrap();
1551 let var_access = String::from_utf8(var.into_inner()).unwrap();
1553 let conv_ty = if needs_ref_map { only_contained_type.as_ref().unwrap() } else { ty };
1555 write!(w, "{} {{ ", pfx).unwrap();
1556 let new_var_name = format!("{}_{}", ident, idx);
1557 let new_var = self.write_conversion_new_var_intern(w, &syn::Ident::new(&new_var_name, Span::call_site()),
1558 &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);
1559 if new_var { write!(w, " ").unwrap(); }
1560 if (!only_contained_has_inner || !to_c) && !contains_slice {
1561 var_prefix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1564 if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
1565 write!(w, "Box::into_raw(Box::new(").unwrap();
1567 write!(w, "{}{}", if contains_slice { "local_" } else { "" }, if new_var { new_var_name } else { var_access }).unwrap();
1568 if (!only_contained_has_inner || !to_c) && !contains_slice {
1569 var_suffix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1571 if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
1572 write!(w, "))").unwrap();
1574 write!(w, " }}").unwrap();
1576 write!(w, "{}", suffix).unwrap();
1577 if only_contained_has_inner && to_c {
1578 var_suffix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
1580 write!(w, ";").unwrap();
1581 if !to_c && needs_ref_map {
1582 write!(w, " let mut local_{} = local_{}_base.as_ref()", ident, ident).unwrap();
1584 write!(w, ".map(|a| &a[..])").unwrap();
1586 write!(w, ";").unwrap();
1594 syn::Type::Reference(r) => {
1595 if let syn::Type::Slice(_) = &*r.elem {
1596 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)
1598 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)
1601 syn::Type::Path(p) => {
1602 if p.qself.is_some() {
1605 let resolved_path = self.resolve_path(&p.path, generics);
1606 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1607 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);
1609 if self.is_known_container(&resolved_path, is_ref) || self.is_transparent_container(&resolved_path, is_ref) {
1610 if let syn::PathArguments::AngleBracketed(args) = &p.path.segments.iter().next().unwrap().arguments {
1611 convert_container!(resolved_path, args.args.len(), || args.args.iter().map(|arg| {
1612 if let syn::GenericArgument::Type(ty) = arg {
1614 } else { unimplemented!(); }
1616 } else { unimplemented!(); }
1618 if self.is_primitive(&resolved_path) {
1620 } else if let Some(ty_ident) = single_ident_generic_path_to_ident(&p.path) {
1621 if let Some((prefix, suffix)) = path_lookup(&resolved_path, is_ref) {
1622 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
1624 } else if self.declared.get(ty_ident).is_some() {
1629 syn::Type::Array(_) => {
1630 // We assume all arrays contain only primitive types.
1631 // This may result in some outputs not compiling.
1634 syn::Type::Slice(s) => {
1635 if let syn::Type::Path(p) = &*s.elem {
1636 let resolved = self.resolve_path(&p.path, generics);
1637 assert!(self.is_primitive(&resolved));
1638 let slice_path = format!("[{}]", resolved);
1639 if let Some((prefix, suffix)) = path_lookup(&slice_path, true) {
1640 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
1643 } else if let syn::Type::Reference(ty) = &*s.elem {
1644 let tyref = [&*ty.elem];
1646 convert_container!("Slice", 1, || tyref.iter());
1647 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
1648 } else if let syn::Type::Tuple(t) = &*s.elem {
1649 // When mapping into a temporary new var, we need to own all the underlying objects.
1650 // Thus, we drop any references inside the tuple and convert with non-reference types.
1651 let mut elems = syn::punctuated::Punctuated::new();
1652 for elem in t.elems.iter() {
1653 if let syn::Type::Reference(r) = elem {
1654 elems.push((*r.elem).clone());
1656 elems.push(elem.clone());
1659 let ty = [syn::Type::Tuple(syn::TypeTuple {
1660 paren_token: t.paren_token, elems
1664 convert_container!("Slice", 1, || ty.iter());
1665 unimplemented!("convert_container should return true as container_lookup should succeed for slices");
1666 } else { unimplemented!() }
1668 syn::Type::Tuple(t) => {
1669 if !t.elems.is_empty() {
1670 // We don't (yet) support tuple elements which cannot be converted inline
1671 write!(w, "let (").unwrap();
1672 for idx in 0..t.elems.len() {
1673 if idx != 0 { write!(w, ", ").unwrap(); }
1674 write!(w, "{} orig_{}_{}", if is_ref { "ref" } else { "mut" }, ident, idx).unwrap();
1676 write!(w, ") = {}{}; ", var, if !to_c { ".to_rust()" } else { "" }).unwrap();
1677 // Like other template types, tuples are always mapped as their non-ref
1678 // versions for types which have different ref mappings. Thus, we convert to
1679 // non-ref versions and handle opaque types with inner pointers manually.
1680 for (idx, elem) in t.elems.iter().enumerate() {
1681 if let syn::Type::Path(p) = elem {
1682 let v_name = format!("orig_{}_{}", ident, idx);
1683 let tuple_elem_ident = syn::Ident::new(&v_name, Span::call_site());
1684 if self.write_conversion_new_var_intern(w, &tuple_elem_ident, &v_name, elem, generics,
1685 false, ptr_for_ref, to_c,
1686 path_lookup, container_lookup, var_prefix, var_suffix) {
1687 write!(w, " ").unwrap();
1688 // Opaque types with inner pointers shouldn't ever create new stack
1689 // variables, so we don't handle it and just assert that it doesn't
1691 assert!(!self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)));
1695 write!(w, "let mut local_{} = (", ident).unwrap();
1696 for (idx, elem) in t.elems.iter().enumerate() {
1697 let ty_has_inner = {
1699 // "To C ptr_for_ref" means "return the regular object with
1700 // is_owned set to false", which is totally what we want
1701 // if we're about to set ty_has_inner.
1704 if let syn::Type::Reference(t) = elem {
1705 if let syn::Type::Path(p) = &*t.elem {
1706 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1708 } else if let syn::Type::Path(p) = elem {
1709 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1712 if idx != 0 { write!(w, ", ").unwrap(); }
1713 var_prefix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1714 if is_ref && ty_has_inner {
1715 // For ty_has_inner, the regular var_prefix mapping will take a
1716 // reference, so deref once here to make sure we keep the original ref.
1717 write!(w, "*").unwrap();
1719 write!(w, "orig_{}_{}", ident, idx).unwrap();
1720 if is_ref && !ty_has_inner {
1721 // If we don't have an inner variable's reference to maintain, just
1722 // hope the type is Clonable and use that.
1723 write!(w, ".clone()").unwrap();
1725 var_suffix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1727 write!(w, "){};", if to_c { ".into()" } else { "" }).unwrap();
1731 _ => unimplemented!(),
1735 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 {
1736 self.write_conversion_new_var_intern(w, ident, var_access, t, generics, false, ptr_for_ref, true,
1737 &|a, b| self.to_c_conversion_new_var_from_path(a, b),
1738 &|a, b, c, d, e| self.to_c_conversion_container_new_var(generics, a, b, c, d, e),
1739 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
1740 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_prefix_inner(a, b, c, d, e, f),
1741 &|a, b, c, d, e, f| self.write_to_c_conversion_inline_suffix_inner(a, b, c, d, e, f))
1743 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 {
1744 self.write_to_c_conversion_new_var_inner(w, ident, &format!("{}", ident), t, generics, ptr_for_ref)
1746 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 {
1747 self.write_conversion_new_var_intern(w, ident, &format!("{}", ident), t, generics, false, false, false,
1748 &|a, b| self.from_c_conversion_new_var_from_path(a, b),
1749 &|a, b, c, d, e| self.from_c_conversion_container_new_var(generics, a, b, c, d, e),
1750 // We force ptr_for_ref here since we can't generate a ref on one line and use it later
1751 &|a, b, c, d, e, _f| self.write_from_c_conversion_prefix_inner(a, b, c, d, e),
1752 &|a, b, c, d, e, _f| self.write_from_c_conversion_suffix_inner(a, b, c, d, e))
1755 // ******************************************************
1756 // *** C Container Type Equivalent and alias Printing ***
1757 // ******************************************************
1759 fn write_template_constructor<W: std::io::Write>(&mut self, w: &mut W, container_type: &str, mangled_container: &str, args: &Vec<&syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
1760 if container_type == "Result" {
1761 assert_eq!(args.len(), 2);
1762 macro_rules! write_fn {
1763 ($call: expr) => { {
1764 writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_{}() -> {} {{", mangled_container, $call, mangled_container).unwrap();
1765 writeln!(w, "\t{}::CResultTempl::{}(0)\n}}\n", Self::container_templ_path(), $call).unwrap();
1768 macro_rules! write_alias {
1769 ($call: expr, $item: expr) => { {
1770 write!(w, "#[no_mangle]\npub static {}_{}: extern \"C\" fn (", mangled_container, $call).unwrap();
1771 if let syn::Type::Path(syn::TypePath { path, .. }) = $item {
1772 let resolved = self.resolve_path(path, generics);
1773 if self.is_known_container(&resolved, is_ref) || self.is_transparent_container(&resolved, is_ref) {
1774 self.write_c_mangled_container_path_intern(w, Self::path_to_generic_args(path), generics,
1775 &format!("{}", single_ident_generic_path_to_ident(path).unwrap()), is_ref, false, false, false);
1777 self.write_template_generics(w, &mut [$item].iter().map(|t| *t), generics, is_ref, true);
1779 } else if let syn::Type::Tuple(syn::TypeTuple { elems, .. }) = $item {
1780 self.write_c_mangled_container_path_intern(w, elems.iter().collect(), generics,
1781 &format!("{}Tuple", elems.len()), is_ref, false, false, false);
1782 } else { unimplemented!(); }
1783 write!(w, ") -> {} =\n\t{}::CResultTempl::<", mangled_container, Self::container_templ_path()).unwrap();
1784 self.write_template_generics(w, &mut args.iter().map(|t| *t), generics, is_ref, true);
1785 writeln!(w, ">::{};\n", $call).unwrap();
1789 syn::Type::Tuple(t) if t.elems.is_empty() => write_fn!("ok"),
1790 _ => write_alias!("ok", args[0]),
1793 syn::Type::Tuple(t) if t.elems.is_empty() => write_fn!("err"),
1794 _ => write_alias!("err", args[1]),
1796 } else if container_type.ends_with("Tuple") {
1797 write!(w, "#[no_mangle]\npub extern \"C\" fn {}_new(", mangled_container).unwrap();
1798 for (idx, gen) in args.iter().enumerate() {
1799 write!(w, "{}{}: ", if idx != 0 { ", " } else { "" }, ('a' as u8 + idx as u8) as char).unwrap();
1800 if !self.write_c_type_intern(w, gen, None, false, false, false) { return false; }
1802 writeln!(w, ") -> {} {{", mangled_container).unwrap();
1803 write!(w, "\t{} {{ ", mangled_container).unwrap();
1804 for idx in 0..args.len() {
1805 write!(w, "{}, ", ('a' as u8 + idx as u8) as char).unwrap();
1807 writeln!(w, "}}\n}}\n").unwrap();
1809 writeln!(w, "").unwrap();
1814 fn write_template_generics<'b, W: std::io::Write>(&self, w: &mut W, args: &mut dyn Iterator<Item=&'b syn::Type>, generics: Option<&GenericTypes>, is_ref: bool, in_crate: bool) {
1815 for (idx, t) in args.enumerate() {
1817 write!(w, ", ").unwrap();
1819 if let syn::Type::Tuple(tup) = t {
1820 if tup.elems.is_empty() {
1821 write!(w, "u8").unwrap();
1823 write!(w, "{}::C{}TupleTempl<", Self::container_templ_path(), tup.elems.len()).unwrap();
1824 self.write_template_generics(w, &mut tup.elems.iter(), generics, is_ref, in_crate);
1825 write!(w, ">").unwrap();
1827 } else if let syn::Type::Path(p_arg) = t {
1828 let resolved_generic = self.resolve_path(&p_arg.path, generics);
1829 if self.is_primitive(&resolved_generic) {
1830 write!(w, "{}", resolved_generic).unwrap();
1831 } else if let Some(c_type) = self.c_type_from_path(&resolved_generic, is_ref, false) {
1832 if self.is_known_container(&resolved_generic, is_ref) {
1833 write!(w, "{}::C{}Templ<", Self::container_templ_path(), single_ident_generic_path_to_ident(&p_arg.path).unwrap()).unwrap();
1834 assert_eq!(p_arg.path.segments.len(), 1);
1835 if let syn::PathArguments::AngleBracketed(args) = &p_arg.path.segments.iter().next().unwrap().arguments {
1836 self.write_template_generics(w, &mut args.args.iter().map(|gen|
1837 if let syn::GenericArgument::Type(t) = gen { t } else { unimplemented!() }),
1838 generics, is_ref, in_crate);
1839 } else { unimplemented!(); }
1840 write!(w, ">").unwrap();
1841 } else if resolved_generic == "Option" {
1842 if let syn::PathArguments::AngleBracketed(args) = &p_arg.path.segments.iter().next().unwrap().arguments {
1843 self.write_template_generics(w, &mut args.args.iter().map(|gen|
1844 if let syn::GenericArgument::Type(t) = gen { t } else { unimplemented!() }),
1845 generics, is_ref, in_crate);
1846 } else { unimplemented!(); }
1847 } else if in_crate {
1848 write!(w, "{}", c_type).unwrap();
1850 self.write_rust_type(w, generics, &t);
1853 // If we just write out resolved_generic, it may mostly work, however for
1854 // original types which are generic, we need the template args. We could
1855 // figure them out and write them out, too, but its much easier to just
1856 // reference the native{} type alias which exists at least for opaque types.
1858 write!(w, "crate::{}", resolved_generic).unwrap();
1860 let path_name: Vec<&str> = resolved_generic.rsplitn(2, "::").collect();
1861 if path_name.len() > 1 {
1862 write!(w, "crate::{}::native{}", path_name[1], path_name[0]).unwrap();
1864 write!(w, "crate::native{}", path_name[0]).unwrap();
1868 } else if let syn::Type::Reference(r_arg) = t {
1869 if let syn::Type::Path(p_arg) = &*r_arg.elem {
1870 let resolved = self.resolve_path(&p_arg.path, generics);
1871 if self.crate_types.opaques.get(&resolved).is_some() {
1872 write!(w, "crate::{}", resolved).unwrap();
1874 let cty = self.c_type_from_path(&resolved, true, true).expect("Template generics should be opaque or have a predefined mapping");
1875 w.write(cty.as_bytes()).unwrap();
1877 } else { unimplemented!(); }
1878 } else if let syn::Type::Array(a_arg) = t {
1879 if let syn::Type::Path(p_arg) = &*a_arg.elem {
1880 let resolved = self.resolve_path(&p_arg.path, generics);
1881 assert!(self.is_primitive(&resolved));
1882 if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(len), .. }) = &a_arg.len {
1884 self.c_type_from_path(&format!("[{}; {}]", resolved, len.base10_digits()), is_ref, false).unwrap()).unwrap();
1890 fn check_create_container(&mut self, mangled_container: String, container_type: &str, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
1891 if !self.crate_types.templates_defined.get(&mangled_container).is_some() {
1892 let mut created_container: Vec<u8> = Vec::new();
1894 write!(&mut created_container, "pub type {} = ", mangled_container).unwrap();
1895 write!(&mut created_container, "{}::C{}Templ<", Self::container_templ_path(), container_type).unwrap();
1896 self.write_template_generics(&mut created_container, &mut args.iter().map(|t| *t), generics, is_ref, true);
1897 writeln!(&mut created_container, ">;").unwrap();
1899 write!(&mut created_container, "#[no_mangle]\npub static {}_free: extern \"C\" fn({}) = ", mangled_container, mangled_container).unwrap();
1900 write!(&mut created_container, "{}::C{}Templ_free::<", Self::container_templ_path(), container_type).unwrap();
1901 self.write_template_generics(&mut created_container, &mut args.iter().map(|t| *t), generics, is_ref, true);
1902 writeln!(&mut created_container, ">;").unwrap();
1904 if !self.write_template_constructor(&mut created_container, container_type, &mangled_container, &args, generics, is_ref) {
1907 self.crate_types.templates_defined.insert(mangled_container.clone(), true);
1909 self.crate_types.template_file.write(&created_container).unwrap();
1913 fn path_to_generic_args(path: &syn::Path) -> Vec<&syn::Type> {
1914 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().next().unwrap().arguments {
1915 args.args.iter().map(|gen| if let syn::GenericArgument::Type(t) = gen { t } else { unimplemented!() }).collect()
1916 } else { unimplemented!(); }
1918 fn write_c_mangled_container_path_intern<W: std::io::Write>
1919 (&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 {
1920 let mut mangled_type: Vec<u8> = Vec::new();
1921 if !self.is_transparent_container(ident, is_ref) {
1922 write!(w, "C{}_", ident).unwrap();
1923 write!(mangled_type, "C{}_", ident).unwrap();
1924 } else { assert_eq!(args.len(), 1); }
1925 for arg in args.iter() {
1926 macro_rules! write_path {
1927 ($p_arg: expr, $extra_write: expr) => {
1928 if let Some(subtype) = self.maybe_resolve_path(&$p_arg.path, generics) {
1929 if self.is_transparent_container(ident, is_ref) {
1930 // We dont (yet) support primitives or containers inside transparent
1931 // containers, so check for that first:
1932 if self.is_primitive(&subtype) { return false; }
1933 if self.is_known_container(&subtype, is_ref) { return false; }
1935 if self.c_type_has_inner_from_path(&subtype) {
1936 if !self.write_c_path_intern(w, &$p_arg.path, generics, is_ref, is_mut, ptr_for_ref) { return false; }
1938 // Option<T> needs to be converted to a *mut T, ie mut ptr-for-ref
1939 if !self.write_c_path_intern(w, &$p_arg.path, generics, true, true, true) { return false; }
1942 if $p_arg.path.segments.len() == 1 {
1943 write!(w, "{}", $p_arg.path.segments.iter().next().unwrap().ident).unwrap();
1948 } else if self.is_known_container(&subtype, is_ref) || self.is_transparent_container(&subtype, is_ref) {
1949 if !self.write_c_mangled_container_path_intern(w, Self::path_to_generic_args(&$p_arg.path), generics,
1950 &subtype, is_ref, is_mut, ptr_for_ref, true) {
1953 self.write_c_mangled_container_path_intern(&mut mangled_type, Self::path_to_generic_args(&$p_arg.path),
1954 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
1955 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
1956 self.write_c_mangled_container_path_intern(w2, Self::path_to_generic_args(&$p_arg.path),
1957 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
1960 let id = &&$p_arg.path.segments.iter().rev().next().unwrap().ident;
1961 write!(w, "{}", id).unwrap();
1962 write!(mangled_type, "{}", id).unwrap();
1963 if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
1964 write!(w2, "{}", id).unwrap();
1967 } else { return false; }
1970 if let syn::Type::Tuple(tuple) = arg {
1971 if tuple.elems.len() == 0 {
1972 write!(w, "None").unwrap();
1973 write!(mangled_type, "None").unwrap();
1975 let mut mangled_tuple_type: Vec<u8> = Vec::new();
1977 // Figure out what the mangled type should look like. To disambiguate
1978 // ((A, B), C) and (A, B, C) we prefix the generic args with a _ and suffix
1979 // them with a Z. Ideally we wouldn't use Z, but not many special chars are
1980 // available for use in type names.
1981 write!(w, "C{}Tuple_", tuple.elems.len()).unwrap();
1982 write!(mangled_type, "C{}Tuple_", tuple.elems.len()).unwrap();
1983 write!(mangled_tuple_type, "C{}Tuple_", tuple.elems.len()).unwrap();
1984 for elem in tuple.elems.iter() {
1985 if let syn::Type::Path(p) = elem {
1986 write_path!(p, Some(&mut mangled_tuple_type));
1987 } else if let syn::Type::Reference(refelem) = elem {
1988 if let syn::Type::Path(p) = &*refelem.elem {
1989 write_path!(p, Some(&mut mangled_tuple_type));
1990 } else { return false; }
1991 } else { return false; }
1993 write!(w, "Z").unwrap();
1994 write!(mangled_type, "Z").unwrap();
1995 write!(mangled_tuple_type, "Z").unwrap();
1996 if !self.check_create_container(String::from_utf8(mangled_tuple_type).unwrap(),
1997 &format!("{}Tuple", tuple.elems.len()), tuple.elems.iter().collect(), generics, is_ref) {
2001 } else if let syn::Type::Path(p_arg) = arg {
2002 write_path!(p_arg, None);
2003 } else if let syn::Type::Reference(refty) = arg {
2004 if args.len() != 1 { return false; }
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 write!(w, "*mut ").unwrap();
2013 self.write_c_type(w, arg, None, true);
2014 } else { return false; }
2015 } else if let syn::Type::Array(a) = arg {
2016 if let syn::Type::Path(p_arg) = &*a.elem {
2017 let resolved = self.resolve_path(&p_arg.path, generics);
2018 if !self.is_primitive(&resolved) { return false; }
2019 if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(len), .. }) = &a.len {
2020 if self.c_type_from_path(&format!("[{}; {}]", resolved, len.base10_digits()), is_ref, ptr_for_ref).is_none() { return false; }
2021 write!(w, "_{}{}", resolved, len.base10_digits()).unwrap();
2022 write!(mangled_type, "_{}{}", resolved, len.base10_digits()).unwrap();
2023 } else { return false; }
2024 } else { return false; }
2025 } else { return false; }
2027 if self.is_transparent_container(ident, is_ref) { return true; }
2028 // Push the "end of type" Z
2029 write!(w, "Z").unwrap();
2030 write!(mangled_type, "Z").unwrap();
2032 // Make sure the type is actually defined:
2033 self.check_create_container(String::from_utf8(mangled_type).unwrap(), ident, args, generics, is_ref)
2035 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 {
2036 if !self.is_transparent_container(ident, is_ref) {
2037 write!(w, "{}::", Self::generated_container_path()).unwrap();
2039 self.write_c_mangled_container_path_intern(w, args, generics, ident, is_ref, is_mut, ptr_for_ref, false)
2042 // **********************************
2043 // *** C Type Equivalent Printing ***
2044 // **********************************
2046 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 {
2047 let full_path = match self.maybe_resolve_path(&path, generics) {
2048 Some(path) => path, None => return false };
2049 if let Some(c_type) = self.c_type_from_path(&full_path, is_ref, ptr_for_ref) {
2050 write!(w, "{}", c_type).unwrap();
2052 } else if self.crate_types.traits.get(&full_path).is_some() {
2053 if is_ref && ptr_for_ref {
2054 write!(w, "*{} crate::{}", if is_mut { "mut" } else { "const" }, full_path).unwrap();
2056 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2058 write!(w, "crate::{}", full_path).unwrap();
2061 } else if self.crate_types.opaques.get(&full_path).is_some() || self.crate_types.mirrored_enums.get(&full_path).is_some() {
2062 if is_ref && ptr_for_ref {
2063 // ptr_for_ref implies we're returning the object, which we can't really do for
2064 // opaque or mirrored types without box'ing them, which is quite a waste, so return
2065 // the actual object itself (for opaque types we'll set the pointer to the actual
2066 // type and note that its a reference).
2067 write!(w, "crate::{}", full_path).unwrap();
2069 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2071 write!(w, "crate::{}", full_path).unwrap();
2078 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 {
2080 syn::Type::Path(p) => {
2081 if p.qself.is_some() {
2084 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
2085 if self.is_known_container(&full_path, is_ref) || self.is_transparent_container(&full_path, is_ref) {
2086 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);
2088 if let Some(aliased_type) = self.crate_types.type_aliases.get(&full_path).cloned() {
2089 return self.write_c_type_intern(w, &aliased_type, None, is_ref, is_mut, ptr_for_ref);
2092 self.write_c_path_intern(w, &p.path, generics, is_ref, is_mut, ptr_for_ref)
2094 syn::Type::Reference(r) => {
2095 self.write_c_type_intern(w, &*r.elem, generics, true, r.mutability.is_some(), ptr_for_ref)
2097 syn::Type::Array(a) => {
2098 if is_ref && is_mut {
2099 write!(w, "*mut [").unwrap();
2100 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2102 write!(w, "*const [").unwrap();
2103 if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2105 let mut typecheck = Vec::new();
2106 if !self.write_c_type_intern(&mut typecheck, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2107 if typecheck[..] != ['u' as u8, '8' as u8] { return false; }
2109 if let syn::Expr::Lit(l) = &a.len {
2110 if let syn::Lit::Int(i) = &l.lit {
2112 if let Some(ty) = self.c_type_from_path(&format!("[u8; {}]", i.base10_digits()), false, ptr_for_ref) {
2113 write!(w, "{}", ty).unwrap();
2117 write!(w, "; {}]", i).unwrap();
2123 syn::Type::Slice(s) => {
2124 if !is_ref || is_mut { return false; }
2125 if let syn::Type::Path(p) = &*s.elem {
2126 let resolved = self.resolve_path(&p.path, generics);
2127 if self.is_primitive(&resolved) {
2128 write!(w, "{}::{}slice", Self::container_templ_path(), resolved).unwrap();
2131 } else if let syn::Type::Reference(r) = &*s.elem {
2132 if let syn::Type::Path(p) = &*r.elem {
2133 // Slices with "real types" inside are mapped as the equivalent non-ref Vec
2134 let resolved = self.resolve_path(&p.path, generics);
2135 let mangled_container = if let Some(ident) = self.crate_types.opaques.get(&resolved) {
2136 format!("CVec_{}Z", ident)
2137 } else if let Some(en) = self.crate_types.mirrored_enums.get(&resolved) {
2138 format!("CVec_{}Z", en.ident)
2139 } else if let Some(id) = p.path.get_ident() {
2140 format!("CVec_{}Z", id)
2141 } else { return false; };
2142 write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
2143 self.check_create_container(mangled_container, "Vec", vec![&*r.elem], generics, false)
2145 } else if let syn::Type::Tuple(_) = &*s.elem {
2146 let mut args = syn::punctuated::Punctuated::new();
2147 args.push(syn::GenericArgument::Type((*s.elem).clone()));
2148 let mut segments = syn::punctuated::Punctuated::new();
2149 segments.push(syn::PathSegment {
2150 ident: syn::Ident::new("Vec", Span::call_site()),
2151 arguments: syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
2152 colon2_token: None, lt_token: syn::Token![<](Span::call_site()), args, gt_token: syn::Token![>](Span::call_site()),
2155 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)
2158 syn::Type::Tuple(t) => {
2159 if t.elems.len() == 0 {
2162 self.write_c_mangled_container_path(w, t.elems.iter().collect(), generics,
2163 &format!("{}Tuple", t.elems.len()), is_ref, is_mut, ptr_for_ref)
2169 pub fn write_c_type<W: std::io::Write>(&mut self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) {
2170 assert!(self.write_c_type_intern(w, t, generics, false, false, ptr_for_ref));
2172 pub fn understood_c_path(&mut self, p: &syn::Path) -> bool {
2173 if p.leading_colon.is_some() { return false; }
2174 self.write_c_path_intern(&mut std::io::sink(), p, None, false, false, false)
2176 pub fn understood_c_type(&mut self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
2177 self.write_c_type_intern(&mut std::io::sink(), t, generics, false, false, false)