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