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