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