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