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