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