1 //! Printing logic for basic blocks of Rust-mapped code - parts of functions and declarations but
2 //! not the full mapping logic.
6 use proc_macro2::{TokenTree, Span};
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();
20 writeln!(cpp_header_file, "\t~{}() {{ {}_free(self); }}", ty, ty).unwrap();
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();
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() {
39 TokenTree::Punct(c) if c.as_char() == '=' => {
40 // syn gets '=' from '///' or '//!' as it is syntax for #[doc = ""]
42 TokenTree::Group(_) => continue, // eg #[derive()]
43 _ => unimplemented!(),
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();
54 _ => unimplemented!(),
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();
64 _ => unimplemented!(),
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.
75 /// Usable both for a function definition and declaration.
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() {
84 if sig.generics.lt_token.is_some() {
85 for generic in sig.generics.params.iter() {
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.
91 _ => unimplemented!(),
96 let mut first_arg = true;
97 let mut num_unused = 0;
98 for inp in sig.inputs.iter() {
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();
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);
119 syn::Pat::Ident(ident) => {
120 if !ident.attrs.is_empty() || ident.subpat.is_some() {
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();
126 syn::Pat::Wild(wild) => {
127 if !wild.attrs.is_empty() { unimplemented!(); }
128 write!(w, "{}unused_{}: ", if first_arg { "" } else { ", " }, num_unused).unwrap();
131 _ => unimplemented!(),
133 w.write(&c_type).unwrap();
137 write!(w, ")").unwrap();
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();
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);
151 types.write_c_type(w, &*rtype, generics, true);
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() {
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) => {
173 if types.write_to_c_conversion_new_var(w, &$ident, &$ty, generics, false) {
174 write!(w, "\n\t{}", extra_indent).unwrap();
177 if types.write_from_c_conversion_new_var(w, &$ident, &$ty, generics) {
178 write!(w, "\n\t{}", extra_indent).unwrap();
184 syn::Pat::Ident(ident) => {
185 if !ident.attrs.is_empty() || ident.subpat.is_some() {
188 write_new_var!(ident.ident, *arg.ty);
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);
195 _ => unimplemented!(),
201 syn::ReturnType::Type(_, _) => {
202 write!(w, "let mut ret = ").unwrap();
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
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() {
219 syn::FnArg::Receiver(recv) => {
220 if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
222 write!(w, "self.this_arg").unwrap();
226 syn::FnArg::Typed(arg) => {
227 if types.skip_arg(&*arg.ty, generics) {
230 write!(w, ", ").unwrap();
233 types.no_arg_to_rust(w, &*arg.ty, generics);
237 if !arg.attrs.is_empty() { unimplemented!(); }
238 macro_rules! write_ident {
241 write!(w, ", ").unwrap();
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);
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);
256 syn::Pat::Ident(ident) => {
257 if !ident.attrs.is_empty() || ident.subpat.is_some() {
260 write_ident!(ident.ident);
262 syn::Pat::Wild(w) => {
263 if !w.attrs.is_empty() { unimplemented!(); }
264 write_ident!(format!("unused_{}", num_unused));
267 _ => unimplemented!(),
272 write!(w, ")").unwrap();
274 syn::ReturnType::Type(_, rtype) => {
275 write!(w, ";\n\t{}", extra_indent).unwrap();
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();
285 let new_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("ret", Span::call_site()), rtype, generics);
287 write!(w, "\n\t{}", extra_indent).unwrap();
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);
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);
296 write!(w, "\n\t{}", extra_indent).unwrap();
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);
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() {
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();
323 unimplemented!("Can't print generic params that have multiple non-lifetime bounds");
325 printed_param = true;
329 syn::GenericParam::Lifetime(lt) => {
330 if concrete_lifetimes {
331 write!(w, "'static").unwrap();
333 write!(w, "{}'{}", if idx != 0 { ", " } else { "" }, lt.lifetime.ident).unwrap();
336 _ => unimplemented!(),
339 write!(w, ">").unwrap();