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