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};
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 writeln!(cpp_header_file, "\t{}({}&& o) : self(o.self) {{ memset(&o, 0, sizeof({})); }}", ty, ty, ty).unwrap();
21 writeln!(cpp_header_file, "\t{}(LDK{}&& m_self) : self(m_self) {{ memset(&m_self, 0, sizeof(LDK{})); }}", ty, ty, ty).unwrap();
22 writeln!(cpp_header_file, "\toperator LDK{}() && {{ LDK{} res = self; memset(&self, 0, sizeof(LDK{})); return res; }}", ty, ty, ty).unwrap();
24 writeln!(cpp_header_file, "\t~{}() {{ {}_free(self); }}", ty, ty).unwrap();
25 writeln!(cpp_header_file, "\t{}& operator=({}&& o) {{ {}_free(self); self = o.self; memset(&o, 0, sizeof({})); return *this; }}", ty, ty, ty, ty).unwrap();
27 writeln!(cpp_header_file, "\t{}& operator=({}&& o) {{ self = o.self; memset(&o, 0, sizeof({})); return *this; }}", ty, ty, ty).unwrap();
29 writeln!(cpp_header_file, "\tLDK{}* operator &() {{ return &self; }}", ty).unwrap();
30 writeln!(cpp_header_file, "\tLDK{}* operator ->() {{ return &self; }}", ty).unwrap();
31 writeln!(cpp_header_file, "\tconst LDK{}* operator &() const {{ return &self; }}", ty).unwrap();
32 writeln!(cpp_header_file, "\tconst LDK{}* operator ->() const {{ return &self; }}", ty).unwrap();
33 writeln!(cpp_header_file, "}};").unwrap();
36 /// Writes out a C-callable concrete Result<A, B> struct and utility methods
37 pub fn write_result_block<W: std::io::Write>(w: &mut W, opts: &GlobalOpts, mangled_container: &str, ok_type: &str, err_type: &str) {
38 writeln!(w, "#[repr(C)]").unwrap();
39 writeln!(w, "pub union {}Ptr {{", mangled_container).unwrap();
41 writeln!(w, "\tpub result: *mut {},", ok_type).unwrap();
43 writeln!(w, "\t/// Note that this value is always NULL, as there are no contents in the OK variant").unwrap();
44 writeln!(w, "\tpub result: *mut std::ffi::c_void,").unwrap();
47 writeln!(w, "\tpub err: *mut {},", err_type).unwrap();
49 writeln!(w, "\t/// Note that this value is always NULL, as there are no contents in the Err variant").unwrap();
50 writeln!(w, "\tpub err: *mut std::ffi::c_void,").unwrap();
52 writeln!(w, "}}").unwrap();
53 writeln!(w, "{}", opts.struct_attributes).unwrap();
54 writeln!(w, "pub struct {} {{", mangled_container).unwrap();
55 writeln!(w, "\tpub contents: {}Ptr,", mangled_container).unwrap();
56 writeln!(w, "\tpub result_ok: bool,").unwrap();
57 writeln!(w, "}}").unwrap();
59 writeln!(w, "#[no_mangle]").unwrap();
61 writeln!(w, "pub extern \"C\" fn {}_ok(o: {}) -> {} {{", mangled_container, ok_type, mangled_container).unwrap();
63 writeln!(w, "pub extern \"C\" fn {}_ok() -> {} {{", mangled_container, mangled_container).unwrap();
65 writeln!(w, "\t{} {{", mangled_container).unwrap();
66 writeln!(w, "\t\tcontents: {}Ptr {{", mangled_container).unwrap();
68 writeln!(w, "\t\t\tresult: Box::into_raw(Box::new(o)),").unwrap();
70 writeln!(w, "\t\t\tresult: std::ptr::null_mut(),").unwrap();
72 writeln!(w, "\t\t}},").unwrap();
73 writeln!(w, "\t\tresult_ok: true,").unwrap();
74 writeln!(w, "\t}}").unwrap();
75 writeln!(w, "}}").unwrap();
77 writeln!(w, "#[no_mangle]").unwrap();
79 writeln!(w, "pub extern \"C\" fn {}_err(e: {}) -> {} {{", mangled_container, err_type, mangled_container).unwrap();
81 writeln!(w, "pub extern \"C\" fn {}_err() -> {} {{", mangled_container, mangled_container).unwrap();
83 writeln!(w, "\t{} {{", mangled_container).unwrap();
84 writeln!(w, "\t\tcontents: {}Ptr {{", mangled_container).unwrap();
86 writeln!(w, "\t\t\terr: Box::into_raw(Box::new(e)),").unwrap();
88 writeln!(w, "\t\t\terr: std::ptr::null_mut(),").unwrap();
90 writeln!(w, "\t\t}},").unwrap();
91 writeln!(w, "\t\tresult_ok: false,").unwrap();
92 writeln!(w, "\t}}").unwrap();
93 writeln!(w, "}}").unwrap();
95 writeln!(w, "#[no_mangle]").unwrap();
96 writeln!(w, "pub extern \"C\" fn {}_free(_res: {}) {{ }}", mangled_container, mangled_container).unwrap();
97 writeln!(w, "impl Drop for {} {{", mangled_container).unwrap();
98 writeln!(w, "\tfn drop(&mut self) {{").unwrap();
99 writeln!(w, "\t\tif self.result_ok {{").unwrap();
101 writeln!(w, "\t\t\tif unsafe {{ !(self.contents.result as *mut ()).is_null() }} {{").unwrap();
102 writeln!(w, "\t\t\t\tlet _ = unsafe {{ Box::from_raw(self.contents.result) }};").unwrap();
103 writeln!(w, "\t\t\t}}").unwrap();
105 writeln!(w, "\t\t}} else {{").unwrap();
106 if err_type != "()" {
107 writeln!(w, "\t\t\tif unsafe {{ !(self.contents.err as *mut ()).is_null() }} {{").unwrap();
108 writeln!(w, "\t\t\t\tlet _ = unsafe {{ Box::from_raw(self.contents.err) }};").unwrap();
109 writeln!(w, "\t\t\t}}").unwrap();
111 writeln!(w, "\t\t}}").unwrap();
112 writeln!(w, "\t}}").unwrap();
113 writeln!(w, "}}").unwrap();
115 // TODO: Templates should use () now that they can, too
116 let templ_ok_type = if ok_type != "()" { ok_type } else { "u8" };
117 let templ_err_type = if err_type != "()" { err_type } else { "u8" };
119 writeln!(w, "impl From<crate::c_types::CResultTempl<{}, {}>> for {} {{", templ_ok_type, templ_err_type, mangled_container).unwrap();
120 writeln!(w, "\tfn from(mut o: crate::c_types::CResultTempl<{}, {}>) -> Self {{", templ_ok_type, templ_err_type).unwrap();
121 writeln!(w, "\t\tlet contents = if o.result_ok {{").unwrap();
123 writeln!(w, "\t\t\tlet result = unsafe {{ o.contents.result }};").unwrap();
124 writeln!(w, "\t\t\tunsafe {{ o.contents.result = std::ptr::null_mut() }};").unwrap();
125 writeln!(w, "\t\t\t{}Ptr {{ result }}", mangled_container).unwrap();
127 writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(o.contents.result) }};").unwrap();
128 writeln!(w, "\t\t\to.contents.result = std::ptr::null_mut();").unwrap();
129 writeln!(w, "\t\t\t{}Ptr {{ result: std::ptr::null_mut() }}", mangled_container).unwrap();
131 writeln!(w, "\t\t}} else {{").unwrap();
132 if err_type != "()" {
133 writeln!(w, "\t\t\tlet err = unsafe {{ o.contents.err }};").unwrap();
134 writeln!(w, "\t\t\tunsafe {{ o.contents.err = std::ptr::null_mut(); }}").unwrap();
135 writeln!(w, "\t\t\t{}Ptr {{ err }}", mangled_container).unwrap();
137 writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(o.contents.err) }};").unwrap();
138 writeln!(w, "\t\t\to.contents.err = std::ptr::null_mut();").unwrap();
139 writeln!(w, "\t\t\t{}Ptr {{ err: std::ptr::null_mut() }}", mangled_container).unwrap();
141 writeln!(w, "\t\t}};").unwrap();
142 writeln!(w, "\t\tSelf {{").unwrap();
143 writeln!(w, "\t\t\tcontents,").unwrap();
144 writeln!(w, "\t\t\tresult_ok: o.result_ok,").unwrap();
145 writeln!(w, "\t\t}}").unwrap();
146 writeln!(w, "\t}}").unwrap();
147 writeln!(w, "}}").unwrap();
150 /// Writes out a C-callable concrete Vec<A> struct and utility methods
151 pub fn write_vec_block<W: std::io::Write>(w: &mut W, opts: &GlobalOpts, mangled_container: &str, inner_type: &str) {
152 writeln!(w, "{}", opts.struct_attributes).unwrap();
153 writeln!(w, "pub struct {} {{", mangled_container).unwrap();
154 writeln!(w, "\tpub data: *mut {},", inner_type).unwrap();
155 writeln!(w, "\tpub datalen: usize").unwrap();
156 writeln!(w, "}}").unwrap();
158 writeln!(w, "impl {} {{", mangled_container).unwrap();
159 writeln!(w, "\t#[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<{}> {{", inner_type).unwrap();
160 writeln!(w, "\t\tif self.datalen == 0 {{ return Vec::new(); }}").unwrap();
161 writeln!(w, "\t\tlet ret = unsafe {{ Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }}.into();").unwrap();
162 writeln!(w, "\t\tself.data = std::ptr::null_mut();").unwrap();
163 writeln!(w, "\t\tself.datalen = 0;").unwrap();
164 writeln!(w, "\t\tret").unwrap();
165 writeln!(w, "\t}}").unwrap();
166 writeln!(w, "\t#[allow(unused)] pub(crate) fn as_slice(&self) -> &[{}] {{", inner_type).unwrap();
167 writeln!(w, "\t\tunsafe {{ std::slice::from_raw_parts_mut(self.data, self.datalen) }}").unwrap();
168 writeln!(w, "\t}}").unwrap();
169 writeln!(w, "}}").unwrap();
171 writeln!(w, "impl From<Vec<{}>> for {} {{", inner_type, mangled_container).unwrap();
172 writeln!(w, "\tfn from(v: Vec<{}>) -> Self {{", inner_type).unwrap();
173 writeln!(w, "\t\tlet datalen = v.len();").unwrap();
174 writeln!(w, "\t\tlet data = Box::into_raw(v.into_boxed_slice());").unwrap();
175 writeln!(w, "\t\tSelf {{ datalen, data: unsafe {{ (*data).as_mut_ptr() }} }}").unwrap();
176 writeln!(w, "\t}}").unwrap();
177 writeln!(w, "}}").unwrap();
179 writeln!(w, "#[no_mangle]").unwrap();
180 writeln!(w, "pub extern \"C\" fn {}_free(_res: {}) {{ }}", mangled_container, mangled_container).unwrap();
181 writeln!(w, "impl Drop for {} {{", mangled_container).unwrap();
182 writeln!(w, "\tfn drop(&mut self) {{").unwrap();
183 writeln!(w, "\t\tif self.datalen == 0 {{ return; }}").unwrap();
184 writeln!(w, "\t\tunsafe {{ Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }};").unwrap();
185 writeln!(w, "\t}}").unwrap();
186 writeln!(w, "}}").unwrap();
187 if inner_type == "u8" || mangled_container == "CVec_SpendableOutputDescriptorZ" { // XXX
188 writeln!(w, "impl Clone for {} {{", mangled_container).unwrap();
189 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
190 writeln!(w, "\t\tlet mut res = Vec::new();").unwrap();
191 writeln!(w, "\t\tif self.datalen == 0 {{ return Self::from(res); }}").unwrap();
192 writeln!(w, "\t\tres.extend_from_slice(unsafe {{ std::slice::from_raw_parts_mut(self.data, self.datalen) }});").unwrap();
193 writeln!(w, "\t\tSelf::from(res)").unwrap();
194 writeln!(w, "\t}}").unwrap();
195 writeln!(w, "}}").unwrap();
199 /// Writes out a C-callable concrete (A, B, ...) struct and utility methods
200 pub fn write_tuple_block<W: std::io::Write>(w: &mut W, opts: &GlobalOpts, mangled_container: &str, types: &[String]) {
201 writeln!(w, "{}", opts.struct_attributes).unwrap();
202 writeln!(w, "pub struct {} {{", mangled_container).unwrap();
203 for (idx, ty) in types.iter().enumerate() {
204 writeln!(w, "\tpub {}: {},", ('a' as u8 + idx as u8) as char, ty).unwrap();
206 writeln!(w, "}}").unwrap();
208 let mut needs_clone = true;
209 let mut tuple_str = "(".to_owned();
210 for (idx, ty) in types.iter().enumerate() {
211 if idx != 0 { tuple_str += ", "; }
213 if !ty.starts_with("u") ||
214 ty.len() > 3 || ty.len() < 2 ||
215 ty.as_bytes()[1] < '0' as u8 || ty.as_bytes()[1] > '9' as u8 ||
216 (ty.len() == 3 && (ty.as_bytes()[2] < '0' as u8 || ty.as_bytes()[2] > '9' as u8)) {
217 // For non-uXX types, we don't implement clone
223 writeln!(w, "impl From<{}> for {} {{", tuple_str, mangled_container).unwrap();
224 writeln!(w, "\tfn from (tup: {}) -> Self {{", tuple_str).unwrap();
225 writeln!(w, "\t\tSelf {{").unwrap();
226 for idx in 0..types.len() {
227 writeln!(w, "\t\t\t{}: tup.{},", ('a' as u8 + idx as u8) as char, idx).unwrap();
229 writeln!(w, "\t\t}}").unwrap();
230 writeln!(w, "\t}}").unwrap();
231 writeln!(w, "}}").unwrap();
232 writeln!(w, "impl {} {{", mangled_container).unwrap();
233 writeln!(w, "\t#[allow(unused)] pub(crate) fn to_rust(mut self) -> {} {{", tuple_str).unwrap();
234 write!(w, "\t\t(").unwrap();
235 for idx in 0..types.len() {
236 write!(w, "{}self.{}", if idx != 0 {", "} else {""}, ('a' as u8 + idx as u8) as char).unwrap();
238 writeln!(w, ")").unwrap();
239 writeln!(w, "\t}}").unwrap();
240 writeln!(w, "}}").unwrap();
243 writeln!(w, "impl Clone for {} {{", mangled_container).unwrap();
244 writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
245 writeln!(w, "\t\tSelf {{").unwrap();
246 for idx in 0..types.len() {
247 writeln!(w, "\t\t\t{}: self.{}.clone(),", ('a' as u8 + idx as u8) as char, ('a' as u8 + idx as u8) as char).unwrap();
249 writeln!(w, "\t\t}}").unwrap();
250 writeln!(w, "\t}}").unwrap();
251 writeln!(w, "}}").unwrap();
254 writeln!(w, "#[no_mangle]").unwrap();
255 writeln!(w, "pub extern \"C\" fn {}_free(_res: {}) {{ }}", mangled_container, mangled_container).unwrap();
258 /// Prints the docs from a given attribute list unless its tagged no export
259 pub fn writeln_docs<W: std::io::Write>(w: &mut W, attrs: &[syn::Attribute], prefix: &str) {
260 for attr in attrs.iter() {
261 let tokens_clone = attr.tokens.clone();
262 let mut token_iter = tokens_clone.into_iter();
263 if let Some(token) = token_iter.next() {
265 TokenTree::Punct(c) if c.as_char() == '=' => {
266 // syn gets '=' from '///' or '//!' as it is syntax for #[doc = ""]
268 TokenTree::Group(_) => continue, // eg #[derive()]
269 _ => unimplemented!(),
273 syn::AttrStyle::Inner(_) => {
274 match token_iter.next().unwrap() {
275 TokenTree::Literal(lit) => {
276 // Drop the first and last chars from lit as they are always "
277 let doc = format!("{}", lit);
278 writeln!(w, "{}//!{}", prefix, &doc[1..doc.len() - 1]).unwrap();
280 _ => unimplemented!(),
283 syn::AttrStyle::Outer => {
284 match token_iter.next().unwrap() {
285 TokenTree::Literal(lit) => {
286 // Drop the first and last chars from lit as they are always "
287 let doc = format!("{}", lit);
288 writeln!(w, "{}///{}", prefix, &doc[1..doc.len() - 1]).unwrap();
290 _ => unimplemented!(),
297 /// Print the parameters in a method declaration, starting after the open parenthesis, through and
298 /// including the closing parenthesis and return value, but not including the open bracket or any
299 /// trailing semicolons.
301 /// Usable both for a function definition and declaration.
303 /// this_param is used when returning Self or accepting a self parameter, and should be the
304 /// concrete, mapped type.
305 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) {
306 if sig.constness.is_some() || sig.asyncness.is_some() || sig.unsafety.is_some() ||
307 sig.abi.is_some() || sig.variadic.is_some() {
310 if sig.generics.lt_token.is_some() {
311 for generic in sig.generics.params.iter() {
313 syn::GenericParam::Type(_)|syn::GenericParam::Lifetime(_) => {
314 // We ignore these, if they're not on skipped args, we'll blow up
315 // later, and lifetimes we just hope the C client enforces.
317 _ => unimplemented!(),
322 let mut first_arg = true;
323 let mut num_unused = 0;
324 for inp in sig.inputs.iter() {
326 syn::FnArg::Receiver(recv) => {
327 if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
328 write!(w, "this_arg: {}{}",
329 match (self_ptr, recv.mutability.is_some()) {
330 (true, true) => "*mut ",
331 (true, false) => "*const ",
332 (false, true) => "&mut ",
333 (false, false) => "&",
334 }, this_param).unwrap();
338 syn::FnArg::Typed(arg) => {
339 if types.skip_arg(&*arg.ty, generics) { continue; }
340 if !arg.attrs.is_empty() { unimplemented!(); }
341 // First get the c type so that we can check if it ends up being a reference:
342 let mut c_type = Vec::new();
343 types.write_c_type(&mut c_type, &*arg.ty, generics, false);
345 syn::Pat::Ident(ident) => {
346 if !ident.attrs.is_empty() || ident.subpat.is_some() {
349 write!(w, "{}{}{}: ", if first_arg { "" } else { ", " }, if !fn_decl || c_type[0] == '&' as u8 || c_type[0] == '*' as u8 { "" } else { "mut " }, ident.ident).unwrap();
352 syn::Pat::Wild(wild) => {
353 if !wild.attrs.is_empty() { unimplemented!(); }
354 write!(w, "{}unused_{}: ", if first_arg { "" } else { ", " }, num_unused).unwrap();
357 _ => unimplemented!(),
359 w.write(&c_type).unwrap();
363 write!(w, ")").unwrap();
365 syn::ReturnType::Type(_, rtype) => {
366 write!(w, " -> ").unwrap();
367 if let Some(mut remaining_path) = first_seg_self(&*rtype) {
368 if remaining_path.next().is_none() {
369 write!(w, "{}", this_param).unwrap();
373 if let syn::Type::Reference(r) = &**rtype {
374 // We can't return a reference, cause we allocate things on the stack.
375 types.write_c_type(w, &*r.elem, generics, true);
377 types.write_c_type(w, &*rtype, generics, true);
384 /// Print the main part of a method declaration body, starting with a newline after the function
385 /// open bracket and converting each function parameter to or from C-mapped types. Ends with "let
386 /// mut ret = " assuming the next print will be the unmapped Rust function to call followed by the
387 /// parameters we mapped to/from C here.
388 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) {
389 let mut num_unused = 0;
390 for inp in sig.inputs.iter() {
392 syn::FnArg::Receiver(_) => {},
393 syn::FnArg::Typed(arg) => {
394 if types.skip_arg(&*arg.ty, generics) { continue; }
395 if !arg.attrs.is_empty() { unimplemented!(); }
396 macro_rules! write_new_var {
397 ($ident: expr, $ty: expr) => {
399 if types.write_to_c_conversion_new_var(w, &$ident, &$ty, generics, false) {
400 write!(w, "\n\t{}", extra_indent).unwrap();
403 if types.write_from_c_conversion_new_var(w, &$ident, &$ty, generics) {
404 write!(w, "\n\t{}", extra_indent).unwrap();
410 syn::Pat::Ident(ident) => {
411 if !ident.attrs.is_empty() || ident.subpat.is_some() {
414 write_new_var!(ident.ident, *arg.ty);
416 syn::Pat::Wild(w) => {
417 if !w.attrs.is_empty() { unimplemented!(); }
418 write_new_var!(syn::Ident::new(&format!("unused_{}", num_unused), Span::call_site()), *arg.ty);
421 _ => unimplemented!(),
427 syn::ReturnType::Type(_, _) => {
428 write!(w, "let mut ret = ").unwrap();
434 /// Prints the parameters in a method call, starting after the open parenthesis and ending with a
435 /// final return statement returning the method's result. Should be followed by a single closing
438 /// The return value is expected to be bound to a variable named `ret` which is available after a
439 /// method-call-ending semicolon.
440 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) {
441 let mut first_arg = true;
442 let mut num_unused = 0;
443 for inp in sig.inputs.iter() {
445 syn::FnArg::Receiver(recv) => {
446 if !recv.attrs.is_empty() || recv.reference.is_none() { unimplemented!(); }
448 write!(w, "self.this_arg").unwrap();
452 syn::FnArg::Typed(arg) => {
453 if types.skip_arg(&*arg.ty, generics) {
456 write!(w, ", ").unwrap();
459 types.no_arg_to_rust(w, &*arg.ty, generics);
463 if !arg.attrs.is_empty() { unimplemented!(); }
464 macro_rules! write_ident {
467 write!(w, ", ").unwrap();
471 types.write_to_c_conversion_inline_prefix(w, &*arg.ty, generics, false);
472 write!(w, "{}", $ident).unwrap();
473 types.write_to_c_conversion_inline_suffix(w, &*arg.ty, generics, false);
475 types.write_from_c_conversion_prefix(w, &*arg.ty, generics);
476 write!(w, "{}", $ident).unwrap();
477 types.write_from_c_conversion_suffix(w, &*arg.ty, generics);
482 syn::Pat::Ident(ident) => {
483 if !ident.attrs.is_empty() || ident.subpat.is_some() {
486 write_ident!(ident.ident);
488 syn::Pat::Wild(w) => {
489 if !w.attrs.is_empty() { unimplemented!(); }
490 write_ident!(format!("unused_{}", num_unused));
493 _ => unimplemented!(),
498 write!(w, ")").unwrap();
500 syn::ReturnType::Type(_, rtype) => {
501 write!(w, ";\n\t{}", extra_indent).unwrap();
503 let self_segs_iter = first_seg_self(&*rtype);
504 if to_c && first_seg_self(&*rtype).is_some() {
505 // Assume rather blindly that we're returning an associated trait from a C fn call to a Rust trait object.
506 write!(w, "ret").unwrap();
507 } else if !to_c && self_segs_iter.is_some() && self_segs_iter.unwrap().next().is_none() {
508 // If we're returning "Self" (and not "Self::X"), just do it manually
509 write!(w, "{} {{ inner: Box::into_raw(Box::new(ret)), is_owned: true }}", this_type).unwrap();
511 let new_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("ret", Span::call_site()), rtype, generics);
513 write!(w, "\n\t{}", extra_indent).unwrap();
515 types.write_from_c_conversion_prefix(w, &*rtype, generics);
516 write!(w, "ret").unwrap();
517 types.write_from_c_conversion_suffix(w, &*rtype, generics);
519 let ret_returned = if let syn::Type::Reference(_) = &**rtype { true } else { false };
520 let new_var = types.write_to_c_conversion_new_var(w, &syn::Ident::new("ret", Span::call_site()), &rtype, generics, true);
522 write!(w, "\n\t{}", extra_indent).unwrap();
524 types.write_to_c_conversion_inline_prefix(w, &rtype, generics, true);
525 write!(w, "{}ret", if ret_returned && !new_var { "*" } else { "" }).unwrap();
526 types.write_to_c_conversion_inline_suffix(w, &rtype, generics, true);
533 /// Prints concrete generic parameters for a struct/trait/function, including the less-than and
534 /// greater-than symbols, if any generic parameters are defined.
535 pub fn maybe_write_generics<W: std::io::Write>(w: &mut W, generics: &syn::Generics, types: &TypeResolver, concrete_lifetimes: bool) {
536 let mut gen_types = GenericTypes::new();
537 assert!(gen_types.learn_generics(generics, types));
538 if !generics.params.is_empty() {
539 write!(w, "<").unwrap();
540 for (idx, generic) in generics.params.iter().enumerate() {
542 syn::GenericParam::Type(type_param) => {
543 let mut printed_param = false;
544 for bound in type_param.bounds.iter() {
545 if let syn::TypeParamBound::Trait(trait_bound) = bound {
546 assert_simple_bound(&trait_bound);
547 write!(w, "{}{}", if idx != 0 { ", " } else { "" }, gen_types.maybe_resolve_ident(&type_param.ident).unwrap()).unwrap();
549 unimplemented!("Can't print generic params that have multiple non-lifetime bounds");
551 printed_param = true;
555 syn::GenericParam::Lifetime(lt) => {
556 if concrete_lifetimes {
557 write!(w, "'static").unwrap();
559 write!(w, "{}'{}", if idx != 0 { ", " } else { "" }, lt.lifetime.ident).unwrap();
562 _ => unimplemented!(),
565 write!(w, ">").unwrap();