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