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