1use crate::miniextendr_impl::ClassSystem;
4use crate::type_inspect::first_type_argument;
5use proc_macro2::TokenStream;
6use quote::quote;
7use syn::{GenericArgument, PathArguments, ReturnType, Type};
8
9#[derive(#[automatically_derived]impl ::core::fmt::Debug for Container {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Container::Option => "Option",
Container::Result => "Result",
Container::Vec => "Vec",
})
}
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Container {
}
#[automatically_derived]impl ::core::clone::Clone for Container {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Container { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Container
{
}
#[automatically_derived]impl ::core::cmp::PartialEq for Container {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for Container { }Eq)]
10enum Container {
11 Option,
12 Result,
13 Vec,
14}
15
16#[derive(#[automatically_derived]impl ::core::fmt::Debug for ConversionKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ConversionKind::To => "To",
ConversionKind::From => "From",
})
}
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for ConversionKind {
}
#[automatically_derived]impl ::core::clone::Clone for ConversionKind {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ConversionKind { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
ConversionKind {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ConversionKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ConversionKind { }Eq)]
17pub(crate) enum ConversionKind {
18 To,
19 From,
20}
21
22#[derive(#[automatically_derived]impl ::core::fmt::Debug for ReturnWrap {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field5_finish(f,
"ReturnWrap system target containers typed conversion",
&self.system, &self.target, &self.containers, &self.typed,
&&self.conversion)
}
}Debug, #[automatically_derived]impl ::core::clone::Clone for ReturnWrap {
#[inline]
fn clone(&self) -> Self {
ReturnWrap {
system: ::core::clone::Clone::clone(&self.system),
target: ::core::clone::Clone::clone(&self.target),
containers: ::core::clone::Clone::clone(&self.containers),
typed: ::core::clone::Clone::clone(&self.typed),
conversion: ::core::clone::Clone::clone(&self.conversion),
}
}
}Clone)]
23pub struct ReturnWrap {
24 system: ClassSystem,
25 target: String,
26 containers: Vec<Container>,
27 typed: bool,
28 pub(crate) conversion: Option<ConversionKind>,
29}
30
31pub(crate) fn parse_system(value: &syn::LitStr) -> syn::Result<ClassSystem> {
32 value
33 .value()
34 .parse()
35 .map_err(|message| syn::Error::new(value.span(), message))
36}
37
38fn marker_system(name: &syn::Ident) -> Option<ClassSystem> {
39 Some(match name.to_string().as_str() {
40 "WrapAsR6" => ClassSystem::R6,
41 "WrapAsS7" | "ConvertTo" | "ConvertFrom" => ClassSystem::S7,
42 "WrapAsS4" => ClassSystem::S4,
43 "WrapAsS3" => ClassSystem::S3,
44 "WrapAsEnv" => ClassSystem::Env,
45 "WrapAsVctrs" => ClassSystem::Vctrs,
46 _ => return None,
47 })
48}
49
50pub(crate) fn contains_marker(ty: &Type) -> bool {
51 match ty {
52 Type::Path(path) => path.path.segments.iter().any(|segment| {
53 marker_system(&segment.ident).is_some()
54 || match &segment.arguments {
55 PathArguments::AngleBracketed(args) => args
56 .args
57 .iter()
58 .any(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
GenericArgument::Type(ty) if contains_marker(ty) => true,
_ => false,
}matches!(arg, GenericArgument::Type(ty) if contains_marker(ty))),
59 _ => false,
60 }
61 }),
62 Type::Reference(ty) => contains_marker(&ty.elem),
63 Type::Paren(ty) => contains_marker(&ty.elem),
64 Type::Group(ty) => contains_marker(&ty.elem),
65 Type::Slice(ty) => contains_marker(&ty.elem),
66 Type::Array(ty) => contains_marker(&ty.elem),
67 Type::Tuple(ty) => ty.elems.iter().any(contains_marker),
68 _ => false,
69 }
70}
71
72pub(crate) fn resolve(
75 output: &ReturnType,
76 attribute: Option<ClassSystem>,
77) -> syn::Result<(Option<ReturnWrap>, ReturnType)> {
78 let ReturnType::Type(arrow, ty) = output else {
79 if attribute.is_some() {
80 return Err(syn::Error::new_spanned(
81 output,
82 "`wrap` requires a named class return value",
83 ));
84 }
85 return Ok((None, output.clone()));
86 };
87 if attribute.is_none() && !contains_marker(ty) {
88 return Ok((None, output.clone()));
89 }
90 let mut leaf = ty.as_ref();
91 let mut containers = Vec::new();
92 while let Type::Path(path) = leaf {
93 let segment = path.path.segments.last().expect("type path has a segment");
94 let container = match segment.ident.to_string().as_str() {
95 "Option" => Container::Option,
96 "Result" => Container::Result,
97 "Vec" => Container::Vec,
98 _ => break,
99 };
100 let PathArguments::AngleBracketed(args) = &segment.arguments else {
101 break;
102 };
103 if container == Container::Result
104 && let Some(GenericArgument::Type(error)) = args.args.iter().nth(1)
105 {
106 if contains_marker(error) {
107 return Err(syn::Error::new_spanned(
108 error,
109 "WrapAs* belongs on the successful Result payload",
110 ));
111 }
112 if #[allow(non_exhaustive_omitted_patterns)] match error {
Type::Tuple(tuple) if tuple.elems.is_empty() => true,
_ => false,
}matches!(error, Type::Tuple(tuple) if tuple.elems.is_empty()) {
113 return Err(syn::Error::new_spanned(
114 error,
115 "explicit class wrapping does not support Result<T, ()>; use a non-unit error type",
116 ));
117 }
118 }
119 let Some(GenericArgument::Type(inner)) = args.args.first() else {
120 break;
121 };
122 containers.push(container);
123 leaf = inner;
124 }
125 if !#[allow(non_exhaustive_omitted_patterns)] match containers.as_slice() {
[] | [Container::Option] | [Container::Result] | [Container::Vec] |
[Container::Option, Container::Vec] |
[Container::Result, Container::Vec] => true,
_ => false,
}matches!(
126 containers.as_slice(),
127 [] | [Container::Option]
128 | [Container::Result]
129 | [Container::Vec]
130 | [Container::Option, Container::Vec]
131 | [Container::Result, Container::Vec]
132 ) {
133 return Err(syn::Error::new_spanned(
134 ty,
135 "explicit class wrapping supports T, Option<T>, Result<T, E>, Vec<T>, Option<Vec<T>>, or Result<Vec<T>, E>",
136 ));
137 }
138 let marker = if let Type::Path(path) = leaf {
139 path.path
140 .segments
141 .last()
142 .and_then(|segment| marker_system(&segment.ident).map(|system| (system, segment)))
143 } else {
144 None
145 };
146 let conversion =
147 marker
148 .as_ref()
149 .and_then(|(_, segment)| match segment.ident.to_string().as_str() {
150 "ConvertTo" => Some(ConversionKind::To),
151 "ConvertFrom" => Some(ConversionKind::From),
152 _ => None,
153 });
154 let typed = marker.is_some();
155 let (system, payload) = match marker {
156 Some((system, segment)) => {
157 if attribute.is_some_and(|attribute| attribute != system) {
158 return Err(syn::Error::new_spanned(
159 ty,
160 "the WrapAs* marker and `wrap` attribute select different class systems",
161 ));
162 }
163 let inner = first_type_argument(segment)
164 .ok_or_else(|| {
165 syn::Error::new_spanned(segment, "WrapAs* requires one class type argument")
166 })?
167 .clone();
168 if !#[allow(non_exhaustive_omitted_patterns)] match &segment.arguments {
PathArguments::AngleBracketed(args) if args.args.len() == 1 => true,
_ => false,
}matches!(&segment.arguments, PathArguments::AngleBracketed(args) if args.args.len() == 1)
169 {
170 return Err(syn::Error::new_spanned(
171 segment,
172 "WrapAs* requires exactly one class type argument",
173 ));
174 }
175 (system, inner)
176 }
177 None => (attribute.ok_or_else(|| syn::Error::new_spanned(ty, "place WrapAs* directly around the class payload, inside Option, Result, or Vec"))?, leaf.clone()),
178 };
179 let leaf = crate::type_inspect::peel_external_ptr(&payload);
182 let Type::Path(path) = leaf else {
183 return Err(syn::Error::new_spanned(
184 leaf,
185 "explicit wrapping requires an owned, named class type",
186 ));
187 };
188 let segment = path.path.segments.last().expect("type path has a segment");
189 if !#[allow(non_exhaustive_omitted_patterns)] match segment.arguments {
PathArguments::None => true,
_ => false,
}matches!(segment.arguments, PathArguments::None) || contains_marker(leaf) {
190 return Err(syn::Error::new_spanned(
191 leaf,
192 "WrapAs* must be closest to the named class type; put containers and visibility outside it",
193 ));
194 }
195 let target = crate::naming::ident_name(&segment.ident);
196 let mut peeled = (**ty).clone();
198 let mut slot = &mut peeled;
199 for _ in &containers {
200 let Type::Path(path) = slot else {
201 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("validated container path")));
}unreachable!("validated container path")
202 };
203 let PathArguments::AngleBracketed(args) = &mut path
204 .path
205 .segments
206 .last_mut()
207 .expect("validated path")
208 .arguments
209 else {
210 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("validated container arguments")));
}unreachable!("validated container arguments")
211 };
212 let GenericArgument::Type(inner) = args.args.first_mut().expect("validated payload") else {
213 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("validated type argument")));
}unreachable!("validated type argument")
214 };
215 slot = inner;
216 }
217 *slot = payload;
218
219 Ok((
220 Some(ReturnWrap {
221 system,
222 target,
223 containers,
224 typed,
225 conversion,
226 }),
227 ReturnType::Type(*arrow, Box::new(peeled)),
228 ))
229}
230
231impl ReturnWrap {
232 pub(crate) fn system(&self) -> ClassSystem {
233 self.system
234 }
235 pub(crate) fn target(&self) -> &str {
236 &self.target
237 }
238 pub(crate) fn set_target(&mut self, target: String) {
239 self.target = target;
240 }
241 pub(crate) fn has_vector(&self) -> bool {
242 self.containers.contains(&Container::Vec)
243 }
244
245 pub(crate) fn is_optional_class(&self) -> bool {
250 self.containers == [Container::Option]
251 }
252
253 pub(crate) fn prepare_value(&self, call: TokenStream) -> TokenStream {
255 fn map(call: TokenStream, containers: &[Container]) -> TokenStream {
256 match containers.split_first() {
257 None => {
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
{
let mut _s = ::quote::__private::TokenStream::new();
::quote::ToTokens::to_tokens(&call, &mut _s);
_s
});
::quote::__private::push_dot(&mut _s);
::quote::__private::parse(&mut _s, "0");
_s
}quote!((#call).0),
258 Some((container, rest)) => {
259 let inner = map({
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_ident(&mut _s, "__mx_value");
_s
}quote!(__mx_value), rest);
260 if *container == Container::Vec {
261 {
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
{
let mut _s = ::quote::__private::TokenStream::new();
::quote::ToTokens::to_tokens(&call, &mut _s);
_s
});
::quote::__private::push_dot(&mut _s);
::quote::__private::push_ident(&mut _s, "into_iter");
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
::quote::__private::TokenStream::new());
::quote::__private::push_dot(&mut _s);
::quote::__private::push_ident(&mut _s, "map");
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
{
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_or(&mut _s);
::quote::__private::push_ident(&mut _s, "__mx_value");
::quote::__private::push_or(&mut _s);
::quote::ToTokens::to_tokens(&inner, &mut _s);
_s
});
::quote::__private::push_dot(&mut _s);
::quote::__private::push_ident(&mut _s, "collect");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_lt(&mut _s);
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "std");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "vec");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "Vec");
::quote::__private::push_lt(&mut _s);
::quote::__private::push_underscore(&mut _s);
::quote::__private::push_shr(&mut _s);
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
::quote::__private::TokenStream::new());
_s
}quote!((#call).into_iter().map(|__mx_value| #inner).collect::<::std::vec::Vec<_>>())
262 } else {
263 {
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
{
let mut _s = ::quote::__private::TokenStream::new();
::quote::ToTokens::to_tokens(&call, &mut _s);
_s
});
::quote::__private::push_dot(&mut _s);
::quote::__private::push_ident(&mut _s, "map");
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
{
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_or(&mut _s);
::quote::__private::push_ident(&mut _s, "__mx_value");
::quote::__private::push_or(&mut _s);
::quote::ToTokens::to_tokens(&inner, &mut _s);
_s
});
_s
}quote!((#call).map(|__mx_value| #inner))
264 }
265 }
266 }
267 }
268 if self.typed {
269 map(call, &self.containers)
270 } else {
271 call
272 }
273 }
274
275 pub(crate) fn r_expression(&self, value: &str, self_type: Option<&str>) -> String {
283 let target = if self.target == "Self" {
284 self_type.unwrap_or("Self").to_owned()
285 } else {
286 crate::r_class_formatter::class_ref_for(self.system, &self.target)
287 };
288 let wrap = |value: &str| match self.system {
289 ClassSystem::R6 => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}$new(.ptr = {1})", target,
value))
})format!("{target}$new(.ptr = {value})"),
290 ClassSystem::S7 => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}(.ptr = {1})", target, value))
})format!("{target}(.ptr = {value})"),
291 ClassSystem::S4 => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("methods::new(\"{0}\", ptr = {1})",
target, value))
})format!("methods::new(\"{target}\", ptr = {value})"),
292 ClassSystem::S3 | ClassSystem::Env => {
293 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("structure({0}, class = \"{1}\")",
value, target))
})format!("structure({value}, class = \"{target}\")")
294 }
295 ClassSystem::Vctrs => {
296 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("structure({0}, class = unique(c(\"{1}\", class({0}))))",
value, target))
})format!("structure({value}, class = unique(c(\"{target}\", class({value}))))")
297 }
298 };
299 let wrapped = if self.containers.contains(&Container::Vec) {
300 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lapply({1}, function(.item) {0})",
wrap(".item"), value))
})format!("lapply({value}, function(.item) {})", wrap(".item"))
301 } else {
302 wrap(value)
303 };
304 if self.containers.first() == Some(&Container::Option) {
307 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if (is.null({0})) NULL else {1}",
value, wrapped))
})format!("if (is.null({value})) NULL else {wrapped}")
308 } else {
309 wrapped
310 }
311 }
312}
313
314#[cfg(test)]
315mod tests;