1 //! Printing logic for basic blocks of Rust-mapped code - parts of functions and declarations but
2 //! not the full mapping logic.
4 use std::collections::HashMap;
7 use proc_macro2::{TokenTree, Span};
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();
21 writeln!(cpp_header_file, "\t~{}() {{ {}_free(self); }}", ty, ty).unwrap();
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();
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() {
40 TokenTree::Punct(c) if c.as_char() == '=' => {
41 // syn gets '=' from '///' or '//!' as it is syntax for #[doc = ""]
43 TokenTree::Group(_) => continue, // eg #[derive()]
44 _ => unimplemented!(),
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();
55 _ => unimplemented!(),
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();
65 _ => unimplemented!(),
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.
76 /// Usable both for a function definition and declaration.
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() {
85 if sig.generics.lt_token.is_some() {
86 for generic in sig.generics.params.iter() {
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.
92 _ => unimplemented!(),
97 let mut first_arg = true;
98 let mut num_unused = 0;
99 for inp in sig.inputs.iter() {
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();
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.
125 syn::Pat::Ident(ident) => {
126 if !ident.attrs.is_empty() || ident.subpat.is_some() {
129 write!(w, "{}{}{}: ", if first_arg { "" } else { ", " }, if is_ref || !fn_decl { "" } else { "mut " }, ident.ident).unwrap();
132 syn::Pat::Wild(wild) => {
133 if !wild.attrs.is_empty() { unimplemented!(); }
134 write!(w, "{}unused_{}: ", if first_arg { "" } else { ", " }, num_unused).unwrap();
137 _ => unimplemented!(),
139 types.write_c_type(w, &*arg.ty, generics, false);
143 write!(w, ")").unwrap();
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
159 write!(w, "{}", this_param).unwrap();
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);
166 types.write_c_type(w, &*rtype, generics, true);
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() {
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) => {
189 if types.write_to_c_conversion_new_var(w, &$ident, &$ty, generics, false) {
190 write!(w, "\n\t{}", extra_indent).unwrap();
193 if types.write_from_c_conversion_new_var(w, &$ident, &$ty, generics) {
194 write!(w, "\n\t{}", extra_indent).unwrap();
200 syn::Pat::Ident(ident) => {
201 if !ident.attrs.is_empty() || ident.subpat.is_some() {
204 write_new_var!(ident.ident, *arg.ty);
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);
211 _ => unimplemented!(),
217 syn::ReturnType::Type(_, _) => {
218 write!(w, "let mut ret = ").unwrap();
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
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() {
235 syn::FnArg::Receiver(recv) => {
236 if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
238 write!(w, "self.this_arg").unwrap();
242 syn::FnArg::Typed(arg) => {
243 if types.skip_arg(&*arg.ty, generics) {
246 write!(w, ", ").unwrap();
249 types.no_arg_to_rust(w, &*arg.ty, generics);
253 if !arg.attrs.is_empty() { unimplemented!(); }
254 macro_rules! write_ident {
257 write!(w, ", ").unwrap();
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);
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);
272 syn::Pat::Ident(ident) => {
273 if !ident.attrs.is_empty() || ident.subpat.is_some() {
276 write_ident!(ident.ident);
278 syn::Pat::Wild(w) => {
279 if !w.attrs.is_empty() { unimplemented!(); }
280 write_ident!(format!("unused_{}", num_unused));
283 _ => unimplemented!(),
288 write!(w, ")").unwrap();
290 syn::ReturnType::Type(_, rtype) => {
291 write!(w, ";\n\t{}", extra_indent).unwrap();
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
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();
313 write!(w, "{} {{ inner: Box::into_raw(Box::new(ret)), is_owned: true }}", this_type).unwrap();
315 let new_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("ret", Span::call_site()), rtype, generics);
317 write!(w, "\n\t{}", extra_indent).unwrap();
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);
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);
326 write!(w, "\n\t{}", extra_indent).unwrap();
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);
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() {
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();
353 unimplemented!("Can't print generic params that have multiple non-lifetime bounds");
355 printed_param = true;
359 syn::GenericParam::Lifetime(lt) => {
360 if concrete_lifetimes {
361 write!(w, "'static").unwrap();
363 write!(w, "{}'{}", if idx != 0 { ", " } else { "" }, lt.lifetime.ident).unwrap();
366 _ => unimplemented!(),
369 write!(w, ">").unwrap();