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