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