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