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