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