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