afe719ffe2ca11709f50f6942dbf629fc9920084
[rust-lightning] / c-bindings-gen / src / types.rs
1 use std::collections::{HashMap, HashSet};
2 use std::fs::File;
3 use std::io::Write;
4 use std::hash;
5
6 use crate::blocks::*;
7
8 use proc_macro2::{TokenTree, Span};
9
10 // The following utils are used purely to build our known types maps - they break down all the
11 // types we need to resolve to include the given object, and no more.
12
13 pub fn first_seg_self<'a>(t: &'a syn::Type) -> Option<impl Iterator<Item=&syn::PathSegment> + 'a> {
14         match t {
15                 syn::Type::Path(p) => {
16                         if p.qself.is_some() || p.path.leading_colon.is_some() {
17                                 return None;
18                         }
19                         let mut segs = p.path.segments.iter();
20                         let ty = segs.next().unwrap();
21                         if !ty.arguments.is_empty() { return None; }
22                         if format!("{}", ty.ident) == "Self" {
23                                 Some(segs)
24                         } else { None }
25                 },
26                 _ => None,
27         }
28 }
29
30 pub fn get_single_remaining_path_seg<'a, I: Iterator<Item=&'a syn::PathSegment>>(segs: &mut I) -> Option<&'a syn::Ident> {
31         if let Some(ty) = segs.next() {
32                 if !ty.arguments.is_empty() { unimplemented!(); }
33                 if segs.next().is_some() { return None; }
34                 Some(&ty.ident)
35         } else { None }
36 }
37
38 pub fn single_ident_generic_path_to_ident(p: &syn::Path) -> Option<&syn::Ident> {
39         if p.segments.len() == 1 {
40                 Some(&p.segments.iter().next().unwrap().ident)
41         } else { None }
42 }
43
44 pub fn path_matches_nongeneric(p: &syn::Path, exp: &[&str]) -> bool {
45         if p.segments.len() != exp.len() { return false; }
46         for (seg, e) in p.segments.iter().zip(exp.iter()) {
47                 if seg.arguments != syn::PathArguments::None { return false; }
48                 if &format!("{}", seg.ident) != *e { return false; }
49         }
50         true
51 }
52
53 #[derive(Debug, PartialEq)]
54 pub enum ExportStatus {
55         Export,
56         NoExport,
57         TestOnly,
58 }
59 /// Gets the ExportStatus of an object (struct, fn, etc) given its attributes.
60 pub fn export_status(attrs: &[syn::Attribute]) -> ExportStatus {
61         for attr in attrs.iter() {
62                 let tokens_clone = attr.tokens.clone();
63                 let mut token_iter = tokens_clone.into_iter();
64                 if let Some(token) = token_iter.next() {
65                         match token {
66                                 TokenTree::Punct(c) if c.as_char() == '=' => {
67                                         // Really not sure where syn gets '=' from here -
68                                         // it somehow represents '///' or '//!'
69                                 },
70                                 TokenTree::Group(g) => {
71                                         if format!("{}", single_ident_generic_path_to_ident(&attr.path).unwrap()) == "cfg" {
72                                                 let mut iter = g.stream().into_iter();
73                                                 if let TokenTree::Ident(i) = iter.next().unwrap() {
74                                                         if i == "any" {
75                                                                 // #[cfg(any(test, feature = ""))]
76                                                                 if let TokenTree::Group(g) = iter.next().unwrap() {
77                                                                         if let TokenTree::Ident(i) = g.stream().into_iter().next().unwrap() {
78                                                                                 if i == "test" || i == "feature" {
79                                                                                         // If its cfg(feature(...)) we assume its test-only
80                                                                                         return ExportStatus::TestOnly;
81                                                                                 }
82                                                                         }
83                                                                 }
84                                                         } else if i == "test" || i == "feature" {
85                                                                 // If its cfg(feature(...)) we assume its test-only
86                                                                 return ExportStatus::TestOnly;
87                                                         }
88                                                 }
89                                         }
90                                         continue; // eg #[derive()]
91                                 },
92                                 _ => unimplemented!(),
93                         }
94                 } else { continue; }
95                 match token_iter.next().unwrap() {
96                         TokenTree::Literal(lit) => {
97                                 let line = format!("{}", lit);
98                                 if line.contains("(C-not exported)") {
99                                         return ExportStatus::NoExport;
100                                 }
101                         },
102                         _ => unimplemented!(),
103                 }
104         }
105         ExportStatus::Export
106 }
107
108 pub fn assert_simple_bound(bound: &syn::TraitBound) {
109         if bound.paren_token.is_some() || bound.lifetimes.is_some() { unimplemented!(); }
110         if let syn::TraitBoundModifier::Maybe(_) = bound.modifier { unimplemented!(); }
111 }
112
113 /// Returns true if the enum will be mapped as an opaue (ie struct with a pointer to the underlying
114 /// type), otherwise it is mapped into a transparent, C-compatible version of itself.
115 pub fn is_enum_opaque(e: &syn::ItemEnum) -> bool {
116         for var in e.variants.iter() {
117                 if let syn::Fields::Unit = var.fields {
118                 } else if let syn::Fields::Named(fields) = &var.fields {
119                         for field in fields.named.iter() {
120                                 match export_status(&field.attrs) {
121                                         ExportStatus::Export|ExportStatus::TestOnly => {},
122                                         ExportStatus::NoExport => return true,
123                                 }
124                         }
125                 } else {
126                         return true;
127                 }
128         }
129         false
130 }
131
132 /// A stack of sets of generic resolutions.
133 ///
134 /// This tracks the template parameters for a function, struct, or trait, allowing resolution into
135 /// a concrete type. By pushing a new context onto the stack, this can track a function's template
136 /// parameters inside of a generic struct or trait.
137 ///
138 /// It maps both direct types as well as Deref<Target = X>, mapping them via the provided
139 /// TypeResolver's resolve_path function (ie traits map to the concrete jump table, structs to the
140 /// concrete C container struct, etc).
141 pub struct GenericTypes<'a> {
142         typed_generics: Vec<HashMap<&'a syn::Ident, (String, Option<&'a syn::Path>)>>,
143 }
144 impl<'a> GenericTypes<'a> {
145         pub fn new() -> Self {
146                 Self { typed_generics: vec![HashMap::new()], }
147         }
148
149         /// push a new context onto the stack, allowing for a new set of generics to be learned which
150         /// will override any lower contexts, but which will still fall back to resoltion via lower
151         /// contexts.
152         pub fn push_ctx(&mut self) {
153                 self.typed_generics.push(HashMap::new());
154         }
155         /// pop the latest context off the stack.
156         pub fn pop_ctx(&mut self) {
157                 self.typed_generics.pop();
158         }
159
160         /// Learn the generics in generics in the current context, given a TypeResolver.
161         pub fn learn_generics<'b, 'c>(&mut self, generics: &'a syn::Generics, types: &'b TypeResolver<'a, 'c>) -> bool {
162                 // First learn simple generics...
163                 for generic in generics.params.iter() {
164                         match generic {
165                                 syn::GenericParam::Type(type_param) => {
166                                         let mut non_lifetimes_processed = false;
167                                         for bound in type_param.bounds.iter() {
168                                                 if let syn::TypeParamBound::Trait(trait_bound) = bound {
169                                                         if let Some(ident) = single_ident_generic_path_to_ident(&trait_bound.path) {
170                                                                 match &format!("{}", ident) as &str { "Send" => continue, "Sync" => continue, _ => {} }
171                                                         }
172                                                         if path_matches_nongeneric(&trait_bound.path, &["core", "clone", "Clone"]) { continue; }
173
174                                                         assert_simple_bound(&trait_bound);
175                                                         if let Some(mut path) = types.maybe_resolve_path(&trait_bound.path, None) {
176                                                                 if types.skip_path(&path) { continue; }
177                                                                 if non_lifetimes_processed { return false; }
178                                                                 non_lifetimes_processed = true;
179                                                                 let new_ident = if path != "std::ops::Deref" {
180                                                                         path = "crate::".to_string() + &path;
181                                                                         Some(&trait_bound.path)
182                                                                 } else { None };
183                                                                 self.typed_generics.last_mut().unwrap().insert(&type_param.ident, (path, new_ident));
184                                                         } else { return false; }
185                                                 }
186                                         }
187                                 },
188                                 _ => {},
189                         }
190                 }
191                 // Then find generics where we are required to pass a Deref<Target=X> and pretend its just X.
192                 if let Some(wh) = &generics.where_clause {
193                         for pred in wh.predicates.iter() {
194                                 if let syn::WherePredicate::Type(t) = pred {
195                                         if let syn::Type::Path(p) = &t.bounded_ty {
196                                                 if p.qself.is_some() { return false; }
197                                                 if p.path.leading_colon.is_some() { return false; }
198                                                 let mut p_iter = p.path.segments.iter();
199                                                 if let Some(gen) = self.typed_generics.last_mut().unwrap().get_mut(&p_iter.next().unwrap().ident) {
200                                                         if gen.0 != "std::ops::Deref" { return false; }
201                                                         if &format!("{}", p_iter.next().unwrap().ident) != "Target" { return false; }
202
203                                                         let mut non_lifetimes_processed = false;
204                                                         for bound in t.bounds.iter() {
205                                                                 if let syn::TypeParamBound::Trait(trait_bound) = bound {
206                                                                         if non_lifetimes_processed { return false; }
207                                                                         non_lifetimes_processed = true;
208                                                                         assert_simple_bound(&trait_bound);
209                                                                         *gen = ("crate::".to_string() + &types.resolve_path(&trait_bound.path, None),
210                                                                                 Some(&trait_bound.path));
211                                                                 }
212                                                         }
213                                                 } else { return false; }
214                                         } else { return false; }
215                                 }
216                         }
217                 }
218                 for (_, (_, ident)) in self.typed_generics.last().unwrap().iter() {
219                         if ident.is_none() { return false; }
220                 }
221                 true
222         }
223
224         /// Learn the associated types from the trait in the current context.
225         pub fn learn_associated_types<'b, 'c>(&mut self, t: &'a syn::ItemTrait, types: &'b TypeResolver<'a, 'c>) {
226                 for item in t.items.iter() {
227                         match item {
228                                 &syn::TraitItem::Type(ref t) => {
229                                         if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
230                                         let mut bounds_iter = t.bounds.iter();
231                                         match bounds_iter.next().unwrap() {
232                                                 syn::TypeParamBound::Trait(tr) => {
233                                                         assert_simple_bound(&tr);
234                                                         if let Some(mut path) = types.maybe_resolve_path(&tr.path, None) {
235                                                                 if types.skip_path(&path) { continue; }
236                                                                 // In general we handle Deref<Target=X> as if it were just X (and
237                                                                 // implement Deref<Target=Self> for relevant types). We don't
238                                                                 // bother to implement it for associated types, however, so we just
239                                                                 // ignore such bounds.
240                                                                 let new_ident = if path != "std::ops::Deref" {
241                                                                         path = "crate::".to_string() + &path;
242                                                                         Some(&tr.path)
243                                                                 } else { None };
244                                                                 self.typed_generics.last_mut().unwrap().insert(&t.ident, (path, new_ident));
245                                                         } else { unimplemented!(); }
246                                                 },
247                                                 _ => unimplemented!(),
248                                         }
249                                         if bounds_iter.next().is_some() { unimplemented!(); }
250                                 },
251                                 _ => {},
252                         }
253                 }
254         }
255
256         /// Attempt to resolve an Ident as a generic parameter and return the full path.
257         pub fn maybe_resolve_ident<'b>(&'b self, ident: &syn::Ident) -> Option<&'b String> {
258                 for gen in self.typed_generics.iter().rev() {
259                         if let Some(res) = gen.get(ident).map(|(a, _)| a) {
260                                 return Some(res);
261                         }
262                 }
263                 None
264         }
265         /// Attempt to resolve a Path as a generic parameter and return the full path. as both a string
266         /// and syn::Path.
267         pub fn maybe_resolve_path<'b>(&'b self, path: &syn::Path) -> Option<(&'b String, &'a syn::Path)> {
268                 if let Some(ident) = path.get_ident() {
269                         for gen in self.typed_generics.iter().rev() {
270                                 if let Some(res) = gen.get(ident).map(|(a, b)| (a, b.unwrap())) {
271                                         return Some(res);
272                                 }
273                         }
274                 } else {
275                         // Associated types are usually specified as "Self::Generic", so we check for that
276                         // explicitly here.
277                         let mut it = path.segments.iter();
278                         if path.segments.len() == 2 && format!("{}", it.next().unwrap().ident) == "Self" {
279                                 let ident = &it.next().unwrap().ident;
280                                 for gen in self.typed_generics.iter().rev() {
281                                         if let Some(res) = gen.get(ident).map(|(a, b)| (a, b.unwrap())) {
282                                                 return Some(res);
283                                         }
284                                 }
285                         }
286                 }
287                 None
288         }
289 }
290
291 #[derive(Clone, PartialEq)]
292 // The type of declaration and the object itself
293 pub enum DeclType<'a> {
294         MirroredEnum,
295         Trait(&'a syn::ItemTrait),
296         StructImported,
297         StructIgnored,
298         EnumIgnored,
299 }
300
301 pub struct ImportResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
302         module_path: &'mod_lifetime str,
303         imports: HashMap<syn::Ident, (String, syn::Path)>,
304         declared: HashMap<syn::Ident, DeclType<'crate_lft>>,
305         priv_modules: HashSet<syn::Ident>,
306 }
307 impl<'mod_lifetime, 'crate_lft: 'mod_lifetime> ImportResolver<'mod_lifetime, 'crate_lft> {
308         fn process_use_intern(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::UseTree, partial_path: &str, mut path: syn::punctuated::Punctuated<syn::PathSegment, syn::token::Colon2>) {
309                 match u {
310                         syn::UseTree::Path(p) => {
311                                 let new_path = format!("{}{}::", partial_path, p.ident);
312                                 path.push(syn::PathSegment { ident: p.ident.clone(), arguments: syn::PathArguments::None });
313                                 Self::process_use_intern(imports, &p.tree, &new_path, path);
314                         },
315                         syn::UseTree::Name(n) => {
316                                 let full_path = format!("{}{}", partial_path, n.ident);
317                                 path.push(syn::PathSegment { ident: n.ident.clone(), arguments: syn::PathArguments::None });
318                                 imports.insert(n.ident.clone(), (full_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
319                         },
320                         syn::UseTree::Group(g) => {
321                                 for i in g.items.iter() {
322                                         Self::process_use_intern(imports, i, partial_path, path.clone());
323                                 }
324                         },
325                         syn::UseTree::Rename(r) => {
326                                 let full_path = format!("{}{}", partial_path, r.ident);
327                                 path.push(syn::PathSegment { ident: r.ident.clone(), arguments: syn::PathArguments::None });
328                                 imports.insert(r.rename.clone(), (full_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
329                         },
330                         syn::UseTree::Glob(_) => {
331                                 eprintln!("Ignoring * use for {} - this may result in resolution failures", partial_path);
332                         },
333                 }
334         }
335
336         fn process_use(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::ItemUse) {
337                 if let syn::Visibility::Public(_) = u.vis {
338                         // We actually only use these for #[cfg(fuzztarget)]
339                         eprintln!("Ignoring pub(use) tree!");
340                         return;
341                 }
342                 if u.leading_colon.is_some() { eprintln!("Ignoring leading-colon use!"); return; }
343                 Self::process_use_intern(imports, &u.tree, "", syn::punctuated::Punctuated::new());
344         }
345
346         fn insert_primitive(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, id: &str) {
347                 let ident = syn::Ident::new(id, Span::call_site());
348                 let mut path = syn::punctuated::Punctuated::new();
349                 path.push(syn::PathSegment { ident: ident.clone(), arguments: syn::PathArguments::None });
350                 imports.insert(ident, (id.to_owned(), syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
351         }
352
353         pub fn new(module_path: &'mod_lifetime str, contents: &'crate_lft [syn::Item]) -> Self {
354                 let mut imports = HashMap::new();
355                 // Add primitives to the "imports" list:
356                 Self::insert_primitive(&mut imports, "bool");
357                 Self::insert_primitive(&mut imports, "u64");
358                 Self::insert_primitive(&mut imports, "u32");
359                 Self::insert_primitive(&mut imports, "u16");
360                 Self::insert_primitive(&mut imports, "u8");
361                 Self::insert_primitive(&mut imports, "usize");
362                 Self::insert_primitive(&mut imports, "str");
363                 Self::insert_primitive(&mut imports, "String");
364
365                 // These are here to allow us to print native Rust types in trait fn impls even if we don't
366                 // have C mappings:
367                 Self::insert_primitive(&mut imports, "Result");
368                 Self::insert_primitive(&mut imports, "Vec");
369                 Self::insert_primitive(&mut imports, "Option");
370
371                 let mut declared = HashMap::new();
372                 let mut priv_modules = HashSet::new();
373
374                 for item in contents.iter() {
375                         match item {
376                                 syn::Item::Use(u) => Self::process_use(&mut imports, &u),
377                                 syn::Item::Struct(s) => {
378                                         if let syn::Visibility::Public(_) = s.vis {
379                                                 match export_status(&s.attrs) {
380                                                         ExportStatus::Export => { declared.insert(s.ident.clone(), DeclType::StructImported); },
381                                                         ExportStatus::NoExport => { declared.insert(s.ident.clone(), DeclType::StructIgnored); },
382                                                         ExportStatus::TestOnly => continue,
383                                                 }
384                                         }
385                                 },
386                                 syn::Item::Enum(e) => {
387                                         if let syn::Visibility::Public(_) = e.vis {
388                                                 match export_status(&e.attrs) {
389                                                         ExportStatus::Export if is_enum_opaque(e) => { declared.insert(e.ident.clone(), DeclType::EnumIgnored); },
390                                                         ExportStatus::Export => { declared.insert(e.ident.clone(), DeclType::MirroredEnum); },
391                                                         _ => continue,
392                                                 }
393                                         }
394                                 },
395                                 syn::Item::Trait(t) if export_status(&t.attrs) == ExportStatus::Export => {
396                                         if let syn::Visibility::Public(_) = t.vis {
397                                                 declared.insert(t.ident.clone(), DeclType::Trait(t));
398                                         }
399                                 },
400                                 syn::Item::Mod(m) => {
401                                         priv_modules.insert(m.ident.clone());
402                                 },
403                                 _ => {},
404                         }
405                 }
406
407                 Self { module_path, imports, declared, priv_modules }
408         }
409
410         pub fn get_declared_type(&self, ident: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
411                 self.declared.get(ident)
412         }
413
414         pub fn maybe_resolve_declared(&self, id: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
415                 self.declared.get(id)
416         }
417
418         pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
419                 if let Some((imp, _)) = self.imports.get(id) {
420                         Some(imp.clone())
421                 } else if self.declared.get(id).is_some() {
422                         Some(self.module_path.to_string() + "::" + &format!("{}", id))
423                 } else { None }
424         }
425
426         pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
427                 if let Some((imp, _)) = self.imports.get(id) {
428                         Some(imp.clone())
429                 } else if let Some(decl_type) = self.declared.get(id) {
430                         match decl_type {
431                                 DeclType::StructIgnored => None,
432                                 _ => Some(self.module_path.to_string() + "::" + &format!("{}", id)),
433                         }
434                 } else { None }
435         }
436
437         pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
438                 let p = if let Some(gen_types) = generics {
439                         if let Some((_, synpath)) = gen_types.maybe_resolve_path(p_arg) {
440                                 synpath
441                         } else { p_arg }
442                 } else { p_arg };
443
444                 if p.leading_colon.is_some() {
445                         Some(p.segments.iter().enumerate().map(|(idx, seg)| {
446                                 format!("{}{}", if idx == 0 { "" } else { "::" }, seg.ident)
447                         }).collect())
448                 } else if let Some(id) = p.get_ident() {
449                         self.maybe_resolve_ident(id)
450                 } else {
451                         if p.segments.len() == 1 {
452                                 let seg = p.segments.iter().next().unwrap();
453                                 return self.maybe_resolve_ident(&seg.ident);
454                         }
455                         let mut seg_iter = p.segments.iter();
456                         let first_seg = seg_iter.next().unwrap();
457                         let remaining: String = seg_iter.map(|seg| {
458                                 format!("::{}", seg.ident)
459                         }).collect();
460                         if let Some((imp, _)) = self.imports.get(&first_seg.ident) {
461                                 if remaining != "" {
462                                         Some(imp.clone() + &remaining)
463                                 } else {
464                                         Some(imp.clone())
465                                 }
466                         } else if let Some(_) = self.priv_modules.get(&first_seg.ident) {
467                                 Some(format!("{}::{}{}", self.module_path, first_seg.ident, remaining))
468                         } else { None }
469                 }
470         }
471
472         /// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern)
473         pub fn resolve_imported_refs(&self, mut ty: syn::Type) -> syn::Type {
474                 match &mut ty {
475                         syn::Type::Path(p) => {
476                                 if let Some(ident) = p.path.get_ident() {
477                                         if let Some((_, newpath)) = self.imports.get(ident) {
478                                                 p.path = newpath.clone();
479                                         }
480                                 } else { unimplemented!(); }
481                         },
482                         syn::Type::Reference(r) => {
483                                 r.elem = Box::new(self.resolve_imported_refs((*r.elem).clone()));
484                         },
485                         syn::Type::Slice(s) => {
486                                 s.elem = Box::new(self.resolve_imported_refs((*s.elem).clone()));
487                         },
488                         syn::Type::Tuple(t) => {
489                                 for e in t.elems.iter_mut() {
490                                         *e = self.resolve_imported_refs(e.clone());
491                                 }
492                         },
493                         _ => unimplemented!(),
494                 }
495                 ty
496         }
497 }
498
499 // templates_defined is walked to write the C++ header, so if we use the default hashing it get
500 // reordered on each genbindings run. Instead, we use SipHasher (which defaults to 0-keys) so that
501 // the sorting is stable across runs. It is deprecated, but the "replacement" doesn't actually
502 // accomplish the same goals, so we just ignore it.
503 #[allow(deprecated)]
504 pub type NonRandomHash = hash::BuildHasherDefault<hash::SipHasher>;
505
506 /// Top-level struct tracking everything which has been defined while walking the crate.
507 pub struct CrateTypes<'a> {
508         /// This may contain structs or enums, but only when either is mapped as
509         /// struct X { inner: *mut originalX, .. }
510         pub opaques: HashMap<String, &'a syn::Ident>,
511         /// Enums which are mapped as C enums with conversion functions
512         pub mirrored_enums: HashMap<String, &'a syn::ItemEnum>,
513         /// Traits which are mapped as a pointer + jump table
514         pub traits: HashMap<String, &'a syn::ItemTrait>,
515         /// Aliases from paths to some other Type
516         pub type_aliases: HashMap<String, syn::Type>,
517         /// Template continer types defined, map from mangled type name -> whether a destructor fn
518         /// exists.
519         ///
520         /// This is used at the end of processing to make C++ wrapper classes
521         pub templates_defined: HashMap<String, bool, NonRandomHash>,
522         /// The output file for any created template container types, written to as we find new
523         /// template containers which need to be defined.
524         pub template_file: &'a mut File,
525         /// Set of containers which are clonable
526         pub clonable_types: HashSet<String>,
527 }
528
529 /// A struct which tracks resolving rust types into C-mapped equivalents, exists for one specific
530 /// module but contains a reference to the overall CrateTypes tracking.
531 pub struct TypeResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
532         pub orig_crate: &'mod_lifetime str,
533         pub module_path: &'mod_lifetime str,
534         pub crate_types: &'mod_lifetime mut CrateTypes<'crate_lft>,
535         types: ImportResolver<'mod_lifetime, 'crate_lft>,
536 }
537
538 /// Returned by write_empty_rust_val_check_suffix to indicate what type of dereferencing needs to
539 /// happen to get the inner value of a generic.
540 enum EmptyValExpectedTy {
541         /// A type which has a flag for being empty (eg an array where we treat all-0s as empty).
542         NonPointer,
543         /// A pointer that we want to dereference and move out of.
544         OwnedPointer,
545         /// A pointer which we want to convert to a reference.
546         ReferenceAsPointer,
547 }
548
549 impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
550         pub fn new(orig_crate: &'a str, module_path: &'a str, types: ImportResolver<'a, 'c>, crate_types: &'a mut CrateTypes<'c>) -> Self {
551                 Self { orig_crate, module_path, types, crate_types }
552         }
553
554         // *************************************************
555         // *** Well know type and conversion definitions ***
556         // *************************************************
557
558         /// Returns true we if can just skip passing this to C entirely
559         fn skip_path(&self, full_path: &str) -> bool {
560                 full_path == "bitcoin::secp256k1::Secp256k1" ||
561                 full_path == "bitcoin::secp256k1::Signing" ||
562                 full_path == "bitcoin::secp256k1::Verification"
563         }
564         /// Returns true we if can just skip passing this to C entirely
565         fn no_arg_path_to_rust(&self, full_path: &str) -> &str {
566                 if full_path == "bitcoin::secp256k1::Secp256k1" {
567                         "&bitcoin::secp256k1::Secp256k1::new()"
568                 } else { unimplemented!(); }
569         }
570
571         /// Returns true if the object is a primitive and is mapped as-is with no conversion
572         /// whatsoever.
573         pub fn is_primitive(&self, full_path: &str) -> bool {
574                 match full_path {
575                         "bool" => true,
576                         "u64" => true,
577                         "u32" => true,
578                         "u16" => true,
579                         "u8" => true,
580                         "usize" => true,
581                         _ => false,
582                 }
583         }
584         pub fn is_clonable(&self, ty: &str) -> bool {
585                 if self.crate_types.clonable_types.contains(ty) { return true; }
586                 if self.is_primitive(ty) { return true; }
587                 match ty {
588                         "()" => true,
589                         "crate::c_types::Signature" => true,
590                         "crate::c_types::TxOut" => true,
591                         _ => false,
592                 }
593         }
594         /// Gets the C-mapped type for types which are outside of the crate, or which are manually
595         /// ignored by for some reason need mapping anyway.
596         fn c_type_from_path<'b>(&self, full_path: &'b str, is_ref: bool, ptr_for_ref: bool) -> Option<&'b str> {
597                 if self.is_primitive(full_path) {
598                         return Some(full_path);
599                 }
600                 match full_path {
601                         "Result" => Some("crate::c_types::derived::CResult"),
602                         "Vec" if !is_ref => Some("crate::c_types::derived::CVec"),
603                         "Option" => Some(""),
604
605                         // Note that no !is_ref types can map to an array because Rust and C's call semantics
606                         // for arrays are different (https://github.com/eqrion/cbindgen/issues/528)
607
608                         "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
609                         "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes"),
610                         "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes"),
611                         "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes"),
612                         "[u8; 3]" if !is_ref => Some("crate::c_types::ThreeBytes"), // Used for RGB values
613
614                         "str" if is_ref => Some("crate::c_types::Str"),
615                         "String" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
616                         "String" if is_ref => Some("crate::c_types::Str"),
617
618                         "std::time::Duration" => Some("u64"),
619
620                         "bitcoin::secp256k1::key::PublicKey" => Some("crate::c_types::PublicKey"),
621                         "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature"),
622                         "bitcoin::secp256k1::key::SecretKey" if is_ref  => Some("*const [u8; 32]"),
623                         "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some("crate::c_types::SecretKey"),
624                         "bitcoin::secp256k1::Error" if !is_ref => Some("crate::c_types::Secp256k1Error"),
625                         "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice"),
626                         "bitcoin::blockdata::script::Script" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
627                         "bitcoin::blockdata::transaction::OutPoint" => Some("crate::chain::transaction::OutPoint"),
628                         "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction"),
629                         "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut"),
630                         "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network"),
631                         "bitcoin::blockdata::block::BlockHeader" if is_ref  => Some("*const [u8; 80]"),
632                         "bitcoin::blockdata::block::Block" if is_ref  => Some("crate::c_types::u8slice"),
633
634                         // Newtypes that we just expose in their original form.
635                         "bitcoin::hash_types::Txid" if is_ref  => Some("*const [u8; 32]"),
636                         "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
637                         "bitcoin::hash_types::BlockHash" if is_ref  => Some("*const [u8; 32]"),
638                         "bitcoin::hash_types::BlockHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
639                         "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
640                         "ln::channelmanager::PaymentHash" if is_ref => Some("*const [u8; 32]"),
641                         "ln::channelmanager::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
642                         "ln::channelmanager::PaymentPreimage" if is_ref => Some("*const [u8; 32]"),
643                         "ln::channelmanager::PaymentPreimage" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
644                         "ln::channelmanager::PaymentSecret" if is_ref => Some("crate::c_types::ThirtyTwoBytes"),
645                         "ln::channelmanager::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
646
647                         // Override the default since Records contain an fmt with a lifetime:
648                         "util::logger::Record" => Some("*const std::os::raw::c_char"),
649
650                         // List of structs we map that aren't detected:
651                         "ln::features::InitFeatures" if is_ref && ptr_for_ref => Some("crate::ln::features::InitFeatures"),
652                         "ln::features::InitFeatures" if is_ref => Some("*const crate::ln::features::InitFeatures"),
653                         "ln::features::InitFeatures" => Some("crate::ln::features::InitFeatures"),
654                         _ => None,
655                 }
656         }
657
658         fn from_c_conversion_new_var_from_path<'b>(&self, _full_path: &str, _is_ref: bool) -> Option<(&'b str, &'b str)> {
659                 None
660         }
661         fn from_c_conversion_prefix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
662                 if self.is_primitive(full_path) {
663                         return Some("".to_owned());
664                 }
665                 match full_path {
666                         "Vec" if !is_ref => Some("local_"),
667                         "Result" if !is_ref => Some("local_"),
668                         "Option" if is_ref => Some("&local_"),
669                         "Option" => Some("local_"),
670
671                         "[u8; 32]" if is_ref => Some("unsafe { &*"),
672                         "[u8; 32]" if !is_ref => Some(""),
673                         "[u8; 16]" if !is_ref => Some(""),
674                         "[u8; 10]" if !is_ref => Some(""),
675                         "[u8; 4]" if !is_ref => Some(""),
676                         "[u8; 3]" if !is_ref => Some(""),
677
678                         "[u8]" if is_ref => Some(""),
679                         "[usize]" if is_ref => Some(""),
680
681                         "str" if is_ref => Some(""),
682                         "String" if !is_ref => Some("String::from_utf8("),
683                         // Note that we'll panic for String if is_ref, as we only have non-owned memory, we
684                         // cannot create a &String.
685
686                         "std::time::Duration" => Some("std::time::Duration::from_secs("),
687
688                         "bitcoin::secp256k1::key::PublicKey" if is_ref => Some("&"),
689                         "bitcoin::secp256k1::key::PublicKey" => Some(""),
690                         "bitcoin::secp256k1::Signature" if is_ref => Some("&"),
691                         "bitcoin::secp256k1::Signature" => Some(""),
692                         "bitcoin::secp256k1::key::SecretKey" if is_ref => Some("&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *"),
693                         "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some(""),
694                         "bitcoin::blockdata::script::Script" if is_ref => Some("&::bitcoin::blockdata::script::Script::from(Vec::from("),
695                         "bitcoin::blockdata::script::Script" if !is_ref => Some("::bitcoin::blockdata::script::Script::from("),
696                         "bitcoin::blockdata::transaction::Transaction" if is_ref => Some("&"),
697                         "bitcoin::blockdata::transaction::Transaction" => Some(""),
698                         "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(""),
699                         "bitcoin::network::constants::Network" => Some(""),
700                         "bitcoin::blockdata::block::BlockHeader" => Some("&::bitcoin::consensus::encode::deserialize(unsafe { &*"),
701                         "bitcoin::blockdata::block::Block" if is_ref => Some("&::bitcoin::consensus::encode::deserialize("),
702
703                         // Newtypes that we just expose in their original form.
704                         "bitcoin::hash_types::Txid" if is_ref => Some("&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*"),
705                         "bitcoin::hash_types::Txid" if !is_ref => Some("::bitcoin::hash_types::Txid::from_slice(&"),
706                         "bitcoin::hash_types::BlockHash" => Some("::bitcoin::hash_types::BlockHash::from_slice(&"),
707                         "ln::channelmanager::PaymentHash" if !is_ref => Some("::lightning::ln::channelmanager::PaymentHash("),
708                         "ln::channelmanager::PaymentHash" if is_ref => Some("&::lightning::ln::channelmanager::PaymentHash(unsafe { *"),
709                         "ln::channelmanager::PaymentPreimage" if !is_ref => Some("::lightning::ln::channelmanager::PaymentPreimage("),
710                         "ln::channelmanager::PaymentPreimage" if is_ref => Some("&::lightning::ln::channelmanager::PaymentPreimage(unsafe { *"),
711                         "ln::channelmanager::PaymentSecret" => Some("::lightning::ln::channelmanager::PaymentSecret("),
712
713                         // List of structs we map (possibly during processing of other files):
714                         "ln::features::InitFeatures" if !is_ref => Some("*unsafe { Box::from_raw("),
715
716                         // List of traits we map (possibly during processing of other files):
717                         "crate::util::logger::Logger" => Some(""),
718
719                         _ => None,
720                 }.map(|s| s.to_owned())
721         }
722         fn from_c_conversion_suffix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
723                 if self.is_primitive(full_path) {
724                         return Some("".to_owned());
725                 }
726                 match full_path {
727                         "Vec" if !is_ref => Some(""),
728                         "Option" => Some(""),
729                         "Result" if !is_ref => Some(""),
730
731                         "[u8; 32]" if is_ref => Some("}"),
732                         "[u8; 32]" if !is_ref => Some(".data"),
733                         "[u8; 16]" if !is_ref => Some(".data"),
734                         "[u8; 10]" if !is_ref => Some(".data"),
735                         "[u8; 4]" if !is_ref => Some(".data"),
736                         "[u8; 3]" if !is_ref => Some(".data"),
737
738                         "[u8]" if is_ref => Some(".to_slice()"),
739                         "[usize]" if is_ref => Some(".to_slice()"),
740
741                         "str" if is_ref => Some(".into()"),
742                         "String" if !is_ref => Some(".into_rust()).unwrap()"),
743
744                         "std::time::Duration" => Some(")"),
745
746                         "bitcoin::secp256k1::key::PublicKey" => Some(".into_rust()"),
747                         "bitcoin::secp256k1::Signature" => Some(".into_rust()"),
748                         "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some(".into_rust()"),
749                         "bitcoin::secp256k1::key::SecretKey" if is_ref => Some("}[..]).unwrap()"),
750                         "bitcoin::blockdata::script::Script" if is_ref => Some(".to_slice()))"),
751                         "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_rust())"),
752                         "bitcoin::blockdata::transaction::Transaction" => Some(".into_bitcoin()"),
753                         "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(".into_rust()"),
754                         "bitcoin::network::constants::Network" => Some(".into_bitcoin()"),
755                         "bitcoin::blockdata::block::BlockHeader" => Some(" }).unwrap()"),
756                         "bitcoin::blockdata::block::Block" => Some(".to_slice()).unwrap()"),
757
758                         // Newtypes that we just expose in their original form.
759                         "bitcoin::hash_types::Txid" if is_ref => Some(" }[..]).unwrap()"),
760                         "bitcoin::hash_types::Txid" => Some(".data[..]).unwrap()"),
761                         "bitcoin::hash_types::BlockHash" if !is_ref => Some(".data[..]).unwrap()"),
762                         "ln::channelmanager::PaymentHash" if !is_ref => Some(".data)"),
763                         "ln::channelmanager::PaymentHash" if is_ref => Some(" })"),
764                         "ln::channelmanager::PaymentPreimage" if !is_ref => Some(".data)"),
765                         "ln::channelmanager::PaymentPreimage" if is_ref => Some(" })"),
766                         "ln::channelmanager::PaymentSecret" => Some(".data)"),
767
768                         // List of structs we map (possibly during processing of other files):
769                         "ln::features::InitFeatures" if is_ref => Some(".inner) }"),
770                         "ln::features::InitFeatures" if !is_ref => Some(".take_inner()) }"),
771
772                         // List of traits we map (possibly during processing of other files):
773                         "crate::util::logger::Logger" => Some(""),
774
775                         _ => None,
776                 }.map(|s| s.to_owned())
777         }
778
779         fn to_c_conversion_new_var_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<(&'b str, &'b str)> {
780                 if self.is_primitive(full_path) {
781                         return None;
782                 }
783                 match full_path {
784                         "[u8]" if is_ref => Some(("crate::c_types::u8slice::from_slice(", ")")),
785                         "[usize]" if is_ref => Some(("crate::c_types::usizeslice::from_slice(", ")")),
786
787                         "bitcoin::blockdata::transaction::Transaction" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
788                         "bitcoin::blockdata::transaction::Transaction" if !is_ref => Some(("::bitcoin::consensus::encode::serialize(&", ")")),
789                         "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(("{ let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(", ")); s }")),
790                         "bitcoin::blockdata::block::Block" if is_ref => Some(("::bitcoin::consensus::encode::serialize(", ")")),
791                         "bitcoin::hash_types::Txid" => None,
792
793                         // Override the default since Records contain an fmt with a lifetime:
794                         // TODO: We should include the other record fields
795                         "util::logger::Record" => Some(("std::ffi::CString::new(format!(\"{}\", ", ".args)).unwrap()")),
796                         _ => None,
797                 }.map(|s| s.to_owned())
798         }
799         fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, ptr_for_ref: bool) -> Option<String> {
800                 if self.is_primitive(full_path) {
801                         return Some("".to_owned());
802                 }
803                 match full_path {
804                         "Result" if !is_ref => Some("local_"),
805                         "Vec" if !is_ref => Some("local_"),
806                         "Option" => Some("local_"),
807
808                         "[u8; 32]" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
809                         "[u8; 32]" if is_ref => Some("&"),
810                         "[u8; 16]" if !is_ref => Some("crate::c_types::SixteenBytes { data: "),
811                         "[u8; 10]" if !is_ref => Some("crate::c_types::TenBytes { data: "),
812                         "[u8; 4]" if !is_ref => Some("crate::c_types::FourBytes { data: "),
813                         "[u8; 3]" if is_ref => Some("&"),
814
815                         "[u8]" if is_ref => Some("local_"),
816                         "[usize]" if is_ref => Some("local_"),
817
818                         "str" if is_ref => Some(""),
819                         "String" => Some(""),
820
821                         "std::time::Duration" => Some(""),
822
823                         "bitcoin::secp256k1::key::PublicKey" => Some("crate::c_types::PublicKey::from_rust(&"),
824                         "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature::from_rust(&"),
825                         "bitcoin::secp256k1::key::SecretKey" if is_ref  => Some(""),
826                         "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some("crate::c_types::SecretKey::from_rust("),
827                         "bitcoin::secp256k1::Error" if !is_ref => Some("crate::c_types::Secp256k1Error::from_rust("),
828                         "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice::from_slice(&"),
829                         "bitcoin::blockdata::script::Script" if !is_ref => Some(""),
830                         "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction::from_vec(local_"),
831                         "bitcoin::blockdata::transaction::OutPoint" => Some("crate::c_types::bitcoin_to_C_outpoint("),
832                         "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut::from_rust("),
833                         "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("&local_"),
834                         "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice::from_slice(&local_"),
835
836                         "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
837
838                         // Newtypes that we just expose in their original form.
839                         "bitcoin::hash_types::Txid" if is_ref => Some(""),
840                         "bitcoin::hash_types::BlockHash" if is_ref => Some(""),
841                         "bitcoin::hash_types::BlockHash" => Some("crate::c_types::ThirtyTwoBytes { data: "),
842                         "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
843                         "ln::channelmanager::PaymentHash" if is_ref => Some("&"),
844                         "ln::channelmanager::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
845                         "ln::channelmanager::PaymentPreimage" if is_ref => Some("&"),
846                         "ln::channelmanager::PaymentPreimage" => Some("crate::c_types::ThirtyTwoBytes { data: "),
847                         "ln::channelmanager::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
848
849                         // Override the default since Records contain an fmt with a lifetime:
850                         "util::logger::Record" => Some("local_"),
851
852                         // List of structs we map (possibly during processing of other files):
853                         "ln::features::InitFeatures" if is_ref && ptr_for_ref => Some("crate::ln::features::InitFeatures { inner: &mut "),
854                         "ln::features::InitFeatures" if is_ref => Some("Box::into_raw(Box::new(crate::ln::features::InitFeatures { inner: &mut "),
855                         "ln::features::InitFeatures" if !is_ref => Some("crate::ln::features::InitFeatures { inner: Box::into_raw(Box::new("),
856
857                         _ => None,
858                 }.map(|s| s.to_owned())
859         }
860         fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, ptr_for_ref: bool) -> Option<String> {
861                 if self.is_primitive(full_path) {
862                         return Some("".to_owned());
863                 }
864                 match full_path {
865                         "Result" if !is_ref => Some(""),
866                         "Vec" if !is_ref => Some(".into()"),
867                         "Option" => Some(""),
868
869                         "[u8; 32]" if !is_ref => Some(" }"),
870                         "[u8; 32]" if is_ref => Some(""),
871                         "[u8; 16]" if !is_ref => Some(" }"),
872                         "[u8; 10]" if !is_ref => Some(" }"),
873                         "[u8; 4]" if !is_ref => Some(" }"),
874                         "[u8; 3]" if is_ref => Some(""),
875
876                         "[u8]" if is_ref => Some(""),
877                         "[usize]" if is_ref => Some(""),
878
879                         "str" if is_ref => Some(".into()"),
880                         "String" if !is_ref => Some(".into_bytes().into()"),
881                         "String" if is_ref => Some(".as_str().into()"),
882
883                         "std::time::Duration" => Some(".as_secs()"),
884
885                         "bitcoin::secp256k1::key::PublicKey" => Some(")"),
886                         "bitcoin::secp256k1::Signature" => Some(")"),
887                         "bitcoin::secp256k1::key::SecretKey" if !is_ref => Some(")"),
888                         "bitcoin::secp256k1::key::SecretKey" if is_ref => Some(".as_ref()"),
889                         "bitcoin::secp256k1::Error" if !is_ref => Some(")"),
890                         "bitcoin::blockdata::script::Script" if is_ref => Some("[..])"),
891                         "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_bytes().into()"),
892                         "bitcoin::blockdata::transaction::Transaction" => Some(")"),
893                         "bitcoin::blockdata::transaction::OutPoint" => Some(")"),
894                         "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(")"),
895                         "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(""),
896                         "bitcoin::blockdata::block::Block" if is_ref => Some(")"),
897
898                         "bitcoin::hash_types::Txid" if !is_ref => Some(".into_inner() }"),
899
900                         // Newtypes that we just expose in their original form.
901                         "bitcoin::hash_types::Txid" if is_ref => Some(".as_inner()"),
902                         "bitcoin::hash_types::BlockHash" if is_ref => Some(".as_inner()"),
903                         "bitcoin::hash_types::BlockHash" => Some(".into_inner() }"),
904                         "bitcoin::secp256k1::Message" if !is_ref => Some(".as_ref().clone() }"),
905                         "ln::channelmanager::PaymentHash" if is_ref => Some(".0"),
906                         "ln::channelmanager::PaymentHash" => Some(".0 }"),
907                         "ln::channelmanager::PaymentPreimage" if is_ref => Some(".0"),
908                         "ln::channelmanager::PaymentPreimage" => Some(".0 }"),
909                         "ln::channelmanager::PaymentSecret" if !is_ref => Some(".0 }"),
910
911                         // Override the default since Records contain an fmt with a lifetime:
912                         "util::logger::Record" => Some(".as_ptr()"),
913
914                         // List of structs we map (possibly during processing of other files):
915                         "ln::features::InitFeatures" if is_ref && ptr_for_ref => Some(", is_owned: false }"),
916                         "ln::features::InitFeatures" if is_ref => Some(", is_owned: false }))"),
917                         "ln::features::InitFeatures" => Some(")), is_owned: true }"),
918
919                         _ => None,
920                 }.map(|s| s.to_owned())
921         }
922
923         fn empty_val_check_suffix_from_path(&self, full_path: &str) -> Option<&str> {
924                 match full_path {
925                         "ln::channelmanager::PaymentSecret" => Some(".data == [0; 32]"),
926                         "bitcoin::secp256k1::key::PublicKey" => Some(".is_null()"),
927                         "bitcoin::secp256k1::Signature" => Some(".is_null()"),
928                         _ => None
929                 }
930         }
931
932         // ****************************
933         // *** Container Processing ***
934         // ****************************
935
936         /// Returns the module path in the generated mapping crate to the containers which we generate
937         /// when writing to CrateTypes::template_file.
938         pub fn generated_container_path() -> &'static str {
939                 "crate::c_types::derived"
940         }
941         /// Returns the module path in the generated mapping crate to the container templates, which
942         /// are then concretized and put in the generated container path/template_file.
943         fn container_templ_path() -> &'static str {
944                 "crate::c_types"
945         }
946
947         /// Returns true if this is a "transparent" container, ie an Option or a container which does
948         /// not require a generated continer class.
949         fn is_transparent_container(&self, full_path: &str, _is_ref: bool) -> bool {
950                 full_path == "Option"
951         }
952         /// Returns true if this is a known, supported, non-transparent container.
953         fn is_known_container(&self, full_path: &str, is_ref: bool) -> bool {
954                 (full_path == "Result" && !is_ref) || (full_path == "Vec" && !is_ref) || full_path.ends_with("Tuple")
955         }
956         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)
957                         // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
958                         // expecting one element in the vec per generic type, each of which is inline-converted
959                         -> Option<(&'b str, Vec<(String, String)>, &'b str)> {
960                 match full_path {
961                         "Result" if !is_ref => {
962                                 Some(("match ",
963                                                 vec![(" { Ok(mut o) => crate::c_types::CResultTempl::ok(".to_string(), "o".to_string()),
964                                                         (").into(), Err(mut e) => crate::c_types::CResultTempl::err(".to_string(), "e".to_string())],
965                                                 ").into() }"))
966                         },
967                         "Vec" if !is_ref => {
968                                 Some(("Vec::new(); for item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }"))
969                         },
970                         "Slice" => {
971                                 Some(("Vec::new(); for item in ", vec![(format!(".iter() {{ local_{}.push(", var_name), "**item".to_string())], "); }"))
972                         },
973                         "Option" => {
974                                 if let Some(syn::Type::Path(p)) = single_contained {
975                                         if self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)) {
976                                                 if is_ref {
977                                                         return Some(("if ", vec![
978                                                                 (".is_none() { std::ptr::null() } else { ".to_owned(), format!("({}.as_ref().unwrap())", var_access))
979                                                                 ], " }"));
980                                                 } else {
981                                                         return Some(("if ", vec![
982                                                                 (".is_none() { std::ptr::null_mut() } else { ".to_owned(), format!("({}.unwrap())", var_access))
983                                                                 ], " }"));
984                                                 }
985                                         }
986                                 }
987                                 if let Some(t) = single_contained {
988                                         let mut v = Vec::new();
989                                         self.write_empty_rust_val(generics, &mut v, t);
990                                         let s = String::from_utf8(v).unwrap();
991                                         return Some(("if ", vec![
992                                                 (format!(".is_none() {{ {} }} else {{ ", s), format!("({}.unwrap())", var_access))
993                                                 ], " }"));
994                                 } else { unreachable!(); }
995                         },
996                         _ => None,
997                 }
998         }
999
1000         /// only_contained_has_inner implies that there is only one contained element in the container
1001         /// and it has an inner field (ie is an "opaque" type we've defined).
1002         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)
1003                         // Returns prefix + Vec<(prefix, var-name-to-inline-convert)> + suffix
1004                         // expecting one element in the vec per generic type, each of which is inline-converted
1005                         -> Option<(&'b str, Vec<(String, String)>, &'b str)> {
1006                 match full_path {
1007                         "Result" if !is_ref => {
1008                                 Some(("match ",
1009                                                 vec![(".result_ok { true => Ok(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.result)) }})", var_name)),
1010                                                      ("), false => Err(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.err)) }})", var_name))],
1011                                                 ")}"))
1012                         },
1013                         "Vec"|"Slice" if !is_ref => {
1014                                 Some(("Vec::new(); for mut item in ", vec![(format!(".into_rust().drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }"))
1015                         },
1016                         "Slice" if is_ref => {
1017                                 Some(("Vec::new(); for mut item in ", vec![(format!(".as_slice().iter() {{ local_{}.push(", var_name), "item".to_string())], "); }"))
1018                         },
1019                         "Option" => {
1020                                 if let Some(syn::Type::Path(p)) = single_contained {
1021                                         if self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)) {
1022                                                 if is_ref {
1023                                                         return Some(("if ", vec![(".inner.is_null() { None } else { Some((*".to_string(), format!("{}", var_name))], ").clone()) }"))
1024                                                 } else {
1025                                                         return Some(("if ", vec![(".inner.is_null() { None } else { Some(".to_string(), format!("{}", var_name))], ") }"));
1026                                                 }
1027                                         }
1028                                 }
1029
1030                                 if let Some(t) = single_contained {
1031                                         let mut v = Vec::new();
1032                                         let ret_ref = self.write_empty_rust_val_check_suffix(generics, &mut v, t);
1033                                         let s = String::from_utf8(v).unwrap();
1034                                         match ret_ref {
1035                                                 EmptyValExpectedTy::ReferenceAsPointer =>
1036                                                         return Some(("if ", vec![
1037                                                                 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ &mut *{} }}", var_access))
1038                                                         ], ") }")),
1039                                                 EmptyValExpectedTy::OwnedPointer =>
1040                                                         return Some(("if ", vec![
1041                                                                 (format!("{} {{ None }} else {{ Some(", s), format!("unsafe {{ *Box::from_raw({}) }}", var_access))
1042                                                         ], ") }")),
1043                                                 EmptyValExpectedTy::NonPointer =>
1044                                                         return Some(("if ", vec![
1045                                                                 (format!("{} {{ None }} else {{ Some(", s), format!("{}", var_access))
1046                                                         ], ") }")),
1047                                         }
1048                                 } else { unreachable!(); }
1049                         },
1050                         _ => None,
1051                 }
1052         }
1053
1054         // *************************************************
1055         // *** Type definition during main.rs processing ***
1056         // *************************************************
1057
1058         pub fn get_declared_type(&'a self, ident: &syn::Ident) -> Option<&'a DeclType<'c>> {
1059                 self.types.get_declared_type(ident)
1060         }
1061         /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
1062         pub fn c_type_has_inner_from_path(&self, full_path: &str) -> bool{
1063                 self.crate_types.opaques.get(full_path).is_some()
1064         }
1065
1066         pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
1067                 self.types.maybe_resolve_ident(id)
1068         }
1069
1070         pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
1071                 self.types.maybe_resolve_non_ignored_ident(id)
1072         }
1073
1074         pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
1075                 self.types.maybe_resolve_path(p_arg, generics)
1076         }
1077         pub fn resolve_path(&self, p: &syn::Path, generics: Option<&GenericTypes>) -> String {
1078                 self.maybe_resolve_path(p, generics).unwrap()
1079         }
1080
1081         // ***********************************
1082         // *** Original Rust Type Printing ***
1083         // ***********************************
1084
1085         fn in_rust_prelude(resolved_path: &str) -> bool {
1086                 match resolved_path {
1087                         "Vec" => true,
1088                         "Result" => true,
1089                         "Option" => true,
1090                         _ => false,
1091                 }
1092         }
1093
1094         fn write_rust_path<W: std::io::Write>(&self, w: &mut W, generics_resolver: Option<&GenericTypes>, path: &syn::Path) {
1095                 if let Some(resolved) = self.maybe_resolve_path(&path, generics_resolver) {
1096                         if self.is_primitive(&resolved) {
1097                                 write!(w, "{}", path.get_ident().unwrap()).unwrap();
1098                         } else {
1099                                 // TODO: We should have a generic "is from a dependency" check here instead of
1100                                 // checking for "bitcoin" explicitly.
1101                                 if resolved.starts_with("bitcoin::") || Self::in_rust_prelude(&resolved) {
1102                                         write!(w, "{}", resolved).unwrap();
1103                                 // If we're printing a generic argument, it needs to reference the crate, otherwise
1104                                 // the original crate:
1105                                 } else if self.maybe_resolve_path(&path, None).as_ref() == Some(&resolved) {
1106                                         write!(w, "{}::{}", self.orig_crate, resolved).unwrap();
1107                                 } else {
1108                                         write!(w, "crate::{}", resolved).unwrap();
1109                                 }
1110                         }
1111                         if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().last().unwrap().arguments {
1112                                 self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1113                         }
1114                 } else {
1115                         if path.leading_colon.is_some() {
1116                                 write!(w, "::").unwrap();
1117                         }
1118                         for (idx, seg) in path.segments.iter().enumerate() {
1119                                 if idx != 0 { write!(w, "::").unwrap(); }
1120                                 write!(w, "{}", seg.ident).unwrap();
1121                                 if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
1122                                         self.write_rust_generic_arg(w, generics_resolver, args.args.iter());
1123                                 }
1124                         }
1125                 }
1126         }
1127         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>) {
1128                 let mut had_params = false;
1129                 for (idx, arg) in generics.enumerate() {
1130                         if idx != 0 { write!(w, ", ").unwrap(); } else { write!(w, "<").unwrap(); }
1131                         had_params = true;
1132                         match arg {
1133                                 syn::GenericParam::Lifetime(lt) => write!(w, "'{}", lt.lifetime.ident).unwrap(),
1134                                 syn::GenericParam::Type(t) => {
1135                                         write!(w, "{}", t.ident).unwrap();
1136                                         if t.colon_token.is_some() { write!(w, ":").unwrap(); }
1137                                         for (idx, bound) in t.bounds.iter().enumerate() {
1138                                                 if idx != 0 { write!(w, " + ").unwrap(); }
1139                                                 match bound {
1140                                                         syn::TypeParamBound::Trait(tb) => {
1141                                                                 if tb.paren_token.is_some() || tb.lifetimes.is_some() { unimplemented!(); }
1142                                                                 self.write_rust_path(w, generics_resolver, &tb.path);
1143                                                         },
1144                                                         _ => unimplemented!(),
1145                                                 }
1146                                         }
1147                                         if t.eq_token.is_some() || t.default.is_some() { unimplemented!(); }
1148                                 },
1149                                 _ => unimplemented!(),
1150                         }
1151                 }
1152                 if had_params { write!(w, ">").unwrap(); }
1153         }
1154
1155         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>) {
1156                 write!(w, "<").unwrap();
1157                 for (idx, arg) in generics.enumerate() {
1158                         if idx != 0 { write!(w, ", ").unwrap(); }
1159                         match arg {
1160                                 syn::GenericArgument::Type(t) => self.write_rust_type(w, generics_resolver, t),
1161                                 _ => unimplemented!(),
1162                         }
1163                 }
1164                 write!(w, ">").unwrap();
1165         }
1166         pub fn write_rust_type<W: std::io::Write>(&self, w: &mut W, generics: Option<&GenericTypes>, t: &syn::Type) {
1167                 match t {
1168                         syn::Type::Path(p) => {
1169                                 if p.qself.is_some() {
1170                                         unimplemented!();
1171                                 }
1172                                 self.write_rust_path(w, generics, &p.path);
1173                         },
1174                         syn::Type::Reference(r) => {
1175                                 write!(w, "&").unwrap();
1176                                 if let Some(lft) = &r.lifetime {
1177                                         write!(w, "'{} ", lft.ident).unwrap();
1178                                 }
1179                                 if r.mutability.is_some() {
1180                                         write!(w, "mut ").unwrap();
1181                                 }
1182                                 self.write_rust_type(w, generics, &*r.elem);
1183                         },
1184                         syn::Type::Array(a) => {
1185                                 write!(w, "[").unwrap();
1186                                 self.write_rust_type(w, generics, &a.elem);
1187                                 if let syn::Expr::Lit(l) = &a.len {
1188                                         if let syn::Lit::Int(i) = &l.lit {
1189                                                 write!(w, "; {}]", i).unwrap();
1190                                         } else { unimplemented!(); }
1191                                 } else { unimplemented!(); }
1192                         }
1193                         syn::Type::Slice(s) => {
1194                                 write!(w, "[").unwrap();
1195                                 self.write_rust_type(w, generics, &s.elem);
1196                                 write!(w, "]").unwrap();
1197                         },
1198                         syn::Type::Tuple(s) => {
1199                                 write!(w, "(").unwrap();
1200                                 for (idx, t) in s.elems.iter().enumerate() {
1201                                         if idx != 0 { write!(w, ", ").unwrap(); }
1202                                         self.write_rust_type(w, generics, &t);
1203                                 }
1204                                 write!(w, ")").unwrap();
1205                         },
1206                         _ => unimplemented!(),
1207                 }
1208         }
1209
1210         /// Prints a constructor for something which is "uninitialized" (but obviously not actually
1211         /// unint'd memory).
1212         pub fn write_empty_rust_val<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) {
1213                 match t {
1214                         syn::Type::Path(p) => {
1215                                 let resolved = self.resolve_path(&p.path, generics);
1216                                 if self.crate_types.opaques.get(&resolved).is_some() {
1217                                         write!(w, "crate::{} {{ inner: std::ptr::null_mut(), is_owned: true }}", resolved).unwrap();
1218                                 } else {
1219                                         // Assume its a manually-mapped C type, where we can just define an null() fn
1220                                         write!(w, "{}::null()", self.c_type_from_path(&resolved, false, false).unwrap()).unwrap();
1221                                 }
1222                         },
1223                         syn::Type::Array(a) => {
1224                                 if let syn::Expr::Lit(l) = &a.len {
1225                                         if let syn::Lit::Int(i) = &l.lit {
1226                                                 if i.base10_digits().parse::<usize>().unwrap() < 32 {
1227                                                         // Blindly assume that if we're trying to create an empty value for an
1228                                                         // array < 32 entries that all-0s may be a valid state.
1229                                                         unimplemented!();
1230                                                 }
1231                                                 let arrty = format!("[u8; {}]", i.base10_digits());
1232                                                 write!(w, "{}", self.to_c_conversion_inline_prefix_from_path(&arrty, false, false).unwrap()).unwrap();
1233                                                 write!(w, "[0; {}]", i.base10_digits()).unwrap();
1234                                                 write!(w, "{}", self.to_c_conversion_inline_suffix_from_path(&arrty, false, false).unwrap()).unwrap();
1235                                         } else { unimplemented!(); }
1236                                 } else { unimplemented!(); }
1237                         }
1238                         _ => unimplemented!(),
1239                 }
1240         }
1241
1242         /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1243         /// See EmptyValExpectedTy for information on return types.
1244         fn write_empty_rust_val_check_suffix<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type) -> EmptyValExpectedTy {
1245                 match t {
1246                         syn::Type::Path(p) => {
1247                                 let resolved = self.resolve_path(&p.path, generics);
1248                                 if self.crate_types.opaques.get(&resolved).is_some() {
1249                                         write!(w, ".inner.is_null()").unwrap();
1250                                         EmptyValExpectedTy::NonPointer
1251                                 } else {
1252                                         if let Some(suffix) = self.empty_val_check_suffix_from_path(&resolved) {
1253                                                 write!(w, "{}", suffix).unwrap();
1254                                                 // We may eventually need to allow empty_val_check_suffix_from_path to specify if we need a deref or not
1255                                                 EmptyValExpectedTy::NonPointer
1256                                         } else {
1257                                                 write!(w, " == std::ptr::null_mut()").unwrap();
1258                                                 EmptyValExpectedTy::OwnedPointer
1259                                         }
1260                                 }
1261                         },
1262                         syn::Type::Array(a) => {
1263                                 if let syn::Expr::Lit(l) = &a.len {
1264                                         if let syn::Lit::Int(i) = &l.lit {
1265                                                 write!(w, " == [0; {}]", i.base10_digits()).unwrap();
1266                                                 EmptyValExpectedTy::NonPointer
1267                                         } else { unimplemented!(); }
1268                                 } else { unimplemented!(); }
1269                         },
1270                         syn::Type::Slice(_) => {
1271                                 // Option<[]> always implies that we want to treat len() == 0 differently from
1272                                 // None, so we always map an Option<[]> into a pointer.
1273                                 write!(w, " == std::ptr::null_mut()").unwrap();
1274                                 EmptyValExpectedTy::ReferenceAsPointer
1275                         },
1276                         _ => unimplemented!(),
1277                 }
1278         }
1279
1280         /// Prints a suffix to determine if a variable is empty (ie was set by write_empty_rust_val).
1281         pub fn write_empty_rust_val_check<W: std::io::Write>(&self, generics: Option<&GenericTypes>, w: &mut W, t: &syn::Type, var_access: &str) {
1282                 match t {
1283                         syn::Type::Path(_) => {
1284                                 write!(w, "{}", var_access).unwrap();
1285                                 self.write_empty_rust_val_check_suffix(generics, w, t);
1286                         },
1287                         syn::Type::Array(a) => {
1288                                 if let syn::Expr::Lit(l) = &a.len {
1289                                         if let syn::Lit::Int(i) = &l.lit {
1290                                                 let arrty = format!("[u8; {}]", i.base10_digits());
1291                                                 // We don't (yet) support a new-var conversion here.
1292                                                 assert!(self.from_c_conversion_new_var_from_path(&arrty, false).is_none());
1293                                                 write!(w, "{}{}{}",
1294                                                         self.from_c_conversion_prefix_from_path(&arrty, false).unwrap(),
1295                                                         var_access,
1296                                                         self.from_c_conversion_suffix_from_path(&arrty, false).unwrap()).unwrap();
1297                                                 self.write_empty_rust_val_check_suffix(generics, w, t);
1298                                         } else { unimplemented!(); }
1299                                 } else { unimplemented!(); }
1300                         }
1301                         _ => unimplemented!(),
1302                 }
1303         }
1304
1305         // ********************************
1306         // *** Type conversion printing ***
1307         // ********************************
1308
1309         /// Returns true we if can just skip passing this to C entirely
1310         pub fn skip_arg(&self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
1311                 match t {
1312                         syn::Type::Path(p) => {
1313                                 if p.qself.is_some() { unimplemented!(); }
1314                                 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1315                                         self.skip_path(&full_path)
1316                                 } else { false }
1317                         },
1318                         syn::Type::Reference(r) => {
1319                                 self.skip_arg(&*r.elem, generics)
1320                         },
1321                         _ => false,
1322                 }
1323         }
1324         pub fn no_arg_to_rust<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1325                 match t {
1326                         syn::Type::Path(p) => {
1327                                 if p.qself.is_some() { unimplemented!(); }
1328                                 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
1329                                         write!(w, "{}", self.no_arg_path_to_rust(&full_path)).unwrap();
1330                                 }
1331                         },
1332                         syn::Type::Reference(r) => {
1333                                 self.no_arg_to_rust(w, &*r.elem, generics);
1334                         },
1335                         _ => {},
1336                 }
1337         }
1338
1339         fn write_conversion_inline_intern<W: std::io::Write,
1340                         LP: Fn(&str, bool, bool) -> Option<String>, DL: Fn(&mut W, &DeclType, &str, bool, bool), SC: Fn(bool) -> &'static str>
1341                         (&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool,
1342                          tupleconv: &str, prefix: bool, sliceconv: SC, path_lookup: LP, decl_lookup: DL) {
1343                 match t {
1344                         syn::Type::Reference(r) => {
1345                                 self.write_conversion_inline_intern(w, &*r.elem, generics, true, r.mutability.is_some(),
1346                                         ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1347                         },
1348                         syn::Type::Path(p) => {
1349                                 if p.qself.is_some() {
1350                                         unimplemented!();
1351                                 }
1352
1353                                 let resolved_path = self.resolve_path(&p.path, generics);
1354                                 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1355                                         return self.write_conversion_inline_intern(w, aliased_type, None, is_ref, is_mut, ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup);
1356                                 } else if let Some(c_type) = path_lookup(&resolved_path, is_ref, ptr_for_ref) {
1357                                         write!(w, "{}", c_type).unwrap();
1358                                 } else if self.crate_types.opaques.get(&resolved_path).is_some() {
1359                                         decl_lookup(w, &DeclType::StructImported, &resolved_path, is_ref, is_mut);
1360                                 } else if self.crate_types.mirrored_enums.get(&resolved_path).is_some() {
1361                                         decl_lookup(w, &DeclType::MirroredEnum, &resolved_path, is_ref, is_mut);
1362                                 } else if let Some(t) = self.crate_types.traits.get(&resolved_path) {
1363                                         decl_lookup(w, &DeclType::Trait(t), &resolved_path, is_ref, is_mut);
1364                                 } else if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
1365                                         if let Some(decl_type) = self.types.maybe_resolve_declared(ident) {
1366                                                 decl_lookup(w, decl_type, &self.maybe_resolve_ident(ident).unwrap(), is_ref, is_mut);
1367                                         } else { unimplemented!(); }
1368                                 } else { unimplemented!(); }
1369                         },
1370                         syn::Type::Array(a) => {
1371                                 // We assume all arrays contain only [int_literal; X]s.
1372                                 // This may result in some outputs not compiling.
1373                                 if let syn::Expr::Lit(l) = &a.len {
1374                                         if let syn::Lit::Int(i) = &l.lit {
1375                                                 write!(w, "{}", path_lookup(&format!("[u8; {}]", i.base10_digits()), is_ref, ptr_for_ref).unwrap()).unwrap();
1376                                         } else { unimplemented!(); }
1377                                 } else { unimplemented!(); }
1378                         },
1379                         syn::Type::Slice(s) => {
1380                                 // We assume all slices contain only literals or references.
1381                                 // This may result in some outputs not compiling.
1382                                 if let syn::Type::Path(p) = &*s.elem {
1383                                         let resolved = self.resolve_path(&p.path, generics);
1384                                         assert!(self.is_primitive(&resolved));
1385                                         write!(w, "{}", path_lookup("[u8]", is_ref, ptr_for_ref).unwrap()).unwrap();
1386                                 } else if let syn::Type::Reference(r) = &*s.elem {
1387                                         if let syn::Type::Path(p) = &*r.elem {
1388                                                 write!(w, "{}", sliceconv(self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)))).unwrap();
1389                                         } else { unimplemented!(); }
1390                                 } else if let syn::Type::Tuple(t) = &*s.elem {
1391                                         assert!(!t.elems.is_empty());
1392                                         if prefix {
1393                                                 write!(w, "&local_").unwrap();
1394                                         } else {
1395                                                 let mut needs_map = false;
1396                                                 for e in t.elems.iter() {
1397                                                         if let syn::Type::Reference(_) = e {
1398                                                                 needs_map = true;
1399                                                         }
1400                                                 }
1401                                                 if needs_map {
1402                                                         write!(w, ".iter().map(|(").unwrap();
1403                                                         for i in 0..t.elems.len() {
1404                                                                 write!(w, "{}{}", if i != 0 { ", " } else { "" }, ('a' as u8 + i as u8) as char).unwrap();
1405                                                         }
1406                                                         write!(w, ")| (").unwrap();
1407                                                         for (idx, e) in t.elems.iter().enumerate() {
1408                                                                 if let syn::Type::Reference(_) = e {
1409                                                                         write!(w, "{}{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1410                                                                 } else if let syn::Type::Path(_) = e {
1411                                                                         write!(w, "{}*{}", if idx != 0 { ", " } else { "" }, (idx as u8 + 'a' as u8) as char).unwrap();
1412                                                                 } else { unimplemented!(); }
1413                                                         }
1414                                                         write!(w, ")).collect::<Vec<_>>()[..]").unwrap();
1415                                                 }
1416                                         }
1417                                 } else { unimplemented!(); }
1418                         },
1419                         syn::Type::Tuple(t) => {
1420                                 if t.elems.is_empty() {
1421                                         // cbindgen has poor support for (), see, eg https://github.com/eqrion/cbindgen/issues/527
1422                                         // so work around it by just pretending its a 0u8
1423                                         write!(w, "{}", tupleconv).unwrap();
1424                                 } else {
1425                                         if prefix { write!(w, "local_").unwrap(); }
1426                                 }
1427                         },
1428                         _ => unimplemented!(),
1429                 }
1430         }
1431
1432         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) {
1433                 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "0u8 /*", true, |_| "local_",
1434                                 |a, b, c| self.to_c_conversion_inline_prefix_from_path(a, b, c),
1435                                 |w, decl_type, decl_path, is_ref, _is_mut| {
1436                                         match decl_type {
1437                                                 DeclType::MirroredEnum if is_ref && ptr_for_ref => write!(w, "crate::{}::from_native(&", decl_path).unwrap(),
1438                                                 DeclType::MirroredEnum if is_ref => write!(w, "&crate::{}::from_native(&", decl_path).unwrap(),
1439                                                 DeclType::MirroredEnum => write!(w, "crate::{}::native_into(", decl_path).unwrap(),
1440                                                 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1441                                                         write!(w, "crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1442                                                 DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1443                                                         write!(w, "crate::{} {{ inner: unsafe {{ ( (&(", decl_path).unwrap(),
1444                                                 DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1445                                                         write!(w, "&crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
1446                                                 DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1447                                                         write!(w, "crate::{} {{ inner: ", decl_path).unwrap(),
1448                                                 DeclType::EnumIgnored|DeclType::StructImported if !is_ref =>
1449                                                         write!(w, "crate::{} {{ inner: Box::into_raw(Box::new(", decl_path).unwrap(),
1450                                                 DeclType::Trait(_) if is_ref => write!(w, "&").unwrap(),
1451                                                 DeclType::Trait(_) if !is_ref => {},
1452                                                 _ => panic!("{:?}", decl_path),
1453                                         }
1454                                 });
1455         }
1456         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) {
1457                 self.write_to_c_conversion_inline_prefix_inner(w, t, generics, false, ptr_for_ref, false);
1458         }
1459         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) {
1460                 self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "*/", false, |_| ".into()",
1461                                 |a, b, c| self.to_c_conversion_inline_suffix_from_path(a, b, c),
1462                                 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1463                                         DeclType::MirroredEnum => write!(w, ")").unwrap(),
1464                                         DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
1465                                                 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1466                                         DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
1467                                                 write!(w, ") as *const _) as *mut _) }}, is_owned: false }}").unwrap(),
1468                                         DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
1469                                                 write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
1470                                         DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
1471                                                 write!(w, ", is_owned: true }}").unwrap(),
1472                                         DeclType::EnumIgnored|DeclType::StructImported if !is_ref => write!(w, ")), is_owned: true }}").unwrap(),
1473                                         DeclType::Trait(_) if is_ref => {},
1474                                         DeclType::Trait(_) => {
1475                                                 // This is used when we're converting a concrete Rust type into a C trait
1476                                                 // for use when a Rust trait method returns an associated type.
1477                                                 // Because all of our C traits implement From<RustTypesImplementingTraits>
1478                                                 // we can just call .into() here and be done.
1479                                                 write!(w, ".into()").unwrap()
1480                                         },
1481                                         _ => unimplemented!(),
1482                                 });
1483         }
1484         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) {
1485                 self.write_to_c_conversion_inline_suffix_inner(w, t, generics, false, ptr_for_ref, false);
1486         }
1487
1488         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) {
1489                 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "() /*", true, |_| "&local_",
1490                                 |a, b, _c| self.from_c_conversion_prefix_from_path(a, b),
1491                                 |w, decl_type, _full_path, is_ref, is_mut| match decl_type {
1492                                         DeclType::StructImported if is_ref && ptr_for_ref => write!(w, "unsafe {{ &*(*").unwrap(),
1493                                         DeclType::StructImported if is_mut && is_ref => write!(w, "unsafe {{ &mut *").unwrap(),
1494                                         DeclType::StructImported if is_ref => write!(w, "unsafe {{ &*").unwrap(),
1495                                         DeclType::StructImported if !is_ref => write!(w, "*unsafe {{ Box::from_raw(").unwrap(),
1496                                         DeclType::MirroredEnum if is_ref => write!(w, "&").unwrap(),
1497                                         DeclType::MirroredEnum => {},
1498                                         DeclType::Trait(_) => {},
1499                                         _ => unimplemented!(),
1500                                 });
1501         }
1502         pub fn write_from_c_conversion_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1503                 self.write_from_c_conversion_prefix_inner(w, t, generics, false, false);
1504         }
1505         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) {
1506                 self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "*/", false,
1507                                 |has_inner| match has_inner {
1508                                         false => ".iter().collect::<Vec<_>>()[..]",
1509                                         true => "[..]",
1510                                 },
1511                                 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1512                                 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1513                                         DeclType::StructImported if is_ref && ptr_for_ref => write!(w, ").inner }}").unwrap(),
1514                                         DeclType::StructImported if is_ref => write!(w, ".inner }}").unwrap(),
1515                                         DeclType::StructImported if !is_ref => write!(w, ".take_inner()) }}").unwrap(),
1516                                         DeclType::MirroredEnum if is_ref => write!(w, ".to_native()").unwrap(),
1517                                         DeclType::MirroredEnum => write!(w, ".into_native()").unwrap(),
1518                                         DeclType::Trait(_) => {},
1519                                         _ => unimplemented!(),
1520                                 });
1521         }
1522         pub fn write_from_c_conversion_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1523                 self.write_from_c_conversion_suffix_inner(w, t, generics, false, false);
1524         }
1525         // Note that compared to the above conversion functions, the following two are generally
1526         // significantly undertested:
1527         pub fn write_from_c_conversion_to_ref_prefix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1528                 self.write_conversion_inline_intern(w, t, generics, false, false, false, "() /*", true, |_| "&local_",
1529                                 |a, b, _c| {
1530                                         if let Some(conv) = self.from_c_conversion_prefix_from_path(a, b) {
1531                                                 Some(format!("&{}", conv))
1532                                         } else { None }
1533                                 },
1534                                 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1535                                         DeclType::StructImported if !is_ref => write!(w, "unsafe {{ &*").unwrap(),
1536                                         _ => unimplemented!(),
1537                                 });
1538         }
1539         pub fn write_from_c_conversion_to_ref_suffix<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>) {
1540                 self.write_conversion_inline_intern(w, t, generics, false, false, false, "*/", false,
1541                                 |has_inner| match has_inner {
1542                                         false => ".iter().collect::<Vec<_>>()[..]",
1543                                         true => "[..]",
1544                                 },
1545                                 |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
1546                                 |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
1547                                         DeclType::StructImported if !is_ref => write!(w, ".inner }}").unwrap(),
1548                                         _ => unimplemented!(),
1549                                 });
1550         }
1551
1552         fn write_conversion_new_var_intern<'b, W: std::io::Write,
1553                 LP: Fn(&str, bool) -> Option<(&str, &str)>,
1554                 LC: Fn(&str, bool, Option<&syn::Type>, &syn::Ident, &str) ->  Option<(&'b str, Vec<(String, String)>, &'b str)>,
1555                 VP: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool),
1556                 VS: Fn(&mut W, &syn::Type, Option<&GenericTypes>, bool, bool, bool)>
1557                         (&self, w: &mut W, ident: &syn::Ident, var: &str, t: &syn::Type, generics: Option<&GenericTypes>,
1558                          mut is_ref: bool, mut ptr_for_ref: bool, to_c: bool,
1559                          path_lookup: &LP, container_lookup: &LC, var_prefix: &VP, var_suffix: &VS) -> bool {
1560
1561                 macro_rules! convert_container {
1562                         ($container_type: expr, $args_len: expr, $args_iter: expr) => { {
1563                                 // For slices (and Options), we refuse to directly map them as is_ref when they
1564                                 // aren't opaque types containing an inner pointer. This is due to the fact that,
1565                                 // in both cases, the actual higher-level type is non-is_ref.
1566                                 let ty_has_inner = if self.is_transparent_container(&$container_type, is_ref) || $container_type == "Slice" {
1567                                         let ty = $args_iter().next().unwrap();
1568                                         if $container_type == "Slice" && to_c {
1569                                                 // "To C ptr_for_ref" means "return the regular object with is_owned
1570                                                 // set to false", which is totally what we want in a slice if we're about to
1571                                                 // set ty_has_inner.
1572                                                 ptr_for_ref = true;
1573                                         }
1574                                         if let syn::Type::Reference(t) = ty {
1575                                                 if let syn::Type::Path(p) = &*t.elem {
1576                                                         self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1577                                                 } else { false }
1578                                         } else if let syn::Type::Path(p) = ty {
1579                                                 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1580                                         } else { false }
1581                                 } else { true };
1582
1583                                 // Options get a bunch of special handling, since in general we map Option<>al
1584                                 // types into the same C type as non-Option-wrapped types. This ends up being
1585                                 // pretty manual here and most of the below special-cases are for Options.
1586                                 let mut needs_ref_map = false;
1587                                 let mut only_contained_type = None;
1588                                 let mut only_contained_has_inner = false;
1589                                 let mut contains_slice = false;
1590                                 if $args_len == 1 && self.is_transparent_container(&$container_type, is_ref) {
1591                                         only_contained_has_inner = ty_has_inner;
1592                                         let arg = $args_iter().next().unwrap();
1593                                         if let syn::Type::Reference(t) = arg {
1594                                                 only_contained_type = Some(&*t.elem);
1595                                                 if let syn::Type::Path(_) = &*t.elem {
1596                                                         is_ref = true;
1597                                                 } else if let syn::Type::Slice(_) = &*t.elem {
1598                                                         contains_slice = true;
1599                                                 } else { return false; }
1600                                                 needs_ref_map = true;
1601                                         } else if let syn::Type::Path(_) = arg {
1602                                                 only_contained_type = Some(&arg);
1603                                         } else { unimplemented!(); }
1604                                 }
1605
1606                                 if let Some((prefix, conversions, suffix)) = container_lookup(&$container_type, is_ref && ty_has_inner, only_contained_type, ident, var) {
1607                                         assert_eq!(conversions.len(), $args_len);
1608                                         write!(w, "let mut local_{}{} = ", ident, if !to_c && needs_ref_map {"_base"} else { "" }).unwrap();
1609                                         if only_contained_has_inner && to_c {
1610                                                 var_prefix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
1611                                         }
1612                                         write!(w, "{}{}", prefix, var).unwrap();
1613
1614                                         for ((pfx, var_name), (idx, ty)) in conversions.iter().zip($args_iter().enumerate()) {
1615                                                 let mut var = std::io::Cursor::new(Vec::new());
1616                                                 write!(&mut var, "{}", var_name).unwrap();
1617                                                 let var_access = String::from_utf8(var.into_inner()).unwrap();
1618
1619                                                 let conv_ty = if needs_ref_map { only_contained_type.as_ref().unwrap() } else { ty };
1620
1621                                                 write!(w, "{} {{ ", pfx).unwrap();
1622                                                 let new_var_name = format!("{}_{}", ident, idx);
1623                                                 let new_var = self.write_conversion_new_var_intern(w, &syn::Ident::new(&new_var_name, Span::call_site()),
1624                                                                 &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);
1625                                                 if new_var { write!(w, " ").unwrap(); }
1626                                                 if (!only_contained_has_inner || !to_c) && !contains_slice {
1627                                                         var_prefix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1628                                                 }
1629
1630                                                 if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
1631                                                         write!(w, "Box::into_raw(Box::new(").unwrap();
1632                                                 }
1633                                                 write!(w, "{}{}", if contains_slice { "local_" } else { "" }, if new_var { new_var_name } else { var_access }).unwrap();
1634                                                 if (!only_contained_has_inner || !to_c) && !contains_slice {
1635                                                         var_suffix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1636                                                 }
1637                                                 if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
1638                                                         write!(w, "))").unwrap();
1639                                                 }
1640                                                 write!(w, " }}").unwrap();
1641                                         }
1642                                         write!(w, "{}", suffix).unwrap();
1643                                         if only_contained_has_inner && to_c {
1644                                                 var_suffix(w, $args_iter().next().unwrap(), generics, is_ref, ptr_for_ref, true);
1645                                         }
1646                                         write!(w, ";").unwrap();
1647                                         if !to_c && needs_ref_map {
1648                                                 write!(w, " let mut local_{} = local_{}_base.as_ref()", ident, ident).unwrap();
1649                                                 if contains_slice {
1650                                                         write!(w, ".map(|a| &a[..])").unwrap();
1651                                                 }
1652                                                 write!(w, ";").unwrap();
1653                                         }
1654                                         return true;
1655                                 }
1656                         } }
1657                 }
1658
1659                 match t {
1660                         syn::Type::Reference(r) => {
1661                                 if let syn::Type::Slice(_) = &*r.elem {
1662                                         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)
1663                                 } else {
1664                                         self.write_conversion_new_var_intern(w, ident, var, &*r.elem, generics, true, ptr_for_ref, to_c, path_lookup, container_lookup, var_prefix, var_suffix)
1665                                 }
1666                         },
1667                         syn::Type::Path(p) => {
1668                                 if p.qself.is_some() {
1669                                         unimplemented!();
1670                                 }
1671                                 let resolved_path = self.resolve_path(&p.path, generics);
1672                                 if let Some(aliased_type) = self.crate_types.type_aliases.get(&resolved_path) {
1673                                         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);
1674                                 }
1675                                 if self.is_known_container(&resolved_path, is_ref) || self.is_transparent_container(&resolved_path, is_ref) {
1676                                         if let syn::PathArguments::AngleBracketed(args) = &p.path.segments.iter().next().unwrap().arguments {
1677                                                 convert_container!(resolved_path, args.args.len(), || args.args.iter().map(|arg| {
1678                                                         if let syn::GenericArgument::Type(ty) = arg {
1679                                                                 ty
1680                                                         } else { unimplemented!(); }
1681                                                 }));
1682                                         } else { unimplemented!(); }
1683                                 }
1684                                 if self.is_primitive(&resolved_path) {
1685                                         false
1686                                 } else if let Some(ty_ident) = single_ident_generic_path_to_ident(&p.path) {
1687                                         if let Some((prefix, suffix)) = path_lookup(&resolved_path, is_ref) {
1688                                                 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
1689                                                 true
1690                                         } else if self.types.maybe_resolve_declared(ty_ident).is_some() {
1691                                                 false
1692                                         } else { false }
1693                                 } else { false }
1694                         },
1695                         syn::Type::Array(_) => {
1696                                 // We assume all arrays contain only primitive types.
1697                                 // This may result in some outputs not compiling.
1698                                 false
1699                         },
1700                         syn::Type::Slice(s) => {
1701                                 if let syn::Type::Path(p) = &*s.elem {
1702                                         let resolved = self.resolve_path(&p.path, generics);
1703                                         assert!(self.is_primitive(&resolved));
1704                                         let slice_path = format!("[{}]", resolved);
1705                                         if let Some((prefix, suffix)) = path_lookup(&slice_path, true) {
1706                                                 write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
1707                                                 true
1708                                         } else { false }
1709                                 } else if let syn::Type::Reference(ty) = &*s.elem {
1710                                         let tyref = [&*ty.elem];
1711                                         is_ref = true;
1712                                         convert_container!("Slice", 1, || tyref.iter());
1713                                         unimplemented!("convert_container should return true as container_lookup should succeed for slices");
1714                                 } else if let syn::Type::Tuple(t) = &*s.elem {
1715                                         // When mapping into a temporary new var, we need to own all the underlying objects.
1716                                         // Thus, we drop any references inside the tuple and convert with non-reference types.
1717                                         let mut elems = syn::punctuated::Punctuated::new();
1718                                         for elem in t.elems.iter() {
1719                                                 if let syn::Type::Reference(r) = elem {
1720                                                         elems.push((*r.elem).clone());
1721                                                 } else {
1722                                                         elems.push(elem.clone());
1723                                                 }
1724                                         }
1725                                         let ty = [syn::Type::Tuple(syn::TypeTuple {
1726                                                 paren_token: t.paren_token, elems
1727                                         })];
1728                                         is_ref = false;
1729                                         ptr_for_ref = true;
1730                                         convert_container!("Slice", 1, || ty.iter());
1731                                         unimplemented!("convert_container should return true as container_lookup should succeed for slices");
1732                                 } else { unimplemented!() }
1733                         },
1734                         syn::Type::Tuple(t) => {
1735                                 if !t.elems.is_empty() {
1736                                         // We don't (yet) support tuple elements which cannot be converted inline
1737                                         write!(w, "let (").unwrap();
1738                                         for idx in 0..t.elems.len() {
1739                                                 if idx != 0 { write!(w, ", ").unwrap(); }
1740                                                 write!(w, "{} orig_{}_{}", if is_ref { "ref" } else { "mut" }, ident, idx).unwrap();
1741                                         }
1742                                         write!(w, ") = {}{}; ", var, if !to_c { ".to_rust()" } else { "" }).unwrap();
1743                                         // Like other template types, tuples are always mapped as their non-ref
1744                                         // versions for types which have different ref mappings. Thus, we convert to
1745                                         // non-ref versions and handle opaque types with inner pointers manually.
1746                                         for (idx, elem) in t.elems.iter().enumerate() {
1747                                                 if let syn::Type::Path(p) = elem {
1748                                                         let v_name = format!("orig_{}_{}", ident, idx);
1749                                                         let tuple_elem_ident = syn::Ident::new(&v_name, Span::call_site());
1750                                                         if self.write_conversion_new_var_intern(w, &tuple_elem_ident, &v_name, elem, generics,
1751                                                                         false, ptr_for_ref, to_c,
1752                                                                         path_lookup, container_lookup, var_prefix, var_suffix) {
1753                                                                 write!(w, " ").unwrap();
1754                                                                 // Opaque types with inner pointers shouldn't ever create new stack
1755                                                                 // variables, so we don't handle it and just assert that it doesn't
1756                                                                 // here.
1757                                                                 assert!(!self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)));
1758                                                         }
1759                                                 }
1760                                         }
1761                                         write!(w, "let mut local_{} = (", ident).unwrap();
1762                                         for (idx, elem) in t.elems.iter().enumerate() {
1763                                                 let ty_has_inner = {
1764                                                                 if to_c {
1765                                                                         // "To C ptr_for_ref" means "return the regular object with
1766                                                                         // is_owned set to false", which is totally what we want
1767                                                                         // if we're about to set ty_has_inner.
1768                                                                         ptr_for_ref = true;
1769                                                                 }
1770                                                                 if let syn::Type::Reference(t) = elem {
1771                                                                         if let syn::Type::Path(p) = &*t.elem {
1772                                                                                 self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1773                                                                         } else { false }
1774                                                                 } else if let syn::Type::Path(p) = elem {
1775                                                                         self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics))
1776                                                                 } else { false }
1777                                                         };
1778                                                 if idx != 0 { write!(w, ", ").unwrap(); }
1779                                                 var_prefix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1780                                                 if is_ref && ty_has_inner {
1781                                                         // For ty_has_inner, the regular var_prefix mapping will take a
1782                                                         // reference, so deref once here to make sure we keep the original ref.
1783                                                         write!(w, "*").unwrap();
1784                                                 }
1785                                                 write!(w, "orig_{}_{}", ident, idx).unwrap();
1786                                                 if is_ref && !ty_has_inner {
1787                                                         // If we don't have an inner variable's reference to maintain, just
1788                                                         // hope the type is Clonable and use that.
1789                                                         write!(w, ".clone()").unwrap();
1790                                                 }
1791                                                 var_suffix(w, elem, generics, is_ref && ty_has_inner, ptr_for_ref, false);
1792                                         }
1793                                         write!(w, "){};", if to_c { ".into()" } else { "" }).unwrap();
1794                                         true
1795                                 } else { false }
1796                         },
1797                         _ => unimplemented!(),
1798                 }
1799         }
1800
1801         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 {
1802                 self.write_conversion_new_var_intern(w, ident, var_access, t, generics, false, ptr_for_ref, true,
1803                         &|a, b| self.to_c_conversion_new_var_from_path(a, b),
1804                         &|a, b, c, d, e| self.to_c_conversion_container_new_var(generics, a, b, c, d, e),
1805                         // We force ptr_for_ref here since we can't generate a ref on one line and use it later
1806                         &|a, b, c, d, e, f| self.write_to_c_conversion_inline_prefix_inner(a, b, c, d, e, f),
1807                         &|a, b, c, d, e, f| self.write_to_c_conversion_inline_suffix_inner(a, b, c, d, e, f))
1808         }
1809         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 {
1810                 self.write_to_c_conversion_new_var_inner(w, ident, &format!("{}", ident), t, generics, ptr_for_ref)
1811         }
1812         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 {
1813                 self.write_conversion_new_var_intern(w, ident, &format!("{}", ident), t, generics, false, false, false,
1814                         &|a, b| self.from_c_conversion_new_var_from_path(a, b),
1815                         &|a, b, c, d, e| self.from_c_conversion_container_new_var(generics, a, b, c, d, e),
1816                         // We force ptr_for_ref here since we can't generate a ref on one line and use it later
1817                         &|a, b, c, d, e, _f| self.write_from_c_conversion_prefix_inner(a, b, c, d, e),
1818                         &|a, b, c, d, e, _f| self.write_from_c_conversion_suffix_inner(a, b, c, d, e))
1819         }
1820
1821         // ******************************************************
1822         // *** C Container Type Equivalent and alias Printing ***
1823         // ******************************************************
1824
1825         fn write_template_generics<'b, W: std::io::Write>(&mut self, w: &mut W, args: &mut dyn Iterator<Item=&'b syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
1826                 assert!(!is_ref); // We don't currently support outer reference types
1827                 for (idx, t) in args.enumerate() {
1828                         if idx != 0 {
1829                                 write!(w, ", ").unwrap();
1830                         }
1831                         if let syn::Type::Reference(r_arg) = t {
1832                                 if !self.write_c_type_intern(w, &*r_arg.elem, generics, false, false, false) { return false; }
1833
1834                                 // While write_c_type_intern, above is correct, we don't want to blindly convert a
1835                                 // reference to something stupid, so check that the container is either opaque or a
1836                                 // predefined type (currently only Transaction).
1837                                 if let syn::Type::Path(p_arg) = &*r_arg.elem {
1838                                         let resolved = self.resolve_path(&p_arg.path, generics);
1839                                         assert!(self.crate_types.opaques.get(&resolved).is_some() ||
1840                                                         self.c_type_from_path(&resolved, true, true).is_some(), "Template generics should be opaque or have a predefined mapping");
1841                                 } else { unimplemented!(); }
1842                         } else {
1843                                 if !self.write_c_type_intern(w, t, generics, false, false, false) { return false; }
1844                         }
1845                 }
1846                 true
1847         }
1848         fn check_create_container(&mut self, mangled_container: String, container_type: &str, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
1849                 if !self.crate_types.templates_defined.get(&mangled_container).is_some() {
1850                         let mut created_container: Vec<u8> = Vec::new();
1851
1852                         if container_type == "Result" {
1853                                 let mut a_ty: Vec<u8> = Vec::new();
1854                                 if let syn::Type::Tuple(tup) = args.iter().next().unwrap() {
1855                                         if tup.elems.is_empty() {
1856                                                 write!(&mut a_ty, "()").unwrap();
1857                                         } else {
1858                                                 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
1859                                         }
1860                                 } else {
1861                                         if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
1862                                 }
1863
1864                                 let mut b_ty: Vec<u8> = Vec::new();
1865                                 if let syn::Type::Tuple(tup) = args.iter().skip(1).next().unwrap() {
1866                                         if tup.elems.is_empty() {
1867                                                 write!(&mut b_ty, "()").unwrap();
1868                                         } else {
1869                                                 if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
1870                                         }
1871                                 } else {
1872                                         if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
1873                                 }
1874
1875                                 let ok_str = String::from_utf8(a_ty).unwrap();
1876                                 let err_str = String::from_utf8(b_ty).unwrap();
1877                                 let is_clonable = self.is_clonable(&ok_str) && self.is_clonable(&err_str);
1878                                 write_result_block(&mut created_container, &mangled_container, &ok_str, &err_str, is_clonable);
1879                                 if is_clonable {
1880                                         self.crate_types.clonable_types.insert(Self::generated_container_path().to_owned() + "::" + &mangled_container);
1881                                 }
1882                         } else if container_type == "Vec" {
1883                                 let mut a_ty: Vec<u8> = Vec::new();
1884                                 if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
1885                                 let ty = String::from_utf8(a_ty).unwrap();
1886                                 let is_clonable = self.is_clonable(&ty);
1887                                 write_vec_block(&mut created_container, &mangled_container, &ty, is_clonable);
1888                                 if is_clonable {
1889                                         self.crate_types.clonable_types.insert(Self::generated_container_path().to_owned() + "::" + &mangled_container);
1890                                 }
1891                         } else if container_type.ends_with("Tuple") {
1892                                 let mut tuple_args = Vec::new();
1893                                 let mut is_clonable = true;
1894                                 for arg in args.iter() {
1895                                         let mut ty: Vec<u8> = Vec::new();
1896                                         if !self.write_template_generics(&mut ty, &mut [arg].iter().map(|t| **t), generics, is_ref) { return false; }
1897                                         let ty_str = String::from_utf8(ty).unwrap();
1898                                         if !self.is_clonable(&ty_str) {
1899                                                 is_clonable = false;
1900                                         }
1901                                         tuple_args.push(ty_str);
1902                                 }
1903                                 write_tuple_block(&mut created_container, &mangled_container, &tuple_args, is_clonable);
1904                                 if is_clonable {
1905                                         self.crate_types.clonable_types.insert(Self::generated_container_path().to_owned() + "::" + &mangled_container);
1906                                 }
1907                         } else {
1908                                 unreachable!();
1909                         }
1910                         self.crate_types.templates_defined.insert(mangled_container.clone(), true);
1911
1912                         self.crate_types.template_file.write(&created_container).unwrap();
1913                 }
1914                 true
1915         }
1916         fn path_to_generic_args(path: &syn::Path) -> Vec<&syn::Type> {
1917                 if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().next().unwrap().arguments {
1918                         args.args.iter().map(|gen| if let syn::GenericArgument::Type(t) = gen { t } else { unimplemented!() }).collect()
1919                 } else { unimplemented!(); }
1920         }
1921         fn write_c_mangled_container_path_intern<W: std::io::Write>
1922                         (&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 {
1923                 let mut mangled_type: Vec<u8> = Vec::new();
1924                 if !self.is_transparent_container(ident, is_ref) {
1925                         write!(w, "C{}_", ident).unwrap();
1926                         write!(mangled_type, "C{}_", ident).unwrap();
1927                 } else { assert_eq!(args.len(), 1); }
1928                 for arg in args.iter() {
1929                         macro_rules! write_path {
1930                                 ($p_arg: expr, $extra_write: expr) => {
1931                                         if let Some(subtype) = self.maybe_resolve_path(&$p_arg.path, generics) {
1932                                                 if self.is_transparent_container(ident, is_ref) {
1933                                                         // We dont (yet) support primitives or containers inside transparent
1934                                                         // containers, so check for that first:
1935                                                         if self.is_primitive(&subtype) { return false; }
1936                                                         if self.is_known_container(&subtype, is_ref) { return false; }
1937                                                         if !in_type {
1938                                                                 if self.c_type_has_inner_from_path(&subtype) {
1939                                                                         if !self.write_c_path_intern(w, &$p_arg.path, generics, is_ref, is_mut, ptr_for_ref) { return false; }
1940                                                                 } else {
1941                                                                         // Option<T> needs to be converted to a *mut T, ie mut ptr-for-ref
1942                                                                         if !self.write_c_path_intern(w, &$p_arg.path, generics, true, true, true) { return false; }
1943                                                                 }
1944                                                         } else {
1945                                                                 if $p_arg.path.segments.len() == 1 {
1946                                                                         write!(w, "{}", $p_arg.path.segments.iter().next().unwrap().ident).unwrap();
1947                                                                 } else {
1948                                                                         return false;
1949                                                                 }
1950                                                         }
1951                                                 } else if self.is_known_container(&subtype, is_ref) || self.is_transparent_container(&subtype, is_ref) {
1952                                                         if !self.write_c_mangled_container_path_intern(w, Self::path_to_generic_args(&$p_arg.path), generics,
1953                                                                         &subtype, is_ref, is_mut, ptr_for_ref, true) {
1954                                                                 return false;
1955                                                         }
1956                                                         self.write_c_mangled_container_path_intern(&mut mangled_type, Self::path_to_generic_args(&$p_arg.path),
1957                                                                 generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
1958                                                         if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
1959                                                                 self.write_c_mangled_container_path_intern(w2, Self::path_to_generic_args(&$p_arg.path),
1960                                                                         generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
1961                                                         }
1962                                                 } else {
1963                                                         let id = subtype.rsplitn(2, ':').next().unwrap(); // Get the "Base" name of the resolved type
1964                                                         write!(w, "{}", id).unwrap();
1965                                                         write!(mangled_type, "{}", id).unwrap();
1966                                                         if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
1967                                                                 write!(w2, "{}", id).unwrap();
1968                                                         }
1969                                                 }
1970                                         } else { return false; }
1971                                 }
1972                         }
1973                         if let syn::Type::Tuple(tuple) = arg {
1974                                 if tuple.elems.len() == 0 {
1975                                         write!(w, "None").unwrap();
1976                                         write!(mangled_type, "None").unwrap();
1977                                 } else {
1978                                         let mut mangled_tuple_type: Vec<u8> = Vec::new();
1979
1980                                         // Figure out what the mangled type should look like. To disambiguate
1981                                         // ((A, B), C) and (A, B, C) we prefix the generic args with a _ and suffix
1982                                         // them with a Z. Ideally we wouldn't use Z, but not many special chars are
1983                                         // available for use in type names.
1984                                         write!(w, "C{}Tuple_", tuple.elems.len()).unwrap();
1985                                         write!(mangled_type, "C{}Tuple_", tuple.elems.len()).unwrap();
1986                                         write!(mangled_tuple_type, "C{}Tuple_", tuple.elems.len()).unwrap();
1987                                         for elem in tuple.elems.iter() {
1988                                                 if let syn::Type::Path(p) = elem {
1989                                                         write_path!(p, Some(&mut mangled_tuple_type));
1990                                                 } else if let syn::Type::Reference(refelem) = elem {
1991                                                         if let syn::Type::Path(p) = &*refelem.elem {
1992                                                                 write_path!(p, Some(&mut mangled_tuple_type));
1993                                                         } else { return false; }
1994                                                 } else { return false; }
1995                                         }
1996                                         write!(w, "Z").unwrap();
1997                                         write!(mangled_type, "Z").unwrap();
1998                                         write!(mangled_tuple_type, "Z").unwrap();
1999                                         if !self.check_create_container(String::from_utf8(mangled_tuple_type).unwrap(),
2000                                                         &format!("{}Tuple", tuple.elems.len()), tuple.elems.iter().collect(), generics, is_ref) {
2001                                                 return false;
2002                                         }
2003                                 }
2004                         } else if let syn::Type::Path(p_arg) = arg {
2005                                 write_path!(p_arg, None);
2006                         } else if let syn::Type::Reference(refty) = arg {
2007                                 if let syn::Type::Path(p_arg) = &*refty.elem {
2008                                         write_path!(p_arg, None);
2009                                 } else if let syn::Type::Slice(_) = &*refty.elem {
2010                                         // write_c_type will actually do exactly what we want here, we just need to
2011                                         // make it a pointer so that its an option. Note that we cannot always convert
2012                                         // the Vec-as-slice (ie non-ref types) containers, so sometimes need to be able
2013                                         // to edit it, hence we use *mut here instead of *const.
2014                                         if args.len() != 1 { return false; }
2015                                         write!(w, "*mut ").unwrap();
2016                                         self.write_c_type(w, arg, None, true);
2017                                 } else { return false; }
2018                         } else if let syn::Type::Array(a) = arg {
2019                                 if let syn::Type::Path(p_arg) = &*a.elem {
2020                                         let resolved = self.resolve_path(&p_arg.path, generics);
2021                                         if !self.is_primitive(&resolved) { return false; }
2022                                         if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(len), .. }) = &a.len {
2023                                                 if self.c_type_from_path(&format!("[{}; {}]", resolved, len.base10_digits()), is_ref, ptr_for_ref).is_none() { return false; }
2024                                                 write!(w, "_{}{}", resolved, len.base10_digits()).unwrap();
2025                                                 write!(mangled_type, "_{}{}", resolved, len.base10_digits()).unwrap();
2026                                         } else { return false; }
2027                                 } else { return false; }
2028                         } else { return false; }
2029                 }
2030                 if self.is_transparent_container(ident, is_ref) { return true; }
2031                 // Push the "end of type" Z
2032                 write!(w, "Z").unwrap();
2033                 write!(mangled_type, "Z").unwrap();
2034
2035                 // Make sure the type is actually defined:
2036                 self.check_create_container(String::from_utf8(mangled_type).unwrap(), ident, args, generics, is_ref)
2037         }
2038         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 {
2039                 if !self.is_transparent_container(ident, is_ref) {
2040                         write!(w, "{}::", Self::generated_container_path()).unwrap();
2041                 }
2042                 self.write_c_mangled_container_path_intern(w, args, generics, ident, is_ref, is_mut, ptr_for_ref, false)
2043         }
2044
2045         // **********************************
2046         // *** C Type Equivalent Printing ***
2047         // **********************************
2048
2049         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 {
2050                 let full_path = match self.maybe_resolve_path(&path, generics) {
2051                         Some(path) => path, None => return false };
2052                 if let Some(c_type) = self.c_type_from_path(&full_path, is_ref, ptr_for_ref) {
2053                         write!(w, "{}", c_type).unwrap();
2054                         true
2055                 } else if self.crate_types.traits.get(&full_path).is_some() {
2056                         if is_ref && ptr_for_ref {
2057                                 write!(w, "*{} crate::{}", if is_mut { "mut" } else { "const" }, full_path).unwrap();
2058                         } else if is_ref {
2059                                 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2060                         } else {
2061                                 write!(w, "crate::{}", full_path).unwrap();
2062                         }
2063                         true
2064                 } else if self.crate_types.opaques.get(&full_path).is_some() || self.crate_types.mirrored_enums.get(&full_path).is_some() {
2065                         if is_ref && ptr_for_ref {
2066                                 // ptr_for_ref implies we're returning the object, which we can't really do for
2067                                 // opaque or mirrored types without box'ing them, which is quite a waste, so return
2068                                 // the actual object itself (for opaque types we'll set the pointer to the actual
2069                                 // type and note that its a reference).
2070                                 write!(w, "crate::{}", full_path).unwrap();
2071                         } else if is_ref {
2072                                 write!(w, "&{}crate::{}", if is_mut { "mut " } else { "" }, full_path).unwrap();
2073                         } else {
2074                                 write!(w, "crate::{}", full_path).unwrap();
2075                         }
2076                         true
2077                 } else {
2078                         false
2079                 }
2080         }
2081         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 {
2082                 match t {
2083                         syn::Type::Path(p) => {
2084                                 if p.qself.is_some() {
2085                                         return false;
2086                                 }
2087                                 if let Some(full_path) = self.maybe_resolve_path(&p.path, generics) {
2088                                         if self.is_known_container(&full_path, is_ref) || self.is_transparent_container(&full_path, is_ref) {
2089                                                 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);
2090                                         }
2091                                         if let Some(aliased_type) = self.crate_types.type_aliases.get(&full_path).cloned() {
2092                                                 return self.write_c_type_intern(w, &aliased_type, None, is_ref, is_mut, ptr_for_ref);
2093                                         }
2094                                 }
2095                                 self.write_c_path_intern(w, &p.path, generics, is_ref, is_mut, ptr_for_ref)
2096                         },
2097                         syn::Type::Reference(r) => {
2098                                 self.write_c_type_intern(w, &*r.elem, generics, true, r.mutability.is_some(), ptr_for_ref)
2099                         },
2100                         syn::Type::Array(a) => {
2101                                 if is_ref && is_mut {
2102                                         write!(w, "*mut [").unwrap();
2103                                         if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2104                                 } else if is_ref {
2105                                         write!(w, "*const [").unwrap();
2106                                         if !self.write_c_type_intern(w, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2107                                 } else {
2108                                         let mut typecheck = Vec::new();
2109                                         if !self.write_c_type_intern(&mut typecheck, &a.elem, generics, false, false, ptr_for_ref) { return false; }
2110                                         if typecheck[..] != ['u' as u8, '8' as u8] { return false; }
2111                                 }
2112                                 if let syn::Expr::Lit(l) = &a.len {
2113                                         if let syn::Lit::Int(i) = &l.lit {
2114                                                 if !is_ref {
2115                                                         if let Some(ty) = self.c_type_from_path(&format!("[u8; {}]", i.base10_digits()), false, ptr_for_ref) {
2116                                                                 write!(w, "{}", ty).unwrap();
2117                                                                 true
2118                                                         } else { false }
2119                                                 } else {
2120                                                         write!(w, "; {}]", i).unwrap();
2121                                                         true
2122                                                 }
2123                                         } else { false }
2124                                 } else { false }
2125                         }
2126                         syn::Type::Slice(s) => {
2127                                 if !is_ref || is_mut { return false; }
2128                                 if let syn::Type::Path(p) = &*s.elem {
2129                                         let resolved = self.resolve_path(&p.path, generics);
2130                                         if self.is_primitive(&resolved) {
2131                                                 write!(w, "{}::{}slice", Self::container_templ_path(), resolved).unwrap();
2132                                                 true
2133                                         } else { false }
2134                                 } else if let syn::Type::Reference(r) = &*s.elem {
2135                                         if let syn::Type::Path(p) = &*r.elem {
2136                                                 // Slices with "real types" inside are mapped as the equivalent non-ref Vec
2137                                                 let resolved = self.resolve_path(&p.path, generics);
2138                                                 let mangled_container = if let Some(ident) = self.crate_types.opaques.get(&resolved) {
2139                                                         format!("CVec_{}Z", ident)
2140                                                 } else if let Some(en) = self.crate_types.mirrored_enums.get(&resolved) {
2141                                                         format!("CVec_{}Z", en.ident)
2142                                                 } else if let Some(id) = p.path.get_ident() {
2143                                                         format!("CVec_{}Z", id)
2144                                                 } else { return false; };
2145                                                 write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
2146                                                 self.check_create_container(mangled_container, "Vec", vec![&*r.elem], generics, false)
2147                                         } else { false }
2148                                 } else if let syn::Type::Tuple(_) = &*s.elem {
2149                                         let mut args = syn::punctuated::Punctuated::new();
2150                                         args.push(syn::GenericArgument::Type((*s.elem).clone()));
2151                                         let mut segments = syn::punctuated::Punctuated::new();
2152                                         segments.push(syn::PathSegment {
2153                                                 ident: syn::Ident::new("Vec", Span::call_site()),
2154                                                 arguments: syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
2155                                                         colon2_token: None, lt_token: syn::Token![<](Span::call_site()), args, gt_token: syn::Token![>](Span::call_site()),
2156                                                 })
2157                                         });
2158                                         self.write_c_type_intern(w, &syn::Type::Path(syn::TypePath { qself: None, path: syn::Path { leading_colon: None, segments } }), generics, false, is_mut, ptr_for_ref)
2159                                 } else { false }
2160                         },
2161                         syn::Type::Tuple(t) => {
2162                                 if t.elems.len() == 0 {
2163                                         true
2164                                 } else {
2165                                         self.write_c_mangled_container_path(w, t.elems.iter().collect(), generics,
2166                                                 &format!("{}Tuple", t.elems.len()), is_ref, is_mut, ptr_for_ref)
2167                                 }
2168                         },
2169                         _ => false,
2170                 }
2171         }
2172         pub fn write_c_type<W: std::io::Write>(&mut self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, ptr_for_ref: bool) {
2173                 assert!(self.write_c_type_intern(w, t, generics, false, false, ptr_for_ref));
2174         }
2175         pub fn understood_c_path(&mut self, p: &syn::Path) -> bool {
2176                 if p.leading_colon.is_some() { return false; }
2177                 self.write_c_path_intern(&mut std::io::sink(), p, None, false, false, false)
2178         }
2179         pub fn understood_c_type(&mut self, t: &syn::Type, generics: Option<&GenericTypes>) -> bool {
2180                 self.write_c_type_intern(&mut std::io::sink(), t, generics, false, false, false)
2181         }
2182 }