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