1pub(crate) fn nth_type_argument(seg: &syn::PathSegment, n: usize) -> Option<&syn::Type> {
5 if let syn::PathArguments::AngleBracketed(ab) = &seg.arguments {
6 let mut count = 0;
7 for arg in ab.args.iter() {
8 if let syn::GenericArgument::Type(ty) = arg {
9 if count == n {
10 return Some(ty);
11 }
12 count += 1;
13 }
14 }
15 }
16 None
17}
18
19pub(crate) fn first_type_argument(seg: &syn::PathSegment) -> Option<&syn::Type> {
21 nth_type_argument(seg, 0)
22}
23
24pub(crate) fn second_type_argument(seg: &syn::PathSegment) -> Option<&syn::Type> {
26 nth_type_argument(seg, 1)
27}
28
29pub(crate) fn peel_visibility_marker(ty: &syn::Type) -> (Option<bool>, &syn::Type) {
39 let syn::Type::Path(p) = ty else {
40 return (None, ty);
41 };
42 let Some(seg) = p.path.segments.last() else {
43 return (None, ty);
44 };
45 let invisible = match seg.ident.to_string().as_str() {
46 "Invisible" => true,
47 "Visible" => false,
48 _ => return (None, ty),
49 };
50 match first_type_argument(seg) {
51 Some(inner) => (Some(invisible), inner),
52 None => (None, ty),
53 }
54}
55
56pub(crate) fn peel_return_visibility(output: &syn::ReturnType) -> (Option<bool>, syn::ReturnType) {
61 match output {
62 syn::ReturnType::Type(arrow, ty) => {
63 let (marker, inner) = peel_visibility_marker(ty);
64 match marker {
65 Some(_) => (
66 marker,
67 syn::ReturnType::Type(*arrow, Box::new(inner.clone())),
68 ),
69 None => (None, output.clone()),
70 }
71 }
72 syn::ReturnType::Default => (None, output.clone()),
73 }
74}
75
76pub(crate) fn serialize_return_type(output: &syn::ReturnType, serialize: bool) -> syn::ReturnType {
80 if !serialize {
81 return output.clone();
82 }
83 let ty: syn::Type = match output {
84 syn::ReturnType::Default => ::syn::__private::parse_quote({
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
::quote::__private::TokenStream::new());
_s
})syn::parse_quote!(()),
85 syn::ReturnType::Type(_, ty) => (**ty).clone(),
86 };
87 ::syn::__private::parse_quote({
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_rarrow(&mut _s);
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "miniextendr_api");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "serde");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "AsSerialize");
::quote::__private::push_lt(&mut _s);
::quote::ToTokens::to_tokens(&ty, &mut _s);
::quote::__private::push_gt(&mut _s);
_s
})syn::parse_quote!(-> ::miniextendr_api::serde::AsSerialize<#ty>)
88}
89
90pub(crate) fn prepare_return_value(
93 call: proc_macro2::TokenStream,
94 visibility_marker: Option<bool>,
95 serialize: bool,
96) -> proc_macro2::TokenStream {
97 let value = if visibility_marker.is_some() {
98 {
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::quote! { (#call).0 }
99 } else {
100 call
101 };
102 if serialize {
103 {
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "miniextendr_api");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "serde");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "AsSerialize");
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
{
let mut _s = ::quote::__private::TokenStream::new();
::quote::ToTokens::to_tokens(&value, &mut _s);
_s
});
_s
}quote::quote! { ::miniextendr_api::serde::AsSerialize(#value) }
104 } else {
105 value
106 }
107}
108
109pub(crate) fn resolve_visibility(
114 marker: Option<bool>,
115 attr: Option<bool>,
116 shape_default: bool,
117 span: proc_macro2::Span,
118) -> syn::Result<bool> {
119 match (marker, attr) {
120 (Some(m), Some(a)) if m != a => Err(syn::Error::new(
121 span,
122 "the return type's visibility marker and the `invisible` / `visible` attribute disagree; keep one of them (or make them agree)",
123 )),
124 (Some(m), _) => Ok(m),
125 (None, Some(a)) => Ok(a),
126 (None, None) => Ok(shape_default),
127 }
128}
129
130pub(crate) fn visibility_marker_error(ty: &syn::Type, what: &str) -> Option<syn::Error> {
135 let (marker, inner) = peel_visibility_marker(ty);
136 if what == "return"
137 && let Some((param_marker, _)) = outer_param_marker(inner)
138 {
139 return Some(syn::Error::new_spanned(
140 ty,
141 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}<T>` marks a parameter only; it cannot be used as a return type (return the inner `T`)",
param_marker.name()))
})format!(
142 "`{}<T>` marks a parameter only; it cannot be used as a return type (return the \
143 inner `T`)",
144 param_marker.name()
145 ),
146 ));
147 }
148 marker?;
149 if what == "argument" {
150 return Some(syn::Error::new_spanned(
151 ty,
152 "`Invisible<T>` / `Visible<T>` mark the return type only; they cannot be used as a parameter type",
153 ));
154 }
155 if peel_visibility_marker(inner).0.is_some() {
156 return Some(syn::Error::new_spanned(
157 ty,
158 "visibility markers cannot be nested; use a single `Invisible<T>` or `Visible<T>` around the return type",
159 ));
160 }
161 None
162}
163
164pub(crate) fn call_marker(ty: &syn::Type) -> Option<crate::r_wrapper_builder::CallAttribution> {
173 let syn::Type::Path(p) = ty else {
174 return None;
175 };
176 let seg = p.path.segments.last()?;
177 if !#[allow(non_exhaustive_omitted_patterns)] match seg.arguments {
syn::PathArguments::None => true,
_ => false,
}matches!(seg.arguments, syn::PathArguments::None) {
178 return None;
179 }
180 match seg.ident.to_string().as_str() {
181 "Call" => Some(crate::r_wrapper_builder::CallAttribution::Wrapper),
182 "CallerCall" => Some(crate::r_wrapper_builder::CallAttribution::Caller),
183 _ => None,
184 }
185}
186
187pub(crate) fn is_nargs_marker(ty: &syn::Type) -> bool {
199 let syn::Type::Path(p) = ty else {
200 return false;
201 };
202 p.path
203 .segments
204 .last()
205 .is_some_and(|seg| seg.ident == "NArgs" && seg.arguments.is_none())
206}
207
208pub(crate) fn is_rng_guard_param(ty: &syn::Type) -> bool {
217 let syn::Type::Reference(reference) = ty else {
218 return false;
219 };
220 reference.mutability.is_none()
221 && #[allow(non_exhaustive_omitted_patterns)] match reference.elem.as_ref() {
syn::Type::Path(p) if
p.qself.is_none() &&
p.path.segments.last().is_some_and(|seg|
seg.ident == "RngGuard" && seg.arguments.is_none()) => true,
_ => false,
}matches!(reference.elem.as_ref(), syn::Type::Path(p) if p.qself.is_none() && p
222 .path
223 .segments
224 .last()
225 .is_some_and(|seg| seg.ident == "RngGuard" && seg.arguments.is_none()))
226}
227
228pub(crate) fn mentions_rng_guard(ty: &syn::Type) -> bool {
232 match ty {
233 syn::Type::Path(p) => p.path.segments.iter().any(|seg| {
234 seg.ident == "RngGuard"
235 || match &seg.arguments {
236 syn::PathArguments::AngleBracketed(ab) => ab.args.iter().any(
237 |arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
syn::GenericArgument::Type(t) if mentions_rng_guard(t) => true,
_ => false,
}matches!(arg, syn::GenericArgument::Type(t) if mentions_rng_guard(t)),
238 ),
239 _ => false,
240 }
241 }),
242 syn::Type::Reference(r) => mentions_rng_guard(&r.elem),
243 syn::Type::Paren(p) => mentions_rng_guard(&p.elem),
244 syn::Type::Group(g) => mentions_rng_guard(&g.elem),
245 syn::Type::Tuple(t) => t.elems.iter().any(mentions_rng_guard),
246 syn::Type::Array(a) => mentions_rng_guard(&a.elem),
247 syn::Type::Slice(s) => mentions_rng_guard(&s.elem),
248 _ => false,
249 }
250}
251
252pub(crate) fn rng_guard_arg() -> proc_macro2::TokenStream {
257 {
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_and(&mut _s);
::quote::__private::push_ident(&mut _s, "unsafe");
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Brace,
{
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "miniextendr_api");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "rng");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "RngGuard");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "__mx_loaded_by_wrapper");
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
::quote::__private::TokenStream::new());
_s
});
_s
}quote::quote! {
258 &unsafe { ::miniextendr_api::rng::RngGuard::__mx_loaded_by_wrapper() }
259 }
260}
261
262pub(crate) fn is_rooted_view(ty: &syn::Type) -> bool {
269 let syn::Type::Path(path) = ty else {
270 return false;
271 };
272 if path.qself.is_some() {
273 return false;
274 }
275 let Some(seg) = path.path.segments.last() else {
276 return false;
277 };
278 if seg.ident == "StrVec" || seg.ident == "RCow" || seg.ident == "Cow" {
279 return true;
280 }
281 seg.ident == "Vec"
282 && first_type_argument(seg).is_some_and(|elem| {
283 let elem = option_inner_type(elem).unwrap_or(elem);
284 #[allow(non_exhaustive_omitted_patterns)] match elem {
syn::Type::Path(p) if
p.qself.is_none() &&
p.path.segments.last().is_some_and(|s| s.ident == "Cow") => true,
_ => false,
}matches!(elem, syn::Type::Path(p) if p.qself.is_none() && p.path.segments.last()
285 .is_some_and(|s| s.ident == "Cow"))
286 })
287}
288
289pub(crate) fn is_rooted_reference(ty: &syn::Type) -> bool {
293 let ty = option_inner_type(ty).unwrap_or(ty);
294 if let syn::Type::Path(path) = ty
295 && path.qself.is_none()
296 && let Some(segment) = path.path.segments.last()
297 && segment.ident == "Vec"
298 {
299 return first_type_argument(segment).is_some_and(is_rooted_reference);
300 }
301 let syn::Type::Reference(reference) = ty else {
302 return false;
303 };
304 if reference.mutability.is_some() {
305 return false;
306 }
307 match reference.elem.as_ref() {
308 syn::Type::Slice(_) => true,
309 syn::Type::Path(path) if path.qself.is_none() => {
310 path.path.segments.last().is_some_and(|seg| {
311 seg.arguments.is_none()
312 && #[allow(non_exhaustive_omitted_patterns)] match seg.ident.to_string().as_str()
{
"i32" | "f64" | "u8" | "RLogical" | "Rcomplex" | "str" => true,
_ => false,
}matches!(
313 seg.ident.to_string().as_str(),
314 "i32" | "f64" | "u8" | "RLogical" | "Rcomplex" | "str"
315 )
316 })
317 }
318 _ => false,
319 }
320}
321
322pub(crate) fn static_rooted_view_binding(
331 ident: &syn::Ident,
332 ty: &syn::Type,
333) -> Option<proc_macro2::TokenStream> {
334 let lifetime = static_lifetime(ty)?;
335 Some({
let mut _s = ::quote::__private::TokenStream::new();
let _span: ::quote::__private::Span =
::quote::__private::get_span(lifetime.span()).__into_span();
::quote::__private::push_colon2_spanned(&mut _s, _span);
::quote::__private::push_ident_spanned(&mut _s, _span, "core");
::quote::__private::push_colon2_spanned(&mut _s, _span);
::quote::__private::push_ident_spanned(&mut _s, _span, "compile_error");
::quote::__private::push_bang_spanned(&mut _s, _span);
::quote::__private::push_group_spanned(&mut _s, _span,
::quote::__private::Delimiter::Parenthesis,
{
let mut _s = ::quote::__private::TokenStream::new();
let _span: ::quote::__private::Span =
::quote::__private::get_span(_span).__into_span();
::quote::__private::parse_spanned(&mut _s, _span,
"\"this parameter borrows the call\'s argument and cannot be `\'static`; write `\'_` or \\\n elide the lifetime, or take an owned type (`ProtectedStrVec`, `Vec`, `String`) to \\\n keep the data after the call\"");
_s
});
::quote::__private::push_semi_spanned(&mut _s, _span);
::quote::__private::push_ident_spanned(&mut _s, _span, "let");
::quote::ToTokens::to_tokens(&ident, &mut _s);
::quote::__private::push_colon_spanned(&mut _s, _span);
::quote::ToTokens::to_tokens(&ty, &mut _s);
::quote::__private::push_eq_spanned(&mut _s, _span);
::quote::__private::push_colon2_spanned(&mut _s, _span);
::quote::__private::push_ident_spanned(&mut _s, _span, "core");
::quote::__private::push_colon2_spanned(&mut _s, _span);
::quote::__private::push_ident_spanned(&mut _s, _span, "option");
::quote::__private::push_colon2_spanned(&mut _s, _span);
::quote::__private::push_ident_spanned(&mut _s, _span, "Option");
::quote::__private::push_colon2_spanned(&mut _s, _span);
::quote::__private::push_lt_spanned(&mut _s, _span);
::quote::ToTokens::to_tokens(&ty, &mut _s);
::quote::__private::push_gt_spanned(&mut _s, _span);
::quote::__private::push_colon2_spanned(&mut _s, _span);
::quote::__private::push_ident_spanned(&mut _s, _span, "None");
::quote::__private::push_dot_spanned(&mut _s, _span);
::quote::__private::push_ident_spanned(&mut _s, _span, "unwrap");
::quote::__private::push_group_spanned(&mut _s, _span,
::quote::__private::Delimiter::Parenthesis,
{
let _: ::quote::__private::Span =
::quote::__private::get_span(_span).__into_span();
::quote::__private::TokenStream::new()
});
::quote::__private::push_semi_spanned(&mut _s, _span);
_s
}quote::quote_spanned! {lifetime.span()=>
336 ::core::compile_error!(
337 "this parameter borrows the call's argument and cannot be `'static`; write `'_` or \
338 elide the lifetime, or take an owned type (`ProtectedStrVec`, `Vec`, `String`) to \
339 keep the data after the call"
340 );
341 let #ident: #ty = ::core::option::Option::<#ty>::None.unwrap();
342 })
343}
344
345pub(crate) fn static_lifetime(ty: &syn::Type) -> Option<&syn::Lifetime> {
347 let is_static = |lt: &&syn::Lifetime| lt.ident == "static";
348 match ty {
349 syn::Type::Reference(r) => r
350 .lifetime
351 .as_ref()
352 .filter(is_static)
353 .or_else(|| static_lifetime(&r.elem)),
354 syn::Type::Path(p) => p.path.segments.iter().find_map(|seg| {
355 let syn::PathArguments::AngleBracketed(args) = &seg.arguments else {
356 return None;
357 };
358 args.args.iter().find_map(|arg| match arg {
359 syn::GenericArgument::Lifetime(lt) => Some(lt).filter(is_static),
360 syn::GenericArgument::Type(ty) => static_lifetime(ty),
361 _ => None,
362 })
363 }),
364 syn::Type::Slice(s) => static_lifetime(&s.elem),
365 syn::Type::Array(a) => static_lifetime(&a.elem),
366 syn::Type::Paren(p) => static_lifetime(&p.elem),
367 syn::Type::Group(g) => static_lifetime(&g.elem),
368 syn::Type::Tuple(t) => t.elems.iter().find_map(static_lifetime),
369 _ => None,
370 }
371}
372
373pub(crate) fn is_lazy_dots_marker(ty: &syn::Type) -> bool {
387 let syn::Type::Path(p) = ty else {
388 return false;
389 };
390 p.path.segments.last().is_some_and(|seg| {
391 seg.ident == "LazyDots"
392 && match &seg.arguments {
393 syn::PathArguments::None => true,
394 syn::PathArguments::AngleBracketed(ab) => ab
395 .args
396 .iter()
397 .all(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
syn::GenericArgument::Lifetime(_) => true,
_ => false,
}matches!(arg, syn::GenericArgument::Lifetime(_))),
398 syn::PathArguments::Parenthesized(_) => false,
399 }
400 })
401}
402
403pub(crate) fn mentions_lazy_dots(ty: &syn::Type) -> bool {
405 match ty {
406 syn::Type::Path(p) => p.path.segments.iter().any(|seg| {
407 seg.ident == "LazyDots"
408 || match &seg.arguments {
409 syn::PathArguments::AngleBracketed(ab) => ab.args.iter().any(
410 |arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
syn::GenericArgument::Type(t) if mentions_lazy_dots(t) => true,
_ => false,
}matches!(arg, syn::GenericArgument::Type(t) if mentions_lazy_dots(t)),
411 ),
412 _ => false,
413 }
414 }),
415 syn::Type::Reference(r) => mentions_lazy_dots(&r.elem),
416 syn::Type::Paren(p) => mentions_lazy_dots(&p.elem),
417 syn::Type::Group(g) => mentions_lazy_dots(&g.elem),
418 syn::Type::Tuple(t) => t.elems.iter().any(mentions_lazy_dots),
419 syn::Type::Array(a) => mentions_lazy_dots(&a.elem),
420 syn::Type::Slice(s) => mentions_lazy_dots(&s.elem),
421 _ => false,
422 }
423}
424
425#[derive(#[automatically_derived]impl ::core::fmt::Debug for UnevaluatedKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
UnevaluatedKind::Quoted => "Quoted",
UnevaluatedKind::Quosure => "Quosure",
})
}
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for UnevaluatedKind {
}
#[automatically_derived]impl ::core::clone::Clone for UnevaluatedKind {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for UnevaluatedKind { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
UnevaluatedKind {
}
#[automatically_derived]impl ::core::cmp::PartialEq for UnevaluatedKind {
#[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 UnevaluatedKind { }Eq)]
431pub(crate) enum UnevaluatedKind {
432 Quoted,
434 Quosure,
436}
437
438impl UnevaluatedKind {
439 pub(crate) fn name(self) -> &'static str {
441 match self {
442 Self::Quoted => "Quoted",
443 Self::Quosure => "Quosure",
444 }
445 }
446
447 pub(crate) fn r_call_arg(self, p: &str) -> String {
451 let capture = match self {
452 Self::Quoted => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("list(substitute({0}), parent.frame())",
p))
})format!("list(substitute({p}), parent.frame())"),
453 Self::Quosure => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rlang::enquo({0})", p))
})format!("rlang::enquo({p})"),
454 };
455 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if (missing({0})) quote(expr=) else {1}",
p, capture))
})format!("if (missing({p})) quote(expr=) else {capture}")
456 }
457
458 pub(crate) fn api_path(self) -> proc_macro2::TokenStream {
460 match self {
461 Self::Quoted => {
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "miniextendr_api");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "Quoted");
_s
}quote::quote!(::miniextendr_api::Quoted),
462 Self::Quosure => {
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "miniextendr_api");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "Quosure");
_s
}quote::quote!(::miniextendr_api::Quosure),
463 }
464 }
465
466 fn of_segment(seg: &syn::PathSegment) -> Option<Self> {
469 let lifetimes_only = match &seg.arguments {
470 syn::PathArguments::None => true,
471 syn::PathArguments::AngleBracketed(ab) => ab
472 .args
473 .iter()
474 .all(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
syn::GenericArgument::Lifetime(_) => true,
_ => false,
}matches!(arg, syn::GenericArgument::Lifetime(_))),
475 syn::PathArguments::Parenthesized(_) => false,
476 };
477 if !lifetimes_only {
478 return None;
479 }
480 match seg.ident.to_string().as_str() {
481 "Quoted" => Some(Self::Quoted),
482 "Quosure" => Some(Self::Quosure),
483 _ => None,
484 }
485 }
486}
487
488#[derive(#[automatically_derived]impl ::core::fmt::Debug for UnevaluatedParam {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"UnevaluatedParam kind optional", &self.kind, &&self.optional)
}
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for UnevaluatedParam {
}
#[automatically_derived]impl ::core::clone::Clone for UnevaluatedParam {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<UnevaluatedKind>;
let _: ::core::clone::AssertParamIsClone<bool>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for UnevaluatedParam { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
UnevaluatedParam {
}
#[automatically_derived]impl ::core::cmp::PartialEq for UnevaluatedParam {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.optional == other.optional && self.kind == other.kind
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for UnevaluatedParam {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<UnevaluatedKind>;
let _: ::core::cmp::AssertParamIsEq<bool>;
}
}Eq)]
491pub(crate) struct UnevaluatedParam {
492 pub(crate) kind: UnevaluatedKind,
493 pub(crate) optional: bool,
496}
497
498pub(crate) fn unevaluated_param(ty: &syn::Type) -> Option<UnevaluatedParam> {
504 let marker = |ty: &syn::Type| match ty {
505 syn::Type::Path(p) => p.path.segments.last().and_then(UnevaluatedKind::of_segment),
506 _ => None,
507 };
508 if let Some(kind) = marker(ty) {
509 return Some(UnevaluatedParam {
510 kind,
511 optional: false,
512 });
513 }
514 let inner = crate::miniextendr_fn::get_missing_inner_type(ty)?;
515 marker(inner).map(|kind| UnevaluatedParam {
516 kind,
517 optional: true,
518 })
519}
520
521pub(crate) fn mentions_unevaluated_marker(ty: &syn::Type) -> bool {
523 match ty {
524 syn::Type::Path(p) => p.path.segments.iter().any(|seg| {
525 #[allow(non_exhaustive_omitted_patterns)] match seg.ident.to_string().as_str()
{
"Quoted" | "Quosure" => true,
_ => false,
}matches!(seg.ident.to_string().as_str(), "Quoted" | "Quosure")
526 || match &seg.arguments {
527 syn::PathArguments::AngleBracketed(ab) => ab.args.iter().any(|arg| {
528 #[allow(non_exhaustive_omitted_patterns)] match arg {
syn::GenericArgument::Type(t) if mentions_unevaluated_marker(t) => true,
_ => false,
}matches!(arg, syn::GenericArgument::Type(t) if mentions_unevaluated_marker(t))
529 }),
530 _ => false,
531 }
532 }),
533 syn::Type::Reference(r) => mentions_unevaluated_marker(&r.elem),
534 syn::Type::Paren(p) => mentions_unevaluated_marker(&p.elem),
535 syn::Type::Group(g) => mentions_unevaluated_marker(&g.elem),
536 syn::Type::Tuple(t) => t.elems.iter().any(mentions_unevaluated_marker),
537 syn::Type::Array(a) => mentions_unevaluated_marker(&a.elem),
538 syn::Type::Slice(s) => mentions_unevaluated_marker(&s.elem),
539 _ => false,
540 }
541}
542
543#[derive(#[automatically_derived]impl ::core::fmt::Debug for ParamMarker {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ParamMarker::Checked => "Checked",
ParamMarker::Unchecked => "Unchecked",
ParamMarker::NonNa => "NonNa",
})
}
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for ParamMarker {
}
#[automatically_derived]impl ::core::clone::Clone for ParamMarker {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ParamMarker { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
ParamMarker {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ParamMarker {
#[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 ParamMarker { }Eq)]
551pub(crate) enum ParamMarker {
552 Checked,
554 Unchecked,
556 NonNa,
559}
560
561#[derive(#[automatically_derived]impl ::core::fmt::Debug for ParamMarkerFamily {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ParamMarkerFamily::Preconditions => "Preconditions",
ParamMarkerFamily::NoNa => "NoNa",
})
}
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for ParamMarkerFamily {
}
#[automatically_derived]impl ::core::clone::Clone for ParamMarkerFamily {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ParamMarkerFamily { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
ParamMarkerFamily {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ParamMarkerFamily {
#[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 ParamMarkerFamily { }Eq)]
564pub(crate) enum ParamMarkerFamily {
565 Preconditions,
567 NoNa,
569}
570
571impl ParamMarker {
572 fn from_ident(ident: &syn::Ident) -> Option<Self> {
574 match ident.to_string().as_str() {
575 "Checked" => Some(Self::Checked),
576 "Unchecked" => Some(Self::Unchecked),
577 "NonNa" => Some(Self::NonNa),
578 _ => None,
579 }
580 }
581
582 pub(crate) fn name(self) -> &'static str {
584 match self {
585 Self::Checked => "Checked",
586 Self::Unchecked => "Unchecked",
587 Self::NonNa => "NonNa",
588 }
589 }
590
591 pub(crate) fn family(self) -> ParamMarkerFamily {
593 match self {
594 Self::Checked | Self::Unchecked => ParamMarkerFamily::Preconditions,
595 Self::NonNa => ParamMarkerFamily::NoNa,
596 }
597 }
598
599 pub(crate) fn wrap(self, value: &syn::Ident) -> proc_macro2::TokenStream {
603 match self {
604 Self::Checked => {
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "miniextendr_api");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "Checked");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "from_inner");
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
{
let mut _s = ::quote::__private::TokenStream::new();
::quote::ToTokens::to_tokens(&value, &mut _s);
_s
});
_s
}quote::quote!(::miniextendr_api::Checked::from_inner(#value)),
605 Self::Unchecked => {
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "miniextendr_api");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "Unchecked");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "from_inner");
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
{
let mut _s = ::quote::__private::TokenStream::new();
::quote::ToTokens::to_tokens(&value, &mut _s);
_s
});
_s
}quote::quote!(::miniextendr_api::Unchecked::from_inner(#value)),
606 Self::NonNa => {
610 {
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_ident(&mut _s, "unsafe");
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Brace,
{
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "miniextendr_api");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "NonNa");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "new_unchecked");
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
{
let mut _s = ::quote::__private::TokenStream::new();
::quote::ToTokens::to_tokens(&value, &mut _s);
_s
});
_s
});
_s
}quote::quote!(unsafe { ::miniextendr_api::NonNa::new_unchecked(#value) })
611 }
612 }
613 }
614
615 pub(crate) fn preconditions(self) -> Option<bool> {
619 match self {
620 Self::Checked => Some(true),
621 Self::Unchecked => Some(false),
622 Self::NonNa => None,
623 }
624 }
625
626 pub(crate) fn impl_keyword(self, param: &str) -> String {
630 match self {
631 Self::Checked => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("preconditions({0})", param))
})format!("preconditions({param})"),
632 Self::Unchecked => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no_preconditions({0})", param))
})format!("no_preconditions({param})"),
633 Self::NonNa => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no_na({0})", param))
})format!("no_na({param})"),
634 }
635 }
636}
637
638fn outer_param_marker(ty: &syn::Type) -> Option<(ParamMarker, &syn::Type)> {
643 let syn::Type::Path(p) = ty else {
644 return None;
645 };
646 let seg = p.path.segments.last()?;
647 let marker = ParamMarker::from_ident(&seg.ident)?;
648 let syn::PathArguments::AngleBracketed(ab) = &seg.arguments else {
649 return None;
650 };
651 let mut types = ab.args.iter().filter_map(|arg| match arg {
652 syn::GenericArgument::Type(t) => Some(t),
653 _ => None,
654 });
655 let inner = types.next()?;
656 if types.next().is_some() {
657 return None;
658 }
659 Some((marker, inner))
660}
661
662pub(crate) fn peel_param_markers(ty: &syn::Type) -> syn::Result<(Vec<ParamMarker>, &syn::Type)> {
670 let mut markers: Vec<ParamMarker> = Vec::new();
671 let mut inner = ty;
672 while let Some((marker, next)) = outer_param_marker(inner) {
673 if let Some(first) = markers.iter().find(|m| m.family() == marker.family()) {
674 let message = match marker.family() {
675 ParamMarkerFamily::Preconditions => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("at most one precondition marker per parameter: `{0}` already decides this parameter\'s R-side type checks, so drop `{1}`",
first.name(), marker.name()))
})format!(
676 "at most one precondition marker per parameter: `{}` already decides this \
677 parameter's R-side type checks, so drop `{}`",
678 first.name(),
679 marker.name()
680 ),
681 ParamMarkerFamily::NoNa => {
682 "`NonNa<NonNa<T>>`: one `NonNa` already refuses an `NA`, so drop the \
683 inner one"
684 .to_string()
685 }
686 };
687 return Err(syn::Error::new_spanned(ty, message));
688 }
689 markers.push(marker);
690 inner = next;
691 }
692 if markers.contains(&ParamMarker::NonNa)
693 && let Some((_, spelling)) = optional_layer(inner)
694 {
695 return Err(syn::Error::new_spanned(
696 ty,
697 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`NonNa<{0}<T>>`: a value without `NA` leaves `{0}` only `NULL` to mean; take `NonNa<T>`, or `{0}<T>` with `#[miniextendr(no_na)]` to accept `NULL`",
spelling.name()))
})format!(
698 "`NonNa<{0}<T>>`: a value without `NA` leaves `{0}` only `NULL` to mean; \
699 take `NonNa<T>`, or `{0}<T>` with `#[miniextendr(no_na)]` to accept `NULL`",
700 spelling.name()
701 ),
702 ));
703 }
704 if let Some(nested) = nested_param_marker(inner) {
705 return Err(syn::Error::new_spanned(
706 ty,
707 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("put `{0}` outermost: `{0}<Option<T>>`, not `Option<{0}<T>>`; the marker applies to the whole parameter",
nested.name()))
})format!(
708 "put `{0}` outermost: `{0}<Option<T>>`, not `Option<{0}<T>>`; the marker \
709 applies to the whole parameter",
710 nested.name()
711 ),
712 ));
713 }
714 Ok((markers, inner))
715}
716
717fn nested_param_marker(ty: &syn::Type) -> Option<ParamMarker> {
720 let arg = match ty {
721 syn::Type::Reference(r) => r.elem.as_ref(),
722 syn::Type::Paren(p) => p.elem.as_ref(),
723 syn::Type::Path(p) => match optional_inner_type(ty) {
724 Some(inner) => inner,
725 None => {
726 let seg = p.path.segments.last()?;
727 if !#[allow(non_exhaustive_omitted_patterns)] match seg.ident.to_string().as_str()
{
"Missing" | "Vec" => true,
_ => false,
}matches!(seg.ident.to_string().as_str(), "Missing" | "Vec") {
728 return None;
729 }
730 first_type_argument(seg)?
731 }
732 },
733 _ => return None,
734 };
735 match outer_param_marker(arg) {
736 Some((marker, _)) => Some(marker),
737 None => nested_param_marker(arg),
738 }
739}
740
741pub(crate) fn marker_in_family(
743 markers: &[ParamMarker],
744 family: ParamMarkerFamily,
745) -> Option<ParamMarker> {
746 markers.iter().copied().find(|m| m.family() == family)
747}
748
749pub(crate) fn type_display(ty: &syn::Type) -> String {
764 let mut out = String::new();
765 write_type_tokens({
let mut _s = ::quote::__private::TokenStream::new();
::quote::ToTokens::to_tokens(&ty, &mut _s);
_s
}quote::quote!(#ty), &mut out);
766 out
767}
768
769fn write_type_tokens(tokens: proc_macro2::TokenStream, out: &mut String) {
770 use proc_macro2::{Delimiter, Spacing, TokenTree};
771
772 #[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Prev {
}
#[automatically_derived]impl ::core::clone::Clone for Prev {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Prev { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Prev { }
#[automatically_derived]impl ::core::cmp::PartialEq for Prev {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
774 enum Prev {
775 Glue,
778 Tick,
780 Word,
782 Keyword,
785 }
786
787 let mut prev = Prev::Glue;
788 let mut pending_arrow = false;
790 let mut pending_path_sep = false;
791 for tt in tokens {
792 match tt {
793 TokenTree::Ident(ident) => {
794 let name = ident.to_string();
795 if #[allow(non_exhaustive_omitted_patterns)] match prev {
Prev::Word | Prev::Keyword => true,
_ => false,
}matches!(prev, Prev::Word | Prev::Keyword) {
796 out.push(' ');
797 }
798 out.push_str(&name);
799 prev = if prev == Prev::Tick
800 || #[allow(non_exhaustive_omitted_patterns)] match name.as_str() {
"mut" | "const" | "dyn" | "impl" => true,
_ => false,
}matches!(name.as_str(), "mut" | "const" | "dyn" | "impl")
801 {
802 Prev::Keyword
803 } else {
804 Prev::Word
805 };
806 }
807 TokenTree::Literal(lit) => {
808 if #[allow(non_exhaustive_omitted_patterns)] match prev {
Prev::Word | Prev::Keyword => true,
_ => false,
}matches!(prev, Prev::Word | Prev::Keyword) {
809 out.push(' ');
810 }
811 out.push_str(&lit.to_string());
812 prev = Prev::Word;
813 }
814 TokenTree::Group(group) => {
815 if prev == Prev::Keyword
816 || (prev == Prev::Word && group.delimiter() == Delimiter::Bracket)
817 {
818 out.push(' ');
819 }
820 let (open, close) = match group.delimiter() {
821 Delimiter::Parenthesis => ("(", ")"),
822 Delimiter::Bracket => ("[", "]"),
823 Delimiter::Brace => ("{", "}"),
824 Delimiter::None => ("", ""),
825 };
826 out.push_str(open);
827 write_type_tokens(group.stream(), out);
828 out.push_str(close);
829 prev = Prev::Word;
830 }
831 TokenTree::Punct(punct) => {
832 let c = punct.as_char();
833 match c {
834 ',' | ';' => {
835 out.push(c);
836 out.push(' ');
837 prev = Prev::Glue;
838 }
839 '+' | '=' => {
840 out.push(' ');
841 out.push(c);
842 out.push(' ');
843 prev = Prev::Glue;
844 }
845 '-' if punct.spacing() == Spacing::Joint => {
846 out.push_str(" -");
847 pending_arrow = true;
848 }
849 '>' if pending_arrow => {
850 out.push_str("> ");
851 pending_arrow = false;
852 prev = Prev::Glue;
853 }
854 '>' => {
855 out.push('>');
856 prev = Prev::Word;
857 }
858 ':' if punct.spacing() == Spacing::Joint => {
859 out.push(':');
860 pending_path_sep = true;
861 prev = Prev::Glue;
862 }
863 ':' if pending_path_sep => {
864 out.push(':');
865 pending_path_sep = false;
866 prev = Prev::Glue;
867 }
868 ':' => {
869 out.push_str(": ");
871 prev = Prev::Glue;
872 }
873 '\'' => {
874 if #[allow(non_exhaustive_omitted_patterns)] match prev {
Prev::Word | Prev::Keyword => true,
_ => false,
}matches!(prev, Prev::Word | Prev::Keyword) {
875 out.push(' ');
876 }
877 out.push('\'');
878 prev = Prev::Tick;
879 }
880 _ => {
881 out.push(c);
882 prev = Prev::Glue;
883 }
884 }
885 }
886 }
887 }
888}
889
890pub(crate) fn erase_lifetimes(ty: &syn::Type) -> syn::Type {
896 use proc_macro2::{Group, Ident, TokenStream, TokenTree};
897
898 fn erase(tokens: TokenStream) -> TokenStream {
899 let mut out = Vec::new();
900 let mut iter = tokens.into_iter();
901 while let Some(tt) = iter.next() {
902 match tt {
903 TokenTree::Punct(p) if p.as_char() == '\'' => {
904 out.push(TokenTree::Punct(p));
905 if let Some(TokenTree::Ident(lifetime)) = iter.next() {
906 out.push(TokenTree::Ident(Ident::new("_", lifetime.span())));
907 }
908 }
909 TokenTree::Group(g) => {
910 let mut erased = Group::new(g.delimiter(), erase(g.stream()));
911 erased.set_span(g.span());
912 out.push(TokenTree::Group(erased));
913 }
914 other => out.push(other),
915 }
916 }
917 out.into_iter().collect()
918 }
919
920 syn::parse2(erase({
let mut _s = ::quote::__private::TokenStream::new();
::quote::ToTokens::to_tokens(&ty, &mut _s);
_s
}quote::quote!(#ty))).unwrap_or_else(|_| ty.clone())
921}
922
923#[cfg(test)]
926mod tests;
927
928pub(crate) fn is_option_type(ty: &syn::Type) -> bool {
930 option_inner_type(ty).is_some()
931}
932
933pub(crate) fn option_inner_type(ty: &syn::Type) -> Option<&syn::Type> {
939 let syn::Type::Path(tp) = ty else {
940 return None;
941 };
942 let seg = tp.path.segments.last()?;
943 if seg.ident != "Option" {
944 return None;
945 }
946 first_type_argument(seg)
947}
948
949#[derive(#[automatically_derived]impl ::core::fmt::Debug for OptionalSpelling {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
OptionalSpelling::Option => "Option",
OptionalSpelling::Nullable => "Nullable",
})
}
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for OptionalSpelling {
}
#[automatically_derived]impl ::core::clone::Clone for OptionalSpelling {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for OptionalSpelling { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
OptionalSpelling {
}
#[automatically_derived]impl ::core::cmp::PartialEq for OptionalSpelling {
#[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 OptionalSpelling { }Eq)]
961pub(crate) enum OptionalSpelling {
962 Option,
964 Nullable,
966}
967
968impl OptionalSpelling {
969 pub(crate) fn name(self) -> &'static str {
971 match self {
972 Self::Option => "Option",
973 Self::Nullable => "Nullable",
974 }
975 }
976
977 pub(crate) fn wrap_ok(self, result: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
981 match self {
982 Self::Option => result,
983 Self::Nullable => {
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "core");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "result");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "Result");
::quote::__private::push_colon2(&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::ToTokens::to_tokens(&result, &mut _s);
::quote::__private::push_comma(&mut _s);
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "miniextendr_api");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "Nullable");
_s
});
_s
}quote::quote! {
984 ::core::result::Result::map(#result, ::miniextendr_api::Nullable)
985 },
986 }
987 }
988}
989
990pub(crate) fn optional_layer(ty: &syn::Type) -> Option<(&syn::Type, OptionalSpelling)> {
993 let syn::Type::Path(tp) = ty else {
994 return None;
995 };
996 let seg = tp.path.segments.last()?;
997 let spelling = if seg.ident == "Option" {
998 OptionalSpelling::Option
999 } else if seg.ident == "Nullable" {
1000 OptionalSpelling::Nullable
1001 } else {
1002 return None;
1003 };
1004 first_type_argument(seg).map(|inner| (inner, spelling))
1005}
1006
1007pub(crate) fn optional_inner_type(ty: &syn::Type) -> Option<&syn::Type> {
1010 optional_layer(ty).map(|(inner, _)| inner)
1011}
1012
1013pub(crate) fn is_optional_type(ty: &syn::Type) -> bool {
1015 optional_layer(ty).is_some()
1016}
1017
1018pub(crate) fn nullable_inner_type(ty: &syn::Type) -> Option<&syn::Type> {
1021 optional_layer(ty)
1022 .filter(|(_, spelling)| *spelling == OptionalSpelling::Nullable)
1023 .map(|(inner, _)| inner)
1024}
1025
1026pub(crate) fn peel_external_ptr(ty: &syn::Type) -> &syn::Type {
1034 let syn::Type::Path(tp) = ty else {
1035 return ty;
1036 };
1037 match tp.path.segments.last() {
1038 Some(seg) if seg.ident == "ExternalPtr" => first_type_argument(seg).unwrap_or(ty),
1039 _ => ty,
1040 }
1041}
1042
1043#[derive(#[automatically_derived]impl<'a> ::core::fmt::Debug for ChoiceLayers<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"ChoiceLayers missing nullable either_right value", &self.missing,
&self.nullable, &self.either_right, &&self.value)
}
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl<'a>
::core::clone::TrivialClone for ChoiceLayers<'a> {
}
#[automatically_derived]impl<'a> ::core::clone::Clone for ChoiceLayers<'a> {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<bool>;
let _: ::core::clone::AssertParamIsClone<Option<OptionalSpelling>>;
let _: ::core::clone::AssertParamIsClone<Option<&'a syn::Type>>;
let _: ::core::clone::AssertParamIsClone<&'a syn::Type>;
*self
}
}Clone, #[automatically_derived]impl<'a> ::core::marker::Copy for ChoiceLayers<'a> { }Copy)]
1058pub(crate) struct ChoiceLayers<'a> {
1059 pub missing: bool,
1061 pub nullable: Option<OptionalSpelling>,
1064 pub either_right: Option<&'a syn::Type>,
1066 pub value: &'a syn::Type,
1069}
1070
1071pub(crate) fn choice_layers(ty: &syn::Type) -> ChoiceLayers<'_> {
1073 let (missing, ty) = match crate::miniextendr_fn::get_missing_inner_type(ty) {
1074 Some(inner) => (true, inner),
1075 None => (false, ty),
1076 };
1077 let (nullable, ty) = match optional_layer(ty) {
1078 Some((inner, spelling)) => (Some(spelling), inner),
1079 None => (None, ty),
1080 };
1081 let (either_right, value) = match either_arms(ty) {
1082 Some((left, right)) => (Some(right), left),
1083 None => (None, ty),
1084 };
1085 ChoiceLayers {
1086 missing,
1087 nullable,
1088 either_right,
1089 value,
1090 }
1091}
1092
1093pub(crate) fn choice_layer_name(ty: &syn::Type) -> Option<&'static str> {
1098 if crate::miniextendr_fn::get_missing_inner_type(ty).is_some() {
1099 Some("Missing")
1100 } else if let Some((_, spelling)) = optional_layer(ty) {
1101 Some(spelling.name())
1102 } else if either_arms(ty).is_some() {
1103 Some("Either")
1104 } else {
1105 None
1106 }
1107}
1108
1109pub(crate) fn either_arms(ty: &syn::Type) -> Option<(&syn::Type, &syn::Type)> {
1112 let syn::Type::Path(tp) = ty else {
1113 return None;
1114 };
1115 let seg = tp.path.segments.last()?;
1116 if seg.ident != "Either" {
1117 return None;
1118 }
1119 let syn::PathArguments::AngleBracketed(args) = &seg.arguments else {
1120 return None;
1121 };
1122 let mut types = args.args.iter().filter_map(|arg| match arg {
1123 syn::GenericArgument::Type(ty) => Some(ty),
1124 _ => None,
1125 });
1126 match (types.next(), types.next(), types.next()) {
1127 (Some(left), Some(right), None) => Some((left, right)),
1128 _ => None,
1129 }
1130}
1131
1132pub(crate) fn r_value_noun(ty: &syn::Type) -> String {
1138 let named = match ty {
1139 syn::Type::Reference(r) => match r.elem.as_ref() {
1140 syn::Type::Slice(s) => vector_noun(&s.elem),
1141 elem => return r_value_noun(elem),
1142 },
1143 syn::Type::Slice(s) => vector_noun(&s.elem),
1144 syn::Type::Path(tp) => {
1145 tp.path
1146 .segments
1147 .last()
1148 .and_then(|seg| match seg.ident.to_string().as_str() {
1149 "DataFrame" | "BuiltDataFrame" => Some("a data frame"),
1150 "List" | "ListMut" | "NamedList" | "HashMap" | "BTreeMap" => Some("a list"),
1151 "String" | "str" | "char" | "PathBuf" | "Path" => Some("a string"),
1152 "f64" | "f32" => Some("a number"),
1153 "i8" | "i16" | "i32" | "i64" | "isize" | "u16" | "u32" | "u64" | "usize" => {
1154 Some("an integer")
1155 }
1156 "bool" | "Rbool" | "Rboolean" => Some("TRUE or FALSE"),
1157 "Rcomplex" => Some("a complex number"),
1158 "ExternalPtr" => Some("an external pointer"),
1159 "SEXP" => Some("any other R value"),
1160 "Vec" => first_type_argument(seg).and_then(vector_noun),
1161 _ => None,
1162 })
1163 }
1164 _ => None,
1165 };
1166 named.map_or_else(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a `{0}`", type_display(ty)))
})format!("a `{}`", type_display(ty)), str::to_string)
1167}
1168
1169fn vector_noun(elem: &syn::Type) -> Option<&'static str> {
1171 let syn::Type::Path(tp) = elem else {
1172 return None;
1173 };
1174 let seg = tp.path.segments.last()?;
1175 match seg.ident.to_string().as_str() {
1176 "f64" | "f32" => Some("a numeric vector"),
1177 "i8" | "i16" | "i32" | "i64" | "isize" | "u16" | "u32" | "u64" | "usize" => {
1178 Some("an integer vector")
1179 }
1180 "String" | "str" => Some("a character vector"),
1181 "bool" | "Rbool" | "Rboolean" => Some("a logical vector"),
1182 "u8" => Some("a raw vector"),
1183 "Option" => first_type_argument(seg).and_then(vector_noun),
1184 _ => None,
1185 }
1186}
1187
1188pub(crate) fn match_arg_choices_ty(param_ty: &syn::Type, several_ok: bool) -> &syn::Type {
1199 let value = choice_layers(param_ty).value;
1200 if several_ok {
1201 classify_several_ok_container(value)
1202 .map(|(_, inner)| inner)
1203 .unwrap_or(value)
1204 } else {
1205 value
1206 }
1207}
1208
1209#[derive(#[automatically_derived]impl ::core::fmt::Debug for SeveralOkContainer {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Vec => ::core::fmt::Formatter::write_str(f, "Vec"),
Self::BoxedSlice =>
::core::fmt::Formatter::write_str(f, "BoxedSlice"),
Self::Array(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Array",
&__self_0),
Self::BorrowedSlice =>
::core::fmt::Formatter::write_str(f, "BorrowedSlice"),
}
}
}Debug, #[automatically_derived]impl ::core::clone::Clone for SeveralOkContainer {
#[inline]
fn clone(&self) -> Self {
match self {
Self::Vec => SeveralOkContainer::Vec,
Self::BoxedSlice => SeveralOkContainer::BoxedSlice,
Self::Array(__self_0) =>
SeveralOkContainer::Array(::core::clone::Clone::clone(__self_0)),
Self::BorrowedSlice => SeveralOkContainer::BorrowedSlice,
}
}
}Clone)]
1214pub(crate) enum SeveralOkContainer {
1215 Vec,
1217 BoxedSlice,
1219 Array(usize),
1221 BorrowedSlice,
1223}
1224
1225pub(crate) fn classify_several_ok_container(
1231 ty: &syn::Type,
1232) -> Option<(SeveralOkContainer, &syn::Type)> {
1233 match ty {
1234 syn::Type::Path(tp) => {
1236 let seg = tp.path.segments.last()?;
1237 if seg.ident == "Vec" {
1238 let inner = first_type_argument(seg)?;
1239 return Some((SeveralOkContainer::Vec, inner));
1240 }
1241 if seg.ident == "Box"
1243 && let syn::PathArguments::AngleBracketed(ab) = &seg.arguments
1244 {
1245 for arg in &ab.args {
1246 if let syn::GenericArgument::Type(syn::Type::Slice(s)) = arg {
1247 return Some((SeveralOkContainer::BoxedSlice, s.elem.as_ref()));
1248 }
1249 }
1250 }
1251 None
1252 }
1253 syn::Type::Array(arr) => {
1255 if let syn::Expr::Lit(syn::ExprLit {
1256 lit: syn::Lit::Int(n),
1257 ..
1258 }) = &arr.len
1259 {
1260 let n = n.base10_parse::<usize>().ok()?;
1261 return Some((SeveralOkContainer::Array(n), arr.elem.as_ref()));
1262 }
1263 None
1264 }
1265 syn::Type::Reference(r) => {
1267 if let syn::Type::Slice(s) = r.elem.as_ref() {
1268 return Some((SeveralOkContainer::BorrowedSlice, s.elem.as_ref()));
1269 }
1270 None
1271 }
1272 _ => None,
1273 }
1274}
1275
1276pub(crate) fn self_ref_mutability(ty: &syn::Type) -> Option<bool> {
1279 if let syn::Type::Reference(reference) = ty
1280 && let syn::Type::Path(path) = reference.elem.as_ref()
1281 && path.path.is_ident("Self")
1282 {
1283 Some(reference.mutability.is_some())
1284 } else {
1285 None
1286 }
1287}