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