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