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