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