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