0e1617a3fc35ada2d9ec76f1420e1cbeba0ac991
[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 core::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 core::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: core::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: core::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, "/// Checks if the given object is currently in the success state").unwrap();
128         writeln!(w, "#[no_mangle]").unwrap();
129         writeln!(w, "pub extern \"C\" fn {}_is_ok(o: &{}) -> bool {{", mangled_container, mangled_container).unwrap();
130         writeln!(w, "\to.result_ok").unwrap();
131         writeln!(w, "}}").unwrap();
132
133         writeln!(w, "#[no_mangle]").unwrap();
134         writeln!(w, "/// Frees any resources used by the {}.", mangled_container).unwrap();
135         writeln!(w, "pub extern \"C\" fn {}_free(_res: {}) {{ }}", mangled_container, mangled_container).unwrap();
136         writeln!(w, "impl Drop for {} {{", mangled_container).unwrap();
137         writeln!(w, "\tfn drop(&mut self) {{").unwrap();
138         writeln!(w, "\t\tif self.result_ok {{").unwrap();
139         if ok_type != "()" {
140                 writeln!(w, "\t\t\tif unsafe {{ !(self.contents.result as *mut ()).is_null() }} {{").unwrap();
141                 writeln!(w, "\t\t\t\tlet _ = unsafe {{ Box::from_raw(self.contents.result) }};").unwrap();
142                 writeln!(w, "\t\t\t}}").unwrap();
143         }
144         writeln!(w, "\t\t}} else {{").unwrap();
145         if err_type != "()" {
146                 writeln!(w, "\t\t\tif unsafe {{ !(self.contents.err as *mut ()).is_null() }} {{").unwrap();
147                 writeln!(w, "\t\t\t\tlet _ = unsafe {{ Box::from_raw(self.contents.err) }};").unwrap();
148                 writeln!(w, "\t\t\t}}").unwrap();
149         }
150         writeln!(w, "\t\t}}").unwrap();
151         writeln!(w, "\t}}").unwrap();
152         writeln!(w, "}}").unwrap();
153
154         writeln!(w, "impl From<crate::c_types::CResultTempl<{}, {}>> for {} {{", ok_type, err_type, mangled_container).unwrap();
155         writeln!(w, "\tfn from(mut o: crate::c_types::CResultTempl<{}, {}>) -> Self {{", ok_type, err_type).unwrap();
156         writeln!(w, "\t\tlet contents = if o.result_ok {{").unwrap();
157         if ok_type != "()" {
158                 writeln!(w, "\t\t\tlet result = unsafe {{ o.contents.result }};").unwrap();
159                 writeln!(w, "\t\t\tunsafe {{ o.contents.result = core::ptr::null_mut() }};").unwrap();
160                 writeln!(w, "\t\t\t{}Ptr {{ result }}", mangled_container).unwrap();
161         } else {
162                 writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(o.contents.result) }};").unwrap();
163                 writeln!(w, "\t\t\to.contents.result = core::ptr::null_mut();").unwrap();
164                 writeln!(w, "\t\t\t{}Ptr {{ result: core::ptr::null_mut() }}", mangled_container).unwrap();
165         }
166         writeln!(w, "\t\t}} else {{").unwrap();
167         if err_type != "()" {
168                 writeln!(w, "\t\t\tlet err = unsafe {{ o.contents.err }};").unwrap();
169                 writeln!(w, "\t\t\tunsafe {{ o.contents.err = core::ptr::null_mut(); }}").unwrap();
170                 writeln!(w, "\t\t\t{}Ptr {{ err }}", mangled_container).unwrap();
171         } else {
172                 writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(o.contents.err) }};").unwrap();
173                 writeln!(w, "\t\t\to.contents.err = core::ptr::null_mut();").unwrap();
174                 writeln!(w, "\t\t\t{}Ptr {{ err: core::ptr::null_mut() }}", mangled_container).unwrap();
175         }
176         writeln!(w, "\t\t}};").unwrap();
177         writeln!(w, "\t\tSelf {{").unwrap();
178         writeln!(w, "\t\t\tcontents,").unwrap();
179         writeln!(w, "\t\t\tresult_ok: o.result_ok,").unwrap();
180         writeln!(w, "\t\t}}").unwrap();
181         writeln!(w, "\t}}").unwrap();
182         writeln!(w, "}}").unwrap();
183
184         if clonable {
185                 writeln!(w, "impl Clone for {} {{", mangled_container).unwrap();
186                 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
187                 writeln!(w, "\t\tif self.result_ok {{").unwrap();
188                 writeln!(w, "\t\t\tSelf {{ result_ok: true, contents: {}Ptr {{", mangled_container).unwrap();
189                 if ok_type != "()" {
190                         writeln!(w, "\t\t\t\tresult: Box::into_raw(Box::new(<{}>::clone(unsafe {{ &*self.contents.result }})))", ok_type).unwrap();
191                 } else {
192                         writeln!(w, "\t\t\t\tresult: core::ptr::null_mut()").unwrap();
193                 }
194                 writeln!(w, "\t\t\t}} }}").unwrap();
195                 writeln!(w, "\t\t}} else {{").unwrap();
196                 writeln!(w, "\t\t\tSelf {{ result_ok: false, contents: {}Ptr {{", mangled_container).unwrap();
197                 if err_type != "()" {
198                         writeln!(w, "\t\t\t\terr: Box::into_raw(Box::new(<{}>::clone(unsafe {{ &*self.contents.err }})))", err_type).unwrap();
199                 } else {
200                         writeln!(w, "\t\t\t\terr: core::ptr::null_mut()").unwrap();
201                 }
202                 writeln!(w, "\t\t\t}} }}").unwrap();
203                 writeln!(w, "\t\t}}").unwrap();
204                 writeln!(w, "\t}}").unwrap();
205                 writeln!(w, "}}").unwrap();
206                 writeln!(w, "#[no_mangle]").unwrap();
207                 writeln!(w, "/// Creates a new {} which has the same data as `orig`", mangled_container).unwrap();
208                 writeln!(w, "/// but with all dynamically-allocated buffers duplicated in new buffers.").unwrap();
209                 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{ Clone::clone(&orig) }}", mangled_container, mangled_container, mangled_container).unwrap();
210         }
211 }
212
213 /// Writes out a C-callable concrete Vec<A> struct and utility methods
214 pub fn write_vec_block<W: std::io::Write>(w: &mut W, mangled_container: &str, inner_type: &str, clonable: bool) {
215         writeln!(w, "#[repr(C)]").unwrap();
216         writeln!(w, "/// A dynamically-allocated array of {}s of arbitrary size.", inner_type).unwrap();
217         writeln!(w, "/// This corresponds to std::vector in C++").unwrap();
218         writeln!(w, "pub struct {} {{", mangled_container).unwrap();
219         writeln!(w, "\t/// The elements in the array.").unwrap();
220         writeln!(w, "\t/// If datalen is non-0 this must be a valid, non-NULL pointer allocated by malloc().").unwrap();
221         writeln!(w, "\tpub data: *mut {},", inner_type).unwrap();
222         writeln!(w, "\t/// The number of elements pointed to by `data`.").unwrap();
223         writeln!(w, "\tpub datalen: usize").unwrap();
224         writeln!(w, "}}").unwrap();
225
226         writeln!(w, "impl {} {{", mangled_container).unwrap();
227         writeln!(w, "\t#[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<{}> {{", inner_type).unwrap();
228         writeln!(w, "\t\tif self.datalen == 0 {{ return Vec::new(); }}").unwrap();
229         writeln!(w, "\t\tlet ret = unsafe {{ Box::from_raw(core::slice::from_raw_parts_mut(self.data, self.datalen)) }}.into();").unwrap();
230         writeln!(w, "\t\tself.data = core::ptr::null_mut();").unwrap();
231         writeln!(w, "\t\tself.datalen = 0;").unwrap();
232         writeln!(w, "\t\tret").unwrap();
233         writeln!(w, "\t}}").unwrap();
234         writeln!(w, "\t#[allow(unused)] pub(crate) fn as_slice(&self) -> &[{}] {{", inner_type).unwrap();
235         writeln!(w, "\t\tunsafe {{ core::slice::from_raw_parts_mut(self.data, self.datalen) }}").unwrap();
236         writeln!(w, "\t}}").unwrap();
237         writeln!(w, "}}").unwrap();
238
239         writeln!(w, "impl From<Vec<{}>> for {} {{", inner_type, mangled_container).unwrap();
240         writeln!(w, "\tfn from(v: Vec<{}>) -> Self {{", inner_type).unwrap();
241         writeln!(w, "\t\tlet datalen = v.len();").unwrap();
242         writeln!(w, "\t\tlet data = Box::into_raw(v.into_boxed_slice());").unwrap();
243         writeln!(w, "\t\tSelf {{ datalen, data: unsafe {{ (*data).as_mut_ptr() }} }}").unwrap();
244         writeln!(w, "\t}}").unwrap();
245         writeln!(w, "}}").unwrap();
246
247         writeln!(w, "#[no_mangle]").unwrap();
248         writeln!(w, "/// Frees the buffer pointed to by `data` if `datalen` is non-0.").unwrap();
249         writeln!(w, "pub extern \"C\" fn {}_free(_res: {}) {{ }}", mangled_container, mangled_container).unwrap();
250         writeln!(w, "impl Drop for {} {{", mangled_container).unwrap();
251         writeln!(w, "\tfn drop(&mut self) {{").unwrap();
252         writeln!(w, "\t\tif self.datalen == 0 {{ return; }}").unwrap();
253         writeln!(w, "\t\tunsafe {{ Box::from_raw(core::slice::from_raw_parts_mut(self.data, self.datalen)) }};").unwrap();
254         writeln!(w, "\t}}").unwrap();
255         writeln!(w, "}}").unwrap();
256         if clonable {
257                 writeln!(w, "impl Clone for {} {{", mangled_container).unwrap();
258                 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
259                 writeln!(w, "\t\tlet mut res = Vec::new();").unwrap();
260                 writeln!(w, "\t\tif self.datalen == 0 {{ return Self::from(res); }}").unwrap();
261                 writeln!(w, "\t\tres.extend_from_slice(unsafe {{ core::slice::from_raw_parts_mut(self.data, self.datalen) }});").unwrap();
262                 writeln!(w, "\t\tSelf::from(res)").unwrap();
263                 writeln!(w, "\t}}").unwrap();
264                 writeln!(w, "}}").unwrap();
265         }
266 }
267
268 /// Writes out a C-callable concrete (A, B, ...) struct and utility methods
269 pub fn write_tuple_block<W: std::io::Write>(w: &mut W, mangled_container: &str, types: &[String], clonable: bool) {
270         writeln!(w, "#[repr(C)]").unwrap();
271         writeln!(w, "/// A tuple of {} elements. See the individual fields for the types contained.", types.len()).unwrap();
272         writeln!(w, "pub struct {} {{", mangled_container).unwrap();
273         for (idx, ty) in types.iter().enumerate() {
274                 writeln!(w, "\t/// The element at position {}", idx).unwrap();
275                 if ty.starts_with("&'static ") {
276                         writeln!(w, "\tpub {}: {},", ('a' as u8 + idx as u8) as char, &ty[9..]).unwrap();
277                 } else {
278                         writeln!(w, "\tpub {}: {},", ('a' as u8 + idx as u8) as char, ty).unwrap();
279                 }
280         }
281         writeln!(w, "}}").unwrap();
282
283         let mut tuple_str = "(".to_owned();
284         for (idx, ty) in types.iter().enumerate() {
285                 if idx != 0 { tuple_str += ", "; }
286                 if ty.starts_with("&'static ") {
287                         tuple_str += &ty[9..];
288                 } else {
289                         tuple_str += ty;
290                 }
291         }
292         tuple_str += ")";
293
294         writeln!(w, "impl From<{}> for {} {{", tuple_str, mangled_container).unwrap();
295         writeln!(w, "\tfn from (tup: {}) -> Self {{", tuple_str).unwrap();
296         writeln!(w, "\t\tSelf {{").unwrap();
297         for idx in 0..types.len() {
298                 writeln!(w, "\t\t\t{}: tup.{},", ('a' as u8 + idx as u8) as char, idx).unwrap();
299         }
300         writeln!(w, "\t\t}}").unwrap();
301         writeln!(w, "\t}}").unwrap();
302         writeln!(w, "}}").unwrap();
303         writeln!(w, "impl {} {{", mangled_container).unwrap();
304         writeln!(w, "\t#[allow(unused)] pub(crate) fn to_rust(mut self) -> {} {{", tuple_str).unwrap();
305         write!(w, "\t\t(").unwrap();
306         for idx in 0..types.len() {
307                 write!(w, "{}self.{}", if idx != 0 {", "} else {""}, ('a' as u8 + idx as u8) as char).unwrap();
308         }
309         writeln!(w, ")").unwrap();
310         writeln!(w, "\t}}").unwrap();
311         writeln!(w, "}}").unwrap();
312
313         if clonable {
314                 writeln!(w, "impl Clone for {} {{", mangled_container).unwrap();
315                 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
316                 writeln!(w, "\t\tSelf {{").unwrap();
317                 for (idx, ty) in types.iter().enumerate() {
318                         if ty.starts_with("&'static ") {
319                                 // Assume blindly the type is opaque. If its not we'll fail to build.
320                                 // Really we should never have derived structs with a reference type.
321                                 write!(w, "\t\t\t{}: {} {{ inner: self.{}.inner, is_owned: false}},", ('a' as u8 + idx as u8) as char, &ty[9..], ('a' as u8 + idx as u8) as char).unwrap();
322                         } else{
323                                 writeln!(w, "\t\t\t{}: Clone::clone(&self.{}),", ('a' as u8 + idx as u8) as char, ('a' as u8 + idx as u8) as char).unwrap();
324                         }
325                 }
326                 writeln!(w, "\t\t}}").unwrap();
327                 writeln!(w, "\t}}").unwrap();
328                 writeln!(w, "}}").unwrap();
329                 writeln!(w, "#[no_mangle]").unwrap();
330                 writeln!(w, "/// Creates a new tuple which has the same data as `orig`").unwrap();
331                 writeln!(w, "/// but with all dynamically-allocated buffers duplicated in new buffers.").unwrap();
332                 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{ Clone::clone(&orig) }}", mangled_container, mangled_container, mangled_container).unwrap();
333         }
334
335         writeln!(w, "/// Creates a new {} from the contained elements.", mangled_container).unwrap();
336         write!(w, "#[no_mangle]\npub extern \"C\" fn {}_new(", mangled_container).unwrap();
337         for (idx, gen) in types.iter().enumerate() {
338                 write!(w, "{}{}: ", if idx != 0 { ", " } else { "" }, ('a' as u8 + idx as u8) as char).unwrap();
339                 //if !self.write_c_type_intern(&mut created_container, gen, generics, false, false, false) { return false; }
340                 write!(w, "{}", gen).unwrap();
341         }
342         writeln!(w, ") -> {} {{", mangled_container).unwrap();
343         write!(w, "\t{} {{ ", mangled_container).unwrap();
344         for (idx, ty) in types.iter().enumerate() {
345                 if ty.starts_with("&'static ") {
346                         // Assume blindly the type is opaque. If its not we'll fail to build.
347                         // Really we should never have derived structs with a reference type.
348                         write!(w, "{}: {} {{ inner: {}.inner, is_owned: false}}, ", ('a' as u8 + idx as u8) as char, &ty[9..], ('a' as u8 + idx as u8) as char).unwrap();
349                 } else {
350                         write!(w, "{}, ", ('a' as u8 + idx as u8) as char).unwrap();
351                 }
352         }
353         writeln!(w, "}}\n}}\n").unwrap();
354
355         writeln!(w, "#[no_mangle]").unwrap();
356         writeln!(w, "/// Frees any resources used by the {}.", mangled_container).unwrap();
357         writeln!(w, "pub extern \"C\" fn {}_free(_res: {}) {{ }}", mangled_container, mangled_container).unwrap();
358 }
359
360 /// Writes out a C-callable concrete Option<A> struct and utility methods
361 pub fn write_option_block<W: std::io::Write>(w: &mut W, mangled_container: &str, inner_type: &str, clonable: bool) {
362         writeln!(w, "#[repr(C)]").unwrap();
363         if clonable {
364                 writeln!(w, "#[derive(Clone)]").unwrap();
365         }
366         writeln!(w, "/// An enum which can either contain a {} or not", inner_type).unwrap();
367         writeln!(w, "pub enum {} {{", mangled_container).unwrap();
368         writeln!(w, "\t/// When we're in this state, this {} contains a {}", mangled_container, inner_type).unwrap();
369         if inner_type != "" {
370                 writeln!(w, "\tSome({}),", inner_type).unwrap();
371         } else {
372                 writeln!(w, "\tSome,").unwrap();
373         }
374         writeln!(w, "\t/// When we're in this state, this {} contains nothing", mangled_container).unwrap();
375         writeln!(w, "\tNone").unwrap();
376         writeln!(w, "}}").unwrap();
377
378         writeln!(w, "impl {} {{", mangled_container).unwrap();
379         writeln!(w, "\t#[allow(unused)] pub(crate) fn is_some(&self) -> bool {{").unwrap();
380         writeln!(w, "\t\tif let Self::None = self {{ false }} else {{ true }}").unwrap();
381         writeln!(w, "\t}}").unwrap();
382         writeln!(w, "\t#[allow(unused)] pub(crate) fn is_none(&self) -> bool {{").unwrap();
383         writeln!(w, "\t\t!self.is_some()").unwrap();
384         writeln!(w, "\t}}").unwrap();
385         if inner_type != "" {
386                 writeln!(w, "\t#[allow(unused)] pub(crate) fn take(mut self) -> {} {{", inner_type).unwrap();
387                 writeln!(w, "\t\tif let Self::Some(v) = self {{ v }} else {{ unreachable!() }}").unwrap();
388                 writeln!(w, "\t}}").unwrap();
389         }
390         writeln!(w, "}}").unwrap();
391
392         writeln!(w, "#[no_mangle]").unwrap();
393         writeln!(w, "/// Constructs a new {} containing a {}", mangled_container, inner_type).unwrap();
394         if inner_type != "" {
395                 writeln!(w, "pub extern \"C\" fn {}_some(o: {}) -> {} {{", mangled_container, inner_type, mangled_container).unwrap();
396                 writeln!(w, "\t{}::Some(o)", mangled_container).unwrap();
397         } else {
398                 writeln!(w, "pub extern \"C\" fn {}_some() -> {} {{", mangled_container, mangled_container).unwrap();
399                 writeln!(w, "\t{}::Some", mangled_container).unwrap();
400         }
401         writeln!(w, "}}").unwrap();
402
403         writeln!(w, "#[no_mangle]").unwrap();
404         writeln!(w, "/// Constructs a new {} containing nothing", mangled_container).unwrap();
405         writeln!(w, "pub extern \"C\" fn {}_none() -> {} {{", mangled_container, mangled_container).unwrap();
406         writeln!(w, "\t{}::None", mangled_container).unwrap();
407         writeln!(w, "}}").unwrap();
408
409         writeln!(w, "#[no_mangle]").unwrap();
410         writeln!(w, "/// Frees any resources associated with the {}, if we are in the Some state", inner_type).unwrap();
411         writeln!(w, "pub extern \"C\" fn {}_free(_res: {}) {{ }}", mangled_container, mangled_container).unwrap();
412         if clonable {
413                 writeln!(w, "#[no_mangle]").unwrap();
414                 writeln!(w, "/// Creates a new {} which has the same data as `orig`", mangled_container).unwrap();
415                 writeln!(w, "/// but with all dynamically-allocated buffers duplicated in new buffers.").unwrap();
416                 writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{ Clone::clone(&orig) }}", mangled_container, mangled_container, mangled_container).unwrap();
417         }
418 }
419
420 /// Prints the docs from a given attribute list unless its tagged no export
421 pub fn writeln_fn_docs<'a, W: std::io::Write, I>(w: &mut W, attrs: &[syn::Attribute], prefix: &str, types: &mut TypeResolver, generics: Option<&GenericTypes>, args: I, ret: &syn::ReturnType) where I: Iterator<Item = &'a syn::FnArg> {
422         writeln_docs_impl(w, attrs, prefix, Some((types, generics,
423                 args.filter_map(|arg| if let syn::FnArg::Typed(ty) = arg {
424                                 if let syn::Pat::Ident(id) = &*ty.pat {
425                                         Some((id.ident.to_string(), &*ty.ty))
426                                 } else { unimplemented!() }
427                         } else { None }),
428                 if let syn::ReturnType::Type(_, ty) = ret { Some(&**ty) } else { None },
429                 None
430         )));
431 }
432
433 /// Prints the docs from a given attribute list unless its tagged no export
434 pub fn writeln_docs<W: std::io::Write>(w: &mut W, attrs: &[syn::Attribute], prefix: &str) {
435         writeln_docs_impl(w, attrs, prefix, None::<(_, _, std::vec::Drain<'_, (String, &syn::Type)>, _, _)>);
436 }
437
438 pub fn writeln_arg_docs<'a, W: std::io::Write, I>(w: &mut W, attrs: &[syn::Attribute], prefix: &str, types: &mut TypeResolver, generics: Option<&GenericTypes>, args: I, ret: Option<&syn::Type>) where I: Iterator<Item = (String, &'a syn::Type)> {
439         writeln_docs_impl(w, attrs, prefix, Some((types, generics, args, ret, None)))
440 }
441
442 pub fn writeln_field_docs<W: std::io::Write>(w: &mut W, attrs: &[syn::Attribute], prefix: &str, types: &mut TypeResolver, generics: Option<&GenericTypes>, field: &syn::Type) {
443         writeln_docs_impl(w, attrs, prefix, Some((types, generics, vec![].drain(..), None, Some(field))))
444 }
445
446 /// Prints the docs from a given attribute list unless its tagged no export
447 fn writeln_docs_impl<'a, W: std::io::Write, I>(w: &mut W, attrs: &[syn::Attribute], prefix: &str, method_args_ret: Option<(&mut TypeResolver, Option<&GenericTypes>, I, Option<&syn::Type>, Option<&syn::Type>)>) where I: Iterator<Item = (String, &'a syn::Type)> {
448         for attr in attrs.iter() {
449                 let tokens_clone = attr.tokens.clone();
450                 let mut token_iter = tokens_clone.into_iter();
451                 if let Some(token) = token_iter.next() {
452                         match token {
453                                 TokenTree::Punct(c) if c.as_char() == '=' => {
454                                         // syn gets '=' from '///' or '//!' as it is syntax for #[doc = ""]
455                                 },
456                                 TokenTree::Group(_) => continue, // eg #[derive()]
457                                 _ => unimplemented!(),
458                         }
459                 } else { continue; }
460                 match attr.style {
461                         syn::AttrStyle::Inner(_) => {
462                                 match token_iter.next().unwrap() {
463                                         TokenTree::Literal(lit) => {
464                                                 // Drop the first and last chars from lit as they are always "
465                                                 let doc = format!("{}", lit);
466                                                 writeln!(w, "{}//!{}", prefix, &doc[1..doc.len() - 1]).unwrap();
467                                         },
468                                         _ => unimplemented!(),
469                                 }
470                         },
471                         syn::AttrStyle::Outer => {
472                                 match token_iter.next().unwrap() {
473                                         TokenTree::Literal(lit) => {
474                                                 // Drop the first and last chars from lit as they are always "
475                                                 let doc = format!("{}", lit);
476                                                 writeln!(w, "{}///{}", prefix, &doc[1..doc.len() - 1]).unwrap();
477                                         },
478                                         _ => unimplemented!(),
479                                 }
480                         },
481                 }
482         }
483         if let Some((types, generics, inp, outp, field)) = method_args_ret {
484                 let mut nullable_found = false;
485                 for (name, inp) in inp {
486                         if types.skip_arg(inp, generics) { continue; }
487                         if if let syn::Type::Reference(syn::TypeReference { elem, .. }) = inp {
488                                 if let syn::Type::Path(syn::TypePath { ref path, .. }) = &**elem {
489                                         types.is_path_transparent_container(path, generics, true)
490                                 } else { false }
491                         } else if let syn::Type::Path(syn::TypePath { ref path, .. }) = inp {
492                                 types.is_path_transparent_container(path, generics, true)
493                         } else { false } {
494                                 // Note downstream clients match this text exactly so any changes may require
495                                 // changes in the Java and Swift bindings, at least.
496                                 if !nullable_found { writeln!(w, "{}///", prefix).unwrap(); }
497                                 nullable_found = true;
498                                 writeln!(w, "{}/// Note that {} (or a relevant inner pointer) may be NULL or all-0s to represent None", prefix, name).unwrap();
499                         }
500                 }
501                 if if let Some(syn::Type::Reference(syn::TypeReference { elem, .. })) = outp {
502                         if let syn::Type::Path(syn::TypePath { ref path, .. }) = &**elem {
503                                 types.is_path_transparent_container(path, generics, true)
504                         } else { false }
505                 } else if let Some(syn::Type::Path(syn::TypePath { ref path, .. })) = outp {
506                         types.is_path_transparent_container(path, generics, true)
507                 } else { false } {
508                         // Note downstream clients match this text exactly so any changes may require
509                         // changes in the Java and Swift bindings, at least.
510                         if !nullable_found { writeln!(w, "{}///", prefix).unwrap(); }
511                         nullable_found = true;
512                         writeln!(w, "{}/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None", prefix).unwrap();
513                 }
514                 if if let Some(syn::Type::Reference(syn::TypeReference { elem, .. })) = field {
515                         if let syn::Type::Path(syn::TypePath { ref path, .. }) = &**elem {
516                                 types.is_path_transparent_container(path, generics, true)
517                         } else { false }
518                 } else if let Some(syn::Type::Path(syn::TypePath { ref path, .. })) = field {
519                         types.is_path_transparent_container(path, generics, true)
520                 } else { false } {
521                         // Note downstream clients match this text exactly so any changes may require
522                         // changes in the Java and Swift bindings, at least.
523                         if !nullable_found { writeln!(w, "{}///", prefix).unwrap(); }
524                         writeln!(w, "{}/// Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None", prefix).unwrap();
525                 }
526         }
527
528 }
529
530 /// Print the parameters in a method declaration, starting after the open parenthesis, through and
531 /// including the closing parenthesis and return value, but not including the open bracket or any
532 /// trailing semicolons.
533 ///
534 /// Usable both for a function definition and declaration.
535 ///
536 /// this_param is used when returning Self or accepting a self parameter, and should be the
537 /// concrete, mapped type.
538 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) {
539         if sig.constness.is_some() || sig.asyncness.is_some() || sig.unsafety.is_some() ||
540                         sig.abi.is_some() || sig.variadic.is_some() {
541                 unimplemented!();
542         }
543         if sig.generics.lt_token.is_some() {
544                 for generic in sig.generics.params.iter() {
545                         match generic {
546                                 syn::GenericParam::Type(_)|syn::GenericParam::Lifetime(_) => {
547                                         // We ignore these, if they're not on skipped args, we'll blow up
548                                         // later, and lifetimes we just hope the C client enforces.
549                                 },
550                                 _ => unimplemented!(),
551                         }
552                 }
553         }
554
555         let mut first_arg = true;
556         let mut num_unused = 0;
557         for inp in sig.inputs.iter() {
558                 match inp {
559                         syn::FnArg::Receiver(recv) => {
560                                 if !recv.attrs.is_empty() { unimplemented!(); }
561                                 write!(w, "{}this_arg: {}{}", if recv.reference.is_none() { "mut " } else { "" },
562                                         if recv.reference.is_some() {
563                                                 match (self_ptr, recv.mutability.is_some()) {
564                                                         (true, true) => "*mut ",
565                                                         (true, false) => "*const ",
566                                                         (false, true) => "&mut ",
567                                                         (false, false) => "&",
568                                                 }
569                                         } else { "" }, this_param).unwrap();
570                                 assert!(first_arg);
571                                 first_arg = false;
572                         },
573                         syn::FnArg::Typed(arg) => {
574                                 if types.skip_arg(&*arg.ty, generics) { continue; }
575                                 if !arg.attrs.is_empty() { unimplemented!(); }
576                                 // First get the c type so that we can check if it ends up being a reference:
577                                 let mut c_type = Vec::new();
578                                 types.write_c_type(&mut c_type, &*arg.ty, generics, false);
579                                 match &*arg.pat {
580                                         syn::Pat::Ident(ident) => {
581                                                 if !ident.attrs.is_empty() || ident.subpat.is_some() {
582                                                         unimplemented!();
583                                                 }
584                                                 write!(w, "{}{}{}: ", if first_arg { "" } else { ", " }, if !fn_decl || c_type[0] == '&' as u8 || c_type[0] == '*' as u8 { "" } else { "mut " }, ident.ident).unwrap();
585                                                 first_arg = false;
586                                         },
587                                         syn::Pat::Wild(wild) => {
588                                                 if !wild.attrs.is_empty() { unimplemented!(); }
589                                                 write!(w, "{}unused_{}: ", if first_arg { "" } else { ", " }, num_unused).unwrap();
590                                                 num_unused += 1;
591                                         },
592                                         _ => unimplemented!(),
593                                 }
594                                 w.write(&c_type).unwrap();
595                         }
596                 }
597         }
598         write!(w, ")").unwrap();
599         match &sig.output {
600                 syn::ReturnType::Type(_, rtype) => {
601                         write!(w, " -> ").unwrap();
602                         if let Some(mut remaining_path) = first_seg_self(&*rtype) {
603                                 if remaining_path.next().is_none() {
604                                         write!(w, "{}", this_param).unwrap();
605                                         return;
606                                 }
607                         }
608                         types.write_c_type(w, &*rtype, generics, true);
609                 },
610                 _ => {},
611         }
612 }
613
614 /// Print the main part of a method declaration body, starting with a newline after the function
615 /// open bracket and converting each function parameter to or from C-mapped types. Ends with "let
616 /// mut ret = " assuming the next print will be the unmapped Rust function to call followed by the
617 /// parameters we mapped to/from C here.
618 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) {
619         let mut num_unused = 0u32;
620         for inp in sig.inputs.iter() {
621                 match inp {
622                         syn::FnArg::Receiver(_) => {},
623                         syn::FnArg::Typed(arg) => {
624                                 if types.skip_arg(&*arg.ty, generics) { continue; }
625                                 if !arg.attrs.is_empty() { unimplemented!(); }
626                                 macro_rules! write_new_var {
627                                         ($ident: expr, $ty: expr) => {
628                                                 if to_c {
629                                                         if types.write_to_c_conversion_new_var(w, &$ident, &$ty, generics, false) {
630                                                                 write!(w, "\n\t{}", extra_indent).unwrap();
631                                                         }
632                                                 } else {
633                                                         if types.write_from_c_conversion_new_var(w, &$ident, &$ty, generics) {
634                                                                 write!(w, "\n\t{}", extra_indent).unwrap();
635                                                         }
636                                                 }
637                                         }
638                                 }
639                                 match &*arg.pat {
640                                         syn::Pat::Ident(ident) => {
641                                                 if !ident.attrs.is_empty() || ident.subpat.is_some() {
642                                                         unimplemented!();
643                                                 }
644                                                 write_new_var!(ident.ident, *arg.ty);
645                                         },
646                                         syn::Pat::Wild(w) => {
647                                                 if !w.attrs.is_empty() { unimplemented!(); }
648                                                 write_new_var!(format_ident!("unused_{}", num_unused), *arg.ty);
649                                                 num_unused += 1;
650                                         },
651                                         _ => unimplemented!(),
652                                 }
653                         }
654                 }
655         }
656         match &sig.output {
657                 syn::ReturnType::Type(_, _) => {
658                         write!(w, "let mut ret = ").unwrap();
659                 },
660                 _ => {},
661         }
662 }
663
664 /// Prints the parameters in a method call, starting after the open parenthesis and ending with a
665 /// final return statement returning the method's result. Should be followed by a single closing
666 /// bracket.
667 ///
668 /// The return value is expected to be bound to a variable named `ret` which is available after a
669 /// method-call-ending semicolon.
670 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) {
671         let mut first_arg = true;
672         let mut num_unused = 0;
673         for inp in sig.inputs.iter() {
674                 match inp {
675                         syn::FnArg::Receiver(recv) => {
676                                 if !recv.attrs.is_empty() { unimplemented!(); }
677                                 if to_c {
678                                         if recv.reference.is_none() { unimplemented!(); }
679                                         write!(w, "self.this_arg").unwrap();
680                                         first_arg = false;
681                                 }
682                         },
683                         syn::FnArg::Typed(arg) => {
684                                 if types.skip_arg(&*arg.ty, generics) {
685                                         if !to_c {
686                                                 if !first_arg {
687                                                         write!(w, ", ").unwrap();
688                                                 }
689                                                 first_arg = false;
690                                                 types.no_arg_to_rust(w, &*arg.ty, generics);
691                                         }
692                                         continue;
693                                 }
694                                 if !arg.attrs.is_empty() { unimplemented!(); }
695                                 macro_rules! write_ident {
696                                         ($ident: expr) => {
697                                                 if !first_arg {
698                                                         write!(w, ", ").unwrap();
699                                                 }
700                                                 first_arg = false;
701                                                 if to_c {
702                                                         types.write_to_c_conversion_inline_prefix(w, &*arg.ty, generics, false);
703                                                         write!(w, "{}", $ident).unwrap();
704                                                         types.write_to_c_conversion_inline_suffix(w, &*arg.ty, generics, false);
705                                                 } else {
706                                                         types.write_from_c_conversion_prefix(w, &*arg.ty, generics);
707                                                         write!(w, "{}", $ident).unwrap();
708                                                         types.write_from_c_conversion_suffix(w, &*arg.ty, generics);
709                                                 }
710                                         }
711                                 }
712                                 match &*arg.pat {
713                                         syn::Pat::Ident(ident) => {
714                                                 if !ident.attrs.is_empty() || ident.subpat.is_some() {
715                                                         unimplemented!();
716                                                 }
717                                                 write_ident!(ident.ident);
718                                         },
719                                         syn::Pat::Wild(w) => {
720                                                 if !w.attrs.is_empty() { unimplemented!(); }
721                                                 write_ident!(format!("unused_{}", num_unused));
722                                                 num_unused += 1;
723                                         },
724                                         _ => unimplemented!(),
725                                 }
726                         }
727                 }
728         }
729         write!(w, ")").unwrap();
730         match &sig.output {
731                 syn::ReturnType::Type(_, rtype) => {
732                         write!(w, ";\n\t{}", extra_indent).unwrap();
733
734                         let self_segs_iter = first_seg_self(&*rtype);
735                         if to_c && first_seg_self(&*rtype).is_some() {
736                                 // Assume rather blindly that we're returning an associated trait from a C fn call to a Rust trait object.
737                                 write!(w, "ret").unwrap();
738                         } else if !to_c && self_segs_iter.is_some() && self_segs_iter.unwrap().next().is_none() {
739                                 // If we're returning "Self" (and not "Self::X"), just do it manually
740                                 write!(w, "{} {{ inner: ObjOps::heap_alloc(ret), is_owned: true }}", this_type).unwrap();
741                         } else if to_c {
742                                 let new_var = types.write_from_c_conversion_new_var(w, &format_ident!("ret"), rtype, generics);
743                                 if new_var {
744                                         write!(w, "\n\t{}", extra_indent).unwrap();
745                                 }
746                                 types.write_from_c_conversion_prefix(w, &*rtype, generics);
747                                 write!(w, "ret").unwrap();
748                                 types.write_from_c_conversion_suffix(w, &*rtype, generics);
749                         } else {
750                                 let new_var = types.write_to_c_conversion_new_var(w, &format_ident!("ret"), &rtype, generics, true);
751                                 if new_var {
752                                         write!(w, "\n\t{}", extra_indent).unwrap();
753                                 }
754                                 types.write_to_c_conversion_inline_prefix(w, &rtype, generics, true);
755                                 write!(w, "ret").unwrap();
756                                 types.write_to_c_conversion_inline_suffix(w, &rtype, generics, true);
757                         }
758                 }
759                 _ => {},
760         }
761 }
762
763 /// Prints concrete generic parameters for a struct/trait/function, including the less-than and
764 /// greater-than symbols, if any generic parameters are defined.
765 pub fn maybe_write_generics<W: std::io::Write>(w: &mut W, generics: &syn::Generics, types: &TypeResolver, concrete_lifetimes: bool) {
766         let mut gen_types = GenericTypes::new(None);
767         assert!(gen_types.learn_generics(generics, types));
768         if generics.params.is_empty() { return; }
769         for generic in generics.params.iter() {
770                 match generic {
771                         syn::GenericParam::Type(type_param) => {
772                                 for bound in type_param.bounds.iter() {
773                                         match bound {
774                                                 syn::TypeParamBound::Trait(t) => {
775                                                         if let Some(trait_bound) = types.maybe_resolve_path(&t.path, None) {
776                                                                 if types.skip_path(&trait_bound) {
777                                                                         // Just hope rust deduces generic params if some bounds are skipable.
778                                                                         return;
779                                                                 }
780                                                         }
781                                                 }
782                                                 _ => {},
783                                         }
784                                 }
785                         }
786                         _ => {},
787                 }
788         }
789
790         write!(w, "<").unwrap();
791         for (idx, generic) in generics.params.iter().enumerate() {
792                 match generic {
793                         syn::GenericParam::Type(type_param) => {
794                                 write!(w, "{}", if idx != 0 { ", " } else { "" }).unwrap();
795                                 let type_ident = &type_param.ident;
796                                 types.write_c_type_in_generic_param(w, &syn::parse_quote!(#type_ident), Some(&gen_types), false);
797                         },
798                         syn::GenericParam::Lifetime(lt) => {
799                                 if concrete_lifetimes {
800                                         write!(w, "'static").unwrap();
801                                 } else {
802                                         write!(w, "{}'{}", if idx != 0 { ", " } else { "" }, lt.lifetime.ident).unwrap();
803                                 }
804                         },
805                         _ => unimplemented!(),
806                 }
807         }
808         write!(w, ">").unwrap();
809 }
810
811 pub fn maybe_write_lifetime_generics<W: std::io::Write>(w: &mut W, generics: &syn::Generics, types: &TypeResolver) {
812         let mut gen_types = GenericTypes::new(None);
813         assert!(gen_types.learn_generics(generics, types));
814         if generics.params.iter().any(|param| if let syn::GenericParam::Lifetime(_) = param { true } else { false }) {
815                 write!(w, "<").unwrap();
816                 for (idx, generic) in generics.params.iter().enumerate() {
817                         match generic {
818                                 syn::GenericParam::Type(_) => {},
819                                 syn::GenericParam::Lifetime(lt) => {
820                                         write!(w, "{}'{}", if idx != 0 { ", " } else { "" }, lt.lifetime.ident).unwrap();
821                                 },
822                                 _ => unimplemented!(),
823                         }
824                 }
825                 write!(w, ">").unwrap();
826         }
827 }