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