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