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