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