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