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