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