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