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