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 // 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);
120 syn::Pat::Ident(ident) => {
121 if !ident.attrs.is_empty() || ident.subpat.is_some() {
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();
127 syn::Pat::Wild(wild) => {
128 if !wild.attrs.is_empty() { unimplemented!(); }
129 write!(w, "{}unused_{}: ", if first_arg { "" } else { ", " }, num_unused).unwrap();
132 _ => unimplemented!(),
134 w.write(&c_type).unwrap();
138 write!(w, ")").unwrap();
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
154 write!(w, "{}", this_param).unwrap();
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);
161 types.write_c_type(w, &*rtype, generics, true);
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() {
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) => {
184 if types.write_to_c_conversion_new_var(w, &$ident, &$ty, generics, false) {
185 write!(w, "\n\t{}", extra_indent).unwrap();
188 if types.write_from_c_conversion_new_var(w, &$ident, &$ty, generics) {
189 write!(w, "\n\t{}", extra_indent).unwrap();
195 syn::Pat::Ident(ident) => {
196 if !ident.attrs.is_empty() || ident.subpat.is_some() {
199 write_new_var!(ident.ident, *arg.ty);
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);
206 _ => unimplemented!(),
212 syn::ReturnType::Type(_, _) => {
213 write!(w, "let mut ret = ").unwrap();
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
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() {
230 syn::FnArg::Receiver(recv) => {
231 if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
233 write!(w, "self.this_arg").unwrap();
237 syn::FnArg::Typed(arg) => {
238 if types.skip_arg(&*arg.ty, generics) {
241 write!(w, ", ").unwrap();
244 types.no_arg_to_rust(w, &*arg.ty, generics);
248 if !arg.attrs.is_empty() { unimplemented!(); }
249 macro_rules! write_ident {
252 write!(w, ", ").unwrap();
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);
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);
267 syn::Pat::Ident(ident) => {
268 if !ident.attrs.is_empty() || ident.subpat.is_some() {
271 write_ident!(ident.ident);
273 syn::Pat::Wild(w) => {
274 if !w.attrs.is_empty() { unimplemented!(); }
275 write_ident!(format!("unused_{}", num_unused));
278 _ => unimplemented!(),
283 write!(w, ")").unwrap();
285 syn::ReturnType::Type(_, rtype) => {
286 write!(w, ";\n\t{}", extra_indent).unwrap();
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
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();
308 write!(w, "{} {{ inner: Box::into_raw(Box::new(ret)), is_owned: true }}", this_type).unwrap();
310 let new_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("ret", Span::call_site()), rtype, generics);
312 write!(w, "\n\t{}", extra_indent).unwrap();
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);
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);
321 write!(w, "\n\t{}", extra_indent).unwrap();
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);
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() {
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();
348 unimplemented!("Can't print generic params that have multiple non-lifetime bounds");
350 printed_param = true;
354 syn::GenericParam::Lifetime(lt) => {
355 if concrete_lifetimes {
356 write!(w, "'static").unwrap();
358 write!(w, "{}'{}", if idx != 0 { ", " } else { "" }, lt.lifetime.ident).unwrap();
361 _ => unimplemented!(),
364 write!(w, ">").unwrap();