Merge pull request #4 from TheBlueMatt/main
[ldk-c-bindings] / c-bindings-gen / src / blocks.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE>
5 // or the MIT license <LICENSE-MIT>, at your option.
6 // You may not use this file except in accordance with one or both of these
7 // licenses.
8
9 //! Printing logic for basic blocks of Rust-mapped code - parts of functions and declarations but
10 //! not the full mapping logic.
11
12 use std::fs::File;
13 use std::io::Write;
14 use proc_macro2::{TokenTree, Span};
15
16 use crate::types::*;
17
18 /// Writes out a C++ wrapper class for the given type, which contains various utilities to access
19 /// the underlying C-mapped type safely avoiding some common memory management issues by handling
20 /// resource-freeing and prevending accidental raw copies.
21 pub fn write_cpp_wrapper(cpp_header_file: &mut File, ty: &str, has_destructor: bool) {
22         writeln!(cpp_header_file, "class {} {{", ty).unwrap();
23         writeln!(cpp_header_file, "private:").unwrap();
24         writeln!(cpp_header_file, "\tLDK{} self;", ty).unwrap();
25         writeln!(cpp_header_file, "public:").unwrap();
26         writeln!(cpp_header_file, "\t{}(const {}&) = delete;", ty, ty).unwrap();
27         writeln!(cpp_header_file, "\t{}({}&& o) : self(o.self) {{ memset(&o, 0, sizeof({})); }}", ty, ty, ty).unwrap();
28         writeln!(cpp_header_file, "\t{}(LDK{}&& m_self) : self(m_self) {{ memset(&m_self, 0, sizeof(LDK{})); }}", ty, ty, ty).unwrap();
29         writeln!(cpp_header_file, "\toperator LDK{}() && {{ LDK{} res = self; memset(&self, 0, sizeof(LDK{})); return res; }}", ty, ty, ty).unwrap();
30         if has_destructor {
31                 writeln!(cpp_header_file, "\t~{}() {{ {}_free(self); }}", ty, ty).unwrap();
32                 writeln!(cpp_header_file, "\t{}& operator=({}&& o) {{ {}_free(self); self = o.self; memset(&o, 0, sizeof({})); return *this; }}", ty, ty, ty, ty).unwrap();
33         } else {
34                 writeln!(cpp_header_file, "\t{}& operator=({}&& o) {{ self = o.self; memset(&o, 0, sizeof({})); return *this; }}", ty, ty, ty).unwrap();
35         }
36         writeln!(cpp_header_file, "\tLDK{}* operator &() {{ return &self; }}", ty).unwrap();
37         writeln!(cpp_header_file, "\tLDK{}* operator ->() {{ return &self; }}", ty).unwrap();
38         writeln!(cpp_header_file, "\tconst LDK{}* operator &() const {{ return &self; }}", ty).unwrap();
39         writeln!(cpp_header_file, "\tconst LDK{}* operator ->() const {{ return &self; }}", ty).unwrap();
40         writeln!(cpp_header_file, "}};").unwrap();
41 }
42
43 /// Writes out a C-callable concrete Result<A, B> struct and utility methods
44 pub fn write_result_block<W: std::io::Write>(w: &mut W, mangled_container: &str, ok_type: &str, err_type: &str, clonable: bool) {
45         writeln!(w, "#[repr(C)]").unwrap();
46         writeln!(w, "pub union {}Ptr {{", mangled_container).unwrap();
47         if ok_type != "()" {
48                 writeln!(w, "\tpub result: *mut {},", ok_type).unwrap();
49         } else {
50                 writeln!(w, "\t/// Note that this value is always NULL, as there are no contents in the OK variant").unwrap();
51                 writeln!(w, "\tpub result: *mut std::ffi::c_void,").unwrap();
52         }
53         if err_type != "()" {
54                 writeln!(w, "\tpub err: *mut {},", err_type).unwrap();
55         } else {
56                 writeln!(w, "\t/// Note that this value is always NULL, as there are no contents in the Err variant").unwrap();
57                 writeln!(w, "\tpub err: *mut std::ffi::c_void,").unwrap();
58         }
59         writeln!(w, "}}").unwrap();
60         writeln!(w, "#[repr(C)]").unwrap();
61         writeln!(w, "pub struct {} {{", mangled_container).unwrap();
62         writeln!(w, "\tpub contents: {}Ptr,", mangled_container).unwrap();
63         writeln!(w, "\tpub result_ok: bool,").unwrap();
64         writeln!(w, "}}").unwrap();
65
66         writeln!(w, "#[no_mangle]").unwrap();
67         if ok_type != "()" {
68                 writeln!(w, "pub extern \"C\" fn {}_ok(o: {}) -> {} {{", mangled_container, ok_type, mangled_container).unwrap();
69         } else {
70                 writeln!(w, "pub extern \"C\" fn {}_ok() -> {} {{", mangled_container, mangled_container).unwrap();
71         }
72         writeln!(w, "\t{} {{", mangled_container).unwrap();
73         writeln!(w, "\t\tcontents: {}Ptr {{", mangled_container).unwrap();
74         if ok_type != "()" {
75                 writeln!(w, "\t\t\tresult: Box::into_raw(Box::new(o)),").unwrap();
76         } else {
77                 writeln!(w, "\t\t\tresult: std::ptr::null_mut(),").unwrap();
78         }
79         writeln!(w, "\t\t}},").unwrap();
80         writeln!(w, "\t\tresult_ok: true,").unwrap();
81         writeln!(w, "\t}}").unwrap();
82         writeln!(w, "}}").unwrap();
83
84         writeln!(w, "#[no_mangle]").unwrap();
85         if err_type != "()" {
86                 writeln!(w, "pub extern \"C\" fn {}_err(e: {}) -> {} {{", mangled_container, err_type, mangled_container).unwrap();
87         } else {
88                 writeln!(w, "pub extern \"C\" fn {}_err() -> {} {{", mangled_container, mangled_container).unwrap();
89         }
90         writeln!(w, "\t{} {{", mangled_container).unwrap();
91         writeln!(w, "\t\tcontents: {}Ptr {{", mangled_container).unwrap();
92         if err_type != "()" {
93                 writeln!(w, "\t\t\terr: Box::into_raw(Box::new(e)),").unwrap();
94         } else {
95                 writeln!(w, "\t\t\terr: std::ptr::null_mut(),").unwrap();
96         }
97         writeln!(w, "\t\t}},").unwrap();
98         writeln!(w, "\t\tresult_ok: false,").unwrap();
99         writeln!(w, "\t}}").unwrap();
100         writeln!(w, "}}").unwrap();
101
102         writeln!(w, "#[no_mangle]").unwrap();
103         writeln!(w, "pub extern \"C\" fn {}_free(_res: {}) {{ }}", mangled_container, mangled_container).unwrap();
104         writeln!(w, "impl Drop for {} {{", mangled_container).unwrap();
105         writeln!(w, "\tfn drop(&mut self) {{").unwrap();
106         writeln!(w, "\t\tif self.result_ok {{").unwrap();
107         if ok_type != "()" {
108                 writeln!(w, "\t\t\tif unsafe {{ !(self.contents.result as *mut ()).is_null() }} {{").unwrap();
109                 writeln!(w, "\t\t\t\tlet _ = unsafe {{ Box::from_raw(self.contents.result) }};").unwrap();
110                 writeln!(w, "\t\t\t}}").unwrap();
111         }
112         writeln!(w, "\t\t}} else {{").unwrap();
113         if err_type != "()" {
114                 writeln!(w, "\t\t\tif unsafe {{ !(self.contents.err as *mut ()).is_null() }} {{").unwrap();
115                 writeln!(w, "\t\t\t\tlet _ = unsafe {{ Box::from_raw(self.contents.err) }};").unwrap();
116                 writeln!(w, "\t\t\t}}").unwrap();
117         }
118         writeln!(w, "\t\t}}").unwrap();
119         writeln!(w, "\t}}").unwrap();
120         writeln!(w, "}}").unwrap();
121
122         // TODO: Templates should use () now that they can, too
123         let templ_ok_type = if ok_type != "()" { ok_type } else { "u8" };
124         let templ_err_type = if err_type != "()" { err_type } else { "u8" };
125
126         writeln!(w, "impl From<crate::c_types::CResultTempl<{}, {}>> for {} {{", templ_ok_type, templ_err_type, mangled_container).unwrap();
127         writeln!(w, "\tfn from(mut o: crate::c_types::CResultTempl<{}, {}>) -> Self {{", templ_ok_type, templ_err_type).unwrap();
128         writeln!(w, "\t\tlet contents = if o.result_ok {{").unwrap();
129         if ok_type != "()" {
130                 writeln!(w, "\t\t\tlet result = unsafe {{ o.contents.result }};").unwrap();
131                 writeln!(w, "\t\t\tunsafe {{ o.contents.result = std::ptr::null_mut() }};").unwrap();
132                 writeln!(w, "\t\t\t{}Ptr {{ result }}", mangled_container).unwrap();
133         } else {
134                 writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(o.contents.result) }};").unwrap();
135                 writeln!(w, "\t\t\to.contents.result = std::ptr::null_mut();").unwrap();
136                 writeln!(w, "\t\t\t{}Ptr {{ result: std::ptr::null_mut() }}", mangled_container).unwrap();
137         }
138         writeln!(w, "\t\t}} else {{").unwrap();
139         if err_type != "()" {
140                 writeln!(w, "\t\t\tlet err = unsafe {{ o.contents.err }};").unwrap();
141                 writeln!(w, "\t\t\tunsafe {{ o.contents.err = std::ptr::null_mut(); }}").unwrap();
142                 writeln!(w, "\t\t\t{}Ptr {{ err }}", mangled_container).unwrap();
143         } else {
144                 writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(o.contents.err) }};").unwrap();
145                 writeln!(w, "\t\t\to.contents.err = std::ptr::null_mut();").unwrap();
146                 writeln!(w, "\t\t\t{}Ptr {{ err: std::ptr::null_mut() }}", mangled_container).unwrap();
147         }
148         writeln!(w, "\t\t}};").unwrap();
149         writeln!(w, "\t\tSelf {{").unwrap();
150         writeln!(w, "\t\t\tcontents,").unwrap();
151         writeln!(w, "\t\t\tresult_ok: o.result_ok,").unwrap();
152         writeln!(w, "\t\t}}").unwrap();
153         writeln!(w, "\t}}").unwrap();
154         writeln!(w, "}}").unwrap();
155
156         if clonable {
157                 writeln!(w, "impl Clone for {} {{", mangled_container).unwrap();
158                 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
159                 writeln!(w, "\t\tif self.result_ok {{").unwrap();
160                 writeln!(w, "\t\t\tSelf {{ result_ok: true, contents: {}Ptr {{", mangled_container).unwrap();
161                 if ok_type != "()" {
162                         writeln!(w, "\t\t\t\tresult: Box::into_raw(Box::new(<{}>::clone(unsafe {{ &*self.contents.result }})))", ok_type).unwrap();
163                 } else {
164                         writeln!(w, "\t\t\t\tresult: std::ptr::null_mut()").unwrap();
165                 }
166                 writeln!(w, "\t\t\t}} }}").unwrap();
167                 writeln!(w, "\t\t}} else {{").unwrap();
168                 writeln!(w, "\t\t\tSelf {{ result_ok: false, contents: {}Ptr {{", mangled_container).unwrap();
169                 if err_type != "()" {
170                         writeln!(w, "\t\t\t\terr: Box::into_raw(Box::new(<{}>::clone(unsafe {{ &*self.contents.err }})))", err_type).unwrap();
171                 } else {
172                         writeln!(w, "\t\t\t\terr: std::ptr::null_mut()").unwrap();
173                 }
174                 writeln!(w, "\t\t\t}} }}").unwrap();
175                 writeln!(w, "\t\t}}").unwrap();
176                 writeln!(w, "\t}}").unwrap();
177                 writeln!(w, "}}").unwrap();
178                 writeln!(w, "#[no_mangle]").unwrap();
179                 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{ orig.clone() }}", mangled_container, mangled_container, mangled_container).unwrap();
180         }
181 }
182
183 /// Writes out a C-callable concrete Vec<A> struct and utility methods
184 pub fn write_vec_block<W: std::io::Write>(w: &mut W, mangled_container: &str, inner_type: &str, clonable: bool) {
185         writeln!(w, "#[repr(C)]").unwrap();
186         writeln!(w, "pub struct {} {{", mangled_container).unwrap();
187         writeln!(w, "\tpub data: *mut {},", inner_type).unwrap();
188         writeln!(w, "\tpub datalen: usize").unwrap();
189         writeln!(w, "}}").unwrap();
190
191         writeln!(w, "impl {} {{", mangled_container).unwrap();
192         writeln!(w, "\t#[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<{}> {{", inner_type).unwrap();
193         writeln!(w, "\t\tif self.datalen == 0 {{ return Vec::new(); }}").unwrap();
194         writeln!(w, "\t\tlet ret = unsafe {{ Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }}.into();").unwrap();
195         writeln!(w, "\t\tself.data = std::ptr::null_mut();").unwrap();
196         writeln!(w, "\t\tself.datalen = 0;").unwrap();
197         writeln!(w, "\t\tret").unwrap();
198         writeln!(w, "\t}}").unwrap();
199         writeln!(w, "\t#[allow(unused)] pub(crate) fn as_slice(&self) -> &[{}] {{", inner_type).unwrap();
200         writeln!(w, "\t\tunsafe {{ std::slice::from_raw_parts_mut(self.data, self.datalen) }}").unwrap();
201         writeln!(w, "\t}}").unwrap();
202         writeln!(w, "}}").unwrap();
203
204         writeln!(w, "impl From<Vec<{}>> for {} {{", inner_type, mangled_container).unwrap();
205         writeln!(w, "\tfn from(v: Vec<{}>) -> Self {{", inner_type).unwrap();
206         writeln!(w, "\t\tlet datalen = v.len();").unwrap();
207         writeln!(w, "\t\tlet data = Box::into_raw(v.into_boxed_slice());").unwrap();
208         writeln!(w, "\t\tSelf {{ datalen, data: unsafe {{ (*data).as_mut_ptr() }} }}").unwrap();
209         writeln!(w, "\t}}").unwrap();
210         writeln!(w, "}}").unwrap();
211
212         writeln!(w, "#[no_mangle]").unwrap();
213         writeln!(w, "pub extern \"C\" fn {}_free(_res: {}) {{ }}", mangled_container, mangled_container).unwrap();
214         writeln!(w, "impl Drop for {} {{", mangled_container).unwrap();
215         writeln!(w, "\tfn drop(&mut self) {{").unwrap();
216         writeln!(w, "\t\tif self.datalen == 0 {{ return; }}").unwrap();
217         writeln!(w, "\t\tunsafe {{ Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }};").unwrap();
218         writeln!(w, "\t}}").unwrap();
219         writeln!(w, "}}").unwrap();
220         if clonable {
221                 writeln!(w, "impl Clone for {} {{", mangled_container).unwrap();
222                 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
223                 writeln!(w, "\t\tlet mut res = Vec::new();").unwrap();
224                 writeln!(w, "\t\tif self.datalen == 0 {{ return Self::from(res); }}").unwrap();
225                 writeln!(w, "\t\tres.extend_from_slice(unsafe {{ std::slice::from_raw_parts_mut(self.data, self.datalen) }});").unwrap();
226                 writeln!(w, "\t\tSelf::from(res)").unwrap();
227                 writeln!(w, "\t}}").unwrap();
228                 writeln!(w, "}}").unwrap();
229         }
230 }
231
232 /// Writes out a C-callable concrete (A, B, ...) struct and utility methods
233 pub fn write_tuple_block<W: std::io::Write>(w: &mut W, mangled_container: &str, types: &[String], clonable: bool) {
234         writeln!(w, "#[repr(C)]").unwrap();
235         writeln!(w, "pub struct {} {{", mangled_container).unwrap();
236         for (idx, ty) in types.iter().enumerate() {
237                 writeln!(w, "\tpub {}: {},", ('a' as u8 + idx as u8) as char, ty).unwrap();
238         }
239         writeln!(w, "}}").unwrap();
240
241         let mut tuple_str = "(".to_owned();
242         for (idx, ty) in types.iter().enumerate() {
243                 if idx != 0 { tuple_str += ", "; }
244                 tuple_str += ty;
245         }
246         tuple_str += ")";
247
248         writeln!(w, "impl From<{}> for {} {{", tuple_str, mangled_container).unwrap();
249         writeln!(w, "\tfn from (tup: {}) -> Self {{", tuple_str).unwrap();
250         writeln!(w, "\t\tSelf {{").unwrap();
251         for idx in 0..types.len() {
252                 writeln!(w, "\t\t\t{}: tup.{},", ('a' as u8 + idx as u8) as char, idx).unwrap();
253         }
254         writeln!(w, "\t\t}}").unwrap();
255         writeln!(w, "\t}}").unwrap();
256         writeln!(w, "}}").unwrap();
257         writeln!(w, "impl {} {{", mangled_container).unwrap();
258         writeln!(w, "\t#[allow(unused)] pub(crate) fn to_rust(mut self) -> {} {{", tuple_str).unwrap();
259         write!(w, "\t\t(").unwrap();
260         for idx in 0..types.len() {
261                 write!(w, "{}self.{}", if idx != 0 {", "} else {""}, ('a' as u8 + idx as u8) as char).unwrap();
262         }
263         writeln!(w, ")").unwrap();
264         writeln!(w, "\t}}").unwrap();
265         writeln!(w, "}}").unwrap();
266
267         if clonable {
268                 writeln!(w, "impl Clone for {} {{", mangled_container).unwrap();
269                 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
270                 writeln!(w, "\t\tSelf {{").unwrap();
271                 for idx in 0..types.len() {
272                         writeln!(w, "\t\t\t{}: self.{}.clone(),", ('a' as u8 + idx as u8) as char, ('a' as u8 + idx as u8) as char).unwrap();
273                 }
274                 writeln!(w, "\t\t}}").unwrap();
275                 writeln!(w, "\t}}").unwrap();
276                 writeln!(w, "}}").unwrap();
277                 writeln!(w, "#[no_mangle]").unwrap();
278                 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{ orig.clone() }}", mangled_container, mangled_container, mangled_container).unwrap();
279         }
280
281         write!(w, "#[no_mangle]\npub extern \"C\" fn {}_new(", mangled_container).unwrap();
282         for (idx, gen) in types.iter().enumerate() {
283                 write!(w, "{}{}: ", if idx != 0 { ", " } else { "" }, ('a' as u8 + idx as u8) as char).unwrap();
284                 //if !self.write_c_type_intern(&mut created_container, gen, generics, false, false, false) { return false; }
285                 write!(w, "{}", gen).unwrap();
286         }
287         writeln!(w, ") -> {} {{", mangled_container).unwrap();
288         write!(w, "\t{} {{ ", mangled_container).unwrap();
289         for idx in 0..types.len() {
290                 write!(w, "{}, ", ('a' as u8 + idx as u8) as char).unwrap();
291         }
292         writeln!(w, "}}\n}}\n").unwrap();
293
294         writeln!(w, "#[no_mangle]").unwrap();
295         writeln!(w, "pub extern \"C\" fn {}_free(_res: {}) {{ }}", mangled_container, mangled_container).unwrap();
296 }
297
298 /// Prints the docs from a given attribute list unless its tagged no export
299 pub fn writeln_docs<W: std::io::Write>(w: &mut W, attrs: &[syn::Attribute], prefix: &str) {
300         for attr in attrs.iter() {
301                 let tokens_clone = attr.tokens.clone();
302                 let mut token_iter = tokens_clone.into_iter();
303                 if let Some(token) = token_iter.next() {
304                         match token {
305                                 TokenTree::Punct(c) if c.as_char() == '=' => {
306                                         // syn gets '=' from '///' or '//!' as it is syntax for #[doc = ""]
307                                 },
308                                 TokenTree::Group(_) => continue, // eg #[derive()]
309                                 _ => unimplemented!(),
310                         }
311                 } else { continue; }
312                 match attr.style {
313                         syn::AttrStyle::Inner(_) => {
314                                 match token_iter.next().unwrap() {
315                                         TokenTree::Literal(lit) => {
316                                                 // Drop the first and last chars from lit as they are always "
317                                                 let doc = format!("{}", lit);
318                                                 writeln!(w, "{}//!{}", prefix, &doc[1..doc.len() - 1]).unwrap();
319                                         },
320                                         _ => unimplemented!(),
321                                 }
322                         },
323                         syn::AttrStyle::Outer => {
324                                 match token_iter.next().unwrap() {
325                                         TokenTree::Literal(lit) => {
326                                                 // Drop the first and last chars from lit as they are always "
327                                                 let doc = format!("{}", lit);
328                                                 writeln!(w, "{}///{}", prefix, &doc[1..doc.len() - 1]).unwrap();
329                                         },
330                                         _ => unimplemented!(),
331                                 }
332                         },
333                 }
334         }
335 }
336
337 /// Print the parameters in a method declaration, starting after the open parenthesis, through and
338 /// including the closing parenthesis and return value, but not including the open bracket or any
339 /// trailing semicolons.
340 ///
341 /// Usable both for a function definition and declaration.
342 ///
343 /// this_param is used when returning Self or accepting a self parameter, and should be the
344 /// concrete, mapped type.
345 pub fn write_method_params<W: std::io::Write>(w: &mut W, sig: &syn::Signature, this_param: &str, types: &mut TypeResolver, generics: Option<&GenericTypes>, self_ptr: bool, fn_decl: bool) {
346         if sig.constness.is_some() || sig.asyncness.is_some() || sig.unsafety.is_some() ||
347                         sig.abi.is_some() || sig.variadic.is_some() {
348                 unimplemented!();
349         }
350         if sig.generics.lt_token.is_some() {
351                 for generic in sig.generics.params.iter() {
352                         match generic {
353                                 syn::GenericParam::Type(_)|syn::GenericParam::Lifetime(_) => {
354                                         // We ignore these, if they're not on skipped args, we'll blow up
355                                         // later, and lifetimes we just hope the C client enforces.
356                                 },
357                                 _ => unimplemented!(),
358                         }
359                 }
360         }
361
362         let mut first_arg = true;
363         let mut num_unused = 0;
364         for inp in sig.inputs.iter() {
365                 match inp {
366                         syn::FnArg::Receiver(recv) => {
367                                 if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
368                                 write!(w, "this_arg: {}{}",
369                                         match (self_ptr, recv.mutability.is_some()) {
370                                                 (true, true) => "*mut ",
371                                                 (true, false) => "*const ",
372                                                 (false, true) => "&mut ",
373                                                 (false, false) => "&",
374                                         }, this_param).unwrap();
375                                 assert!(first_arg);
376                                 first_arg = false;
377                         },
378                         syn::FnArg::Typed(arg) => {
379                                 if types.skip_arg(&*arg.ty, generics) { continue; }
380                                 if !arg.attrs.is_empty() { unimplemented!(); }
381                                 // First get the c type so that we can check if it ends up being a reference:
382                                 let mut c_type = Vec::new();
383                                 types.write_c_type(&mut c_type, &*arg.ty, generics, false);
384                                 match &*arg.pat {
385                                         syn::Pat::Ident(ident) => {
386                                                 if !ident.attrs.is_empty() || ident.subpat.is_some() {
387                                                         unimplemented!();
388                                                 }
389                                                 write!(w, "{}{}{}: ", if first_arg { "" } else { ", " }, if !fn_decl || c_type[0] == '&' as u8 || c_type[0] == '*' as u8 { "" } else { "mut " }, ident.ident).unwrap();
390                                                 first_arg = false;
391                                         },
392                                         syn::Pat::Wild(wild) => {
393                                                 if !wild.attrs.is_empty() { unimplemented!(); }
394                                                 write!(w, "{}unused_{}: ", if first_arg { "" } else { ", " }, num_unused).unwrap();
395                                                 num_unused += 1;
396                                         },
397                                         _ => unimplemented!(),
398                                 }
399                                 w.write(&c_type).unwrap();
400                         }
401                 }
402         }
403         write!(w, ")").unwrap();
404         match &sig.output {
405                 syn::ReturnType::Type(_, rtype) => {
406                         write!(w, " -> ").unwrap();
407                         if let Some(mut remaining_path) = first_seg_self(&*rtype) {
408                                 if remaining_path.next().is_none() {
409                                         write!(w, "{}", this_param).unwrap();
410                                         return;
411                                 }
412                         }
413                         if let syn::Type::Reference(r) = &**rtype {
414                                 // We can't return a reference, cause we allocate things on the stack.
415                                 types.write_c_type(w, &*r.elem, generics, true);
416                         } else {
417                                 types.write_c_type(w, &*rtype, generics, true);
418                         }
419                 },
420                 _ => {},
421         }
422 }
423
424 /// Print the main part of a method declaration body, starting with a newline after the function
425 /// open bracket and converting each function parameter to or from C-mapped types. Ends with "let
426 /// mut ret = " assuming the next print will be the unmapped Rust function to call followed by the
427 /// parameters we mapped to/from C here.
428 pub fn write_method_var_decl_body<W: std::io::Write>(w: &mut W, sig: &syn::Signature, extra_indent: &str, types: &TypeResolver, generics: Option<&GenericTypes>, to_c: bool) {
429         let mut num_unused = 0;
430         for inp in sig.inputs.iter() {
431                 match inp {
432                         syn::FnArg::Receiver(_) => {},
433                         syn::FnArg::Typed(arg) => {
434                                 if types.skip_arg(&*arg.ty, generics) { continue; }
435                                 if !arg.attrs.is_empty() { unimplemented!(); }
436                                 macro_rules! write_new_var {
437                                         ($ident: expr, $ty: expr) => {
438                                                 if to_c {
439                                                         if types.write_to_c_conversion_new_var(w, &$ident, &$ty, generics, false) {
440                                                                 write!(w, "\n\t{}", extra_indent).unwrap();
441                                                         }
442                                                 } else {
443                                                         if types.write_from_c_conversion_new_var(w, &$ident, &$ty, generics) {
444                                                                 write!(w, "\n\t{}", extra_indent).unwrap();
445                                                         }
446                                                 }
447                                         }
448                                 }
449                                 match &*arg.pat {
450                                         syn::Pat::Ident(ident) => {
451                                                 if !ident.attrs.is_empty() || ident.subpat.is_some() {
452                                                         unimplemented!();
453                                                 }
454                                                 write_new_var!(ident.ident, *arg.ty);
455                                         },
456                                         syn::Pat::Wild(w) => {
457                                                 if !w.attrs.is_empty() { unimplemented!(); }
458                                                 write_new_var!(syn::Ident::new(&format!("unused_{}", num_unused), Span::call_site()), *arg.ty);
459                                                 num_unused += 1;
460                                         },
461                                         _ => unimplemented!(),
462                                 }
463                         }
464                 }
465         }
466         match &sig.output {
467                 syn::ReturnType::Type(_, _) => {
468                         write!(w, "let mut ret = ").unwrap();
469                 },
470                 _ => {},
471         }
472 }
473
474 /// Prints the parameters in a method call, starting after the open parenthesis and ending with a
475 /// final return statement returning the method's result. Should be followed by a single closing
476 /// bracket.
477 ///
478 /// The return value is expected to be bound to a variable named `ret` which is available after a
479 /// method-call-ending semicolon.
480 pub fn write_method_call_params<W: std::io::Write>(w: &mut W, sig: &syn::Signature, extra_indent: &str, types: &TypeResolver, generics: Option<&GenericTypes>, this_type: &str, to_c: bool) {
481         let mut first_arg = true;
482         let mut num_unused = 0;
483         for inp in sig.inputs.iter() {
484                 match inp {
485                         syn::FnArg::Receiver(recv) => {
486                                 if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
487                                 if to_c {
488                                         write!(w, "self.this_arg").unwrap();
489                                         first_arg = false;
490                                 }
491                         },
492                         syn::FnArg::Typed(arg) => {
493                                 if types.skip_arg(&*arg.ty, generics) {
494                                         if !to_c {
495                                                 if !first_arg {
496                                                         write!(w, ", ").unwrap();
497                                                 }
498                                                 first_arg = false;
499                                                 types.no_arg_to_rust(w, &*arg.ty, generics);
500                                         }
501                                         continue;
502                                 }
503                                 if !arg.attrs.is_empty() { unimplemented!(); }
504                                 macro_rules! write_ident {
505                                         ($ident: expr) => {
506                                                 if !first_arg {
507                                                         write!(w, ", ").unwrap();
508                                                 }
509                                                 first_arg = false;
510                                                 if to_c {
511                                                         types.write_to_c_conversion_inline_prefix(w, &*arg.ty, generics, false);
512                                                         write!(w, "{}", $ident).unwrap();
513                                                         types.write_to_c_conversion_inline_suffix(w, &*arg.ty, generics, false);
514                                                 } else {
515                                                         types.write_from_c_conversion_prefix(w, &*arg.ty, generics);
516                                                         write!(w, "{}", $ident).unwrap();
517                                                         types.write_from_c_conversion_suffix(w, &*arg.ty, generics);
518                                                 }
519                                         }
520                                 }
521                                 match &*arg.pat {
522                                         syn::Pat::Ident(ident) => {
523                                                 if !ident.attrs.is_empty() || ident.subpat.is_some() {
524                                                         unimplemented!();
525                                                 }
526                                                 write_ident!(ident.ident);
527                                         },
528                                         syn::Pat::Wild(w) => {
529                                                 if !w.attrs.is_empty() { unimplemented!(); }
530                                                 write_ident!(format!("unused_{}", num_unused));
531                                                 num_unused += 1;
532                                         },
533                                         _ => unimplemented!(),
534                                 }
535                         }
536                 }
537         }
538         write!(w, ")").unwrap();
539         match &sig.output {
540                 syn::ReturnType::Type(_, rtype) => {
541                         write!(w, ";\n\t{}", extra_indent).unwrap();
542
543                         let self_segs_iter = first_seg_self(&*rtype);
544                         if to_c && first_seg_self(&*rtype).is_some() {
545                                 // Assume rather blindly that we're returning an associated trait from a C fn call to a Rust trait object.
546                                 write!(w, "ret").unwrap();
547                         } else if !to_c && self_segs_iter.is_some() && self_segs_iter.unwrap().next().is_none() {
548                                 // If we're returning "Self" (and not "Self::X"), just do it manually
549                                 write!(w, "{} {{ inner: Box::into_raw(Box::new(ret)), is_owned: true }}", this_type).unwrap();
550                         } else if to_c {
551                                 let new_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("ret", Span::call_site()), rtype, generics);
552                                 if new_var {
553                                         write!(w, "\n\t{}", extra_indent).unwrap();
554                                 }
555                                 types.write_from_c_conversion_prefix(w, &*rtype, generics);
556                                 write!(w, "ret").unwrap();
557                                 types.write_from_c_conversion_suffix(w, &*rtype, generics);
558                         } else {
559                                 let ret_returned = if let syn::Type::Reference(_) = &**rtype { true } else { false };
560                                 let new_var = types.write_to_c_conversion_new_var(w, &syn::Ident::new("ret", Span::call_site()), &rtype, generics, true);
561                                 if new_var {
562                                         write!(w, "\n\t{}", extra_indent).unwrap();
563                                 }
564                                 types.write_to_c_conversion_inline_prefix(w, &rtype, generics, true);
565                                 write!(w, "{}ret", if ret_returned && !new_var { "*" } else { "" }).unwrap();
566                                 types.write_to_c_conversion_inline_suffix(w, &rtype, generics, true);
567                         }
568                 }
569                 _ => {},
570         }
571 }
572
573 /// Prints concrete generic parameters for a struct/trait/function, including the less-than and
574 /// greater-than symbols, if any generic parameters are defined.
575 pub fn maybe_write_generics<W: std::io::Write>(w: &mut W, generics: &syn::Generics, types: &TypeResolver, concrete_lifetimes: bool) {
576         let mut gen_types = GenericTypes::new();
577         assert!(gen_types.learn_generics(generics, types));
578         if !generics.params.is_empty() {
579                 write!(w, "<").unwrap();
580                 for (idx, generic) in generics.params.iter().enumerate() {
581                         match generic {
582                                 syn::GenericParam::Type(type_param) => {
583                                         let mut printed_param = false;
584                                         for bound in type_param.bounds.iter() {
585                                                 if let syn::TypeParamBound::Trait(trait_bound) = bound {
586                                                         assert_simple_bound(&trait_bound);
587                                                         write!(w, "{}{}", if idx != 0 { ", " } else { "" }, gen_types.maybe_resolve_ident(&type_param.ident).unwrap()).unwrap();
588                                                         if printed_param {
589                                                                 unimplemented!("Can't print generic params that have multiple non-lifetime bounds");
590                                                         }
591                                                         printed_param = true;
592                                                 }
593                                         }
594                                 },
595                                 syn::GenericParam::Lifetime(lt) => {
596                                         if concrete_lifetimes {
597                                                 write!(w, "'static").unwrap();
598                                         } else {
599                                                 write!(w, "{}'{}", if idx != 0 { ", " } else { "" }, lt.lifetime.ident).unwrap();
600                                         }
601                                 },
602                                 _ => unimplemented!(),
603                         }
604                 }
605                 write!(w, ">").unwrap();
606         }
607 }
608
609