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();
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();
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();
26 writeln!(cpp_header_file, "\t{}& operator=({}&& o) {{ self = o.self; memset(&o, 0, sizeof({})); return *this; }}", ty, ty, ty).unwrap();
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();
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() {
42 TokenTree::Punct(c) if c.as_char() == '=' => {
43 // syn gets '=' from '///' or '//!' as it is syntax for #[doc = ""]
45 TokenTree::Group(_) => continue, // eg #[derive()]
46 _ => unimplemented!(),
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();
57 _ => unimplemented!(),
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();
67 _ => unimplemented!(),
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.
78 /// Usable both for a function definition and declaration.
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() {
87 if sig.generics.lt_token.is_some() {
88 for generic in sig.generics.params.iter() {
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.
94 _ => unimplemented!(),
99 let mut first_arg = true;
100 let mut num_unused = 0;
101 for inp in sig.inputs.iter() {
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();
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);
122 syn::Pat::Ident(ident) => {
123 if !ident.attrs.is_empty() || ident.subpat.is_some() {
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();
129 syn::Pat::Wild(wild) => {
130 if !wild.attrs.is_empty() { unimplemented!(); }
131 write!(w, "{}unused_{}: ", if first_arg { "" } else { ", " }, num_unused).unwrap();
134 _ => unimplemented!(),
136 w.write(&c_type).unwrap();
140 write!(w, ")").unwrap();
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();
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);
154 types.write_c_type(w, &*rtype, generics, true);
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() {
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) => {
176 if types.write_to_c_conversion_new_var(w, &$ident, &$ty, generics, false) {
177 write!(w, "\n\t{}", extra_indent).unwrap();
180 if types.write_from_c_conversion_new_var(w, &$ident, &$ty, generics) {
181 write!(w, "\n\t{}", extra_indent).unwrap();
187 syn::Pat::Ident(ident) => {
188 if !ident.attrs.is_empty() || ident.subpat.is_some() {
191 write_new_var!(ident.ident, *arg.ty);
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);
198 _ => unimplemented!(),
204 syn::ReturnType::Type(_, _) => {
205 write!(w, "let mut ret = ").unwrap();
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
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() {
222 syn::FnArg::Receiver(recv) => {
223 if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
225 write!(w, "self.this_arg").unwrap();
229 syn::FnArg::Typed(arg) => {
230 if types.skip_arg(&*arg.ty, generics) {
233 write!(w, ", ").unwrap();
236 types.no_arg_to_rust(w, &*arg.ty, generics);
240 if !arg.attrs.is_empty() { unimplemented!(); }
241 macro_rules! write_ident {
244 write!(w, ", ").unwrap();
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);
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);
259 syn::Pat::Ident(ident) => {
260 if !ident.attrs.is_empty() || ident.subpat.is_some() {
263 write_ident!(ident.ident);
265 syn::Pat::Wild(w) => {
266 if !w.attrs.is_empty() { unimplemented!(); }
267 write_ident!(format!("unused_{}", num_unused));
270 _ => unimplemented!(),
275 write!(w, ")").unwrap();
277 syn::ReturnType::Type(_, rtype) => {
278 write!(w, ";\n\t{}", extra_indent).unwrap();
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();
288 let new_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("ret", Span::call_site()), rtype, generics);
290 write!(w, "\n\t{}", extra_indent).unwrap();
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);
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);
299 write!(w, "\n\t{}", extra_indent).unwrap();
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);
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() {
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();
326 unimplemented!("Can't print generic params that have multiple non-lifetime bounds");
328 printed_param = true;
332 syn::GenericParam::Lifetime(lt) => {
333 if concrete_lifetimes {
334 write!(w, "'static").unwrap();
336 write!(w, "{}'{}", if idx != 0 { ", " } else { "" }, lt.lifetime.ident).unwrap();
339 _ => unimplemented!(),
342 write!(w, ">").unwrap();