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