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