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