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