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