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