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