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