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