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