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