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