]> git.bitcoin.ninja Git - rust-lightning/blob - c-bindings-gen/src/blocks.rs
[bindings] Push generic resolution into resolve_path
[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                                 let mut is_ref = if let syn::Type::Reference(_) = *arg.ty { true } else { false };
117                                 if let syn::Type::Reference(syn::TypeReference { ref elem, .. }) = *arg.ty {
118                                         if let syn::Type::Slice(_) = &**elem {
119                                                 // Slices are mapped to non-ref Vec types, so we want them to be mut
120                                                 // letting us drain(..) the underlying Vec.
121                                                 is_ref = false;
122                                         }
123                                 }
124                                 match &*arg.pat {
125                                         syn::Pat::Ident(ident) => {
126                                                 if !ident.attrs.is_empty() || ident.subpat.is_some() {
127                                                         unimplemented!();
128                                                 }
129                                                 write!(w, "{}{}{}: ", if first_arg { "" } else { ", " }, if is_ref || !fn_decl { "" } else { "mut " }, ident.ident).unwrap();
130                                                 first_arg = false;
131                                         },
132                                         syn::Pat::Wild(wild) => {
133                                                 if !wild.attrs.is_empty() { unimplemented!(); }
134                                                 write!(w, "{}unused_{}: ", if first_arg { "" } else { ", " }, num_unused).unwrap();
135                                                 num_unused += 1;
136                                         },
137                                         _ => unimplemented!(),
138                                 }
139                                 types.write_c_type(w, &*arg.ty, generics, false);
140                         }
141                 }
142         }
143         write!(w, ")").unwrap();
144         match &sig.output {
145                 syn::ReturnType::Type(_, rtype) => {
146                         write!(w, " -> ").unwrap();
147                         if let Some(mut remaining_path) = first_seg_self(&*rtype) {
148                                 if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
149                                         // We're returning an associated type in a trait impl. Its probably a safe bet
150                                         // that its also a trait, so just return the trait type.
151                                         let real_type = associated_types.get(associated_seg).unwrap();
152                                         types.write_c_type(w, &syn::Type::Path(syn::TypePath { qself: None,
153                                                 path: syn::PathSegment {
154                                                         ident: (*real_type).clone(),
155                                                         arguments: syn::PathArguments::None
156                                                 }.into()
157                                         }), generics, true);
158                                 } else {
159                                         write!(w, "{}", this_param).unwrap();
160                                 }
161                         } else {
162                                 if let syn::Type::Reference(r) = &**rtype {
163                                         // We can't return a reference, cause we allocate things on the stack.
164                                         types.write_c_type(w, &*r.elem, generics, true);
165                                 } else {
166                                         types.write_c_type(w, &*rtype, generics, true);
167                                 }
168                         }
169                 },
170                 _ => {},
171         }
172 }
173
174 /// Print the main part of a method declaration body, starting with a newline after the function
175 /// open bracket and converting each function parameter to or from C-mapped types. Ends with "let
176 /// mut ret = " assuming the next print will be the unmapped Rust function to call followed by the
177 /// parameters we mapped to/from C here.
178 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) {
179         let mut num_unused = 0;
180         for inp in sig.inputs.iter() {
181                 match inp {
182                         syn::FnArg::Receiver(_) => {},
183                         syn::FnArg::Typed(arg) => {
184                                 if types.skip_arg(&*arg.ty, generics) { continue; }
185                                 if !arg.attrs.is_empty() { unimplemented!(); }
186                                 macro_rules! write_new_var {
187                                         ($ident: expr, $ty: expr) => {
188                                                 if to_c {
189                                                         if types.write_to_c_conversion_new_var(w, &$ident, &$ty, generics, false) {
190                                                                 write!(w, "\n\t{}", extra_indent).unwrap();
191                                                         }
192                                                 } else {
193                                                         if types.write_from_c_conversion_new_var(w, &$ident, &$ty, generics) {
194                                                                 write!(w, "\n\t{}", extra_indent).unwrap();
195                                                         }
196                                                 }
197                                         }
198                                 }
199                                 match &*arg.pat {
200                                         syn::Pat::Ident(ident) => {
201                                                 if !ident.attrs.is_empty() || ident.subpat.is_some() {
202                                                         unimplemented!();
203                                                 }
204                                                 write_new_var!(ident.ident, *arg.ty);
205                                         },
206                                         syn::Pat::Wild(w) => {
207                                                 if !w.attrs.is_empty() { unimplemented!(); }
208                                                 write_new_var!(syn::Ident::new(&format!("unused_{}", num_unused), Span::call_site()), *arg.ty);
209                                                 num_unused += 1;
210                                         },
211                                         _ => unimplemented!(),
212                                 }
213                         }
214                 }
215         }
216         match &sig.output {
217                 syn::ReturnType::Type(_, _) => {
218                         write!(w, "let mut ret = ").unwrap();
219                 },
220                 _ => {},
221         }
222 }
223
224 /// Prints the parameters in a method call, starting after the open parenthesis and ending with a
225 /// final return statement returning the method's result. Should be followed by a single closing
226 /// bracket.
227 ///
228 /// The return value is expected to be bound to a variable named `ret` which is available after a
229 /// method-call-ending semicolon.
230 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) {
231         let mut first_arg = true;
232         let mut num_unused = 0;
233         for inp in sig.inputs.iter() {
234                 match inp {
235                         syn::FnArg::Receiver(recv) => {
236                                 if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
237                                 if to_c {
238                                         write!(w, "self.this_arg").unwrap();
239                                         first_arg = false;
240                                 }
241                         },
242                         syn::FnArg::Typed(arg) => {
243                                 if types.skip_arg(&*arg.ty, generics) {
244                                         if !to_c {
245                                                 if !first_arg {
246                                                         write!(w, ", ").unwrap();
247                                                 }
248                                                 first_arg = false;
249                                                 types.no_arg_to_rust(w, &*arg.ty, generics);
250                                         }
251                                         continue;
252                                 }
253                                 if !arg.attrs.is_empty() { unimplemented!(); }
254                                 macro_rules! write_ident {
255                                         ($ident: expr) => {
256                                                 if !first_arg {
257                                                         write!(w, ", ").unwrap();
258                                                 }
259                                                 first_arg = false;
260                                                 if to_c {
261                                                         types.write_to_c_conversion_inline_prefix(w, &*arg.ty, generics, false);
262                                                         write!(w, "{}", $ident).unwrap();
263                                                         types.write_to_c_conversion_inline_suffix(w, &*arg.ty, generics, false);
264                                                 } else {
265                                                         types.write_from_c_conversion_prefix(w, &*arg.ty, generics);
266                                                         write!(w, "{}", $ident).unwrap();
267                                                         types.write_from_c_conversion_suffix(w, &*arg.ty, generics);
268                                                 }
269                                         }
270                                 }
271                                 match &*arg.pat {
272                                         syn::Pat::Ident(ident) => {
273                                                 if !ident.attrs.is_empty() || ident.subpat.is_some() {
274                                                         unimplemented!();
275                                                 }
276                                                 write_ident!(ident.ident);
277                                         },
278                                         syn::Pat::Wild(w) => {
279                                                 if !w.attrs.is_empty() { unimplemented!(); }
280                                                 write_ident!(format!("unused_{}", num_unused));
281                                                 num_unused += 1;
282                                         },
283                                         _ => unimplemented!(),
284                                 }
285                         }
286                 }
287         }
288         write!(w, ")").unwrap();
289         match &sig.output {
290                 syn::ReturnType::Type(_, rtype) => {
291                         write!(w, ";\n\t{}", extra_indent).unwrap();
292
293                         if to_c && first_seg_self(&*rtype).is_some() {
294                                 // Assume rather blindly that we're returning an associated trait from a C fn call to a Rust trait object.
295                                 write!(w, "ret").unwrap();
296                         } else if !to_c && first_seg_self(&*rtype).is_some() {
297                                 if let Some(mut remaining_path) = first_seg_self(&*rtype) {
298                                         if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
299                                                 let real_type = associated_types.get(associated_seg).unwrap();
300                                                 if let Some(t) = types.crate_types.traits.get(&types.maybe_resolve_ident(&real_type).unwrap()) {
301                                                         // We're returning an associated trait from a Rust fn call to a C trait
302                                                         // object.
303                                                         writeln!(w, "let mut rust_obj = {} {{ inner: Box::into_raw(Box::new(ret)), is_owned: true }};", this_type).unwrap();
304                                                         writeln!(w, "\t{}let mut ret = {}_as_{}(&rust_obj);", extra_indent, this_type, t.ident).unwrap();
305                                                         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();
306                                                         writeln!(w, "\t{}rust_obj.inner = std::ptr::null_mut();", extra_indent).unwrap();
307                                                         writeln!(w, "\t{}ret.free = Some({}_free_void);", extra_indent, this_type).unwrap();
308                                                         writeln!(w, "\t{}ret", extra_indent).unwrap();
309                                                         return;
310                                                 }
311                                         }
312                                 }
313                                 write!(w, "{} {{ inner: Box::into_raw(Box::new(ret)), is_owned: true }}", this_type).unwrap();
314                         } else if to_c {
315                                 let new_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("ret", Span::call_site()), rtype, generics);
316                                 if new_var {
317                                         write!(w, "\n\t{}", extra_indent).unwrap();
318                                 }
319                                 types.write_from_c_conversion_prefix(w, &*rtype, generics);
320                                 write!(w, "ret").unwrap();
321                                 types.write_from_c_conversion_suffix(w, &*rtype, generics);
322                         } else {
323                                 let ret_returned = if let syn::Type::Reference(_) = &**rtype { true } else { false };
324                                 let new_var = types.write_to_c_conversion_new_var(w, &syn::Ident::new("ret", Span::call_site()), &rtype, generics, true);
325                                 if new_var {
326                                         write!(w, "\n\t{}", extra_indent).unwrap();
327                                 }
328                                 types.write_to_c_conversion_inline_prefix(w, &rtype, generics, true);
329                                 write!(w, "{}ret", if ret_returned && !new_var { "*" } else { "" }).unwrap();
330                                 types.write_to_c_conversion_inline_suffix(w, &rtype, generics, true);
331                         }
332                 }
333                 _ => {},
334         }
335 }
336
337 /// Prints concrete generic parameters for a struct/trait/function, including the less-than and
338 /// greater-than symbols, if any generic parameters are defined.
339 pub fn maybe_write_generics<W: std::io::Write>(w: &mut W, generics: &syn::Generics, types: &TypeResolver, concrete_lifetimes: bool) {
340         let mut gen_types = GenericTypes::new();
341         assert!(gen_types.learn_generics(generics, types));
342         if !generics.params.is_empty() {
343                 write!(w, "<").unwrap();
344                 for (idx, generic) in generics.params.iter().enumerate() {
345                         match generic {
346                                 syn::GenericParam::Type(type_param) => {
347                                         let mut printed_param = false;
348                                         for bound in type_param.bounds.iter() {
349                                                 if let syn::TypeParamBound::Trait(trait_bound) = bound {
350                                                         assert_simple_bound(&trait_bound);
351                                                         write!(w, "{}{}", if idx != 0 { ", " } else { "" }, gen_types.maybe_resolve_ident(&type_param.ident).unwrap()).unwrap();
352                                                         if printed_param {
353                                                                 unimplemented!("Can't print generic params that have multiple non-lifetime bounds");
354                                                         }
355                                                         printed_param = true;
356                                                 }
357                                         }
358                                 },
359                                 syn::GenericParam::Lifetime(lt) => {
360                                         if concrete_lifetimes {
361                                                 write!(w, "'static").unwrap();
362                                         } else {
363                                                 write!(w, "{}'{}", if idx != 0 { ", " } else { "" }, lt.lifetime.ident).unwrap();
364                                         }
365                                 },
366                                 _ => unimplemented!(),
367                         }
368                 }
369                 write!(w, ">").unwrap();
370         }
371 }
372
373