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