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