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