[C++ bindings] Add move-assign operator, require rvalue for move
[rust-lightning] / c-bindings-gen / src / blocks.rs
1 //! Printing logic for basic blocks of Rust-mapped code - parts of functions and declarations but
2 //! not the full mapping logic.
3
4 use std::fs::File;
5 use std::io::Write;
6 use proc_macro2::{TokenTree, Span};
7
8 use crate::types::*;
9
10 /// Writes out a C++ wrapper class for the given type, which contains various utilities to access
11 /// the underlying C-mapped type safely avoiding some common memory management issues by handling
12 /// resource-freeing and prevending accidental raw copies.
13 pub fn write_cpp_wrapper(cpp_header_file: &mut File, ty: &str, has_destructor: bool) {
14         writeln!(cpp_header_file, "class {} {{", ty).unwrap();
15         writeln!(cpp_header_file, "private:").unwrap();
16         writeln!(cpp_header_file, "\tLDK{} self;", ty).unwrap();
17         writeln!(cpp_header_file, "public:").unwrap();
18         writeln!(cpp_header_file, "\t{}(const {}&) = delete;", ty, ty).unwrap();
19         writeln!(cpp_header_file, "\t{}({}&& o) : self(o.self) {{ memset(&o, 0, sizeof({})); }}", ty, ty, ty).unwrap();
20         writeln!(cpp_header_file, "\t{}(LDK{}&& m_self) : self(m_self) {{ memset(&m_self, 0, sizeof(LDK{})); }}", ty, ty, ty).unwrap();
21         writeln!(cpp_header_file, "\toperator LDK{}() && {{ LDK{} res = self; memset(&self, 0, sizeof(LDK{})); return res; }}", ty, ty, ty).unwrap();
22         if has_destructor {
23                 writeln!(cpp_header_file, "\t~{}() {{ {}_free(self); }}", ty, ty).unwrap();
24                 writeln!(cpp_header_file, "\t{}& operator=({}&& o) {{ {}_free(self); self = o.self; memset(&o, 0, sizeof({})); return *this; }}", ty, ty, ty, ty).unwrap();
25         } else {
26                 writeln!(cpp_header_file, "\t{}& operator=({}&& o) {{ self = o.self; memset(&o, 0, sizeof({})); return *this; }}", ty, ty, ty).unwrap();
27         }
28         writeln!(cpp_header_file, "\tLDK{}* operator &() {{ return &self; }}", ty).unwrap();
29         writeln!(cpp_header_file, "\tLDK{}* operator ->() {{ return &self; }}", ty).unwrap();
30         writeln!(cpp_header_file, "\tconst LDK{}* operator &() const {{ return &self; }}", ty).unwrap();
31         writeln!(cpp_header_file, "\tconst LDK{}* operator ->() const {{ return &self; }}", ty).unwrap();
32         writeln!(cpp_header_file, "}};").unwrap();
33 }
34
35 /// Prints the docs from a given attribute list unless its tagged no export
36 pub fn writeln_docs<W: std::io::Write>(w: &mut W, attrs: &[syn::Attribute], prefix: &str) {
37         for attr in attrs.iter() {
38                 let tokens_clone = attr.tokens.clone();
39                 let mut token_iter = tokens_clone.into_iter();
40                 if let Some(token) = token_iter.next() {
41                         match token {
42                                 TokenTree::Punct(c) if c.as_char() == '=' => {
43                                         // syn gets '=' from '///' or '//!' as it is syntax for #[doc = ""]
44                                 },
45                                 TokenTree::Group(_) => continue, // eg #[derive()]
46                                 _ => unimplemented!(),
47                         }
48                 } else { continue; }
49                 match attr.style {
50                         syn::AttrStyle::Inner(_) => {
51                                 match token_iter.next().unwrap() {
52                                         TokenTree::Literal(lit) => {
53                                                 // Drop the first and last chars from lit as they are always "
54                                                 let doc = format!("{}", lit);
55                                                 writeln!(w, "{}//!{}", prefix, &doc[1..doc.len() - 1]).unwrap();
56                                         },
57                                         _ => unimplemented!(),
58                                 }
59                         },
60                         syn::AttrStyle::Outer => {
61                                 match token_iter.next().unwrap() {
62                                         TokenTree::Literal(lit) => {
63                                                 // Drop the first and last chars from lit as they are always "
64                                                 let doc = format!("{}", lit);
65                                                 writeln!(w, "{}///{}", prefix, &doc[1..doc.len() - 1]).unwrap();
66                                         },
67                                         _ => unimplemented!(),
68                                 }
69                         },
70                 }
71         }
72 }
73
74 /// Print the parameters in a method declaration, starting after the open parenthesis, through and
75 /// including the closing parenthesis and return value, but not including the open bracket or any
76 /// trailing semicolons.
77 ///
78 /// Usable both for a function definition and declaration.
79 ///
80 /// this_param is used when returning Self or accepting a self parameter, and should be the
81 /// concrete, mapped type.
82 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) {
83         if sig.constness.is_some() || sig.asyncness.is_some() || sig.unsafety.is_some() ||
84                         sig.abi.is_some() || sig.variadic.is_some() {
85                 unimplemented!();
86         }
87         if sig.generics.lt_token.is_some() {
88                 for generic in sig.generics.params.iter() {
89                         match generic {
90                                 syn::GenericParam::Type(_)|syn::GenericParam::Lifetime(_) => {
91                                         // We ignore these, if they're not on skipped args, we'll blow up
92                                         // later, and lifetimes we just hope the C client enforces.
93                                 },
94                                 _ => unimplemented!(),
95                         }
96                 }
97         }
98
99         let mut first_arg = true;
100         let mut num_unused = 0;
101         for inp in sig.inputs.iter() {
102                 match inp {
103                         syn::FnArg::Receiver(recv) => {
104                                 if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
105                                 write!(w, "this_arg: {}{}",
106                                         match (self_ptr, recv.mutability.is_some()) {
107                                                 (true, true) => "*mut ",
108                                                 (true, false) => "*const ",
109                                                 (false, true) => "&mut ",
110                                                 (false, false) => "&",
111                                         }, this_param).unwrap();
112                                 assert!(first_arg);
113                                 first_arg = false;
114                         },
115                         syn::FnArg::Typed(arg) => {
116                                 if types.skip_arg(&*arg.ty, generics) { continue; }
117                                 if !arg.attrs.is_empty() { unimplemented!(); }
118                                 // First get the c type so that we can check if it ends up being a reference:
119                                 let mut c_type = Vec::new();
120                                 types.write_c_type(&mut c_type, &*arg.ty, generics, false);
121                                 match &*arg.pat {
122                                         syn::Pat::Ident(ident) => {
123                                                 if !ident.attrs.is_empty() || ident.subpat.is_some() {
124                                                         unimplemented!();
125                                                 }
126                                                 write!(w, "{}{}{}: ", if first_arg { "" } else { ", " }, if !fn_decl || c_type[0] == '&' as u8 || c_type[0] == '*' as u8 { "" } else { "mut " }, ident.ident).unwrap();
127                                                 first_arg = false;
128                                         },
129                                         syn::Pat::Wild(wild) => {
130                                                 if !wild.attrs.is_empty() { unimplemented!(); }
131                                                 write!(w, "{}unused_{}: ", if first_arg { "" } else { ", " }, num_unused).unwrap();
132                                                 num_unused += 1;
133                                         },
134                                         _ => unimplemented!(),
135                                 }
136                                 w.write(&c_type).unwrap();
137                         }
138                 }
139         }
140         write!(w, ")").unwrap();
141         match &sig.output {
142                 syn::ReturnType::Type(_, rtype) => {
143                         write!(w, " -> ").unwrap();
144                         if let Some(mut remaining_path) = first_seg_self(&*rtype) {
145                                 if remaining_path.next().is_none() {
146                                         write!(w, "{}", this_param).unwrap();
147                                         return;
148                                 }
149                         }
150                         if let syn::Type::Reference(r) = &**rtype {
151                                 // We can't return a reference, cause we allocate things on the stack.
152                                 types.write_c_type(w, &*r.elem, generics, true);
153                         } else {
154                                 types.write_c_type(w, &*rtype, generics, true);
155                         }
156                 },
157                 _ => {},
158         }
159 }
160
161 /// Print the main part of a method declaration body, starting with a newline after the function
162 /// open bracket and converting each function parameter to or from C-mapped types. Ends with "let
163 /// mut ret = " assuming the next print will be the unmapped Rust function to call followed by the
164 /// parameters we mapped to/from C here.
165 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) {
166         let mut num_unused = 0;
167         for inp in sig.inputs.iter() {
168                 match inp {
169                         syn::FnArg::Receiver(_) => {},
170                         syn::FnArg::Typed(arg) => {
171                                 if types.skip_arg(&*arg.ty, generics) { continue; }
172                                 if !arg.attrs.is_empty() { unimplemented!(); }
173                                 macro_rules! write_new_var {
174                                         ($ident: expr, $ty: expr) => {
175                                                 if to_c {
176                                                         if types.write_to_c_conversion_new_var(w, &$ident, &$ty, generics, false) {
177                                                                 write!(w, "\n\t{}", extra_indent).unwrap();
178                                                         }
179                                                 } else {
180                                                         if types.write_from_c_conversion_new_var(w, &$ident, &$ty, generics) {
181                                                                 write!(w, "\n\t{}", extra_indent).unwrap();
182                                                         }
183                                                 }
184                                         }
185                                 }
186                                 match &*arg.pat {
187                                         syn::Pat::Ident(ident) => {
188                                                 if !ident.attrs.is_empty() || ident.subpat.is_some() {
189                                                         unimplemented!();
190                                                 }
191                                                 write_new_var!(ident.ident, *arg.ty);
192                                         },
193                                         syn::Pat::Wild(w) => {
194                                                 if !w.attrs.is_empty() { unimplemented!(); }
195                                                 write_new_var!(syn::Ident::new(&format!("unused_{}", num_unused), Span::call_site()), *arg.ty);
196                                                 num_unused += 1;
197                                         },
198                                         _ => unimplemented!(),
199                                 }
200                         }
201                 }
202         }
203         match &sig.output {
204                 syn::ReturnType::Type(_, _) => {
205                         write!(w, "let mut ret = ").unwrap();
206                 },
207                 _ => {},
208         }
209 }
210
211 /// Prints the parameters in a method call, starting after the open parenthesis and ending with a
212 /// final return statement returning the method's result. Should be followed by a single closing
213 /// bracket.
214 ///
215 /// The return value is expected to be bound to a variable named `ret` which is available after a
216 /// method-call-ending semicolon.
217 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) {
218         let mut first_arg = true;
219         let mut num_unused = 0;
220         for inp in sig.inputs.iter() {
221                 match inp {
222                         syn::FnArg::Receiver(recv) => {
223                                 if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
224                                 if to_c {
225                                         write!(w, "self.this_arg").unwrap();
226                                         first_arg = false;
227                                 }
228                         },
229                         syn::FnArg::Typed(arg) => {
230                                 if types.skip_arg(&*arg.ty, generics) {
231                                         if !to_c {
232                                                 if !first_arg {
233                                                         write!(w, ", ").unwrap();
234                                                 }
235                                                 first_arg = false;
236                                                 types.no_arg_to_rust(w, &*arg.ty, generics);
237                                         }
238                                         continue;
239                                 }
240                                 if !arg.attrs.is_empty() { unimplemented!(); }
241                                 macro_rules! write_ident {
242                                         ($ident: expr) => {
243                                                 if !first_arg {
244                                                         write!(w, ", ").unwrap();
245                                                 }
246                                                 first_arg = false;
247                                                 if to_c {
248                                                         types.write_to_c_conversion_inline_prefix(w, &*arg.ty, generics, false);
249                                                         write!(w, "{}", $ident).unwrap();
250                                                         types.write_to_c_conversion_inline_suffix(w, &*arg.ty, generics, false);
251                                                 } else {
252                                                         types.write_from_c_conversion_prefix(w, &*arg.ty, generics);
253                                                         write!(w, "{}", $ident).unwrap();
254                                                         types.write_from_c_conversion_suffix(w, &*arg.ty, generics);
255                                                 }
256                                         }
257                                 }
258                                 match &*arg.pat {
259                                         syn::Pat::Ident(ident) => {
260                                                 if !ident.attrs.is_empty() || ident.subpat.is_some() {
261                                                         unimplemented!();
262                                                 }
263                                                 write_ident!(ident.ident);
264                                         },
265                                         syn::Pat::Wild(w) => {
266                                                 if !w.attrs.is_empty() { unimplemented!(); }
267                                                 write_ident!(format!("unused_{}", num_unused));
268                                                 num_unused += 1;
269                                         },
270                                         _ => unimplemented!(),
271                                 }
272                         }
273                 }
274         }
275         write!(w, ")").unwrap();
276         match &sig.output {
277                 syn::ReturnType::Type(_, rtype) => {
278                         write!(w, ";\n\t{}", extra_indent).unwrap();
279
280                         let self_segs_iter = first_seg_self(&*rtype);
281                         if to_c && first_seg_self(&*rtype).is_some() {
282                                 // Assume rather blindly that we're returning an associated trait from a C fn call to a Rust trait object.
283                                 write!(w, "ret").unwrap();
284                         } else if !to_c && self_segs_iter.is_some() && self_segs_iter.unwrap().next().is_none() {
285                                 // If we're returning "Self" (and not "Self::X"), just do it manually
286                                 write!(w, "{} {{ inner: Box::into_raw(Box::new(ret)), is_owned: true }}", this_type).unwrap();
287                         } else if to_c {
288                                 let new_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("ret", Span::call_site()), rtype, generics);
289                                 if new_var {
290                                         write!(w, "\n\t{}", extra_indent).unwrap();
291                                 }
292                                 types.write_from_c_conversion_prefix(w, &*rtype, generics);
293                                 write!(w, "ret").unwrap();
294                                 types.write_from_c_conversion_suffix(w, &*rtype, generics);
295                         } else {
296                                 let ret_returned = if let syn::Type::Reference(_) = &**rtype { true } else { false };
297                                 let new_var = types.write_to_c_conversion_new_var(w, &syn::Ident::new("ret", Span::call_site()), &rtype, generics, true);
298                                 if new_var {
299                                         write!(w, "\n\t{}", extra_indent).unwrap();
300                                 }
301                                 types.write_to_c_conversion_inline_prefix(w, &rtype, generics, true);
302                                 write!(w, "{}ret", if ret_returned && !new_var { "*" } else { "" }).unwrap();
303                                 types.write_to_c_conversion_inline_suffix(w, &rtype, generics, true);
304                         }
305                 }
306                 _ => {},
307         }
308 }
309
310 /// Prints concrete generic parameters for a struct/trait/function, including the less-than and
311 /// greater-than symbols, if any generic parameters are defined.
312 pub fn maybe_write_generics<W: std::io::Write>(w: &mut W, generics: &syn::Generics, types: &TypeResolver, concrete_lifetimes: bool) {
313         let mut gen_types = GenericTypes::new();
314         assert!(gen_types.learn_generics(generics, types));
315         if !generics.params.is_empty() {
316                 write!(w, "<").unwrap();
317                 for (idx, generic) in generics.params.iter().enumerate() {
318                         match generic {
319                                 syn::GenericParam::Type(type_param) => {
320                                         let mut printed_param = false;
321                                         for bound in type_param.bounds.iter() {
322                                                 if let syn::TypeParamBound::Trait(trait_bound) = bound {
323                                                         assert_simple_bound(&trait_bound);
324                                                         write!(w, "{}{}", if idx != 0 { ", " } else { "" }, gen_types.maybe_resolve_ident(&type_param.ident).unwrap()).unwrap();
325                                                         if printed_param {
326                                                                 unimplemented!("Can't print generic params that have multiple non-lifetime bounds");
327                                                         }
328                                                         printed_param = true;
329                                                 }
330                                         }
331                                 },
332                                 syn::GenericParam::Lifetime(lt) => {
333                                         if concrete_lifetimes {
334                                                 write!(w, "'static").unwrap();
335                                         } else {
336                                                 write!(w, "{}'{}", if idx != 0 { ", " } else { "" }, lt.lifetime.ident).unwrap();
337                                         }
338                                 },
339                                 _ => unimplemented!(),
340                         }
341                 }
342                 write!(w, ">").unwrap();
343         }
344 }
345
346