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