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