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