1//! Function signature parsing for `#[miniextendr]`.
2//!
3//! This module handles parsing and normalizing Rust function signatures for the
4//! `#[miniextendr]` attribute macro. It provides:
5//!
6//! - [`MiniextendrFunctionParsed`]: Parsed function with normalization and codegen helpers
7//! - [`MiniextendrFnAttrs`]: Parsed `#[miniextendr(...)]` attribute options
8//! - [`CoercionMapping`]: Type coercion analysis for automatic R→Rust conversion
910use crate::r_wrapper_const_ident_for;
1112// region: Coercion analysis
1314/// Conversion selected by `coerce`, shared by Rust conversion and R checks.
15pub(crate) enum CoercionMapping {
16/// The non-native numeric scalars and vectors, and their `Option` /
17 /// `Vec<Option<_>>` forms, already have checked, multi-source converters.
18Numeric,
19/// Keep logical scalars and additionally accept integer zero or one.
20Bool,
21/// Keep logical vectors and additionally accept integer zeros and ones.
22BoolVec,
23/// Native `i32`: keep `INTSXP`, additionally accept whole-valued doubles,
24 /// logicals, and raws.
25NativeInt,
26/// Native `Vec<i32>`: element-wise form of [`Self::NativeInt`].
27NativeIntVec,
28/// Native `f64`: keep `REALSXP`, additionally accept integers, logicals, and raws.
29NativeReal,
30/// Native `Vec<f64>`: element-wise form of [`Self::NativeReal`].
31NativeRealVec,
32/// `Option<bool>`: `NULL` and `NA` read `None`, any other value converts
33 /// as [`Self::Bool`] (#2274).
34OptionBool,
35/// `Vec<Option<bool>>`: element-wise form of [`Self::OptionBool`].
36OptionBoolVec,
37/// `Option<i32>`: `NULL` and `NA` read `None`, any other value converts
38 /// as [`Self::NativeInt`].
39OptionNativeInt,
40/// `Vec<Option<i32>>`: element-wise form of [`Self::OptionNativeInt`].
41OptionNativeIntVec,
42/// `Option<f64>`: `NULL` and `NA` read `None`, any other value converts
43 /// as [`Self::NativeReal`].
44OptionNativeReal,
45/// `Vec<Option<f64>>`: element-wise form of [`Self::OptionNativeReal`].
46OptionNativeRealVec,
47}
4849impl CoercionMapping {
50/// Recognize the scalar and vector types supported by `coerce`.
51 ///
52 /// Numeric conversion preserves all sources accepted by `TryFromSexp`:
53 /// integer, double, logical, and raw. Booleans extend their logical-only
54 /// converter with integer zero/one input. The native `i32` / `f64` scalars
55 /// and vectors, whose bare conversion accepts one `SEXPTYPE`, widen to the
56 /// same four sources (whole-valued doubles only for `i32`). Each of these
57 /// element types maps in four shapes: `T`, `Vec<T>`, `Option<T>` and
58 /// `Vec<Option<T>>`, and each shape also under `Missing<..>`, whose
59 /// sentinel reads `Missing::Absent` before the mapping converts a present
60 /// value. A `Nullable<T>` maps as `Option<T>` does (#2294), except as a
61 /// `Vec` element, which has no conversion; the caller wraps the
62 /// converter's `Option` in `Nullable`. Borrowed slices and other types
63 /// keep `TryFromSexp`.
64pub(crate) fn from_type(ty: &syn::Type) -> Option<Self> {
65let ty = get_missing_inner_type(ty).unwrap_or(ty);
66let (ty, top_optional) = match crate::type_inspect::optional_inner_type(ty) {
67Some(inner) => (inner, true),
68None => (ty, false),
69 };
70let syn::Type::Path(type_path) = tyelse {
71return None;
72 };
73let mut seg = type_path.path.segments.last()?;
74let is_vec = !top_optional && seg.ident == "Vec";
75if is_vec {
76seg = type_argument_segment(seg)?;
77 }
78let is_option = top_optional || seg.ident == "Option";
79if is_vec && is_option {
80seg = type_argument_segment(seg)?;
81 }
82match (seg.ident.to_string().as_str(), is_vec, is_option) {
83 ("i8" | "i16" | "u16" | "u32" | "i64" | "u64" | "isize" | "usize" | "f32", _, _) => {
84Some(Self::Numeric)
85 }
86 ("bool", false, false) => Some(Self::Bool),
87 ("bool", true, false) => Some(Self::BoolVec),
88 ("bool", false, true) => Some(Self::OptionBool),
89 ("bool", true, true) => Some(Self::OptionBoolVec),
90 ("i32", false, false) => Some(Self::NativeInt),
91 ("i32", true, false) => Some(Self::NativeIntVec),
92 ("i32", false, true) => Some(Self::OptionNativeInt),
93 ("i32", true, true) => Some(Self::OptionNativeIntVec),
94 ("f64", false, false) => Some(Self::NativeReal),
95 ("f64", true, false) => Some(Self::NativeRealVec),
96 ("f64", false, true) => Some(Self::OptionNativeReal),
97 ("f64", true, true) => Some(Self::OptionNativeRealVec),
98_ => None,
99 }
100 }
101102/// The `miniextendr_api::from_r` helper this mapping converts through,
103 /// or `None` for [`Self::Numeric`], whose `TryFromSexp` impls already read
104 /// every source.
105pub(crate) fn converter(&self) -> Option<&'static str> {
106Some(match self {
107Self::Numeric => return None,
108Self::Bool => "try_from_sexp_coerced_bool",
109Self::BoolVec => "try_from_sexp_coerced_bool_vec",
110Self::NativeInt => "try_from_sexp_coerced_i32",
111Self::NativeIntVec => "try_from_sexp_coerced_i32_vec",
112Self::NativeReal => "try_from_sexp_coerced_f64",
113Self::NativeRealVec => "try_from_sexp_coerced_f64_vec",
114Self::OptionBool => "try_from_sexp_coerced_option_bool",
115Self::OptionBoolVec => "try_from_sexp_coerced_option_bool_vec",
116Self::OptionNativeInt => "try_from_sexp_coerced_option_i32",
117Self::OptionNativeIntVec => "try_from_sexp_coerced_option_i32_vec",
118Self::OptionNativeReal => "try_from_sexp_coerced_option_f64",
119Self::OptionNativeRealVec => "try_from_sexp_coerced_option_f64_vec",
120 })
121 }
122}
123124/// The last path segment of a segment's first type argument: `i32` for
125/// `Vec<i32>` or `Option<::core::primitive::i32>`.
126fn type_argument_segment(seg: &syn::PathSegment) -> Option<&syn::PathSegment> {
127let syn::PathArguments::AngleBracketed(args) = &seg.arguments else {
128return None;
129 };
130let syn::GenericArgument::Type(syn::Type::Path(inner)) = args.args.first()? else {
131return None;
132 };
133inner.path.segments.last()
134}
135136/// The error for a per-parameter `coerce` on a type it has no conversion for
137/// (#2274), spanned on the parameter. A function-wide or feature-default
138/// `coerce` skips such a parameter; one that names the parameter would
139/// otherwise do nothing.
140pub(crate) fn unmapped_coerce_error(pat_type: &syn::PatType, param_name: &str) -> syn::Error {
141let slice_hint = match pat_type.ty.as_ref() {
142 syn::Type::Reference(r) if #[allow(non_exhaustive_omitted_patterns)] match r.elem.as_ref() {
syn::Type::Slice(_) => true,
_ => false,
}matches!(r.elem.as_ref(), syn::Type::Slice(_)) => {
143" A borrowed slice reads R's storage as it is and cannot hold a converted \
144 copy; take `Vec<T>`."
145}
146_ => "",
147 };
148 syn::Error::new_spanned(
149pat_type,
150::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`coerce` on parameter `{1}` has no conversion for `{0}`: it widens `i32`, `f64`, `bool` and the other numeric scalars (`i8`, `i16`, `u16`, `u32`, `i64`, `u64`, `isize`, `usize`, `f32`), as `T`, `Vec<T>`, `Option<T>` (or `Nullable<T>`) or `Vec<Option<T>>`, each also under `Missing<..>`. Remove `coerce` from this parameter.{2}",
crate::type_inspect::type_display(&pat_type.ty), param_name,
slice_hint))
})format!(
151"`coerce` on parameter `{param_name}` has no conversion for `{}`: it widens \
152 `i32`, `f64`, `bool` and the other numeric scalars (`i8`, `i16`, `u16`, `u32`, \
153 `i64`, `u64`, `isize`, `usize`, `f32`), as `T`, `Vec<T>`, `Option<T>` (or \
154 `Nullable<T>`) or `Vec<Option<T>>`, each also under `Missing<..>`. Remove \
155 `coerce` from this parameter.{slice_hint}",
156crate::type_inspect::type_display(&pat_type.ty)
157 ),
158 )
159}
160161// endregion
162163// region: Type inspection helpers
164165/// Rejects an `unsafe fn` that would get a generated wrapper (#2124): its R
166/// callers cannot uphold Rust safety preconditions. `rust_only` says how this
167/// kind of item stays out of R instead. Raw `extern "C-unwind"` registration
168/// has its own explicit contract and is not checked here.
169pub(crate) fn require_safe_wrapper(sig: &syn::Signature, rust_only: &str) -> syn::Result<()> {
170if let Some(unsafety) = sig.unsafety {
171return Err(syn::Error::new_spanned(
172unsafety,
173::alloc::__export::must_use({
::alloc::fmt::format(format_args!("an `unsafe fn` cannot get a generated R wrapper: its R callers cannot uphold its safety preconditions. Expose a safe fn that checks them and calls this one in an `unsafe` block, or {0} to keep it Rust-only",
rust_only))
})format!(
174"an `unsafe fn` cannot get a generated R wrapper: its R callers cannot uphold \
175 its safety preconditions. Expose a safe fn that checks them and calls this one \
176 in an `unsafe` block, or {rust_only} to keep it Rust-only"
177),
178 ));
179 }
180Ok(())
181}
182183/// Check if a type path ends with the given identifier (e.g., "Dots", "Missing").
184///
185/// Handles fully-qualified paths like `miniextendr_api::dots::Dots` as well as
186/// bare `Dots`.
187fn type_ends_with(ty: &syn::Type, name: &str) -> bool {
188match ty {
189 syn::Type::Path(tp) => tp190 .path
191 .segments
192 .last()
193 .map(|s| s.ident == name)
194 .unwrap_or(false),
195 syn::Type::Reference(r) => type_ends_with(&r.elem, name),
196_ => false,
197 }
198}
199200/// Which `...` parameter type a parameter takes.
201#[derive(#[automatically_derived]impl ::core::fmt::Debug for DotsKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
DotsKind::Forced => "Forced",
DotsKind::Lazy => "Lazy",
})
}
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for DotsKind {
}
#[automatically_derived]impl ::core::clone::Clone for DotsKind {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for DotsKind { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for DotsKind
{
}
#[automatically_derived]impl ::core::cmp::PartialEq for DotsKind {
#[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 DotsKind { }Eq)]
202pub(crate) enum DotsKind {
203/// `&Dots`: the wrapper passes `list(...)`, every element forced.
204Forced,
205/// `LazyDots`: the wrapper passes its own frame, `environment()`, and
206 /// nothing is forced (#1892).
207Lazy,
208}
209210impl DotsKind {
211/// The parameter type as written, for diagnostics.
212pub(crate) fn type_name(self) -> &'static str {
213match self {
214Self::Forced => "&Dots",
215Self::Lazy => "LazyDots",
216 }
217 }
218219/// The `.Call()` argument the R wrapper passes for the dots.
220pub(crate) fn r_call_arg(self) -> &'static str {
221match self {
222Self::Forced => "list(...)",
223Self::Lazy => "environment()",
224 }
225 }
226}
227228/// The `...` parameter type `ty` is, if any: `Dots` / `&Dots`
229/// ([`DotsKind::Forced`]), or `LazyDots` taken by value ([`DotsKind::Lazy`],
230/// [`crate::type_inspect::is_lazy_dots_marker`]). `&LazyDots` and other
231/// shapes are none; the callers refuse them by name.
232pub(crate) fn dots_kind(ty: &syn::Type) -> Option<DotsKind> {
233if crate::type_inspect::is_lazy_dots_marker(ty) {
234Some(DotsKind::Lazy)
235 } else if type_ends_with(ty, "Dots") {
236Some(DotsKind::Forced)
237 } else {
238None239 }
240}
241242/// Check if a type is a `...` parameter type: `Dots` / `&Dots` or `LazyDots`
243/// (see [`dots_kind`]).
244pub(crate) fn is_dots_type(ty: &syn::Type) -> bool {
245dots_kind(ty).is_some()
246}
247248/// Replace Rust variadic syntax (`name: ...` / `_: ...`) with a trailing
249/// `&miniextendr_api::dots::Dots` parameter, so downstream codegen never
250/// emits a non-extern variadic Rust fn. Named dots keep the user's
251/// identifier; `_: ...` binds `__miniextendr_dots`.
252///
253/// A bare `...` binds `__miniextendr_dots` too, but rustc rejects it before
254/// the macro runs (the deny-by-default `varargs_without_pattern` lint,
255/// rust-lang/rust#145544) unless the crate allows that lint, and its fix is
256/// `_: ...` (#1743).
257///
258/// syn parses the variadic only in last position, so a formal after the dots
259/// is spelled with an explicit `rest: &Dots` parameter instead. A signature
260/// with both is an error: a function takes at most one `...`.
261pub(crate) fn rewrite_variadic_dots(sig: &mut syn::Signature) -> syn::Result<()> {
262use syn::spanned::Spanned;
263264let Some(variadic) = sig.variadic.take() else {
265return Ok(());
266 };
267if let Some(syn::FnArg::Typed(existing)) = dots_index(&sig.inputs).map(|idx| &sig.inputs[idx]) {
268let kind = dots_kind(existing.ty.as_ref()).map_or("&Dots", DotsKind::type_name);
269let existing = match existing.pat.as_ref() {
270 syn::Pat::Ident(pat_ident) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}: {1}`", pat_ident.ident,
kind))
})format!("`{}: {kind}`", pat_ident.ident),
271_ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a `{0}` parameter", kind))
})format!("a `{kind}` parameter"),
272 };
273return Err(syn::Error::new(
274variadic.span(),
275::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this function already takes `...` as {0}; remove one of them",
existing))
})format!("this function already takes `...` as {existing}; remove one of them"),
276 ));
277 }
278let ident = match variadic.pat.map(|(pat, _)| *pat) {
279Some(syn::Pat::Ident(pat_ident)) => pat_ident.ident,
280// `_: ...` (rustc's fix for a bare `...`) and a bare `...`.
281Some(syn::Pat::Wild(_)) | None => {
282// Cannot use `_` as a variable name, so unnamed dots need a
283 // stable synthetic binding that does not collide with user args.
284for arg in &sig.inputs {
285let syn::FnArg::Typed(pat_type) = arg else {
286continue;
287 };
288if let syn::Pat::Ident(pat_ident) = pat_type.pat.as_ref()
289 && pat_ident.ident == "__miniextendr_dots"
290{
291return Err(syn::Error::new(
292 pat_ident.ident.span(),
293"parameter named `__miniextendr_dots` conflicts with the binding of \
294 unnamed dots (`_: ...`); name the dots instead, e.g. `args: ...`",
295 ));
296 }
297 }
298 syn::Ident::new("__miniextendr_dots", proc_macro2::Span::call_site())
299 }
300Some(pat) => {
301return Err(syn::Error::new(
302pat.span(),
303"variadic pattern must be a simple identifier (`args: ...`) or `_` (`_: ...`)",
304 ));
305 }
306 };
307sig.inputs
308 .push(::syn::__private::parse_quote({
let mut _s = ::quote::__private::TokenStream::new();
::quote::ToTokens::to_tokens(&ident, &mut _s);
::quote::__private::push_colon(&mut _s);
::quote::__private::push_and(&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, "dots");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "Dots");
_s
})syn::parse_quote!(#ident: &::miniextendr_api::dots::Dots));
309Ok(())
310}
311312/// Position of the first `...` parameter (`&Dots` or `LazyDots`) in `inputs`
313/// (receiver included, as
314/// [`RArgumentBuilder`](crate::r_wrapper_builder::RArgumentBuilder) counts
315/// them), without validation: for code that runs after [`find_dots_param`]
316/// has accepted the signature.
317pub(crate) fn dots_index(
318 inputs: &syn::punctuated::Punctuated<syn::FnArg, syn::token::Comma>,
319) -> Option<usize> {
320inputs321 .iter()
322 .position(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
syn::FnArg::Typed(pt) if is_dots_type(pt.ty.as_ref()) => true,
_ => false,
}matches!(arg, syn::FnArg::Typed(pt) if is_dots_type(pt.ty.as_ref())))
323}
324325/// Find the dots parameter of a signature by type, at any position, and
326/// return its Rust binding.
327///
328/// The parameter of type `&Dots` or `LazyDots` is R's `...` at its own
329/// position: the R formals and the `.Call()` arguments follow the Rust
330/// signature order, with `...` where it sits (`list(...)` or `environment()`
331/// in the call, [`DotsKind::r_call_arg`]), and every formal after it is
332/// matched by exact name only, as R does for any formal after `...`.
333///
334/// A function takes at most one `...`, so a second `&Dots` / `LazyDots`
335/// parameter is an error spanned on it. The parameter needs a plain name: the
336/// body reads the dots through it.
337pub(crate) fn find_dots_param(
338 inputs: &syn::punctuated::Punctuated<syn::FnArg, syn::token::Comma>,
339) -> syn::Result<Option<syn::Ident>> {
340use syn::spanned::Spanned;
341342let mut found: Option<(syn::Ident, DotsKind)> = None;
343for arg in inputs {
344let syn::FnArg::Typed(pat_type) = arg else {
345continue;
346 };
347let Some(kind) = dots_kind(pat_type.ty.as_ref()) else {
348continue;
349 };
350let syn::Pat::Ident(pat_ident) = pat_type.pat.as_ref() else {
351return Err(syn::Error::new(
352 pat_type.pat.span(),
353::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the `...` parameter needs a plain name, for example `rest: {0}`",
kind.type_name()))
})format!(
354"the `...` parameter needs a plain name, for example `rest: {}`",
355 kind.type_name()
356 ),
357 ));
358 };
359let ident = &pat_ident.ident;
360if let Some((first, first_kind)) = &found {
361let msg = if (*first_kind, kind) == (DotsKind::Forced, DotsKind::Forced) {
362::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a function takes at most one `...`: `{0}` and `{1}` both have type `&Dots`; keep one",
first, ident))
})format!(
363"a function takes at most one `...`: `{first}` and `{ident}` both have type \
364 `&Dots`; keep one"
365)366 } else {
367::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a function takes at most one `...`: `{2}` (`{0}`) and `{3}` (`{1}`) are both R\'s `...`; keep one",
first_kind.type_name(), kind.type_name(), first, ident))
})format!(
368"a function takes at most one `...`: `{first}` (`{}`) and `{ident}` (`{}`) \
369 are both R's `...`; keep one",
370 first_kind.type_name(),
371 kind.type_name()
372 )373 };
374return Err(syn::Error::new(ident.span(), msg));
375 }
376 found = Some((ident.clone(), kind));
377 }
378Ok(found.map(|(ident, _)| ident))
379}
380381/// Check if a type is `Missing<T>`.
382pub(crate) fn is_missing_type(ty: &syn::Type) -> bool {
383type_ends_with(ty, "Missing")
384}
385386/// Check if a type is a vector-like type that `several_ok` can populate.
387///
388/// Accepts `Vec<T>`, `Box<[T]>`, `&[T]` / `&mut [T]`, and `[T; N]`. Rejects
389/// scalar types (like `Mode`, `String`, `&str`) so `several_ok` — which
390/// produces a multi-element R character vector via
391/// `match.arg(..., several.ok = TRUE)` — fails at compile time instead of
392/// deserialization time.
393pub(crate) fn is_vector_like_type(ty: &syn::Type) -> bool {
394match ty {
395 syn::Type::Path(tp) => {
396let Some(seg) = tp.path.segments.last() else {
397return false;
398 };
399if seg.ident == "Vec" {
400return true;
401 }
402if seg.ident == "Box" {
403let syn::PathArguments::AngleBracketed(args) = &seg.arguments else {
404return false;
405 };
406return #[allow(non_exhaustive_omitted_patterns)] match args.args.first() {
Some(syn::GenericArgument::Type(syn::Type::Slice(_))) => true,
_ => false,
}matches!(
407 args.args.first(),
408Some(syn::GenericArgument::Type(syn::Type::Slice(_)))
409 );
410 }
411false
412}
413 syn::Type::Reference(r) => #[allow(non_exhaustive_omitted_patterns)] match &*r.elem {
syn::Type::Slice(_) => true,
_ => false,
}matches!(&*r.elem, syn::Type::Slice(_)),
414 syn::Type::Slice(_) => true,
415 syn::Type::Array(_) => true,
416_ => false,
417 }
418}
419420/// Extract the inner type `T` from `Missing<T>`, if the type is `Missing<T>`.
421///
422/// Returns `None` if the type is not `Missing<T>` or has no generic argument.
423pub(crate) fn get_missing_inner_type(ty: &syn::Type) -> Option<&syn::Type> {
424let syn::Type::Path(tp) = tyelse {
425return None;
426 };
427let seg = tp.path.segments.last()?;
428if seg.ident != "Missing" {
429return None;
430 }
431let syn::PathArguments::AngleBracketed(args) = &seg.arguments else {
432return None;
433 };
434if let Some(syn::GenericArgument::Type(inner)) = args.args.first() {
435Some(inner)
436 } else {
437None438 }
439}
440441/// Validate a parameter's type for `Missing` and `Dots` conflicts.
442///
443/// Returns `Err` if:
444/// - `Missing<Missing<T>>` (nested Missing)
445/// - `Missing<Dots>` or `Missing<&Dots>`
446pub(crate) fn validate_param_type(ty: &syn::Type, span: proc_macro2::Span) -> syn::Result<()> {
447if crate::return_wrap::contains_marker(ty) {
448return Err(syn::Error::new_spanned(
449ty,
450"class return markers are return-position only",
451 ));
452 }
453if let Some(err) = crate::type_inspect::visibility_marker_error(ty, "argument") {
454return Err(err);
455 }
456if let Some(inner) = get_missing_inner_type(ty) {
457if is_missing_type(inner) {
458return Err(syn::Error::new(
459span,
460"Missing<T> cannot be nested; use Missing<T> with the inner type directly",
461 ));
462 }
463if crate::type_inspect::is_lazy_dots_marker(inner) {
464return Err(syn::Error::new(
465span,
466"`Missing<LazyDots>` is not a parameter type: the dots are always present \
467 (`len()` is 0 when the call passes none); take `LazyDots`",
468 ));
469 }
470if is_dots_type(inner) {
471return Err(syn::Error::new(
472span,
473"Missing<T> cannot wrap Dots; variadic parameters (...) are always present when called",
474 ));
475 }
476 }
477Ok(())
478}
479480/// Validate per-parameter attribute conflicts.
481///
482/// Returns `Err` if:
483/// - `coerce` + `match_arg` on the same parameter
484/// - `coerce` + `choices(...)` on the same parameter
485/// - `choices(...)` + explicit `default` on the same parameter
486/// - `match_arg` + `choices(...)` on the same parameter (two sources for one
487/// choice list; the `match_arg` placeholder would shadow the literal list
488/// and, with no `MatchArg` entry to resolve it, dangle in the R formals)
489/// - `no_default` on a parameter that is neither `match_arg` nor `choices`,
490/// or together with `default` (#1828)
491/// - `default` or `formal` on a `&Dots` parameter
492///
493/// The type-dependent checks of a choice parameter live in
494/// [`classify_choice_param`], shared with the method paths.
495pub(crate) fn validate_per_param_attr_conflicts(
496 attr: &PerParamMiniextendrAttr,
497 param_name: &str,
498 is_dots: bool,
499 ty: &syn::Type,
500 span: proc_macro2::Span,
501) -> syn::Result<()> {
502if attr.has_convert {
503 validate_convert_param(
504 ty,
505 attr.has_coerce || attr.has_match_arg || attr.choices.is_some(),
506 )?;
507 }
508if attr.has_no_default
509 && let Some(msg) = no_default_conflict(
510param_name,
511attr.has_match_arg || attr.choices.is_some(),
512attr.default_value.is_some(),
513false,
514 )
515 {
516return Err(syn::Error::new(span, msg));
517 }
518if attr.has_coerce && attr.has_match_arg {
519return Err(syn::Error::new(
520span,
521::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot combine coerce and match_arg on parameter `{0}`; coerce converts the R type while match_arg validates string values",
param_name))
})format!(
522"cannot combine coerce and match_arg on parameter `{}`; \
523 coerce converts the R type while match_arg validates string values",
524 param_name
525 ),
526 ));
527 }
528if attr.has_coerce && attr.choices.is_some() {
529return Err(syn::Error::new(
530span,
531::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot combine coerce and choices on parameter `{0}`; coerce converts the R type while choices validates string values",
param_name))
})format!(
532"cannot combine coerce and choices on parameter `{}`; \
533 coerce converts the R type while choices validates string values",
534 param_name
535 ),
536 ));
537 }
538if attr.choices.is_some() && attr.default_value.is_some() {
539return Err(syn::Error::new(
540span,
541::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot combine choices() and default on parameter `{0}`; choices auto-generates its default from the first choice value",
param_name))
})format!(
542"cannot combine choices() and default on parameter `{}`; \
543 choices auto-generates its default from the first choice value",
544 param_name
545 ),
546 ));
547 }
548if attr.has_match_arg && attr.choices.is_some() {
549return Err(syn::Error::new(
550span,
551::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot combine match_arg and choices() on parameter `{0}`; match_arg takes the choice list from the parameter type\'s `MatchArg` impl, choices() supplies a literal list for a string parameter; use one of them",
param_name))
})format!(
552"cannot combine match_arg and choices() on parameter `{}`; \
553 match_arg takes the choice list from the parameter type's `MatchArg` impl, \
554 choices() supplies a literal list for a string parameter; use one of them",
555 param_name
556 ),
557 ));
558 }
559if attr.has_several_ok && attr.choices.is_none() && !attr.has_match_arg {
560return Err(syn::Error::new(
561span,
562::alloc::__export::must_use({
::alloc::fmt::format(format_args!("several_ok requires choices() or match_arg on parameter `{0}`; several_ok enables multi-value match.arg which needs a choice list",
param_name))
})format!(
563"several_ok requires choices() or match_arg on parameter `{}`; \
564 several_ok enables multi-value match.arg which needs a choice list",
565 param_name
566 ),
567 ));
568 }
569if is_dots && !attr.checks.is_empty() {
570return Err(syn::Error::new(
571span,
572::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`inherits` / `not_inherits` / `no_na` cannot apply to the variadic (...) parameter `{0}`; use `dots = typed_list!(...)` to check the entries",
param_name))
})format!(
573"`inherits` / `not_inherits` / `no_na` cannot apply to the variadic (...) \
574 parameter `{}`; use `dots = typed_list!(...)` to check the entries",
575 param_name
576 ),
577 ));
578 }
579for check in [ClassCheck::Inherits, ClassCheck::NotInherits] {
580if let Some(classes) = check.classes(&attr.checks)
581 && (classes.is_empty() || classes.iter().any(String::is_empty))
582 {
583let key = check.keyword();
584return Err(syn::Error::new(
585 span,
586::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` on parameter `{1}` needs one or more non-empty class names, e.g. `{0} = \"pkg_obj\"` or `{0}(\"pkg_a\", \"pkg_b\")`",
key, param_name))
})format!(
587"`{key}` on parameter `{param_name}` needs one or more non-empty class \
588 names, e.g. `{key} = \"pkg_obj\"` or `{key}(\"pkg_a\", \"pkg_b\")`"
589),
590 ));
591 }
592 }
593if let Some(msg) = attr.checks.class_conflict(param_name) {
594return Err(syn::Error::new(span, msg));
595 }
596if is_dots && attr.default_value.is_some() {
597return Err(syn::Error::new(
598span,
599::alloc::__export::must_use({
::alloc::fmt::format(format_args!("variadic (...) parameter `{0}` cannot have a default value",
param_name))
})format!(
600"variadic (...) parameter `{}` cannot have a default value",
601 param_name
602 ),
603 ));
604 }
605if is_dots && let Some(formal) = &attr.formal {
606return Err(dots_formal_error(formal, param_name));
607 }
608Ok(())
609}
610611/// The error of a `no_default` that cannot apply (#1828), or `None`: on a
612/// parameter that is neither `match_arg` nor `choices` (only a choice
613/// parameter gets a generated default to drop), or together with a default.
614/// `method_list` picks the spellings named: the method-level
615/// `no_default(p)` / `defaults(p = ...)`, else the parameter's own
616/// `no_default` / `default = "..."`.
617pub(crate) fn no_default_conflict(
618 param: &str,
619 is_choice: bool,
620 has_default: bool,
621 method_list: bool,
622) -> Option<String> {
623let (no_default, default) = if method_list {
624 (
625::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`no_default({0})`", param))
})format!("`no_default({param})`"),
626::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`defaults({0} = ...)`", param))
})format!("`defaults({param} = ...)`"),
627 )
628 } else {
629 (
630"`no_default`".to_string(),
631"`default = \"...\"`".to_string(),
632 )
633 };
634if !is_choice {
635return Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} on parameter `{1}`, which is neither `match_arg` nor `choices`; only a choice parameter gets a generated default to drop, and any other parameter without a default already has a bare formal",
no_default, param))
})format!(
636"{no_default} on parameter `{param}`, which is neither `match_arg` nor `choices`; \
637 only a choice parameter gets a generated default to drop, and any other \
638 parameter without a default already has a bare formal"
639));
640 }
641if has_default {
642return Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot combine {0} and {1} on parameter `{2}`; `no_default` leaves the R formal without a default, so drop one of them",
no_default, default, param))
})format!(
643"cannot combine {no_default} and {default} on parameter `{param}`; \
644 `no_default` leaves the R formal without a default, so drop one of them"
645));
646 }
647None648}
649650/// The error of a `formal` on the dots parameter (#1842), at the literal.
651pub(crate) fn dots_formal_error(formal: &syn::LitStr, param_name: &str) -> syn::Error {
652 syn::Error::new(
653formal.span(),
654::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`formal` on the variadic (...) parameter `{0}`: its R formal is always `...`. Declare a named parameter for an argument with a dotted name",
param_name))
})format!(
655"`formal` on the variadic (...) parameter `{param_name}`: its R formal is always \
656 `...`. Declare a named parameter for an argument with a dotted name"
657),
658 )
659}
660661// endregion
662663// region: Per-parameter attribute parsing
664665/// The error of a `formal(...)` on a trait method (#1842), declared or
666/// implemented. A trait method's R formals are its declaration's parameter
667/// names, shared by every implementing type and the trait ABI's metadata;
668/// declared formals cover standalone functions and inherent impl methods.
669pub(crate) const TRAIT_FORMAL_UNSUPPORTED: &str = "`formal(...)` is not supported on trait \
670 methods: a trait method's R formals are the trait declaration's parameter names, which \
671 every implementing type shares. Declare the dotted name on a standalone function or an \
672 inherent impl method instead";
673674/// The error of a `formal` whose value is no string literal (#1842).
675const FORMAL_NOT_STRING: &str =
676"`formal` takes the R argument name as a string, e.g. `formal = \"conf.int\"`";
677678/// The error of a second `formal` on one parameter (#1842).
679const FORMAL_TWICE: &str = "`formal` is given twice on this parameter; a parameter has one R \
680 formal, so keep one of them";
681682/// Parsed per-parameter `#[miniextendr(...)]` attribute content.
683///
684/// A single attribute can contain multiple items, e.g.
685/// `#[miniextendr(match_arg, default = "Safe")]`; a parameter carrying
686/// several attributes gets them merged ([`PerParamMiniextendrAttr::merge`]).
687#[derive(#[automatically_derived]impl ::core::default::Default for
PerParamMiniextendrAttr {
#[inline]
fn default() -> Self {
PerParamMiniextendrAttr {
has_coerce: ::core::default::Default::default(),
has_convert: ::core::default::Default::default(),
has_match_arg: ::core::default::Default::default(),
default_value: ::core::default::Default::default(),
choices: ::core::default::Default::default(),
has_several_ok: ::core::default::Default::default(),
has_no_default: ::core::default::Default::default(),
checks: ::core::default::Default::default(),
preconditions: ::core::default::Default::default(),
formal: ::core::default::Default::default(),
}
}
}Default)]
688pub(crate) struct PerParamMiniextendrAttr {
689/// Whether `coerce` was present, enabling automatic type coercion for this parameter
690 /// (e.g., `i32` to `u16`, `f64` to `f32`).
691pub has_coerce: bool,
692/// Use the reference type's conversion instead of borrowing an ExternalPtr.
693pub has_convert: bool,
694/// Whether `match_arg` was present, generating R `match.arg()` validation for
695 /// string parameters against a set of allowed values.
696pub has_match_arg: bool,
697/// Default value from `default = "..."`, if present. The tuple contains the default
698 /// value string and the attribute span (for error reporting).
699pub default_value: Option<(String, proc_macro2::Span)>,
700/// Choices for string parameters: `#[miniextendr(choices("a", "b", "c"))]`.
701pub choices: Option<Vec<String>>,
702/// Whether `several_ok` was present, enabling multi-value `match.arg(several.ok = TRUE)`.
703 /// Only valid with `choices(...)` or `match_arg`.
704pub has_several_ok: bool,
705/// Whether `no_default` was present: the choice parameter's R formal has
706 /// no default (#1828). Only valid with `choices(...)` or `match_arg`, and
707 /// not together with `default`.
708pub has_no_default: bool,
709/// `inherits = "cls"` / `inherits("a", "b")`, `not_inherits` (the same
710 /// spellings) and `no_na`, each with an optional `message = "..."`: R-side
711 /// checks named by the author (see
712 /// [`crate::r_preconditions::ExplicitChecks`]).
713pub checks: crate::r_preconditions::ExplicitChecks,
714/// `preconditions` / `no_preconditions` on the parameter (#1566):
715 /// `Some(true)` keeps its type-derived R-side checks, `Some(false)` drops
716 /// them. The last one written wins.
717pub preconditions: Option<bool>,
718/// `formal = "conf.int"`: the parameter's R formal (#1842), checked by
719 /// [`crate::r_wrapper_builder::check_r_formals`].
720pub formal: Option<syn::LitStr>,
721}
722723impl PerParamMiniextendrAttr {
724/// Merge the options of another attribute on the same parameter: flags
725 /// add up, the first `default` / `choices(...)` wins, the last
726 /// `preconditions` / `no_preconditions` wins, and the checks merge (one
727 /// `message` per check; the error says which). A second `formal` is an
728 /// error.
729pub(crate) fn merge(&mut self, other: PerParamMiniextendrAttr) -> Result<(), String> {
730if let Some(formal) = other.formal {
731if self.formal.is_some() {
732return Err(FORMAL_TWICE.to_string());
733 }
734self.formal = Some(formal);
735 }
736if other.preconditions.is_some() {
737self.preconditions = other.preconditions;
738 }
739self.has_coerce |= other.has_coerce;
740self.has_convert |= other.has_convert;
741self.has_match_arg |= other.has_match_arg;
742self.has_several_ok |= other.has_several_ok;
743self.has_no_default |= other.has_no_default;
744if self.default_value.is_none() {
745self.default_value = other.default_value;
746 }
747if self.choices.is_none() {
748self.choices = other.choices;
749 }
750self.checks.merge(other.checks)
751 }
752}
753754/// Parse all per-parameter options from a `#[miniextendr(...)]` attribute.
755///
756/// Handles mixed content like `#[miniextendr(match_arg, default = "\"Safe\"")]`
757/// and `#[miniextendr(choices("a", "b", "c"))]`.
758///
759/// Returns `Ok(None)` if `attr` is not a `#[miniextendr(...)]` attribute, if its
760/// content is not a list of options, or if it contains only function-level
761/// options (like `strict`) with no per-parameter options. A malformed
762/// `inherits(...)` / `not_inherits(...)` / `no_na(...)` is an error, as is
763/// `preconditions = bool` / `no_preconditions = bool`, a function-level form
764/// the parameter spells bare, and a `formal` that is not a string or is given
765/// twice.
766///
767/// # Arguments
768///
769/// * `attr` - A `syn::Attribute` to inspect. Only attributes with path `miniextendr`
770/// are considered.
771pub(crate) fn parse_per_param_attr(
772 attr: &syn::Attribute,
773) -> syn::Result<Option<PerParamMiniextendrAttr>> {
774use syn::spanned::Spanned;
775if !attr.path().is_ident("miniextendr") {
776return Ok(None);
777 }
778779let syn::Meta::List(meta_list) = &attr.meta else {
780return Ok(None);
781 };
782783let mut result = PerParamMiniextendrAttr::default();
784let mut is_per_param = false;
785786let Ok(metas) = meta_list.parse_args_with(
787 syn::punctuated::Punctuated::<syn::Meta, ::syn::token::Commasyn::Token![,]>::parse_terminated,
788 ) else {
789return Ok(None);
790 };
791792for meta in &metas {
793match meta {
794 syn::Meta::Path(path) => {
795if path.is_ident("coerce") {
796 result.has_coerce = true;
797 is_per_param = true;
798 } else if path.is_ident("convert") {
799 result.has_convert = true;
800 is_per_param = true;
801 } else if path.is_ident("match_arg") {
802 result.has_match_arg = true;
803 is_per_param = true;
804 } else if path.is_ident("several_ok") {
805 result.has_several_ok = true;
806 is_per_param = true;
807 } else if path.is_ident("no_default") {
808 result.has_no_default = true;
809 is_per_param = true;
810 } else if path.is_ident("no_na") {
811 result.checks.no_na = true;
812 is_per_param = true;
813 } else if path.is_ident("preconditions") {
814 result.preconditions = Some(true);
815 is_per_param = true;
816 } else if path.is_ident("no_preconditions") {
817 result.preconditions = Some(false);
818 is_per_param = true;
819 }
820// Other paths (like `strict`) are function-level, ignore here
821}
822 syn::Meta::NameValue(nv) => {
823if nv.path.is_ident("default")
824 && let syn::Expr::Lit(syn::ExprLit {
825 lit: syn::Lit::Str(lit_str),
826 ..
827 }) = &nv.value
828 {
829 result.default_value = Some((lit_str.value(), attr.span()));
830 is_per_param = true;
831 } else if nv.path.is_ident("formal") {
832// formal = "conf.int" (#1842): the parameter's R formal.
833let syn::Expr::Lit(syn::ExprLit {
834 lit: syn::Lit::Str(lit_str),
835 ..
836 }) = &nv.value
837else {
838return Err(syn::Error::new_spanned(&nv.value, FORMAL_NOT_STRING));
839 };
840if result.formal.replace(lit_str.clone()).is_some() {
841return Err(syn::Error::new_spanned(nv, FORMAL_TWICE));
842 }
843 is_per_param = true;
844 } else if let Some(check) = ClassCheck::of(&nv.path)
845 && let syn::Expr::Lit(syn::ExprLit {
846 lit: syn::Lit::Str(lit_str),
847 ..
848 }) = &nv.value
849 {
850 check
851 .classes_mut(&mut result.checks)
852 .get_or_insert_with(Vec::new)
853 .push(lit_str.value());
854 is_per_param = true;
855 } else if let Some(key) = ["preconditions", "no_preconditions"]
856 .into_iter()
857 .find(|key| nv.path.is_ident(key))
858 {
859return Err(syn::Error::new_spanned(
860 nv,
861::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0} = ...` on a parameter: write the bare `preconditions` or `no_preconditions` (or the `Checked<T>` / `Unchecked<T>` marker); the `= true | false` form is the function attribute\'s",
key))
})format!(
862"`{key} = ...` on a parameter: write the bare `preconditions` or \
863 `no_preconditions` (or the `Checked<T>` / `Unchecked<T>` marker); \
864 the `= true | false` form is the function attribute's"
865),
866 ));
867 }
868// Other name-value pairs are function-level, ignore here
869}
870 syn::Meta::List(list) => {
871if list.path.is_ident("choices") {
872// Parse choices("a", "b", "c") — a comma-separated list of string literals
873let choice_lits = match list.parse_args_with(
874 syn::punctuated::Punctuated::<syn::LitStr, ::syn::token::Commasyn::Token![,]>::parse_terminated,
875 ) {
876Ok(lits) => lits,
877Err(_) => continue,
878 };
879let choices: Vec<String> = choice_lits.iter().map(|l| l.value()).collect();
880 result.choices = Some(choices);
881 is_per_param = true;
882 } else if let Some(check) = ClassCheck::of(&list.path) {
883// inherits("a", "b"[, message = "..."]) / inherits(class = "a", ...),
884 // and the same for not_inherits.
885let checks = parse_class_check_list(list, check)?;
886 result
887 .checks
888 .merge(checks)
889 .map_err(|msg| syn::Error::new_spanned(list, msg))?;
890 is_per_param = true;
891 } else if list.path.is_ident("no_na") {
892// no_na(message = "...")
893let checks = parse_no_na_list(list)?;
894 result
895 .checks
896 .merge(checks)
897 .map_err(|msg| syn::Error::new_spanned(list, msg))?;
898 is_per_param = true;
899 }
900// Other list forms are function-level, ignore here
901}
902 }
903 }
904905if !is_per_param {
906return Ok(None);
907 }
908Ok(Some(result))
909}
910911/// The two class checks a parameter can name: `inherits` (the argument must
912/// inherit from one of the classes) and `not_inherits` (from none of them,
913/// #1815). Both take the same spellings at parameter and method level; this
914/// says which one a spelling is, and words its errors.
915#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for ClassCheck {
}
#[automatically_derived]impl ::core::clone::Clone for ClassCheck {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ClassCheck { }Copy, #[automatically_derived]impl ::core::fmt::Debug for ClassCheck {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ClassCheck::Inherits => "Inherits",
ClassCheck::NotInherits => "NotInherits",
})
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
ClassCheck {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ClassCheck {
#[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 ClassCheck { }Eq)]
916pub(crate) enum ClassCheck {
917 Inherits,
918 NotInherits,
919}
920921impl ClassCheck {
922/// The check `path` names, if it is `inherits` or `not_inherits`.
923pub(crate) fn of(path: &syn::Path) -> Option<Self> {
924if path.is_ident("inherits") {
925Some(Self::Inherits)
926 } else if path.is_ident("not_inherits") {
927Some(Self::NotInherits)
928 } else {
929None930 }
931 }
932933/// The attribute keyword, for error messages.
934fn keyword(self) -> &'static str {
935match self {
936Self::Inherits => "inherits",
937Self::NotInherits => "not_inherits",
938 }
939 }
940941/// The `when(...)` hints in this check's list of options, for errors:
942 /// only `inherits` takes them.
943fn hints_option(self) -> &'static str {
944match self {
945Self::Inherits => ", `when(...)` hints",
946Self::NotInherits => "",
947 }
948 }
949950/// The error for an unknown option `key` in a parameter-level
951 /// `inherits(...)` / `not_inherits(...)`.
952fn unknown_option(self, key: &syn::Ident) -> String {
953::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unknown `{0}` option `{2}`; expected class names (`\"cls\"` or `class = \"cls\"`){1} and an optional `message = \"...\"`",
self.keyword(), self.hints_option(), key))
})format!(
954"unknown `{}` option `{key}`; expected class names \
955 (`\"cls\"` or `class = \"cls\"`){} and an optional `message = \"...\"`",
956self.keyword(),
957self.hints_option()
958 )959 }
960961/// The error for an unknown option in a method-level
962 /// `inherits(p(...))` / `not_inherits(p(...))`.
963fn unknown_method_option(self) -> String {
964::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unknown `{0}` option; expected `class = \"...\"`{1} and an optional `message = \"...\"`",
self.keyword(), self.hints_option()))
})format!(
965"unknown `{}` option; expected `class = \"...\"`{} and an optional \
966 `message = \"...\"`",
967self.keyword(),
968self.hints_option()
969 )970 }
971972/// This check's classes in `checks`, if it is requested.
973fn classes(self, checks: &crate::r_preconditions::ExplicitChecks) -> Option<&[String]> {
974match self {
975Self::Inherits => checks.inherits.as_deref(),
976Self::NotInherits => checks.not_inherits.as_deref(),
977 }
978 }
979980/// This check's classes in `checks`, to add to.
981fn classes_mut(
982self,
983 checks: &mut crate::r_preconditions::ExplicitChecks,
984 ) -> &mut Option<Vec<String>> {
985match self {
986Self::Inherits => &mut checks.inherits,
987Self::NotInherits => &mut checks.not_inherits,
988 }
989 }
990991/// The checks holding this check with `classes` and `message`.
992fn checks(
993self,
994 classes: Vec<String>,
995 message: Option<String>,
996 ) -> crate::r_preconditions::ExplicitChecks {
997let mut checks = crate::r_preconditions::ExplicitChecks::default();
998*self.classes_mut(&mut checks) = Some(classes);
999match self {
1000Self::Inherits => checks.inherits_message = message,
1001Self::NotInherits => checks.not_inherits_message = message,
1002 }
1003checks1004 }
1005}
10061007/// `inherits(...)` / `not_inherits(...)` on a parameter (`check` says
1008/// which): each string literal, and each `class = "..."`, names one class
1009/// (the argument must inherit from one of them, or from none of them);
1010/// `message = "..."` gives the condition message of a failure, for all of
1011/// them. No string is split on commas, as with `inherits = "cls"` (the
1012/// method-level `class = "a, b"` is split, see [`parse_method_class_check`]).
1013///
1014/// `inherits(...)` also takes `when(...)` hints (#1824), each with its
1015/// classes spelled the same way and a required `message = "..."`
1016/// ([`parse_when_list`]).
1017fn parse_class_check_list(
1018 list: &syn::MetaList,
1019 check: ClassCheck,
1020) -> syn::Result<crate::r_preconditions::ExplicitChecks> {
1021use syn::parse::Parseras _;
1022let key_word = check.keyword();
1023let mut classes = Vec::new();
1024let mut message = None;
1025let mut hints = Vec::new();
1026let parser = |input: syn::parse::ParseStream| -> syn::Result<()> {
1027while !input.is_empty() {
1028if input.peek(syn::LitStr) {
1029let class: syn::LitStr = input.parse()?;
1030 classes.push(class.value());
1031 } else {
1032let key: syn::Ident = input.parse()?;
1033if key == "when" && input.peek(syn::token::Paren) {
1034if check != ClassCheck::Inherits {
1035return Err(syn::Error::new_spanned(&key, WHEN_ON_NOT_INHERITS));
1036 }
1037let content;
1038match ::syn::__private::parse_parens(&input) {
::syn::__private::Ok(parens) => {
content = parens.content;
_ = content;
parens.token
}
::syn::__private::Err(error) => { return ::syn::__private::Err(error); }
};syn::parenthesized!(content in input);
1039 hints.push(parse_when_list(&key, &content)?);
1040 } else {
1041 input.parse::<::syn::token::Eqsyn::Token![=]>()?;
1042let value: syn::LitStr = input.parse()?;
1043if key == "class" {
1044 classes.push(value.value());
1045 } else if key == "message" {
1046 set_check_message(&mut message, &value, key_word)?;
1047 } else {
1048return Err(syn::Error::new_spanned(&key, check.unknown_option(&key)));
1049 }
1050 }
1051 }
1052if input.is_empty() {
1053break;
1054 }
1055 input.parse::<::syn::token::Commasyn::Token![,]>()?;
1056 }
1057Ok(())
1058 };
1059 parser.parse2(list.tokens.clone())?;
1060if message.is_some() && classes.is_empty() {
1061return Err(syn::Error::new_spanned(
1062list,
1063::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`message` in `{0}(...)` needs a class to check, e.g. `{0}(class = \"pkg_obj\", message = \"...\")`",
key_word))
})format!(
1064"`message` in `{key_word}(...)` needs a class to check, \
1065 e.g. `{key_word}(class = \"pkg_obj\", message = \"...\")`"
1066),
1067 ));
1068 }
1069if !hints.is_empty() && classes.is_empty() {
1070return Err(syn::Error::new_spanned(
1071list,
1072"`when(...)` in `inherits(...)` needs a class to check, e.g. \
1073 `inherits(class = \"pkg_obj\", when(class = \"data.frame\", message = \"...\"))`",
1074 ));
1075 }
1076let mut checks = check.checks(classes, message);
1077checks.inherits_hints = hints;
1078Ok(checks)
1079}
10801081/// The error for `when(...)` in `not_inherits(...)`.
1082const WHEN_ON_NOT_INHERITS: &str = "`when(...)` is an `inherits` option: it gives a value that \
1083 fails `inherits` a message for its class; `not_inherits` has one `message` for every \
1084 class it refuses";
10851086/// The content of a parameter-level `when(...)` hint in `inherits(...)`
1087/// (`key` is the `when` keyword, for error spans): its classes, spelled as in
1088/// `inherits(...)` (each string literal and each `class = "..."` names one
1089/// class, none split on commas), and its required `message = "..."`.
1090fn parse_when_list(
1091 key: &syn::Ident,
1092 content: syn::parse::ParseStream,
1093) -> syn::Result<crate::r_preconditions::InheritsHint> {
1094let mut classes = Vec::new();
1095let mut message = None;
1096while !content.is_empty() {
1097if content.peek(syn::LitStr) {
1098let class: syn::LitStr = content.parse()?;
1099 classes.push(hint_class(&class)?);
1100 } else {
1101let opt: syn::Ident = content.parse()?;
1102 content.parse::<::syn::token::Eqsyn::Token![=]>()?;
1103let value: syn::LitStr = content.parse()?;
1104if opt == "class" {
1105 classes.push(hint_class(&value)?);
1106 } else if opt == "message" {
1107 set_hint_message(&mut message, &value)?;
1108 } else {
1109return Err(syn::Error::new_spanned(
1110&opt,
1111::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unknown `when` option `{0}`; expected class names (`\"cls\"` or `class = \"cls\"`) and `message = \"...\"`",
opt))
})format!(
1112"unknown `when` option `{opt}`; expected class names (`\"cls\"` or \
1113 `class = \"cls\"`) and `message = \"...\"`"
1114),
1115 ));
1116 }
1117 }
1118if content.is_empty() {
1119break;
1120 }
1121 content.parse::<::syn::token::Commasyn::Token![,]>()?;
1122 }
1123inherits_hint(classes, message).map_err(|msg| syn::Error::new_spanned(key, msg))
1124}
11251126/// One class name of a parameter-level `when(...)` hint: not empty.
1127fn hint_class(value: &syn::LitStr) -> syn::Result<String> {
1128let class = value.value();
1129if class.is_empty() {
1130return Err(syn::Error::new(
1131value.span(),
1132"a class name in `when(...)` must not be empty",
1133 ));
1134 }
1135Ok(class)
1136}
11371138/// A parsed `when(...)` hint, which needs both its classes and its message.
1139fn inherits_hint(
1140 classes: Vec<String>,
1141 message: Option<String>,
1142) -> Result<crate::r_preconditions::InheritsHint, &'static str> {
1143if classes.is_empty() {
1144return Err("`when(...)` needs the classes it is for, e.g. \
1145 `when(class = \"data.frame\", message = \"...\")`");
1146 }
1147let Some(message) = messageelse {
1148return Err(
1149"`when(...)` needs a `message = \"...\"`: the hint a value of its classes gets, \
1150 e.g. `when(class = \"data.frame\", message = \"...\")`",
1151 );
1152 };
1153Ok(crate::r_preconditions::InheritsHint { classes, message })
1154}
11551156/// `no_na(message = "...")` on a parameter: `no_na` with the condition
1157/// message of a failure.
1158fn parse_no_na_list(list: &syn::MetaList) -> syn::Result<crate::r_preconditions::ExplicitChecks> {
1159let mut message = None;
1160 list.parse_nested_meta(|opt| parse_no_na_option(&opt, &mut message))?;
1161Ok(crate::r_preconditions::ExplicitChecks {
1162 no_na: true,
1163 no_na_message: message,
1164 ..Default::default()
1165 })
1166}
11671168/// One option inside `no_na(...)` (parameter level) or `no_na(p(...))`
1169/// (method level): only `message = "..."`.
1170fn parse_no_na_option(
1171 opt: &syn::meta::ParseNestedMeta,
1172 message: &mut Option<String>,
1173) -> syn::Result<()> {
1174if opt.path.is_ident("message") {
1175let value: syn::LitStr = opt.value()?.parse()?;
1176set_check_message(message, &value, "no_na")
1177 } else {
1178Err(opt.error("unknown `no_na` option; expected `message = \"...\"`"))
1179 }
1180}
11811182/// Record the `message = "..."` of an `inherits` / `not_inherits` / `no_na`
1183/// check: the condition message of a failure, used verbatim. It is given
1184/// once, is not empty, and holds no NUL (an R string cannot).
1185fn set_check_message(
1186 slot: &mut Option<String>,
1187 value: &syn::LitStr,
1188 check: &str,
1189) -> syn::Result<()> {
1190set_message(
1191slot,
1192value,
1193check,
1194"leave it out to get the generated message",
1195 )
1196}
11971198/// Record the `message = "..."` of a `when(...)` hint in `inherits(...)`,
1199/// under the rules of [`set_check_message`]; unlike a check's message, the
1200/// hint's is required.
1201fn set_hint_message(slot: &mut Option<String>, value: &syn::LitStr) -> syn::Result<()> {
1202set_message(
1203slot,
1204value,
1205"when",
1206"it is the message a value of those classes gets",
1207 )
1208}
12091210/// Record `value` as the message in `slot` of `check(...)`; `if_empty`
1211/// ends the error for an empty message.
1212fn set_message(
1213 slot: &mut Option<String>,
1214 value: &syn::LitStr,
1215 check: &str,
1216 if_empty: &str,
1217) -> syn::Result<()> {
1218let text = value.value();
1219if slot.is_some() {
1220return Err(syn::Error::new(
1221value.span(),
1222::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`message` is given more than once in `{0}(...)`",
check))
})format!("`message` is given more than once in `{check}(...)`"),
1223 ));
1224 }
1225if text.trim().is_empty() {
1226return Err(syn::Error::new(
1227value.span(),
1228::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`message` in `{0}(...)` must not be empty; {1}",
check, if_empty))
})format!("`message` in `{check}(...)` must not be empty; {if_empty}"),
1229 ));
1230 }
1231if text.contains('\0') {
1232return Err(syn::Error::new(
1233value.span(),
1234"`message` must not contain a NUL character: an R string cannot hold one",
1235 ));
1236 }
1237*slot = Some(text);
1238Ok(())
1239}
12401241/// The parameter an entry of a method-level `match_arg(...)` / `choices(...)`
1242/// / `no_na(...)` / `inherits(...)` / `not_inherits(...)` names, spelled as
1243/// the signature's [`crate::naming::ident_name`] (`r#type` names `type`), so
1244/// [`finalize_method_param_attrs`] finds it.
1245pub(crate) fn method_check_param(entry: &syn::meta::ParseNestedMeta) -> syn::Result<String> {
1246Ok(crate::naming::ident_name(
1247 entry
1248 .path
1249 .get_ident()
1250 .ok_or_else(|| entry.error("expected parameter name"))?,
1251 ))
1252}
12531254/// Method-level `no_na(p, q(message = "..."))` on an impl or trait method,
1255/// whose parameters cannot carry attributes: each entry names a parameter,
1256/// optionally with the condition message of its NA check. Shared by the
1257/// inherent-impl and trait-impl method parsers.
1258pub(crate) fn parse_method_no_na(
1259 meta: &syn::meta::ParseNestedMeta,
1260 per_param: &mut std::collections::HashMap<String, ParamAttrs>,
1261) -> syn::Result<()> {
1262meta.parse_nested_meta(|entry| {
1263let name = method_check_param(&entry)?;
1264let mut message = None;
1265if entry.input.peek(syn::token::Paren) {
1266 entry.parse_nested_meta(|opt| parse_no_na_option(&opt, &mut message))?;
1267 }
1268let checks = crate::r_preconditions::ExplicitChecks {
1269 no_na: true,
1270 no_na_message: message,
1271 ..Default::default()
1272 };
1273per_param1274 .entry(name)
1275 .or_default()
1276 .checks
1277 .merge(checks)
1278 .map_err(|msg| entry.error(msg))
1279 })
1280}
12811282/// Method-level `inherits(p = "a, b", q(class = "a, b", message = "..."))` /
1283/// `not_inherits(...)` (the same shape, `check` says which) on an impl or
1284/// trait method: each entry names a parameter and the classes it must
1285/// inherit from (one of) or must not inherit from (any of), optionally with
1286/// the condition message of the class check. A nested value cannot be a bare
1287/// list of literals, so the classes are one comma-separated string, as in
1288/// `choices(p = "a, b")`. `inherits(q(class = "a", when(class = "b, c",
1289/// message = "...")))` adds a hint (#1824; [`parse_method_when`]). Shared by
1290/// the inherent-impl and trait-impl method parsers.
1291pub(crate) fn parse_method_class_check(
1292 meta: &syn::meta::ParseNestedMeta,
1293 per_param: &mut std::collections::HashMap<String, ParamAttrs>,
1294 check: ClassCheck,
1295) -> syn::Result<()> {
1296let key_word = check.keyword();
1297meta.parse_nested_meta(|entry| {
1298let name = method_check_param(&entry)?;
1299let mut classes = Vec::new();
1300let mut message = None;
1301let mut hints = Vec::new();
1302if entry.input.peek(::syn::token::Eqsyn::Token![=]) {
1303let value: syn::LitStr = entry.value()?.parse()?;
1304classes = method_class_list(&value, check)?;
1305 } else if entry.input.peek(syn::token::Paren) {
1306 entry.parse_nested_meta(|opt| {
1307if opt.path.is_ident("class") {
1308let value: syn::LitStr = opt.value()?.parse()?;
1309 classes.extend(method_class_list(&value, check)?);
1310Ok(())
1311 } else if opt.path.is_ident("message") {
1312let value: syn::LitStr = opt.value()?.parse()?;
1313 set_check_message(&mut message, &value, key_word)
1314 } else if opt.path.is_ident("when") {
1315if check != ClassCheck::Inherits {
1316return Err(opt.error(WHEN_ON_NOT_INHERITS));
1317 }
1318 hints.push(parse_method_when(&opt)?);
1319Ok(())
1320 } else {
1321Err(opt.error(check.unknown_method_option()))
1322 }
1323 })?;
1324if classes.is_empty() {
1325return Err(entry.error(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}({1}(...))` needs `class = \"...\"`, e.g. `{0}({1}(class = \"pkg_obj\", message = \"...\"))`",
key_word, name))
})format!(
1326"`{key_word}({name}(...))` needs `class = \"...\"`, \
1327 e.g. `{key_word}({name}(class = \"pkg_obj\", message = \"...\"))`"
1328)));
1329 }
1330 } else {
1331return Err(entry.error(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0} = \"cls\"` or `{0}(class = \"cls\", message = \"...\")`",
name))
})format!(
1332"expected `{name} = \"cls\"` or `{name}(class = \"cls\", message = \"...\")`"
1333)));
1334 }
1335let mut checks = check.checks(classes, message);
1336checks.inherits_hints = hints;
1337per_param1338 .entry(name)
1339 .or_default()
1340 .checks
1341 .merge(checks)
1342 .map_err(|msg| entry.error(msg))
1343 })
1344}
13451346/// A method-level `when(class = "a, b", message = "...")` hint in
1347/// `inherits(p(...))`: its classes are one comma-separated string, as the
1348/// entry's own `class`, and its message is required.
1349fn parse_method_when(
1350 opt: &syn::meta::ParseNestedMeta,
1351) -> syn::Result<crate::r_preconditions::InheritsHint> {
1352let mut classes = Vec::new();
1353let mut message = None;
1354 opt.parse_nested_meta(|hint| {
1355if hint.path.is_ident("class") {
1356let value: syn::LitStr = hint.value()?.parse()?;
1357let names = crate::r_wrapper_builder::split_choice_list(&value.value());
1358if names.is_empty() {
1359return Err(syn::Error::new(
1360 value.span(),
1361"`when(class = \"...\")` needs one or more class names",
1362 ));
1363 }
1364 classes.extend(names);
1365Ok(())
1366 } else if hint.path.is_ident("message") {
1367let value: syn::LitStr = hint.value()?.parse()?;
1368 set_hint_message(&mut message, &value)
1369 } else {
1370Err(hint
1371 .error("unknown `when` option; expected `class = \"...\"` and `message = \"...\"`"))
1372 }
1373 })?;
1374inherits_hint(classes, message).map_err(|msg| opt.error(msg))
1375}
13761377/// Method-level `no_default(p, q)` on an impl or trait method, whose
1378/// parameters cannot carry attributes: each entry names a `match_arg` /
1379/// `choices` parameter whose R formal has no default (#1828). Shared by the
1380/// inherent-impl and trait-impl method parsers; [`finalize_method_param_attrs`]
1381/// refuses a name that is no parameter, no choice or has a default.
1382pub(crate) fn parse_method_no_default(
1383 meta: &syn::meta::ParseNestedMeta,
1384 per_param: &mut std::collections::HashMap<String, ParamAttrs>,
1385) -> syn::Result<()> {
1386meta.parse_nested_meta(|entry| {
1387let name = method_check_param(&entry)?;
1388per_param.entry(name).or_default().no_default = true;
1389Ok(())
1390 })
1391}
13921393/// Parse a method-level `formal(conf_int = "conf.int", ...)` (#1842): the R
1394/// formal of each named parameter, the method form of a standalone function's
1395/// per-parameter `formal = ".."`. Shared by the inherent-impl parser only:
1396/// trait methods take their formals from the trait declaration, and the
1397/// trait parsers refuse it. A parameter named twice is an error;
1398/// [`finalize_method_param_attrs`] refuses a name that is no parameter, and
1399/// [`crate::r_wrapper_builder::check_r_formals`] checks each formal.
1400pub(crate) fn parse_method_formal(
1401 meta: &syn::meta::ParseNestedMeta,
1402 per_param: &mut std::collections::HashMap<String, ParamAttrs>,
1403) -> syn::Result<()> {
1404meta.parse_nested_meta(|entry| {
1405let name = method_check_param(&entry)?;
1406let value = entry.value()?;
1407let value: syn::LitStr = value
1408 .parse()
1409 .map_err(|e| syn::Error::new(e.span(), FORMAL_NOT_STRING))?;
1410let attrs = per_param.entry(name).or_default();
1411if attrs.formal.replace(value).is_some() {
1412return Err(entry.error(FORMAL_TWICE));
1413 }
1414Ok(())
1415 })
1416}
14171418/// The classes of a method-level `inherits` / `not_inherits` entry: a
1419/// comma-separated, non-empty list.
1420fn method_class_list(value: &syn::LitStr, check: ClassCheck) -> syn::Result<Vec<String>> {
1421let classes = crate::r_wrapper_builder::split_choice_list(&value.value());
1422if classes.is_empty() {
1423return Err(syn::Error::new(
1424value.span(),
1425::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}(param = \"...\")` needs one or more class names",
check.keyword()))
})format!(
1426"`{}(param = \"...\")` needs one or more class names",
1427 check.keyword()
1428 ),
1429 ));
1430 }
1431Ok(classes)
1432}
1433// endregion
14341435// region: per-parameter preconditions (#1566 §2)
14361437/// Method-level `preconditions(p, q)` / `no_preconditions(p)` on an impl or
1438/// trait method, whose parameters cannot carry attributes: each entry names a
1439/// parameter that keeps (`keep`) or drops its type-derived R-side checks.
1440/// Naming one parameter twice follows the pair rule: the last one written
1441/// wins. Shared by the inherent-impl and trait-impl method parsers; the bare
1442/// `preconditions` / `no_preconditions` (the whole method) is theirs to read.
1443pub(crate) fn parse_method_preconditions(
1444 meta: &syn::meta::ParseNestedMeta,
1445 per_param: &mut std::collections::HashMap<String, ParamAttrs>,
1446 keep: bool,
1447) -> syn::Result<()> {
1448meta.parse_nested_meta(|entry| {
1449let name = method_check_param(&entry)?;
1450per_param.entry(name).or_default().preconditions = Some(keep);
1451Ok(())
1452 })
1453}
14541455/// The keyword spelling of a rank-1 precondition decision, for messages:
1456/// the per-parameter attribute on a function parameter, the method-level
1457/// list on a method.
1458fn preconditions_keyword(keep: bool, param: &str, method_list: bool) -> String {
1459let key = if keep {
1460"preconditions"
1461} else {
1462"no_preconditions"
1463};
1464if method_list {
1465::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}({1})`", key, param))
})format!("`{key}({param})`")1466 } else {
1467::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`#[miniextendr({0})]`", key))
})format!("`#[miniextendr({key})]`")1468 }
1469}
14701471/// Combine a parameter's `Checked<T>` / `Unchecked<T>` marker with its
1472/// keyword decision (`keyword`: the per-parameter `preconditions` /
1473/// `no_preconditions`, or the method's `preconditions(p)` /
1474/// `no_preconditions(p)`). A marker is a type, not one more flag of the pair,
1475/// so a marker and a keyword that disagree are an error, as a `Call` marker
1476/// and `call = ...` are; agreeing ones are one decision. The error points at
1477/// `ty`, the parameter's type as written.
1478pub(crate) fn merge_param_policy(
1479 markers: &[crate::type_inspect::ParamMarker],
1480 keyword: Option<bool>,
1481 param: &str,
1482 method_list: bool,
1483 ty: &syn::Type,
1484) -> syn::Result<Option<bool>> {
1485let marker = crate::type_inspect::marker_in_family(
1486markers,
1487crate::type_inspect::ParamMarkerFamily::Preconditions,
1488 );
1489let Some(marker) = markerelse {
1490return Ok(keyword);
1491 };
1492let from_marker = marker.preconditions();
1493if let Some(keep) = keyword1494 && Some(keep) != from_marker1495 {
1496let (marker_does, keyword_does) = if keep {
1497 ("drops", "keeps")
1498 } else {
1499 ("keeps", "drops")
1500 };
1501return Err(syn::Error::new_spanned(
1502ty,
1503::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the `{0}` parameter `{2}` {3} the R-side type checks but {1} {4} them; keep one of them (or make them agree)",
marker.name(),
preconditions_keyword(keep, param, method_list), param,
marker_does, keyword_does))
})format!(
1504"the `{}` parameter `{param}` {marker_does} the R-side type checks but {} \
1505 {keyword_does} them; keep one of them (or make them agree)",
1506 marker.name(),
1507 preconditions_keyword(keep, param, method_list),
1508 ),
1509 ));
1510 }
1511Ok(from_marker)
1512}
15131514/// Reject a parameter's rank-1 precondition decision where it has nothing to
1515/// act on: a `match_arg` / `choices` parameter (validated by `match.arg()`,
1516/// never by type checks) and a type without type-derived checks (`SEXP`,
1517/// `Missing<T>`, `ExternalPtr<T>`, `&Dots`, a type the check table does not
1518/// know). `ty` is the parameter's type with the markers peeled, which the
1519/// errors point at; `markers` are the ones it carried. A no-op when the
1520/// parameter decides nothing itself.
1521pub(crate) fn check_param_preconditions(
1522 attrs: &ParamAttrs,
1523 markers: &[crate::type_inspect::ParamMarker],
1524 param: &str,
1525 ty: &syn::Type,
1526 method_list: bool,
1527) -> syn::Result<()> {
1528let Some(keep) = attrs.preconditions else {
1529return Ok(());
1530 };
1531let marker = crate::type_inspect::marker_in_family(
1532markers,
1533crate::type_inspect::ParamMarkerFamily::Preconditions,
1534 );
1535let spelling = match marker {
1536Some(m) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}<{1}>`", m.name(),
crate::type_inspect::type_display(ty)))
})format!("`{}<{}>`", m.name(), crate::type_inspect::type_display(ty)),
1537None => preconditions_keyword(keep, param, method_list),
1538 };
1539if attrs.is_choice() {
1540return Err(syn::Error::new_spanned(
1541ty,
1542::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} on parameter `{1}`: a match_arg/choices parameter is validated by `match.arg()`, not by type checks; `Checked` / `Unchecked` and `preconditions` / `no_preconditions` do not apply to it",
spelling, param))
})format!(
1543"{spelling} on parameter `{param}`: a match_arg/choices parameter is validated by \
1544 `match.arg()`, not by type checks; `Checked` / `Unchecked` and \
1545 `preconditions` / `no_preconditions` do not apply to it"
1546),
1547 ));
1548 }
1549if !crate::r_preconditions::has_type_check(ty) {
1550return Err(syn::Error::new_spanned(
1551ty,
1552::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1} on parameter `{2}`: `{0}` has no R-side type check to keep or drop",
crate::type_inspect::type_display(ty), spelling, param))
})format!(
1553"{spelling} on parameter `{param}`: `{}` has no R-side type check to keep or drop",
1554crate::type_inspect::type_display(ty)
1555 ),
1556 ));
1557 }
1558Ok(())
1559}
15601561/// `inputs` with each marked parameter's type replaced by the type under its
1562/// markers (`markers`, keyed by Rust name): what every R-side consumer and
1563/// the conversion see. The item re-emitted for the user keeps the markers.
1564pub(crate) fn peeled_inputs(
1565 inputs: &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
1566 markers: &[(String, Vec<crate::type_inspect::ParamMarker>)],
1567) -> syn::Result<syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>> {
1568let mut peeled = inputs.clone();
1569for arg in peeled.iter_mut() {
1570let syn::FnArg::Typed(pt) = arg else {
1571continue;
1572 };
1573let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
1574continue;
1575 };
1576let name = crate::naming::ident_name(&pat_ident.ident);
1577if markers.iter().any(|(n, _)| *n == name) {
1578let (_, inner) = crate::type_inspect::peel_param_markers(pt.ty.as_ref())?;
1579*pt.ty = inner.clone();
1580 }
1581 }
1582Ok(peeled)
1583}
15841585/// The markers of every parameter of `inputs` that carries one, keyed by
1586/// Rust name, in signature order. Nested or stacked markers are an error
1587/// (see [`crate::type_inspect::peel_param_markers`]).
1588pub(crate) fn collect_param_markers(
1589 inputs: &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
1590) -> syn::Result<Vec<(String, Vec<crate::type_inspect::ParamMarker>)>> {
1591let mut out = Vec::new();
1592for arg in inputs {
1593let syn::FnArg::Typed(pt) = arg else {
1594continue;
1595 };
1596let (markers, _) = crate::type_inspect::peel_param_markers(pt.ty.as_ref())?;
1597if markers.is_empty() {
1598continue;
1599 }
1600let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
1601continue;
1602 };
1603 out.push((crate::naming::ident_name(&pat_ident.ident), markers));
1604 }
1605Ok(out)
1606}
1607// endregion
16081609// region: Function parsing
16101611/// Parsed + normalized Rust function item for `#[miniextendr]`.
1612///
1613/// This performs signature normalization that the wrapper generator depends on:
1614/// - `...` → a final `&miniextendr_api::dots::Dots` argument
1615/// - `_` wildcard patterns → synthetic identifiers (`__unused0`, `__unused1`, ...)
1616/// - Destructuring patterns (tuple, struct) → synthetic identifiers with let-binding in body
1617/// - consumes `#[miniextendr(coerce)]` parameter attributes and records which params had it
1618pub(crate) struct MiniextendrFunctionParsed {
1619/// The normalized function item (with dots transformed, wildcards renamed).
1620 /// Re-emitted for the user, so it keeps the parameter markers.
1621item: syn::ItemFn,
1622/// `item`'s parameters with the parameter markers (`Checked<T>` /
1623 /// `Unchecked<T>`, #1566) peeled: what the R wrapper, the preconditions
1624 /// and the C wrapper's conversions see.
1625 inputs: syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
1626/// The markers peeled off each marked parameter (Rust name), in
1627 /// signature order: the C wrapper wraps the converted value in them.
1628param_markers: Vec<(String, Vec<crate::type_inspect::ParamMarker>)>,
1629/// Rust binding of the `&Dots` parameter (R's `...`), from Rust `...` or
1630 /// an explicit `&Dots` parameter at any position (see
1631 /// [`find_dots_param`]).
1632dots: Option<syn::Ident>,
1633/// All per-parameter `#[miniextendr(...)]` options (coerce, match_arg,
1634 /// default, choices, several_ok), keyed by the (possibly synthesized) Rust
1635 /// parameter name. Replaces five parallel `HashSet` / `HashMap` fields.
1636per_param: std::collections::HashMap<String, ParamAttrs>,
1637}
16381639/// Collapsed per-parameter attribute state for a single function parameter.
1640///
1641/// Built during parsing from `#[miniextendr(coerce | match_arg | several_ok |
1642/// no_default | default = "…" | choices("…"))]` on the argument. Accessors on
1643/// [`MiniextendrFunctionParsed`] query this struct rather than looking
1644/// through multiple side-tables.
1645#[derive(#[automatically_derived]impl ::core::default::Default for ParamAttrs {
#[inline]
fn default() -> Self {
ParamAttrs {
coerce: ::core::default::Default::default(),
convert: ::core::default::Default::default(),
match_arg: ::core::default::Default::default(),
several_ok: ::core::default::Default::default(),
choices: ::core::default::Default::default(),
default: ::core::default::Default::default(),
optional: ::core::default::Default::default(),
omittable: ::core::default::Default::default(),
no_default: ::core::default::Default::default(),
either_noun: ::core::default::Default::default(),
checks: ::core::default::Default::default(),
preconditions: ::core::default::Default::default(),
formal: ::core::default::Default::default(),
}
}
}Default, #[automatically_derived]impl ::core::fmt::Debug for ParamAttrs {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
"ParamAttrs coerce convert match_arg several_ok choices default optional omittable no_default either_noun checks preconditions formal";
let values: &[&dyn ::core::fmt::Debug] =
&[&self.coerce, &self.convert, &self.match_arg, &self.several_ok,
&self.choices, &self.default, &self.optional,
&self.omittable, &self.no_default, &self.either_noun,
&self.checks, &self.preconditions, &&self.formal];
::core::fmt::Formatter::debug_struct_fields_finish(f, names, values)
}
}Debug, #[automatically_derived]impl ::core::clone::Clone for ParamAttrs {
#[inline]
fn clone(&self) -> Self {
ParamAttrs {
coerce: ::core::clone::Clone::clone(&self.coerce),
convert: ::core::clone::Clone::clone(&self.convert),
match_arg: ::core::clone::Clone::clone(&self.match_arg),
several_ok: ::core::clone::Clone::clone(&self.several_ok),
choices: ::core::clone::Clone::clone(&self.choices),
default: ::core::clone::Clone::clone(&self.default),
optional: ::core::clone::Clone::clone(&self.optional),
omittable: ::core::clone::Clone::clone(&self.omittable),
no_default: ::core::clone::Clone::clone(&self.no_default),
either_noun: ::core::clone::Clone::clone(&self.either_noun),
checks: ::core::clone::Clone::clone(&self.checks),
preconditions: ::core::clone::Clone::clone(&self.preconditions),
formal: ::core::clone::Clone::clone(&self.formal),
}
}
}Clone)]
1646pub(crate) struct ParamAttrs {
1647pub coerce: bool,
1648pub convert: bool,
1649pub match_arg: bool,
1650pub several_ok: bool,
1651pub choices: Option<Vec<String>>,
1652pub default: Option<String>,
1653/// `Option<..>` layer of a `match_arg` / `choices` parameter (#1473):
1654 /// `NULL` means no choice, so the prelude skips the check for it and Rust
1655 /// sees `None`. Unless [`Self::omittable`] is set too, the R formal is
1656 /// `NULL` instead of the choice vector. Set from the parameter type by
1657 /// [`classify_choice_param`]; together with `several_ok` only under an
1658 /// `Either` layer (`Option<Either<Vec<T>, R>>`), since a plain
1659 /// `several_ok` list already reads `NULL` as every choice.
1660pub optional: bool,
1661/// `Missing<..>` layer of a `match_arg` / `choices` parameter (#1551): the
1662 /// R formal keeps the choice vector, the prelude skips the check for an
1663 /// omitted argument, and Rust sees `Missing::Absent`; a single choice reads
1664 /// its formal passed whole the same way ([`Self::reads_formal_as_absent`], #2152).
1665 /// Set by [`classify_choice_param`].
1666pub omittable: bool,
1667/// `no_default` on a `match_arg` / `choices` parameter (#1828): the R
1668 /// formal is the bare name instead of the choice vector (or `NULL`), so
1669 /// an omitted argument is `Missing::Absent` under `Missing<..>` and R's
1670 /// missing-argument error otherwise. The prelude and the choice list do
1671 /// not change. Set from the parameter's `no_default` or the method's
1672 /// `no_default(p)`.
1673pub no_default: bool,
1674/// `Either<.., R>` layer of a `match_arg` / `choices` parameter, over a
1675 /// scalar choice (`Either<T, R>`) or a `several_ok` list
1676 /// (`Either<Vec<T>, R>` / `Either<Box<[T]>, R>`): the R-facing name of the
1677 /// `R` arm (`"a data frame"`, see [`crate::type_inspect::r_value_noun`])
1678 /// for the `@param` line. The prelude checks only character or factor
1679 /// input; anything else, `NULL` included, reaches Rust unchanged and
1680 /// decodes as `R`. Set by [`classify_choice_param`].
1681pub either_noun: Option<String>,
1682/// R-side checks named by the author: `inherits` / `not_inherits` /
1683 /// `no_na`.
1684pub checks: crate::r_preconditions::ExplicitChecks,
1685/// This parameter's own decision on its type-derived R-side checks
1686 /// (#1566), rank 1 of [`crate::r_preconditions::resolve_type_checks`]:
1687 /// a `Checked<T>` / `Unchecked<T>` marker, the per-parameter
1688 /// `preconditions` / `no_preconditions`, or a method's
1689 /// `preconditions(x)` / `no_preconditions(x)`. `Some(true)` keeps them;
1690 /// `None` defers to the function, impl and crate defaults.
1691pub preconditions: Option<bool>,
1692/// The declared R formal (#1842): a standalone function's
1693 /// `formal = "conf.int"` or a method's `formal(conf_int = "conf.int")`,
1694 /// with the literal that declared it. Read through
1695 /// [`crate::r_wrapper_builder::Formals`], never directly.
1696pub formal: Option<syn::LitStr>,
1697}
16981699impl ParamAttrs {
1700/// Whether this parameter's options leave its argument unforced, as a
1701 /// `Quoted` / `Quosure` parameter needs (#1835): none but `formal`, which
1702 /// only names it (#1842), and `default` when `default_ok` (a
1703 /// `Missing<Quoted>` / `Missing<Quosure>` parameter, whose default only
1704 /// writes the formal).
1705pub(crate) fn leaves_argument_unforced(&self, default_ok: bool) -> bool {
1706let ParamAttrs {
1707 coerce,
1708 convert,
1709 match_arg,
1710 several_ok,
1711 choices,
1712 default,
1713 optional,
1714 omittable,
1715 no_default,
1716 either_noun,
1717 checks,
1718 preconditions,
1719 formal: _,
1720 } = self;
1721 (default_ok || default.is_none())
1722 && !coerce1723 && !convert1724 && !match_arg1725 && !several_ok1726 && choices.is_none()
1727 && !optional1728 && !omittable1729 && !no_default1730 && either_noun.is_none()
1731 && checks.is_empty()
1732 && preconditions.is_none()
1733 }
17341735/// Whether this is a `match_arg` / `choices` parameter.
1736pub(crate) fn is_choice(&self) -> bool {
1737self.match_arg || self.choices.is_some()
1738 }
17391740/// The R formal default of a choice parameter, given its choice list
1741 /// (`c("a", "b")` or the write-time placeholder): `NULL` for the
1742 /// `Option<T>` form (#1473), the choice list otherwise, including
1743 /// `Missing<Option<T>>`, whose omission is reported by `Missing` (#1551).
1744 /// `None` under `no_default` (#1828): the formal is the bare name. The
1745 /// prelude spells the choice list out either way, so a `match_arg`
1746 /// placeholder then lives in the prelude only.
1747pub(crate) fn choice_formal(&self, choices: &str) -> Option<String> {
1748if self.no_default {
1749None1750 } else if self.optional && !self.omittable {
1751Some("NULL".to_string())
1752 } else {
1753Some(choices.to_string())
1754 }
1755 }
17561757/// Whether a value `identical()` to this parameter's formal reads as
1758 /// omitted (#2152): a single-choice `Missing<..>` parameter, whose formal
1759 /// is its choice list ([`Self::choice_formal`]). Its wrapper compares the
1760 /// argument with that list once, before the check, and keeps the answer
1761 /// in a flag (`.mx_absent_<p>`, #2182; see
1762 /// [`crate::r_wrapper_builder::CallAttribution::match_arg_lines`]). For a
1763 /// flagged value it skips the check and forwards the missing-argument
1764 /// sentinel, so passing the default shown in the usage line reaches Rust
1765 /// as `Missing::Absent`, like leaving it out. `false` for every other
1766 /// parameter: a `several_ok` list reads the whole vector as every choice,
1767 /// a parameter without `Missing` reads it as the first choice, and a
1768 /// `no_default` one has no vector in its formal.
1769pub(crate) fn reads_formal_as_absent(&self) -> bool {
1770self.is_choice() && self.omittable && !self.several_ok && !self.no_default
1771 }
17721773/// The text after the quoted choice list in the auto-generated `@param`
1774 /// line (`One of "a", "b"<suffix>.`): the other accepted values, then an
1775 /// omission note. `, or NULL for no choice` for `Option<T>`,
1776 /// `, or a data frame` for `Either<T, DataFrame>`,
1777 /// `, a data frame, or NULL for no choice` for both,
1778 /// `, or NULL; omitting the argument or passing the whole list means no
1779 /// choice` for `Missing<Option<T>>`, `; omitting the argument or passing
1780 /// the whole list means no choice` for `Missing<T>` (#2152; see
1781 /// [`Self::reads_formal_as_absent`]), and nothing for a plain choice. A
1782 /// `Missing<Vec<T>>` `several_ok` list, whose whole vector selects every
1783 /// choice, says only `; omitting the argument means no choice`. Under
1784 /// `no_default` (#1828) the omission note goes (the author documents what
1785 /// omission means) and the rest stays.
1786pub(crate) fn choice_doc_suffix(&self) -> String {
1787let null_word = if self.omittable {
1788"NULL"
1789} else {
1790"NULL for no choice"
1791};
1792let mut suffix =
1793choice_alternatives_suffix(self.either_noun.as_deref(), self.optional, null_word);
1794if self.omittable && !self.no_default {
1795suffix.push_str(if self.several_ok {
1796"; omitting the argument means no choice"
1797} else {
1798"; omitting the argument or passing the whole list means no choice"
1799});
1800 }
1801suffix1802 }
18031804/// The auto-generated `@param` text of a `choices(...)` parameter:
1805 /// `One of "a", "b"<suffix>.` (`One or more of` for `several_ok`), with
1806 /// [`Self::choice_doc_suffix`]. `None` without a literal choice list; a
1807 /// `match_arg` parameter's text is only known at write time (its
1808 /// placeholder, #210).
1809pub(crate) fn literal_choices_doc(&self) -> Option<String> {
1810let choices = self.choices.as_ref()?;
1811let quoted: Vec<String> = choices.iter().map(|c| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\"{0}\"", c))
})format!("\"{c}\"")).collect();
1812let prefix = if self.several_ok {
1813"One or more of"
1814} else {
1815"One of"
1816};
1817Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{2} {0}{1}.", quoted.join(", "),
self.choice_doc_suffix(), prefix))
})format!(
1818"{prefix} {}{}.",
1819 quoted.join(", "),
1820self.choice_doc_suffix()
1821 ))
1822 }
18231824/// How the C wrapper decodes this parameter when a plain `TryFromSexp`
1825 /// cannot: a `match_arg` parameter with a `Missing` / `Option` / `Either`
1826 /// layer (`MatchArgSeveral` for a `several_ok` list, `Either<Vec<T>, R>`
1827 /// included), or a `choices` parameter with an `Either` layer (its string
1828 /// type or `several_ok` string list on the left). `None` for every other
1829 /// parameter (a `choices` string type converts through `TryFromSexp` with
1830 /// its `Missing` / `Option` layers; a plain `several_ok` container has its
1831 /// own path).
1832pub(crate) fn layered_leaf(&self) -> Option<crate::rust_conversion_builder::ChoiceLeaf> {
1833use crate::rust_conversion_builder::ChoiceLeaf;
1834let either = self.either_noun.is_some();
1835if self.match_arg && (self.optional || self.omittable || either) {
1836return Some(if self.several_ok {
1837 ChoiceLeaf::MatchArgSeveral1838 } else {
1839 ChoiceLeaf::MatchArg1840 });
1841 }
1842let choices = self.choices.as_ref().filter(|_| either)?;
1843Some(ChoiceLeaf::Literal {
1844 choices: choices.clone(),
1845 several: self.several_ok,
1846 })
1847 }
1848}
18491850/// The other values a choice parameter accepts, after its quoted choices:
1851/// `, or a data frame` for an `Either<.., R>` layer (`noun`, the `R` arm),
1852/// `, or <null_word>` for an `Option<..>` layer (`optional`), `, a data frame,
1853/// or <null_word>` for both, nothing for neither. Shared by the parameter's
1854/// `@param` line ([`ParamAttrs::choice_doc_suffix`], which passes
1855/// `NULL for no choice`) and the argument error of an `Either` choice
1856/// parameter (which passes `NULL`), so the two word the alternatives alike.
1857pub(crate) fn choice_alternatives_suffix(
1858 noun: Option<&str>,
1859 optional: bool,
1860 null_word: &str,
1861) -> String {
1862match (noun, optional) {
1863 (None, false) => String::new(),
1864 (Some(only), false) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", or {0}", only))
})format!(", or {only}"),
1865 (None, true) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", or {0}", null_word))
})format!(", or {null_word}"),
1866 (Some(noun), true) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}, or {1}", noun, null_word))
})format!(", {noun}, or {null_word}"),
1867 }
1868}
18691870/// Record the layers of a `match_arg` / `choices` parameter's type on its
1871/// [`ParamAttrs`] (`optional`, `omittable`, `either_noun`) and reject the
1872/// shapes the codegen cannot serve, now that the type is known. Shared by the
1873/// standalone-fn parser and [`finalize_method_param_attrs`] so the two cannot
1874/// classify a type differently. A no-op for other parameters.
1875///
1876/// Accepted, outermost layer first: an optional `Missing<..>` (#1551), an
1877/// optional `Option<..>` (#1473), an optional `Either<.., R>`, then the
1878/// scalar choice type (so `T`, `Option<T>`, `Missing<Option<T>>`,
1879/// `Either<T, R>`, `Option<Either<T, R>>`, ...). A `several_ok` parameter
1880/// takes any container (`Vec<T>`, `Box<[T]>`, `&[T]`, `[T; N]`) bare, and
1881/// only the owned `Vec<T>` / `Box<[T]>` under a layer: `Missing<Vec<T>>`,
1882/// `Either<Vec<T>, R>` (#1612) and the `Missing` / `Option` stacks over that
1883/// `Either`, which follow the scalar `Either` rule. A bare
1884/// `Option<Vec<T>>` stays rejected: its `NULL` already means every choice,
1885/// while under `Either` it goes to `R`. `has_default` says whether the
1886/// parameter carries a `default`, which a choice with a `NULL` formal
1887/// (`Option<..>` without `Missing`) cannot, nor one under `Missing<..>`
1888/// ([`missing_choice_default_msg`]).
1889pub(crate) fn classify_choice_param(
1890 attrs: &mut ParamAttrs,
1891 param_name: &str,
1892 ty: &syn::Type,
1893 has_default: bool,
1894) -> syn::Result<()> {
1895use syn::spanned::Spanned;
1896if !attrs.is_choice() {
1897return Ok(());
1898 }
1899let layers = crate::type_inspect::choice_layers(ty);
1900if let Some(layer) = crate::type_inspect::choice_layer_name(layers.value) {
1901return Err(syn::Error::new(
1902ty.span(),
1903::alloc::__export::must_use({
::alloc::fmt::format(format_args!("match_arg/choices parameter `{0}` has `{1}<..>` in an unsupported position; the wrappers go outermost first as `Missing<Option<Either<T, R>>>` (each one optional, the choice type `T` on the left of `Either`)",
param_name, layer))
})format!(
1904"match_arg/choices parameter `{param_name}` has `{layer}<..>` in an unsupported \
1905 position; the wrappers go outermost first as `Missing<Option<Either<T, R>>>` \
1906 (each one optional, the choice type `T` on the left of `Either`)"
1907),
1908 ));
1909 }
1910if attrs.several_ok {
1911let either = layers.either_right.is_some();
1912// Under `Either`, `NULL` goes to the `R` arm, so `Option<Either<Vec<T>, R>>`
1913 // has a `None` of its own; a bare `Option<Vec<T>>` does not.
1914if let Some(spelling) = layers.nullable
1915 && !either1916 {
1917return Err(syn::Error::new(
1918ty.span(),
1919::alloc::__export::must_use({
::alloc::fmt::format(format_args!("several_ok parameter `{1}` cannot be `{0}<..>`; an omitted argument and NULL both select every choice. Use `Missing<Vec<T>>` to tell an omitted argument apart",
spelling.name(), param_name))
})format!(
1920"several_ok parameter `{param_name}` cannot be `{}<..>`; an omitted \
1921 argument and NULL both select every choice. Use `Missing<Vec<T>>` to \
1922 tell an omitted argument apart",
1923 spelling.name()
1924 ),
1925 ));
1926 }
1927if !is_vector_like_type(layers.value) {
1928// Under `Missing` / `Either` only the owned containers decode.
1929let containers = if layers.missing || either {
1930"`Vec<T>` or `Box<[T]>`"
1931} else {
1932"`Vec<T>`, `Box<[T]>`, `&[T]`, or `[T; N]`"
1933};
1934return Err(syn::Error::new(
1935ty.span(),
1936::alloc::__export::must_use({
::alloc::fmt::format(format_args!("several_ok requires a vector type on parameter `{0}`; several_ok enables multi-value match.arg which returns a character vector. Use {1} instead of a scalar type",
param_name, containers))
})format!(
1937"several_ok requires a vector type on parameter `{param_name}`; \
1938 several_ok enables multi-value match.arg which returns a character vector. \
1939 Use {containers} instead of a scalar type"
1940),
1941 ));
1942 }
1943let owned = #[allow(non_exhaustive_omitted_patterns)] match crate::classify_several_ok_container(layers.value)
{
Some((crate::SeveralOkContainer::Vec |
crate::SeveralOkContainer::BoxedSlice, _)) => true,
_ => false,
}matches!(
1944crate::classify_several_ok_container(layers.value),
1945Some((
1946crate::SeveralOkContainer::Vec | crate::SeveralOkContainer::BoxedSlice,
1947_
1948))
1949 );
1950if either && !owned {
1951return Err(syn::Error::new(
1952ty.span(),
1953::alloc::__export::must_use({
::alloc::fmt::format(format_args!("several_ok parameter `{0}` can take another kind of value only as `Either<Vec<T>, R>` or `Either<Box<[T]>, R>`",
param_name))
})format!(
1954"several_ok parameter `{param_name}` can take another kind of value only \
1955 as `Either<Vec<T>, R>` or `Either<Box<[T]>, R>`"
1956),
1957 ));
1958 }
1959if layers.missing && !owned {
1960return Err(syn::Error::new(
1961ty.span(),
1962::alloc::__export::must_use({
::alloc::fmt::format(format_args!("several_ok parameter `{0}` can be omittable only as `Missing<Vec<T>>` or `Missing<Box<[T]>>`",
param_name))
})format!(
1963"several_ok parameter `{param_name}` can be omittable only as \
1964 `Missing<Vec<T>>` or `Missing<Box<[T]>>`"
1965),
1966 ));
1967 }
1968 }
1969// A `NULL` formal (`Option<..>` without `Missing`) makes a `default`
1970 // meaningless, for a scalar choice and for `Option<Either<Vec<T>, R>>`.
1971if let Some(spelling) = layers.nullable
1972 && !layers.missing
1973 && has_default1974 {
1975return Err(syn::Error::new(
1976ty.span(),
1977optional_choice_default_msg(param_name, spelling.name()),
1978 ));
1979 }
1980if layers.missing && has_default {
1981return Err(syn::Error::new(
1982ty.span(),
1983missing_choice_default_msg(param_name),
1984 ));
1985 }
1986attrs.optional = layers.nullable.is_some();
1987attrs.omittable = layers.missing;
1988attrs.either_noun = layers.either_right.map(crate::type_inspect::r_value_noun);
1989Ok(())
1990}
19911992/// The entries of `per_param` in the order their parameters appear in
1993/// `inputs`. Code that emits one line or item per parameter walks this, never
1994/// the map itself: a `HashMap`'s order differs between maps and between
1995/// compiler runs, so the generated R wrapper (and the Rust items) would too.
1996pub(crate) fn per_param_in_signature_order<'a>(
1997 inputs: &'a syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
1998 per_param: &'a std::collections::HashMap<String, ParamAttrs>,
1999) -> impl Iterator<Item = (&'a String, &'a ParamAttrs)> {
2000inputs.iter().filter_map(|arg| {
2001let syn::FnArg::Typed(pt) = argelse {
2002return None;
2003 };
2004let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
2005return None;
2006 };
2007per_param.get_key_value(&crate::naming::ident_name(&pat_ident.ident))
2008 })
2009}
20102011/// The non-empty [`ParamAttrs::checks`] of `per_param` (keyed by Rust name),
2012/// re-keyed by R formal ([`crate::r_wrapper_builder::Formals::of`]) for
2013/// [`crate::r_preconditions::PreconditionOptions::explicit`].
2014pub(crate) fn explicit_checks_by_r_name(
2015 per_param: &std::collections::HashMap<String, ParamAttrs>,
2016) -> std::collections::HashMap<String, crate::r_preconditions::ExplicitChecks> {
2017let formals = crate::r_wrapper_builder::Formals::from_param_attrs(per_param);
2018per_param2019 .iter()
2020 .filter(|(_, a)| !a.checks.is_empty())
2021 .map(|(name, a)| (formals.of(name), a.checks.clone()))
2022 .collect()
2023}
20242025/// The generated `@param` text of an undocumented `Missing<..>` parameter
2026/// with a formal default (#2161): the default only shows in the usage line,
2027/// and an omitted argument still reaches Rust as `Missing::Absent`.
2028pub(crate) const MISSING_DEFAULT_PARAM_DOC: &str =
2029"Omitting the argument means the function's own handling.";
20302031/// R formal → [`MISSING_DEFAULT_PARAM_DOC`] for each `Missing<..>` parameter
2032/// of `inputs` that has a formal default in `defaults` (keyed by Rust name,
2033/// as the per-parameter options are) and is no choice parameter of
2034/// `per_param`, whose own line names the choices. The key is the formal
2035/// `formals` gives the parameter, a declared `formal` included (#1842).
2036/// `Missing<Quoted>` / `Missing<Quosure>` count too: their default is never
2037/// evaluated either.
2038pub(crate) fn missing_default_param_docs(
2039 inputs: &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
2040 per_param: &std::collections::HashMap<String, ParamAttrs>,
2041 defaults: &std::collections::HashMap<String, String>,
2042 formals: &crate::r_wrapper_builder::Formals,
2043) -> std::collections::HashMap<String, String> {
2044inputs2045 .iter()
2046 .filter_map(|arg| {
2047let syn::FnArg::Typed(pt) = argelse {
2048return None;
2049 };
2050let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
2051return None;
2052 };
2053let rust_name = crate::naming::ident_name(&pat_ident.ident);
2054if !is_missing_type(pt.ty.as_ref())
2055 || per_param.get(&rust_name).is_some_and(ParamAttrs::is_choice)
2056 {
2057return None;
2058 }
2059defaults.contains_key(&rust_name).then(|| {
2060 (
2061formals.of(&rust_name),
2062MISSING_DEFAULT_PARAM_DOC.to_string(),
2063 )
2064 })
2065 })
2066 .collect()
2067}
20682069/// The R formals of the parameters of `per_param` (keyed by Rust name) whose
2070/// wrapper reads a value `identical()` to the formal as omitted
2071/// ([`ParamAttrs::reads_formal_as_absent`], #2152). For
2072/// [`crate::r_wrapper_builder::RArgumentBuilder::with_absent_formals`].
2073pub(crate) fn absent_formals_by_r_name(
2074 per_param: &std::collections::HashMap<String, ParamAttrs>,
2075) -> std::collections::HashSet<String> {
2076let formals = crate::r_wrapper_builder::Formals::from_param_attrs(per_param);
2077per_param2078 .iter()
2079 .filter(|(_, a)| a.reads_formal_as_absent())
2080 .map(|(name, _)| formals.of(name))
2081 .collect()
2082}
20832084/// Parse the method-level spelling of a parameter's `convert` option.
2085pub(crate) fn parse_method_convert(
2086 meta: &syn::meta::ParseNestedMeta<'_>,
2087 per_param: &mut std::collections::HashMap<String, ParamAttrs>,
2088) -> syn::Result<()> {
2089meta.parse_nested_meta(|inner| {
2090let name = method_check_param(&inner)?;
2091per_param.entry(name).or_default().convert = true;
2092Ok(())
2093 })
2094}
20952096/// An explicit conversion applies to references, optionally wrapped in Option.
2097/// Receivers and `Self` parameters retain the trait ABI's external-owner protocol.
2098fn validate_convert_param(ty: &syn::Type, conflicting: bool) -> syn::Result<()> {
2099let reference = crate::externalptr_args::conversion_reference(ty).ok_or_else(|| {
2100 syn::Error::new_spanned(
2101 ty,
2102"`convert` requires `&T`, `&mut T`, or an Option of either",
2103 )
2104 })?;
2105if is_dots_type(crate::type_inspect::option_inner_type(ty).unwrap_or(ty))
2106 || #[allow(non_exhaustive_omitted_patterns)] match reference.elem.as_ref() {
syn::Type::Path(p) if p.path.is_ident("Self") => true,
_ => false,
}matches!(reference.elem.as_ref(), syn::Type::Path(p) if p.path.is_ident("Self"))2107 {
2108return Err(syn::Error::new_spanned(
2109ty,
2110"`convert` cannot override Self or dots arguments",
2111 ));
2112 }
2113if let Some(lifetime) = crate::type_inspect::static_lifetime(ty) {
2114return Err(syn::Error::new_spanned(
2115lifetime,
2116"`convert` borrows only for the call; remove the `'static` lifetime",
2117 ));
2118 }
2119if conflicting {
2120return Err(syn::Error::new_spanned(
2121ty,
2122"`convert` cannot be combined with coerce, match_arg, or choices on the same parameter",
2123 ));
2124 }
2125Ok(())
2126}
21272128/// Check an impl or trait method's per-parameter attributes against its
2129/// signature, now that it is known. Every parameter a method-level
2130/// `match_arg(...)` / `choices(...)` / `no_default(...)` / `inherits(...)` /
2131/// `not_inherits(...)` / `no_na(...)` / `preconditions(...)` /
2132/// `no_preconditions(...)` / `formal(...)` names must exist (a typo would
2133/// otherwise drop the option without a word); then a `formal` is refused on
2134/// the `&Dots` parameter, whose formal is `...`, a `no_default(p)` on a parameter
2135/// that is no choice or has a default ([`no_default_conflict`]), the
2136/// choice parameters are classified (see [`classify_choice_param`]), a class
2137/// in both `inherits` and `not_inherits` is refused
2138/// ([`crate::r_preconditions::ExplicitChecks::class_conflict`]), and each
2139/// parameter's own precondition decision is checked
2140/// ([`check_param_preconditions`]). The standalone-fn path does the same
2141/// while parsing; this is the twin for method-level attributes, whose
2142/// parameter names arrive before the types. The inherent-impl and trait-impl
2143/// parsers both call it, so they reject an unknown name the same way.
2144/// `inputs` has the parameter markers peeled; `markers` are the ones peeled
2145/// (empty on a trait impl, whose signature is the trait's). `span` is where
2146/// the errors point: the first such attribute, else the method name.
2147pub(crate) fn finalize_method_param_attrs(
2148 per_param: &mut std::collections::HashMap<String, ParamAttrs>,
2149 inputs: &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
2150 markers: &[(String, Vec<crate::type_inspect::ParamMarker>)],
2151 defaults: &std::collections::HashMap<String, String>,
2152 span: proc_macro2::Span,
2153) -> syn::Result<()> {
2154let sig_names: std::collections::HashSet<String> = inputs2155 .iter()
2156 .filter_map(|arg| match arg {
2157 syn::FnArg::Typed(pt) => match pt.pat.as_ref() {
2158 syn::Pat::Ident(pat_ident) => Some(crate::naming::ident_name(&pat_ident.ident)),
2159_ => None,
2160 },
2161 syn::FnArg::Receiver(_) => None,
2162 })
2163 .collect();
2164let mut unknown: Vec<&String> = per_param2165 .iter()
2166 .filter(|(name, a)| {
2167 (a.convert
2168 || a.match_arg
2169 || a.choices.is_some()
2170 || a.no_default
2171 || !a.checks.is_empty()
2172 || a.preconditions.is_some())
2173 && !sig_names.contains(name.as_str())
2174 })
2175 .map(|(name, _)| name)
2176 .collect();
2177unknown.sort();
2178if let Some(first) = unknown.first() {
2179if per_param[*first].convert {
2180return Err(syn::Error::new(
2181span,
2182::alloc::__export::must_use({
::alloc::fmt::format(format_args!("convert references non-existent parameter `{0}`",
first))
})format!("convert references non-existent parameter `{first}`"),
2183 ));
2184 }
2185return Err(syn::Error::new(
2186span,
2187::alloc::__export::must_use({
::alloc::fmt::format(format_args!("match_arg/choices/no_default/inherits/not_inherits/no_na/(no_)preconditions references non-existent parameter `{0}`",
first))
})format!(
2188"match_arg/choices/no_default/inherits/not_inherits/no_na/(no_)preconditions \
2189 references non-existent parameter `{first}`"
2190),
2191 ));
2192 }
2193let mut unknown_formals: Vec<(&String, &syn::LitStr)> = per_param2194 .iter()
2195 .filter(|(name, _)| !sig_names.contains(name.as_str()))
2196 .filter_map(|(name, a)| Some((name, a.formal.as_ref()?)))
2197 .collect();
2198unknown_formals.sort_by_key(|(name, _)| *name);
2199if let Some((name, formal)) = unknown_formals.first() {
2200return Err(syn::Error::new(
2201formal.span(),
2202::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`formal({1} = {0:?})` names a parameter this method doesn\'t have: there is no `{1}`",
formal.value(), name))
})format!(
2203"`formal({name} = {:?})` names a parameter this method doesn't have: there is \
2204 no `{name}`",
2205 formal.value()
2206 ),
2207 ));
2208 }
2209// An `NArgs` parameter (#1860) takes no option: the method-level forms
2210 // name it like any parameter, and the wrapper, which never makes it a
2211 // formal, would silently drop them.
2212check_nargs_params(inputs, |name| {
2213 per_param.contains_key(name) || defaults.contains_key(name)
2214 })?;
2215// Nor does a `LazyDots` parameter (#1892), R's `...` passed unforced.
2216check_lazy_dots_params(inputs, |name| {
2217 per_param.contains_key(name) || defaults.contains_key(name)
2218 })?;
2219for arg in inputs {
2220let syn::FnArg::Typed(pt) = arg else {
2221continue;
2222 };
2223let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
2224continue;
2225 };
2226let name = crate::naming::ident_name(&pat_ident.ident);
2227let Some(attrs) = per_param.get_mut(&name) else {
2228continue;
2229 };
2230if let Some(formal) = &attrs.formal
2231 && is_dots_type(pt.ty.as_ref())
2232 {
2233return Err(dots_formal_error(formal, &name));
2234 }
2235if attrs.convert {
2236 validate_convert_param(&pt.ty, attrs.coerce || attrs.is_choice())?;
2237 }
2238let has_default = attrs.default.is_some() || defaults.contains_key(&name);
2239if attrs.no_default
2240 && let Some(msg) = no_default_conflict(&name, attrs.is_choice(), has_default, true)
2241 {
2242return Err(syn::Error::new(span, msg));
2243 }
2244 classify_choice_param(attrs, &name, pt.ty.as_ref(), has_default)?;
2245if let Some(msg) = attrs.checks.class_conflict(&name) {
2246return Err(syn::Error::new(span, msg));
2247 }
2248let param_markers = markers
2249 .iter()
2250 .find(|(n, _)| *n == name)
2251 .map_or(&[][..], |(_, m)| m.as_slice());
2252 check_param_preconditions(attrs, param_markers, &name, pt.ty.as_ref(), true)?;
2253 }
2254Ok(())
2255}
22562257/// A `default` on a choice parameter under `Missing<..>` (#2161). An omitted
2258/// argument reaches Rust as `Missing::Absent`, so the default would pick no
2259/// choice; on a `choices(...)` list it would also replace the formal, the
2260/// choice vector that [`ParamAttrs::reads_formal_as_absent`] compares a supplied value
2261/// with (#2152).
2262fn missing_choice_default_msg(param_name: &str) -> String {
2263::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`Missing<..>` parameter `{0}` with match_arg/choices cannot have a default; an omitted argument reaches Rust as `Missing::Absent`, so a default picks no choice, and the formal already shows the choices. Drop the `Missing` to make a choice the default, or drop the default",
param_name))
})format!(
2264"`Missing<..>` parameter `{param_name}` with match_arg/choices cannot have a default; \
2265 an omitted argument reaches Rust as `Missing::Absent`, so a default picks no choice, \
2266 and the formal already shows the choices. Drop the `Missing` to make a choice the \
2267 default, or drop the default"
2268)2269}
22702271/// The refusal of a `default` on a choice parameter under `Option<..>` (or
2272/// `Nullable<..>`, `layer`) without `Missing`.
2273fn optional_choice_default_msg(param_name: &str, layer: &str) -> String {
2274::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}<T>` parameter `{1}` with match_arg/choices cannot have a default; its R formal defaults to NULL, which means no choice. Drop the `{0}` to make a choice the default, or drop the default",
layer, param_name))
})format!(
2275"`{layer}<T>` parameter `{param_name}` with match_arg/choices cannot have a default; \
2276 its R formal defaults to NULL, which means no choice. Drop the `{layer}` to make a \
2277 choice the default, or drop the default"
2278)2279}
22802281/// Parses a Rust `fn` item from a token stream, performing all normalizations
2282/// required by the `#[miniextendr]` codegen pipeline.
2283///
2284/// # Normalizations performed
2285///
2286/// 1. **Variadic (`...`) rewriting**: Replaces Rust variadic syntax with a typed
2287/// `&miniextendr_api::dots::Dots` parameter. Named dots (`my_dots: ...`) preserve
2288/// the user's identifier; `_: ...` becomes `__miniextendr_dots`.
2289/// 2. **Wildcard pattern renaming**: `_` parameter patterns become `__unused0`,
2290/// `__unused1`, etc., so they can be passed by name to the C wrapper.
2291/// 3. **Destructuring expansion**: Tuple/struct destructuring patterns are replaced
2292/// with synthetic identifiers (`__param_0`, ...) and a `let` binding is prepended
2293/// to the function body.
2294/// 4. **Per-parameter attribute consumption**: `#[miniextendr(coerce)]`,
2295/// `#[miniextendr(match_arg)]`, `#[miniextendr(default = "...")]`, and
2296/// `#[miniextendr(choices(...))]` are consumed from parameters and recorded in
2297/// the corresponding `per_param_*` fields.
2298/// 5. **Validation**: Rejects `#[export_name]` on non-extern functions, rejects
2299/// unsupported parameter patterns, and validates that defaults reference existing
2300/// parameter names.
2301impl syn::parse::Parsefor MiniextendrFunctionParsed {
2302fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
2303use syn::spanned::Spanned;
23042305let mut item: syn::ItemFn = input.parse()?;
23062307// dots support: replace `...` with `&Dots` (the dots parameter itself
2308 // is found by type once wildcard patterns have their names).
2309rewrite_variadic_dots(&mut item.sig)?;
23102311// Reject #[export_name] for regular functions (not extern "C-unwind").
2312 // For extern functions, #[export_name] can be used as an alternative to #[no_mangle].
2313let is_extern = item.sig.abi.is_some();
2314if !is_extern {
2315 require_safe_wrapper(&item.sig, "drop `#[miniextendr]`")?;
2316for attr in &item.attrs {
2317if attr.path().is_ident("export_name") {
2318return Err(syn::Error::new_spanned(
2319 attr,
2320"#[export_name] is not supported with #[miniextendr] on regular functions; \
2321 use `#[miniextendr(c_symbol = \"...\")]` to customize the C symbol name. \
2322 For extern \"C-unwind\" functions, #[export_name] is allowed.",
2323 ));
2324 }
2325 }
2326 }
23272328// Transform `_` wildcard patterns to synthetic identifiers, and consume
2329 // per-parameter `#[miniextendr(coerce)]`, `#[miniextendr(default = "...")]`,
2330 // and `#[miniextendr(choices(...))]` attributes.
2331let mut per_param: std::collections::HashMap<String, ParamAttrs> =
2332 std::collections::HashMap::new();
2333let mut per_param_default_spans: std::collections::HashMap<String, proc_macro2::Span> =
2334 std::collections::HashMap::new();
2335let mut unused_counter = 0usize;
2336let mut pattern_destructures: Vec<(Box<syn::Pat>, syn::Ident)> = Vec::new();
2337let mut param_markers: Vec<(String, Vec<crate::type_inspect::ParamMarker>)> = Vec::new();
2338for arg in &mut item.sig.inputs {
2339let syn::FnArg::Typed(pat_type) = arg else {
2340// Self parameters are not allowed in standalone functions.
2341 // Users should use #[miniextendr(env|r6|s3|s4|s7)] on impl blocks instead.
2342 // The error is raised in lib.rs c_wrapper_inputs generation.
2343continue;
2344 };
23452346// Consume the per-parameter miniextendr attributes (coerce,
2347 // match_arg, choices, several_ok, default, inherits, not_inherits,
2348 // no_na), merging
2349 // them when a parameter carries several; keep every other attribute.
2350let mut param_attr = PerParamMiniextendrAttr::default();
2351let mut kept_attrs = Vec::with_capacity(pat_type.attrs.len());
2352for attr in std::mem::take(&mut pat_type.attrs) {
2353match parse_per_param_attr(&attr)? {
2354Some(parsed) => param_attr
2355 .merge(parsed)
2356 .map_err(|msg| syn::Error::new_spanned(&attr, msg))?,
2357None => kept_attrs.push(attr),
2358 }
2359 }
2360 pat_type.attrs = kept_attrs;
2361let PerParamMiniextendrAttr {
2362 has_coerce: had_coerce_attr,
2363 has_convert: had_convert,
2364 has_match_arg: had_match_arg_attr,
2365 default_value: default_with_span,
2366 choices: had_choices,
2367 has_several_ok: had_several_ok,
2368 has_no_default: had_no_default,
2369 checks: had_checks,
2370 preconditions: had_preconditions,
2371 formal: had_formal,
2372 } = param_attr;
23732374if is_extern && had_convert {
2375return Err(syn::Error::new_spanned(
2376&pat_type.ty,
2377"`convert` requires a generated wrapper; remove `extern \"C-unwind\"`",
2378 ));
2379 }
23802381// Parameter markers (`Checked<T>` / `Unchecked<T>`, #1566): the
2382 // parameter converts as the inner type, which every check below
2383 // and every R-side consumer sees; the item keeps the marker, and
2384 // the C wrapper wraps the converted value before the call.
2385let (markers, inner_ty) =
2386crate::type_inspect::peel_param_markers(pat_type.ty.as_ref())?;
2387let inner_ty = inner_ty.clone();
2388if is_extern && let Some(marker) = markers.first() {
2389return Err(syn::Error::new_spanned(
2390&pat_type.ty,
2391::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}<T>` on an `extern \"C-unwind\"` function: it takes the R values as they are, with no generated conversion to unwrap the marker; take the inner type",
marker.name()))
})format!(
2392"`{}<T>` on an `extern \"C-unwind\"` function: it takes the R values \
2393 as they are, with no generated conversion to unwrap the marker; take \
2394 the inner type",
2395 marker.name()
2396 ),
2397 ));
2398 }
2399// `NArgs` (#1860) is filled by the generated R wrapper, which an
2400 // extern function does not have.
2401if is_extern && crate::type_inspect::is_nargs_marker(&inner_ty) {
2402return Err(syn::Error::new_spanned(
2403&pat_type.ty,
2404"`NArgs` on an `extern \"C-unwind\"` function: the generated R wrapper \
2405 passes `nargs()` for it, and an extern function has none (`.Call()` reaches \
2406 it directly). Drop the `extern \"C-unwind\"` to let the macro generate the \
2407 wrapper, or take a `SEXP` and pass the count yourself",
2408 ));
2409 }
24102411// Validate type-based constraints (Missing nesting, Missing<Dots>)
2412validate_param_type(&inner_ty, pat_type.ty.span())?;
24132414// Resolve the Rust parameter name — either the user's identifier,
2415 // or a synthesized one for wildcard / destructuring patterns.
2416let param_name: String = match pat_type.pat.as_ref() {
2417 syn::Pat::Ident(pat_ident) => crate::naming::ident_name(&pat_ident.ident),
2418 syn::Pat::Wild(_) => {
2419let synthetic_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("__unused{0}", unused_counter))
})format!("__unused{}", unused_counter);
2420 unused_counter += 1;
2421let synthetic_ident = syn::Ident::new(&synthetic_name, pat_type.pat.span());
2422*pat_type.pat = syn::Pat::Ident(syn::PatIdent {
2423 attrs: ::alloc::vec::Vec::new()vec![],
2424 by_ref: None,
2425 mutability: None,
2426 ident: synthetic_ident,
2427 subpat: None,
2428 });
2429 synthetic_name
2430 }
2431 syn::Pat::Tuple(_) | syn::Pat::TupleStruct(_) | syn::Pat::Struct(_) => {
2432let synthetic_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("__param_{0}", unused_counter))
})format!("__param_{}", unused_counter);
2433 unused_counter += 1;
2434let synthetic_ident = syn::Ident::new(&synthetic_name, pat_type.pat.span());
2435let original_pat = pat_type.pat.clone();
2436*pat_type.pat = syn::Pat::Ident(syn::PatIdent {
2437 attrs: ::alloc::vec::Vec::new()vec![],
2438 by_ref: None,
2439 mutability: None,
2440 ident: synthetic_ident.clone(),
2441 subpat: None,
2442 });
2443 pattern_destructures.push((original_pat, synthetic_ident));
2444 synthetic_name
2445 }
2446_ => {
2447return Err(syn::Error::new(
2448 pat_type.pat.span(),
2449"miniextendr parameters must be identifiers or destructuring patterns (tuple, struct)",
2450 ));
2451 }
2452 };
2453// `NonNa<T>` is `no_na` written in the type: the R guard and the
2454 // post-conversion check follow from the flag, as for the keyword
2455 // (and its `message`), and the C wrapper adds its own check.
2456let mut had_checks = had_checks;
2457if markers.contains(&crate::type_inspect::ParamMarker::NonNa) {
2458 had_checks.no_na = true;
2459 }
2460// The marker and the per-parameter keyword are one decision.
2461let preconditions = merge_param_policy(
2462&markers,
2463 had_preconditions,
2464¶m_name,
2465false,
2466&pat_type.ty,
2467 )?;
24682469// Validate per-parameter attribute conflicts (coerce+match_arg, coerce+choices, etc.)
2470let per_param_combined = PerParamMiniextendrAttr {
2471 has_coerce: had_coerce_attr,
2472 has_convert: had_convert,
2473 has_match_arg: had_match_arg_attr,
2474 default_value: default_with_span.clone(),
2475 choices: had_choices.clone(),
2476 has_several_ok: had_several_ok,
2477 has_no_default: had_no_default,
2478 checks: had_checks.clone(),
2479 preconditions,
2480 formal: had_formal.clone(),
2481 };
2482 validate_per_param_attr_conflicts(
2483&per_param_combined,
2484¶m_name,
2485 is_dots_type(&inner_ty),
2486&inner_ty,
2487 pat_type.ty.span(),
2488 )?;
24892490// Record per-parameter attrs in one entry instead of five side-tables.
2491if had_coerce_attr
2492 || had_convert
2493 || had_match_arg_attr
2494 || had_several_ok
2495 || had_choices.is_some()
2496 || default_with_span.is_some()
2497 || !had_checks.is_empty()
2498 || preconditions.is_some()
2499 || had_formal.is_some()
2500 {
2501let entry = per_param.entry(param_name.clone()).or_default();
2502 entry.formal = had_formal;
2503 entry.checks = had_checks;
2504 entry.coerce = had_coerce_attr;
2505 entry.convert = had_convert;
2506 entry.match_arg = had_match_arg_attr;
2507 entry.several_ok = had_several_ok;
2508 entry.no_default = had_no_default;
2509 entry.choices = had_choices;
2510 entry.preconditions = preconditions;
2511if let Some((default, span)) = default_with_span {
2512 entry.default = Some(default);
2513 per_param_default_spans.insert(param_name.clone(), span);
2514 }
2515// The `Option` / `Missing` layers of a choice parameter (#1473, #1551).
2516let has_default = entry.default.is_some();
2517 classify_choice_param(entry, ¶m_name, &inner_ty, has_default)?;
2518 check_param_preconditions(entry, &markers, ¶m_name, &inner_ty, false)?;
2519 }
2520if !markers.is_empty() {
2521 param_markers.push((param_name, markers));
2522 }
2523 }
25242525// Insert destructuring let-bindings for pattern parameters at the start of the function body
2526for (pat, ident) in pattern_destructures.iter().rev() {
2527 item.block.stmts.insert(
25280,
2529::syn::__private::parse_quote({
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_ident(&mut _s, "let");
::quote::ToTokens::to_tokens(&pat, &mut _s);
::quote::__private::push_eq(&mut _s);
::quote::ToTokens::to_tokens(&ident, &mut _s);
::quote::__private::push_semi(&mut _s);
_s
})syn::parse_quote! {
2530let #pat = #ident;
2531 },
2532 );
2533 }
25342535// Validate: all defaults reference existing parameters
2536let param_names: std::collections::HashSet<String> = item2537 .sig
2538 .inputs
2539 .iter()
2540 .filter_map(|input| {
2541if let syn::FnArg::Typed(pat_type) = input2542 && let syn::Pat::Ident(pat_ident) = pat_type.pat.as_ref()
2543 {
2544Some(crate::naming::ident_name(&pat_ident.ident))
2545 } else {
2546None2547 }
2548 })
2549 .collect();
25502551let mut invalid_params: Vec<String> = per_param2552 .iter()
2553 .filter_map(|(name, attrs)| {
2554if attrs.default.is_some() && !param_names.contains(name) {
2555Some(name.clone())
2556 } else {
2557None2558 }
2559 })
2560 .collect();
2561invalid_params.sort();
25622563if !invalid_params.is_empty() {
2564// Use the span of the first invalid param's attribute for the error
2565let error_span = invalid_params2566 .first()
2567 .and_then(|p| per_param_default_spans.get(p).copied())
2568 .unwrap_or_else(|| item.sig.ident.span());
2569return Err(syn::Error::new(
2570error_span,
2571::alloc::__export::must_use({
::alloc::fmt::format(format_args!("default attribute(s) reference non-existent parameter(s): {0}",
invalid_params.join(", ")))
})format!(
2572"default attribute(s) reference non-existent parameter(s): {}",
2573 invalid_params.join(", ")
2574 ),
2575 ));
2576 }
25772578let dots = find_dots_param(&item.sig.inputs)?;
2579crate::r_wrapper_builder::check_r_formals(
2580&item.sig.inputs,
2581&crate::r_wrapper_builder::Formals::from_param_attrs(&per_param),
2582&[],
2583 )?;
2584let inputs = peeled_inputs(&item.sig.inputs, ¶m_markers)?;
25852586Ok(Self {
2587item,
2588inputs,
2589param_markers,
2590dots,
2591per_param,
2592 })
2593 }
2594}
25952596/// Accessors and codegen helpers for [`MiniextendrFunctionParsed`].
2597///
2598/// Accessors are split into two groups:
2599/// - **Parsed metadata**: dots, coerce, match_arg, choices, and defaults from
2600/// per-parameter `#[miniextendr(...)]` attributes.
2601/// - **Signature components**: attrs, vis, abi, ident, generics, inputs, output
2602/// from the normalized `syn::ItemFn`.
2603///
2604/// Codegen helpers produce identifiers and perform mutations needed by the
2605/// `#[miniextendr]` expansion pipeline.
2606impl MiniextendrFunctionParsed {
2607// region: Accessors for parsed metadata
26082609/// Whether the function takes `...`: Rust `...` or an explicit `&Dots`
2610 /// parameter, at any position.
2611pub(crate) fn has_dots(&self) -> bool {
2612self.dots.is_some()
2613 }
26142615/// The Rust binding of the dots: the user's name (`args: ...`,
2616 /// `rest: &Dots`), or `__miniextendr_dots` for `_: ...`.
2617pub(crate) fn dots_ident(&self) -> Option<&syn::Ident> {
2618self.dots.as_ref()
2619 }
26202621/// Check if a parameter is the dots (`...`) param, whose R formal is `...`.
2622pub(crate) fn is_dots_param(&self, ident: &syn::Ident) -> bool {
2623self.dots_ident() == Some(ident)
2624 }
26252626/// Whether a parameter carried any per-parameter `#[miniextendr(...)]`
2627 /// option. A `Call` / `CallerCall` marker (#1566) is bound from the call
2628 /// slot, not from an R argument, so none of them apply to it.
2629pub(crate) fn has_param_attrs(&self, param_name: &str) -> bool {
2630self.per_param.contains_key(param_name)
2631 }
26322633/// Check if a parameter name had `#[miniextendr(coerce)]` attribute.
2634pub(crate) fn has_coerce_attr(&self, param_name: &str) -> bool {
2635self.per_param.get(param_name).is_some_and(|a| a.coerce)
2636 }
26372638/// Check if a parameter name had `#[miniextendr(match_arg)]` attribute.
2639pub(crate) fn has_match_arg_attr(&self, param_name: &str) -> bool {
2640self.per_param.get(param_name).is_some_and(|a| a.match_arg)
2641 }
26422643/// Iterator over parameter names annotated with `#[miniextendr(match_arg)]`,
2644 /// in signature order.
2645pub(crate) fn match_arg_params(&self) -> impl Iterator<Item = &String> {
2646per_param_in_signature_order(&self.item.sig.inputs, &self.per_param)
2647 .filter_map(|(name, a)| if a.match_arg { Some(name) } else { None })
2648 }
26492650/// Iterator over parameter names annotated with `#[miniextendr(choices(…))]`,
2651 /// together with their choice lists, in signature order.
2652pub(crate) fn choices_params(&self) -> impl Iterator<Item = (&String, &Vec<String>)> {
2653per_param_in_signature_order(&self.item.sig.inputs, &self.per_param)
2654 .filter_map(|(name, a)| a.choices.as_ref().map(|c| (name, c)))
2655 }
26562657/// Check if a parameter has `several_ok` (multi-value match.arg).
2658pub(crate) fn has_several_ok(&self, param_name: &str) -> bool {
2659self.per_param.get(param_name).is_some_and(|a| a.several_ok)
2660 }
26612662/// The per-parameter attribute state of `param_name`, if it carried any
2663 /// `#[miniextendr(...)]` option. Choice parameters read their layers
2664 /// (`Option` / `Missing`, #1473 / #1551) from here.
2665pub(crate) fn param_attrs(&self, param_name: &str) -> Option<&ParamAttrs> {
2666self.per_param.get(param_name)
2667 }
26682669/// The R formal of each parameter (#1842), from the declared
2670 /// `formal = ".."` options.
2671pub(crate) fn formals(&self) -> crate::r_wrapper_builder::Formals {
2672crate::r_wrapper_builder::Formals::from_param_attrs(&self.per_param)
2673 }
26742675/// The R formals of the parameters that read a value `identical()` to
2676 /// their formal as omitted (see [`absent_formals_by_r_name`]).
2677pub(crate) fn absent_formals(&self) -> std::collections::HashSet<String> {
2678absent_formals_by_r_name(&self.per_param)
2679 }
26802681/// The generated `@param` text of each `Missing<..>` parameter with a
2682 /// default, keyed by R formal (see [`missing_default_param_docs`]).
2683pub(crate) fn missing_default_param_docs(&self) -> std::collections::HashMap<String, String> {
2684missing_default_param_docs(
2685&self.item.sig.inputs,
2686&self.per_param,
2687&self.param_defaults(),
2688&self.formals(),
2689 )
2690 }
26912692/// The `inherits` / `not_inherits` / `no_na` checks of every parameter,
2693 /// keyed by R name (see [`explicit_checks_by_r_name`]).
2694pub(crate) fn explicit_checks(
2695&self,
2696 ) -> std::collections::HashMap<String, crate::r_preconditions::ExplicitChecks> {
2697explicit_checks_by_r_name(&self.per_param)
2698 }
26992700/// R names of the `match_arg` and `choices(...)` parameters, whose
2701 /// type-derived preconditions are skipped because `match.arg()` already
2702 /// validates them. The method paths build the same set.
2703pub(crate) fn precondition_skip_params(&self) -> std::collections::HashSet<String> {
2704crate::r_class_formatter::match_arg_skip_set(&self.per_param)
2705 }
27062707/// Returns all parameter defaults as an owned map from Rust parameter
2708 /// name to default value string (the raw R expression used in the wrapper
2709 /// formals, e.g. `"NULL"`, `"TRUE"`, `"\"Safe\""`). The R wrapper keys
2710 /// them by formal ([`crate::r_wrapper_builder::Formals::rekey`]), so a
2711 /// default on `_seed` is the formal `seed`'s.
2712pub(crate) fn param_defaults(&self) -> std::collections::HashMap<String, String> {
2713self.per_param
2714 .iter()
2715 .filter_map(|(name, a)| a.default.as_ref().map(|d| (name.clone(), d.clone())))
2716 .collect()
2717 }
2718// endregion
27192720 // region: Accessors for signature components
27212722/// Original attributes on the function item (doc comments, cfgs, etc.).
2723pub(crate) fn attrs(&self) -> &[syn::Attribute] {
2724&self.item.attrs
2725 }
27262727/// Visibility of the function (`pub`, `pub(crate)`, or private).
2728pub(crate) fn vis(&self) -> &syn::Visibility {
2729&self.item.vis
2730 }
27312732/// Explicit ABI, if the function was declared `extern "C-unwind"`.
2733pub(crate) fn abi(&self) -> Option<&syn::Abi> {
2734self.item.sig.abi.as_ref()
2735 }
27362737/// Function identifier after normalization.
2738pub(crate) fn ident(&self) -> &syn::Ident {
2739&self.item.sig.ident
2740 }
27412742/// Generic parameters on the function signature.
2743pub(crate) fn generics(&self) -> &syn::Generics {
2744&self.item.sig.generics
2745 }
27462747/// Function inputs after normalization (dots rewritten, wildcards
2748 /// renamed), with the parameter markers peeled (see [`Self::param_markers`]).
2749pub(crate) fn inputs(&self) -> &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]> {
2750&self.inputs
2751 }
27522753/// The `Checked<T>` / `Unchecked<T>` markers peeled off the parameters
2754 /// (Rust name → markers, outermost first), in signature order.
2755pub(crate) fn param_markers(&self) -> &[(String, Vec<crate::type_inspect::ParamMarker>)] {
2756&self.param_markers
2757 }
27582759/// Function return type.
2760pub(crate) fn output(&self) -> &syn::ReturnType {
2761&self.item.sig.output
2762 }
27632764/// The normalized function item (with original doc comments).
2765pub(crate) fn item(&self) -> &syn::ItemFn {
2766&self.item
2767 }
27682769/// The normalized function item with roxygen tags stripped from doc comments.
2770 ///
2771 /// This is used for emitting the Rust function without R-specific documentation
2772 /// tags (e.g., `@param`, `@examples`) that don't belong in rustdoc.
2773pub(crate) fn item_without_roxygen(&self) -> syn::ItemFn {
2774let mut item = self.item.clone();
2775item.attrs = crate::roxygen::strip_roxygen_from_attrs(&item.attrs);
2776item2777 }
2778// endregion
27792780 // region: Codegen helpers
27812782/// Returns `true` if this function needs an internal C wrapper (`C_<crate>_<name>` function).
2783 ///
2784 /// Rust-ABI functions (no explicit `extern`) need a generated `extern "C-unwind"` wrapper
2785 /// that handles SEXP conversion and error propagation. Functions already declared as
2786 /// `extern "C-unwind"` are passed through directly without wrapping.
2787pub(crate) fn uses_internal_c_wrapper(&self) -> bool {
2788self.abi().is_none()
2789 }
27902791/// Returns the identifier for the generated `const &str` holding the R wrapper code.
2792 ///
2793 /// The R wrapper is a string constant containing the R function definition that
2794 /// calls `.Call(C_<crate>_<name>, ...)`. It is collected via linkme distributed slices to
2795 /// produce the `R/miniextendr-wrappers.R` file.
2796pub(crate) fn r_wrapper_const_ident(&self) -> syn::Ident {
2797r_wrapper_const_ident_for(self.ident())
2798 }
27992800/// Returns the identifier for the C-callable entry point.
2801 ///
2802 /// - **Rust ABI functions**: Returns `C_<crate>_<name>` (the generated wrapper
2803 /// function, crate-prefixed for webR cross-package symbol uniqueness — #1273).
2804 /// - **`extern "C-unwind"` functions**: Returns the function's own name, or the
2805 /// value from `#[export_name = "..."]` if present. The user owns these symbols,
2806 /// including their cross-package uniqueness under webR.
2807pub(crate) fn c_wrapper_ident(&self) -> syn::Ident {
2808if self.uses_internal_c_wrapper() {
2809crate::naming::bare_fn_c_wrapper_ident(self.ident())
2810 } else {
2811// For extern functions, check for #[export_name = "..."]
2812self.export_name_ident()
2813 .unwrap_or_else(|| self.ident().clone())
2814 }
2815 }
28162817/// Extracts the custom symbol name from `#[export_name = "..."]`, if present.
2818 ///
2819 /// Only meaningful for `extern "C-unwind"` functions, where `#[export_name]` is
2820 /// allowed as an alternative to `#[no_mangle]`. Returns `None` if no such attribute exists.
2821pub(crate) fn export_name_ident(&self) -> Option<syn::Ident> {
2822for attr in &self.item.attrs {
2823if attr.path().is_ident("export_name")
2824 && let syn::Meta::NameValue(meta) = &attr.meta
2825 && let syn::Expr::Lit(syn::ExprLit {
2826 lit: syn::Lit::Str(lit_str),
2827 ..
2828 }) = &meta.value
2829 {
2830return Some(syn::Ident::new(&lit_str.value(), lit_str.span()));
2831 }
2832 }
2833None2834 }
28352836/// Add `#[inline(never)]` if no `#[inline(...)]` attribute is present.
2837 /// Only for Rust ABI functions - extern "C-unwind" functions are passed through as-is.
2838 ///
2839 /// Preventing inlining ensures:
2840 /// - Worker-dispatched functions retain a distinct call frame
2841 /// - Panic handling and unwinding retain the intended boundary
2842 /// - Stack traces show the actual function name
2843pub(crate) fn add_inline_never_if_needed(&mut self) {
2844let has_explicit_abi = self.item.sig.abi.is_some();
2845let has_inline = self2846 .item
2847 .attrs
2848 .iter()
2849 .any(|attr| attr.path().is_ident("inline"));
2850if !has_inline && !has_explicit_abi {
2851self.item.attrs.push(::syn::__private::parse_quote({
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_pound(&mut _s);
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Bracket,
{
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_ident(&mut _s, "inline");
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
{
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_ident(&mut _s, "never");
_s
});
_s
});
_s
})syn::parse_quote!(#[inline(never)]));
2852 }
2853 }
2854// endregion
2855}
2856// endregion
28572858// region: Attribute parsing
28592860/// Parse the value of a `name = "..."` meta item as a string literal.
2861///
2862/// Returns a compile error spanning the offending token when the RHS is not a
2863/// `&str` literal. `field` is used in the diagnostic (e.g. `"c_symbol"`).
2864/// `postfix = "..."` must be a non-empty R identifier fragment: it is appended
2865/// verbatim to the Rust name, so anything outside letters, digits, `_` and `.`
2866/// would produce an R name that needs backticks.
2867pub(crate) fn validate_postfix(val: &str, span: &dyn quote::ToTokens) -> syn::Result<()> {
2868if val.is_empty() {
2869return Err(syn::Error::new_spanned(span, "postfix must not be empty"));
2870 }
2871if !val2872 .chars()
2873 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
2874 {
2875return Err(syn::Error::new_spanned(
2876span,
2877"postfix must be a valid R identifier fragment (letters, digits, `_`, `.`)",
2878 ));
2879 }
2880Ok(())
2881}
28822883fn parse_lit_str(nv: &syn::MetaNameValue, field: &str) -> syn::Result<String> {
2884match &nv.value {
2885 syn::Expr::Lit(syn::ExprLit {
2886 lit: syn::Lit::Str(lit),
2887 ..
2888 }) => Ok(lit.value()),
2889 syn::Expr::Lit(expr_lit) => Err(syn::Error::new_spanned(
2890&expr_lit.lit,
2891::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} expects a string literal",
field))
})format!("{field} expects a string literal"),
2892 )),
2893 other => Err(syn::Error::new_spanned(
2894other,
2895::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} expects a string literal",
field))
})format!("{field} expects a string literal"),
2896 )),
2897 }
2898}
28992900/// Comma-separated list of all fn-level boolean flags, for error messages.
2901///
2902/// Kept as a single constant so the three "unknown option" error paths (Path,
2903/// NameValue bool, parenthesized bool) all read from the same list and can't
2904/// drift.
2905const FN_BOOL_FLAGS_HELP: &str = "invisible, visible, check_interrupt, coerce, no_coerce, \
2906 rng, unwrap_in_r, serialize, serde_error, strict, no_strict, \
2907 preconditions, no_preconditions, internal, noexport, export, call_arg";
29082909/// Comma-separated list of fn-level nested options, for error messages.
2910const FN_NESTED_OPTIONS_HELP: &str = "`s3(...)`, `lifecycle(...)`, `defaults(...)`, `r_on_exit(...)`, \
2911 `serde_error(...)`, `rng(seed = ...)`";
29122913/// Parsed arguments for the `#[miniextendr(...)]` attribute on functions.
2914///
2915/// This is intentionally a small, "data-only" struct that:
2916/// - Owns the parsing rules for the attribute
2917/// - Produces a normalized, easy-to-consume representation for codegen
2918///
2919/// # Accepted flags
2920///
2921/// - `invisible` / `visible`: control whether the generated R wrapper returns invisibly
2922/// - `check_interrupt`: insert `R_CheckUserInterrupt()` before calling Rust
2923/// - `coerce`: enable automatic coercion for supported parameter types
2924/// - `rng`: enable RNG state management (GetRNGstate/PutRNGstate)
2925/// - `rng(seed = <param>)`: `rng`, plus the seed contract of `stats::simulate()`
2926/// in the R wrapper (#2198); `<param>` names the parameter, by its Rust
2927/// name, whose value goes to `set.seed()`
2928/// - `unwrap_in_r`: return `Result<T, E>` to R without unwrapping
2929/// - `prefer = "auto" | "list" | "externalptr" | "vector"`: prefer a specific `IntoR` path
2930/// - `no_preconditions` / `preconditions` (bare or `= true/false`): drop or
2931/// keep the R-side type checks. Without them `TryFromSexp` still raises on
2932/// bad input, with the same argument-error condition (#1591); the message
2933/// comes from the conversion. Saves one `isTRUE()` guard per check.
2934/// Hot-path opt-in. The last one written wins. A parameter decides for
2935/// itself first (`Checked<T>` / `Unchecked<T>`, or the per-parameter
2936/// `#[miniextendr(preconditions)]` / `#[miniextendr(no_preconditions)]`);
2937/// below the function come the crate's `[package.metadata.miniextendr]
2938/// preconditions = true | false` and then the `no-preconditions-default`
2939/// feature (`crate::r_preconditions::resolve_type_checks`).
2940/// - `call = wrapper | caller | none`: which call the wrapper attributes
2941/// conditions to (#1566), always as written. `wrapper` (the framework
2942/// default) passes `.call = sys.call()`; `caller` binds the caller's call
2943/// first and passes that (internal entry points behind a hand-written R
2944/// function; needs `noexport` / `internal`); `none` passes no call, so
2945/// every condition, the argument errors included, has a NULL call (#1851;
2946/// not with a `Call` / `CallerCall` parameter or `call_arg`). A `Call` /
2947/// `CallerCall` parameter is the marker spelling of `wrapper` / `caller`,
2948/// and `[package.metadata.miniextendr] call_attribution` the crate default;
2949/// see `CallAttribution::resolve`. On an S3 method `wrapper` reports the
2950/// generic's call (`CallAttribution::for_s3_method`).
2951/// - `call_arg`: the wrapper takes a trailing `.call = NULL` formal (#1834),
2952/// exported or not. `NULL` is the wrapper's own call; an R function
2953/// composing the function passes `.call = environment()` (or a call
2954/// object) and its conditions name that function's call instead. Not with
2955/// `call = caller` (whose wrapper already takes `.call`) or `s3(...)`.
2956///
2957/// # Note
2958///
2959/// Unknown flags are rejected with a compile error to avoid silently ignoring typos.
2960#[derive(#[automatically_derived]impl ::core::default::Default for MiniextendrFnAttrs {
#[inline]
fn default() -> Self {
MiniextendrFnAttrs {
force_invisible: ::core::default::Default::default(),
check_interrupt: ::core::default::Default::default(),
coerce_all: ::core::default::Default::default(),
rng: ::core::default::Default::default(),
rng_seed: ::core::default::Default::default(),
unwrap_in_r: ::core::default::Default::default(),
serialize: ::core::default::Default::default(),
wrap: ::core::default::Default::default(),
serde_error: ::core::default::Default::default(),
preconditions: ::core::default::Default::default(),
call_attribution: ::core::default::Default::default(),
call_arg: ::core::default::Default::default(),
return_pref: ::core::default::Default::default(),
return_pref_span: ::core::default::Default::default(),
s3_generic: ::core::default::Default::default(),
s3_class: ::core::default::Default::default(),
dots_spec: ::core::default::Default::default(),
dots_policy: ::core::default::Default::default(),
dots_span: ::core::default::Default::default(),
lifecycle: ::core::default::Default::default(),
strict: ::core::default::Default::default(),
internal: ::core::default::Default::default(),
noexport: ::core::default::Default::default(),
export: ::core::default::Default::default(),
doc: ::core::default::Default::default(),
c_symbol: ::core::default::Default::default(),
r_name: ::core::default::Default::default(),
postfix: ::core::default::Default::default(),
r_entry: ::core::default::Default::default(),
r_post_checks: ::core::default::Default::default(),
r_on_exit: ::core::default::Default::default(),
}
}
}Default)]
2961pub(crate) struct MiniextendrFnAttrs {
2962/// Override visibility; `Some(true)` makes the wrapper return invisibly, `Some(false)` forces visibility.
2963pub(crate) force_invisible: Option<bool>,
2964/// Insert `R_CheckUserInterrupt()` before calling the Rust function.
2965pub(crate) check_interrupt: bool,
2966/// Enable automatic coercion for all parameters that support it.
2967pub(crate) coerce_all: bool,
2968/// Enable RNG state management (GetRNGstate/PutRNGstate). Also set by
2969 /// `rng(seed = ..)`.
2970pub(crate) rng: bool,
2971/// `rng(seed = <param>)` (#2198): the parameter, by its Rust name, whose
2972 /// value the R wrapper passes to `set.seed()` before the call and records
2973 /// in the result's `seed` attribute, as `stats:::simulate.lm` does
2974 /// ([`check_rng_seed`] checks it against the signature).
2975pub(crate) rng_seed: Option<syn::Ident>,
2976/// Return `Result<T, E>` to R without unwrapping.
2977pub(crate) unwrap_in_r: bool,
2978/// Serialize the complete return value through `AsSerialize<T>`.
2979pub(crate) serialize: bool,
2980pub(crate) wrap: Option<crate::miniextendr_impl::ClassSystem>,
2981/// Build the `Err` arm's condition from the error's serde output
2982 /// (`#[miniextendr(serde_error(shape = .., tag = .., prefix = .., ..))]`).
2983pub(crate) serde_error: Option<SerdeErrorSpec>,
2984/// Keep (`Some(true)`) or drop (`Some(false)`) the R-side type-check
2985 /// guards of the parameters that do not decide for themselves.
2986 ///
2987 /// `TryFromSexp` already raises the same argument-error condition on
2988 /// mismatched input (#1591), so the information isn't lost: it is
2989 /// worded by the conversion rather than by the R check. Useful for hot
2990 /// paths where the per-call precondition cost (one `isTRUE()` guard per
2991 /// check) dominates over actual work.
2992 ///
2993 /// `Some(true)` from `#[miniextendr(preconditions)]` (or
2994 /// `preconditions = true`, `no_preconditions = false`), `Some(false)` from
2995 /// `no_preconditions` (or `no_preconditions = true`, `preconditions =
2996 /// false`); the last one written wins. `None`: the crate default, then the
2997 /// `no-preconditions-default` feature decide, at codegen
2998 /// (`crate::r_preconditions::resolve_type_checks`).
2999pub(crate) preconditions: Option<bool>,
3000/// The attribution the attribute asked for, if any (#1566):
3001 /// `call = wrapper | caller | none`. `None` here means the attribute said
3002 /// nothing; the codegen then falls back to a `Call` / `CallerCall`
3003 /// parameter marker, the crate default and finally `wrapper`
3004 /// (`crate::r_wrapper_builder::CallAttribution::resolve`).
3005pub(crate) call_attribution: Option<crate::r_wrapper_builder::CallAttribution>,
3006/// `call_arg` (#1834): the wrapper takes a trailing `.call = NULL` formal,
3007 /// whose `NULL` is the wrapper's own call and through which an R function
3008 /// composing it passes another (`environment()`, a call object). Turns
3009 /// `wrapper` attribution into
3010 /// `crate::r_wrapper_builder::CallAttribution::Argument`.
3011pub(crate) call_arg: bool,
3012/// Preferred return conversion: forces `AsList`/`AsExternalPtr`/`AsRNative` wrapping
3013 /// of the return value before `IntoR::into_sexp` is called.
3014pub(crate) return_pref: ReturnPref,
3015/// Span of the `prefer = ...` attribute, for error reporting when the return type
3016 /// falls into a codegen category (`Option<T>`, `Result<T, E>`, `()`, `Self`, raw
3017 /// `SEXP`, ...) that can't honor it.
3018pub(crate) return_pref_span: Option<proc_macro2::Span>,
3019/// S3 generic name (if this function is an S3 method).
3020 ///
3021 /// Use `#[miniextendr(s3(generic = "vec_proxy", class = "my_vctr"))]` to mark a function
3022 /// as an S3 method for an existing generic. `pkg::generic` registers the
3023 /// method lazily, for a generic of a suggested package (#2154).
3024pub(crate) s3_generic: Option<String>,
3025/// S3 class suffix for the method (e.g., "my_vctr" or "my_vctr.my_vctr" for double-dispatch).
3026pub(crate) s3_class: Option<String>,
3027/// Typed list validation spec for dots parameter.
3028 ///
3029 /// Use `#[miniextendr(dots = typed_list!(...))]` to automatically validate dots
3030 /// at the start of the function and bind the result to `dots_typed`.
3031pub(crate) dots_spec: Option<proc_macro2::TokenStream>,
3032/// What the function's `...` takes: `dots = empty | empty(allow = [..]) |
3033 /// forward(allow = [..]) | data` (#2157, [`crate::dots_policy`]).
3034pub(crate) dots_policy: Option<crate::dots_policy::DotsPolicy>,
3035/// Span of the `dots = ...` attribute for error reporting.
3036pub(crate) dots_span: Option<proc_macro2::Span>,
3037/// Lifecycle specification for deprecation/experimental status.
3038pub(crate) lifecycle: Option<crate::lifecycle::LifecycleSpec>,
3039/// Strict output conversion: panic instead of lossy widening for i64/u64/isize/usize.
3040pub(crate) strict: bool,
3041/// Mark as internal: adds `@keywords internal`, suppresses `@export`.
3042pub(crate) internal: bool,
3043/// Suppress `@export` without adding `@keywords internal`.
3044pub(crate) noexport: bool,
3045/// Force `@export` even on non-pub functions. Antidote to `noexport`.
3046pub(crate) export: bool,
3047/// Custom roxygen documentation override.
3048 ///
3049 /// When set, replaces auto-extracted roxygen from Rust doc comments.
3050 /// Each `\n` in the string becomes a separate `#'` line.
3051pub(crate) doc: Option<String>,
3052/// Custom C symbol name for the generated wrapper.
3053 ///
3054 /// Overrides the default `C_<crate>_<fn_name>` naming convention. The value is used
3055 /// verbatim (no crate prefix) — the author owns cross-package uniqueness on webR (#1273).
3056 /// Must be a valid C identifier (alphanumeric + underscore, starting with letter or underscore).
3057pub(crate) c_symbol: Option<String>,
3058/// Override R wrapper function name.
3059 ///
3060 /// Use `#[miniextendr(r_name = "is.my_type")]` to give the R wrapper a different name
3061 /// than the Rust function. The C symbol is still derived from the Rust name.
3062 /// Cannot be combined with `s3(generic/class)` — use `generic`/`class` for S3 naming.
3063pub(crate) r_name: Option<String>,
3064/// Append a fixed suffix to the Rust name for the R wrapper
3065 /// (`#[miniextendr(noexport, postfix = "_impl")]` on `fn f` yields `f_impl`).
3066 /// States the "hand-written `f()` delegates to generated `f_impl()`"
3067 /// convention without repeating the name in `r_name`. Exclusive with
3068 /// `r_name` and `s3(...)`; the C symbol is unchanged.
3069pub(crate) postfix: Option<String>,
3070/// R code to inject at the very top of the wrapper body (before all built-in checks).
3071 ///
3072 /// Use `#[miniextendr(r_entry = "x <- as.integer(x)")]` to run R code before
3073 /// missing-default handling, lifecycle checks, preconditions, and match.arg.
3074 /// Multi-line via `\n`. No validation of R syntax.
3075pub(crate) r_entry: Option<String>,
3076/// R code to inject after all built-in checks, immediately before `.Call()`.
3077 ///
3078 /// Use `#[miniextendr(r_post_checks = "message('calling rust')")]` to run R code
3079 /// after all precondition checks but before the Rust function is invoked.
3080 /// Multi-line via `\n`. No validation of R syntax.
3081pub(crate) r_post_checks: Option<String>,
3082/// Register `on.exit()` cleanup code in the R wrapper.
3083 ///
3084 /// Short form: `#[miniextendr(r_on_exit = "close(con)")]` → `on.exit(close(con), add = TRUE)`
3085 ///
3086 /// Long form: `#[miniextendr(r_on_exit(expr = "close(con)", add = false))]`
3087 ///
3088 /// Defaults: `add = TRUE`, `after = TRUE`. Injected after `r_entry`, before other checks.
3089pub(crate) r_on_exit: Option<ROnExit>,
3090}
30913092/// Parsed `r_on_exit` attribute for `on.exit()` cleanup code in R wrappers.
3093///
3094/// Two forms:
3095/// - Short: `r_on_exit = "expr"` → `ROnExit { expr, add: true, after: true }`
3096/// - Long: `r_on_exit(expr = "...", add = false, after = false)`
3097///
3098/// Defaults match R conventions for composable code: `add = TRUE`, `after = TRUE`.
3099#[derive(#[automatically_derived]impl ::core::fmt::Debug for ROnExit {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"ROnExit expr add after", &self.expr, &self.add, &&self.after)
}
}Debug, #[automatically_derived]impl ::core::clone::Clone for ROnExit {
#[inline]
fn clone(&self) -> Self {
ROnExit {
expr: ::core::clone::Clone::clone(&self.expr),
add: ::core::clone::Clone::clone(&self.add),
after: ::core::clone::Clone::clone(&self.after),
}
}
}Clone)]
3100pub(crate) struct ROnExit {
3101pub expr: String,
3102pub add: bool,
3103pub after: bool,
3104}
31053106impl ROnExit {
3107/// Generate the R `on.exit(...)` call string.
3108 ///
3109 /// - `add = FALSE` (R default): `on.exit(expr)`
3110 /// - `add = TRUE, after = TRUE`: `on.exit(expr, add = TRUE)`
3111 /// - `add = TRUE, after = FALSE`: `on.exit(expr, add = TRUE, after = FALSE)`
3112pub fn to_r_code(&self) -> String {
3113if !self.add {
3114::alloc::__export::must_use({
::alloc::fmt::format(format_args!("on.exit({0})", self.expr))
})format!("on.exit({})", self.expr)3115 } else if !self.after {
3116::alloc::__export::must_use({
::alloc::fmt::format(format_args!("on.exit({0}, add = TRUE, after = FALSE)",
self.expr))
})format!("on.exit({}, add = TRUE, after = FALSE)", self.expr)3117 } else {
3118::alloc::__export::must_use({
::alloc::fmt::format(format_args!("on.exit({0}, add = TRUE)",
self.expr))
})format!("on.exit({}, add = TRUE)", self.expr)3119 }
3120 }
3121}
31223123/// `#[miniextendr(serde_error)]`: derive the `Err` arm's condition class and
3124/// data from the error type's `serde::Serialize` output instead of the
3125/// `RConditionData`/`Debug` probe.
3126///
3127/// The enum variant (external tagging, or the `tag` field of an internally
3128/// tagged enum) becomes the member class `<prefix>_<variant>`; the payload
3129/// fields become the condition's data. Defaults: `tag = "kind"`,
3130/// `prefix = "<crate>_error"` (from `CARGO_CRATE_NAME` at expansion time).
3131///
3132/// Field control (#1457, #2207): `skip("a", "b")` drops payload fields by
3133/// name, `rename(a = "b")` splices field `a` as `b`, and `as_character("a")`,
3134/// `as_integer(..)`, `as_double(..)`, `as_logical(..)` give a field that atomic
3135/// R type. All name the field as it serializes, before any rename; a variant
3136/// that lacks the field is unaffected. The macro cannot see the error type's
3137/// fields, so only the option grammar is checked here; a `rename` target may
3138/// not be one of the reserved condition slots, and a field takes one of `skip`
3139/// and the `as_*` options.
3140///
3141/// `shape = PATH` names a `miniextendr_api::condition::SerdeErrorShape` const
3142/// holding these options, applied before the function's own (#2207). The
3143/// generated code passes both to `serde_err_parts` as runtime data: the named
3144/// shape, then the function's options as an inline const shape.
3145///
3146/// The serde path itself needs no attribute: under the `serde` feature every
3147/// `Result<T, E>` with `E: Serialize + Display` takes it through the runtime
3148/// probe. A spec only exists to carry options, so the bare flag and the
3149/// boolean forms are rejected with [`SERDE_ERROR_BARE_HELP`].
3150#[derive(#[automatically_derived]impl ::core::fmt::Debug for SerdeErrorSpec {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
"SerdeErrorSpec shape tag prefix skip rename types";
let values: &[&dyn ::core::fmt::Debug] =
&[&self.shape, &self.tag, &self.prefix, &self.skip, &self.rename,
&&self.types];
::core::fmt::Formatter::debug_struct_fields_finish(f, names, values)
}
}Debug, #[automatically_derived]impl ::core::clone::Clone for SerdeErrorSpec {
#[inline]
fn clone(&self) -> Self {
SerdeErrorSpec {
shape: ::core::clone::Clone::clone(&self.shape),
tag: ::core::clone::Clone::clone(&self.tag),
prefix: ::core::clone::Clone::clone(&self.prefix),
skip: ::core::clone::Clone::clone(&self.skip),
rename: ::core::clone::Clone::clone(&self.rename),
types: ::core::clone::Clone::clone(&self.types),
}
}
}Clone, #[automatically_derived]impl ::core::default::Default for SerdeErrorSpec {
#[inline]
fn default() -> Self {
SerdeErrorSpec {
shape: ::core::default::Default::default(),
tag: ::core::default::Default::default(),
prefix: ::core::default::Default::default(),
skip: ::core::default::Default::default(),
rename: ::core::default::Default::default(),
types: ::core::default::Default::default(),
}
}
}Default, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
SerdeErrorSpec {
}
#[automatically_derived]impl ::core::cmp::PartialEq for SerdeErrorSpec {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.shape == other.shape && self.tag == other.tag &&
self.prefix == other.prefix && self.skip == other.skip &&
self.rename == other.rename && self.types == other.types
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for SerdeErrorSpec {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Option<syn::Path>>;
let _: ::core::cmp::AssertParamIsEq<Option<String>>;
let _: ::core::cmp::AssertParamIsEq<Option<String>>;
let _: ::core::cmp::AssertParamIsEq<Vec<String>>;
let _: ::core::cmp::AssertParamIsEq<Vec<(String, String)>>;
let _: ::core::cmp::AssertParamIsEq<Vec<(FieldType, String)>>;
}
}Eq)]
3151pub(crate) struct SerdeErrorSpec {
3152/// A named `SerdeErrorShape` (`shape = PATH`), applied before the options
3153 /// below.
3154pub shape: Option<syn::Path>,
3155/// Internally-tagged discriminator field name (`#[serde(tag = "...")]`).
3156pub tag: Option<String>,
3157/// Condition class prefix (family class).
3158pub prefix: Option<String>,
3159/// Payload fields dropped from the condition data.
3160pub skip: Vec<String>,
3161/// Payload fields spliced under another name: `(from, to)`.
3162pub rename: Vec<(String, String)>,
3163/// Payload fields given an atomic R type (`as_character(..)` & co.), in
3164 /// written order.
3165pub types: Vec<(FieldType, String)>,
3166}
31673168/// The R type an `as_*` option gives a payload field.
3169#[derive(#[automatically_derived]impl ::core::fmt::Debug for FieldType {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
FieldType::Logical => "Logical",
FieldType::Integer => "Integer",
FieldType::Double => "Double",
FieldType::Character => "Character",
})
}
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for FieldType {
}
#[automatically_derived]impl ::core::clone::Clone for FieldType {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for FieldType { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for FieldType
{
}
#[automatically_derived]impl ::core::cmp::PartialEq for FieldType {
#[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 FieldType { }Eq)]
3170pub(crate) enum FieldType {
3171 Logical,
3172 Integer,
3173 Double,
3174 Character,
3175}
31763177impl FieldType {
3178const ALL: [FieldType; 4] = [
3179 FieldType::Logical,
3180 FieldType::Integer,
3181 FieldType::Double,
3182 FieldType::Character,
3183 ];
31843185/// The option's name, which is also the `SerdeErrorShape` method's.
3186pub(crate) fn option(self) -> &'static str {
3187match self {
3188 FieldType::Logical => "as_logical",
3189 FieldType::Integer => "as_integer",
3190 FieldType::Double => "as_double",
3191 FieldType::Character => "as_character",
3192 }
3193 }
31943195fn from_path(path: &syn::Path) -> Option<Self> {
3196Self::ALL.into_iter().find(|ty| path.is_ident(ty.option()))
3197 }
3198}
31993200/// The condition's own slots, mirrored from
3201/// `miniextendr_api::condition::RESERVED_CONDITION_FIELDS` (the macros crate
3202/// cannot depend on the API crate). The runtime check remains the backstop.
3203const RESERVED_CONDITION_FIELDS: &[&str] = &["message", "call", "kind"];
32043205const SERDE_ERROR_OPTIONS_HELP: &str = "unknown serde_error option; expected `shape`, `tag`, \
3206 `prefix`, `skip(...)`, `rename(...)`, `as_character(...)`, `as_integer(...)`, \
3207 `as_double(...)` or `as_logical(...)`";
32083209const SERDE_ERROR_SHAPE_HELP: &str = "serde_error shape takes the path of a `SerdeErrorShape` \
3210 const: `shape = ENGINE`";
32113212/// The bare flag / boolean forms: the serde path is not something to switch
3213/// on per function.
3214pub(crate) const SERDE_ERROR_BARE_HELP: &str = "`serde_error` is not a switch: with the `serde` \
3215 feature every `Result<T, E>` whose `E: Serialize + Display` is already classed from its \
3216 serde shape. The attribute only carries options; write `serde_error(shape = ENGINE)`, \
3217 options such as `serde_error(prefix = \"..\", skip(..), as_character(..))`, or drop it";
32183219impl SerdeErrorSpec {
3220/// Parse `serde_error(...)` contents: a comma-separated list of options.
3221 /// Every problem is reported at once.
3222fn from_metas<'a>(
3223 metas: impl IntoIterator<Item = &'a syn::Meta>,
3224 span: proc_macro2::Span,
3225 ) -> syn::Result<Self> {
3226let mut spec = SerdeErrorSpec::default();
3227let mut errors = Vec::new();
3228let mut any = false;
3229for meta in metas {
3230 any = true;
3231 spec.apply(meta, &mut errors);
3232 }
3233if !any {
3234return Err(syn::Error::new(span, SERDE_ERROR_BARE_HELP));
3235 }
3236let mut errors = errors.into_iter();
3237match errors.next() {
3238None => Ok(spec),
3239Some(mut first) => {
3240first.extend(errors);
3241Err(first)
3242 }
3243 }
3244 }
32453246fn apply(&mut self, meta: &syn::Meta, errors: &mut Vec<syn::Error>) {
3247match meta {
3248 syn::Meta::NameValue(nv) if nv.path.is_ident("shape") => match &nv.value {
3249 syn::Expr::Path(syn::ExprPath {
3250 qself: None, path, ..
3251 }) if self.shape.is_none() => self.shape = Some(path.clone()),
3252 syn::Expr::Path(syn::ExprPath { qself: None, .. }) => errors.push(
3253 syn::Error::new_spanned(&nv.value, "serde_error shape is given twice"),
3254 ),
3255 other => errors.push(syn::Error::new_spanned(other, SERDE_ERROR_SHAPE_HELP)),
3256 },
3257 syn::Meta::NameValue(nv) if nv.path.is_ident("tag") => {
3258match non_empty_lit_str(nv, "tag") {
3259Ok(tag) => self.tag = Some(tag),
3260Err(err) => errors.push(err),
3261 }
3262 }
3263 syn::Meta::NameValue(nv) if nv.path.is_ident("prefix") => {
3264match non_empty_lit_str(nv, "prefix") {
3265Ok(prefix) => self.prefix = Some(prefix),
3266Err(err) => errors.push(err),
3267 }
3268 }
3269 syn::Meta::List(list) if list.path.is_ident("skip") => {
3270for lit in field_names(list, "skip", errors) {
3271let name = lit.value();
3272if self.skip.contains(&name) {
3273 errors.push(syn::Error::new_spanned(
3274&lit,
3275::alloc::__export::must_use({
::alloc::fmt::format(format_args!("serde_error skip names `{0}` twice",
name))
})format!("serde_error skip names `{name}` twice"),
3276 ));
3277 } else if let Some(ty) = self.field_type(&name) {
3278 errors.push(both(
3279&lit,
3280 ty.option(),
3281"skip",
3282"a skipped field has no R type",
3283 ));
3284 } else if self.rename.iter().any(|(from, _)| *from == name) {
3285 errors.push(both(
3286&lit,
3287"rename",
3288"skip",
3289"a skipped field has no name to rename",
3290 ));
3291 } else {
3292self.skip.push(name);
3293 }
3294 }
3295 }
3296 syn::Meta::List(list) if list.path.is_ident("rename") => {
3297let pairs = match list.parse_args_with(
3298 syn::punctuated::Punctuated::<RenamePair, ::syn::token::Commasyn::Token![,]>::parse_terminated,
3299 ) {
3300Ok(pairs) => pairs,
3301Err(err) => return errors.push(err),
3302 };
3303if pairs.is_empty() {
3304errors.push(syn::Error::new_spanned(
3305list,
3306"serde_error rename needs at least one pair: `rename(message = \"detail\")`",
3307 ));
3308 }
3309for RenamePair { from, to, span } in pairs {
3310let error = |message: String| syn::Error::new(span, message);
3311if from.is_empty() || to.is_empty() {
3312 errors.push(error("serde_error rename names must not be empty".into()));
3313 } else if RESERVED_CONDITION_FIELDS.contains(&to.as_str()) {
3314 errors.push(error(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("serde_error rename target `{0}` is reserved: `message`, `call` and `kind` are the condition\'s own slots",
to))
})format!(
3315"serde_error rename target `{to}` is reserved: `message`, `call` \
3316 and `kind` are the condition's own slots"
3317)));
3318 } else if self.rename.iter().any(|(f, _)| *f == from) {
3319 errors.push(error(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("serde_error rename names `{0}` twice",
from))
})format!("serde_error rename names `{from}` twice")));
3320 } else if self.rename.iter().any(|(_, t)| *t == to) {
3321 errors.push(error(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("serde_error rename targets `{0}` twice; the condition would carry two `{0}` fields and R would read only the first",
to))
})format!(
3322"serde_error rename targets `{to}` twice; the condition would \
3323 carry two `{to}` fields and R would read only the first"
3324)));
3325 } else if self.skip.contains(&from) {
3326 errors.push(error(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("serde_error names `{0}` in both skip and rename; a skipped field has no name to rename",
from))
})format!(
3327"serde_error names `{from}` in both skip and rename; a skipped \
3328 field has no name to rename"
3329)));
3330 } else {
3331self.rename.push((from, to));
3332 }
3333 }
3334 }
3335 syn::Meta::List(list) if FieldType::from_path(&list.path).is_some() => {
3336let ty = FieldType::from_path(&list.path).expect("matched above");
3337let option = ty.option();
3338for lit in field_names(list, option, errors) {
3339let name = lit.value();
3340match self.field_type(&name) {
3341Some(other) if other == ty => errors.push(syn::Error::new_spanned(
3342&lit,
3343::alloc::__export::must_use({
::alloc::fmt::format(format_args!("serde_error {0} names `{1}` twice",
option, name))
})format!("serde_error {option} names `{name}` twice"),
3344 )),
3345Some(other) => errors.push(both(
3346&lit,
3347 other.option(),
3348 option,
3349"a field has one R type",
3350 )),
3351None if self.skip.contains(&name) => {
3352 errors.push(both(&lit, "skip", option, "a skipped field has no R type"))
3353 }
3354None => self.types.push((ty, name)),
3355 }
3356 }
3357 }
3358 syn::Meta::NameValue(nv) if nv.path.is_ident("skip") => {
3359errors.push(syn::Error::new_spanned(
3360nv,
3361"serde_error skip takes a list of field names: `skip(\"message\")`",
3362 ));
3363 }
3364 syn::Meta::NameValue(nv) if nv.path.is_ident("rename") => {
3365errors.push(syn::Error::new_spanned(
3366nv,
3367"serde_error rename takes `from = \"to\"` pairs: `rename(message = \"detail\")`",
3368 ));
3369 }
3370 syn::Meta::NameValue(nv) if FieldType::from_path(&nv.path).is_some() => {
3371let option = FieldType::from_path(&nv.path)
3372 .expect("matched above")
3373 .option();
3374errors.push(syn::Error::new_spanned(
3375nv,
3376::alloc::__export::must_use({
::alloc::fmt::format(format_args!("serde_error {0} takes a list of field names: `{0}(\"rule\")`",
option))
})format!(
3377"serde_error {option} takes a list of field names: `{option}(\"rule\")`"
3378),
3379 ));
3380 }
3381 other if other.path().is_ident("shape") => {
3382errors.push(syn::Error::new_spanned(other, SERDE_ERROR_SHAPE_HELP));
3383 }
3384 other => {
3385errors.push(syn::Error::new_spanned(
3386other.path(),
3387SERDE_ERROR_OPTIONS_HELP,
3388 ));
3389 }
3390 }
3391 }
33923393/// A method's spec with `shape = Self::X` naming the impl's type: the C
3394 /// wrapper that reads the shape is a free function, where `Self` doesn't
3395 /// resolve. The type ident takes the `Self` token's span.
3396pub(crate) fn with_self_type(&self, ty: &syn::Ident) -> Self {
3397let mut spec = self.clone();
3398if let Some(path) = &mut spec.shape
3399 && path.leading_colon.is_none()
3400 && path.segments.len() > 1
3401&& let Some(first) = path.segments.first_mut()
3402 && first.ident == "Self"
3403{
3404first.ident = syn::Ident::new(&ty.to_string(), first.ident.span());
3405 }
3406spec3407 }
34083409/// The `as_*` option that names `name`, if any.
3410fn field_type(&self, name: &str) -> Option<FieldType> {
3411self.types
3412 .iter()
3413 .find(|(_, n)| n == name)
3414 .map(|(ty, _)| *ty)
3415 }
34163417/// The function's own options as a `SerdeErrorShape` builder chain;
3418 /// `None` when it only names a shape.
3419pub(crate) fn own_shape(&self) -> Option<proc_macro2::TokenStream> {
3420let mut calls = Vec::new();
3421if let Some(tag) = &self.tag {
3422calls.push({
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_dot(&mut _s);
::quote::__private::push_ident(&mut _s, "tag");
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
{
let mut _s = ::quote::__private::TokenStream::new();
::quote::ToTokens::to_tokens(&tag, &mut _s);
_s
});
_s
}quote::quote!(.tag(#tag)));
3423 }
3424if let Some(prefix) = &self.prefix {
3425calls.push({
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_dot(&mut _s);
::quote::__private::push_ident(&mut _s, "prefix");
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
{
let mut _s = ::quote::__private::TokenStream::new();
::quote::ToTokens::to_tokens(&prefix, &mut _s);
_s
});
_s
}quote::quote!(.prefix(#prefix)));
3426 }
3427if !self.skip.is_empty() {
3428let skip = &self.skip;
3429calls.push({
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_dot(&mut _s);
::quote::__private::push_ident(&mut _s, "skip");
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
{
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_and(&mut _s);
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Bracket,
{
let mut _s = ::quote::__private::TokenStream::new();
{
use ::quote::__private::ext::*;
let mut _first = true;
let has_iter = ::quote::__private::HasIterator::<false>;
#[allow(unused_mut)]
let (mut skip, i) = skip.quote_into_iter();
let has_iter = has_iter | i;
<_ as
::quote::__private::CheckHasIterator<true>>::check(has_iter);
while true {
let skip =
match skip.next() {
Some(_x) => ::quote::__private::RepInterp(_x),
None => break,
};
if !_first { ::quote::__private::push_comma(&mut _s); }
_first = false;
::quote::ToTokens::to_tokens(&skip, &mut _s);
}
}
_s
});
_s
});
_s
}quote::quote!(.skip(&[#(#skip),*])));
3430 }
3431if !self.rename.is_empty() {
3432let (from, to): (Vec<&String>, Vec<&String>) =
3433self.rename.iter().map(|(f, t)| (f, t)).unzip();
3434calls.push({
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_dot(&mut _s);
::quote::__private::push_ident(&mut _s, "rename");
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
{
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_and(&mut _s);
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Bracket,
{
let mut _s = ::quote::__private::TokenStream::new();
{
use ::quote::__private::ext::*;
let mut _first = true;
let has_iter = ::quote::__private::HasIterator::<false>;
#[allow(unused_mut)]
let (mut from, i) = from.quote_into_iter();
let has_iter = has_iter | i;
#[allow(unused_mut)]
let (mut to, i) = to.quote_into_iter();
let has_iter = has_iter | i;
<_ as
::quote::__private::CheckHasIterator<true>>::check(has_iter);
while true {
let from =
match from.next() {
Some(_x) => ::quote::__private::RepInterp(_x),
None => break,
};
let to =
match to.next() {
Some(_x) => ::quote::__private::RepInterp(_x),
None => break,
};
if !_first { ::quote::__private::push_comma(&mut _s); }
_first = false;
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
{
let mut _s = ::quote::__private::TokenStream::new();
::quote::ToTokens::to_tokens(&from, &mut _s);
::quote::__private::push_comma(&mut _s);
::quote::ToTokens::to_tokens(&to, &mut _s);
_s
});
}
}
_s
});
_s
});
_s
}quote::quote!(.rename(&[#((#from, #to)),*])));
3435 }
3436for ty in FieldType::ALL {
3437let names: Vec<&String> = self
3438.types
3439 .iter()
3440 .filter(|(t, _)| *t == ty)
3441 .map(|(_, name)| name)
3442 .collect();
3443if !names.is_empty() {
3444let method = match ::quote::__private::IdentFragmentAdapter(&ty.option()) {
arg =>
::quote::__private::mk_ident(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", arg))
}), ::quote::__private::Option::None.or(arg.span())),
}quote::format_ident!("{}", ty.option());
3445 calls.push({
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_dot(&mut _s);
::quote::ToTokens::to_tokens(&method, &mut _s);
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
{
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_and(&mut _s);
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Bracket,
{
let mut _s = ::quote::__private::TokenStream::new();
{
use ::quote::__private::ext::*;
let mut _first = true;
let has_iter = ::quote::__private::HasIterator::<false>;
#[allow(unused_mut)]
let (mut names, i) = names.quote_into_iter();
let has_iter = has_iter | i;
<_ as
::quote::__private::CheckHasIterator<true>>::check(has_iter);
while true {
let names =
match names.next() {
Some(_x) => ::quote::__private::RepInterp(_x),
None => break,
};
if !_first { ::quote::__private::push_comma(&mut _s); }
_first = false;
::quote::ToTokens::to_tokens(&names, &mut _s);
}
}
_s
});
_s
});
_s
}quote::quote!(.#method(&[#(#names),*])));
3446 }
3447 }
3448 (!calls.is_empty())
3449 .then(|| {
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, "condition");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "SerdeErrorShape");
::quote::__private::push_colon2(&mut _s);
::quote::__private::push_ident(&mut _s, "new");
::quote::__private::push_group(&mut _s,
::quote::__private::Delimiter::Parenthesis,
::quote::__private::TokenStream::new());
{
use ::quote::__private::ext::*;
let has_iter = ::quote::__private::HasIterator::<false>;
#[allow(unused_mut)]
let (mut calls, i) = calls.quote_into_iter();
let has_iter = has_iter | i;
<_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
while true {
let calls =
match calls.next() {
Some(_x) => ::quote::__private::RepInterp(_x),
None => break,
};
::quote::ToTokens::to_tokens(&calls, &mut _s);
}
}
_s
}quote::quote!(::miniextendr_api::condition::SerdeErrorShape::new() #(#calls)*))
3450 }
3451}
34523453/// The non-empty string literals of `skip(..)` / `as_*(..)`; problems go to
3454/// `errors`.
3455fn field_names(
3456 list: &syn::MetaList,
3457 option: &str,
3458 errors: &mut Vec<syn::Error>,
3459) -> Vec<syn::LitStr> {
3460let names = match list.parse_args_with(
3461 syn::punctuated::Punctuated::<syn::LitStr, ::syn::token::Commasyn::Token![,]>::parse_terminated,
3462 ) {
3463Ok(names) => names,
3464Err(err) => {
3465errors.push(err);
3466return Vec::new();
3467 }
3468 };
3469if names.is_empty() {
3470errors.push(syn::Error::new_spanned(
3471list,
3472::alloc::__export::must_use({
::alloc::fmt::format(format_args!("serde_error {0} needs at least one field name: `{0}(\"message\")`",
option))
})format!("serde_error {option} needs at least one field name: `{option}(\"message\")`"),
3473 ));
3474 }
3475names3476 .into_iter()
3477 .filter(|lit| {
3478let empty = lit.value().is_empty();
3479if empty {
3480errors.push(syn::Error::new_spanned(
3481lit,
3482::alloc::__export::must_use({
::alloc::fmt::format(format_args!("serde_error {0} field name must not be empty",
option))
})format!("serde_error {option} field name must not be empty"),
3483 ));
3484 }
3485 !empty3486 })
3487 .collect()
3488}
34893490/// A field named by two options that exclude each other.
3491fn both(lit: &syn::LitStr, first: &str, second: &str, why: &str) -> syn::Error {
3492 syn::Error::new_spanned(
3493lit,
3494::alloc::__export::must_use({
::alloc::fmt::format(format_args!("serde_error names `{0}` in both {1} and {2}; {3}",
lit.value(), first, second, why))
})format!(
3495"serde_error names `{}` in both {first} and {second}; {why}",
3496 lit.value()
3497 ),
3498 )
3499}
35003501/// A `tag = "..."` / `prefix = "..."` value: a non-empty string literal.
3502fn non_empty_lit_str(nv: &syn::MetaNameValue, key: &str) -> syn::Result<String> {
3503let val = parse_lit_str(nv, key)?;
3504if val.is_empty() {
3505return Err(syn::Error::new_spanned(
3506&nv.value,
3507::alloc::__export::must_use({
::alloc::fmt::format(format_args!("serde_error {0} must not be empty",
key))
})format!("serde_error {key} must not be empty"),
3508 ));
3509 }
3510Ok(val)
3511}
35123513/// One `from = "to"` entry of `rename(...)`. `from` is an identifier or, for a
3514/// serde-renamed field whose name is not one, a string literal.
3515struct RenamePair {
3516 from: String,
3517 to: String,
3518 span: proc_macro2::Span,
3519}
35203521impl syn::parse::Parsefor RenamePair {
3522fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
3523use syn::ext::IdentExt;
3524let lookahead = input.lookahead1();
3525let (from, span) = if lookahead.peek(syn::LitStr) {
3526let lit: syn::LitStr = input.parse()?;
3527 (lit.value(), lit.span())
3528 } else if lookahead.peek(syn::Ident::peek_any) {
3529let ident = input.call(syn::Ident::parse_any)?;
3530 (ident.to_string(), ident.span())
3531 } else {
3532return Err(lookahead.error());
3533 };
3534let _: ::syn::token::Eqsyn::Token![=] = input.parse()?;
3535let to: syn::LitStr = input.parse()?;
3536Ok(RenamePair {
3537from,
3538 to: to.value(),
3539span,
3540 })
3541 }
3542}
35433544/// Default family class for `serde_error`: `<crate>_error`, from the crate being
3545/// compiled (cargo sets `CARGO_CRATE_NAME` for the rustc invocation that runs
3546/// this proc macro).
3547pub(crate) fn default_serde_error_prefix() -> String {
3548let krate = std::env::var("CARGO_CRATE_NAME").unwrap_or_else(|_| "rust".to_string());
3549::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}_error", krate))
})format!("{krate}_error")3550}
35513552/// The marker type `miniextendr_init!` defines at the crate root. A
3553/// `serde_error_shape!` declaration is an impl keyed by it, which is what lets
3554/// a crate declare a shape for an error type from another crate (#2207).
3555pub(crate) fn init_marker_ident() -> syn::Ident {
3556 syn::Ident::new("__MiniextendrInitMarker", proc_macro2::Span::call_site())
3557}
35583559/// `crate::__MiniextendrInitMarker`, as the generated `Err` arms pass it to
3560/// the API's probe macros. Those resolve it only under the API's `serde`
3561/// feature, where a shape can be declared.
3562pub(crate) fn init_marker_path() -> proc_macro2::TokenStream {
3563let marker = init_marker_ident();
3564{
let mut _s = ::quote::__private::TokenStream::new();
::quote::__private::push_ident(&mut _s, "crate");
::quote::__private::push_colon2(&mut _s);
::quote::ToTokens::to_tokens(&marker, &mut _s);
_s
}quote::quote!(crate::#marker)3565}
35663567/// Parse `serde_error(shape = .., tag = "...", prefix = "...", skip(...), rename(...), as_*(...))`
3568/// given as a `Meta::List`.
3569pub(crate) fn parse_serde_error_list(list: &syn::MetaList) -> syn::Result<SerdeErrorSpec> {
3570use syn::spanned::Spanned;
3571let metas = list.parse_args_with(
3572 syn::punctuated::Punctuated::<syn::Meta, ::syn::token::Commasyn::Token![,]>::parse_terminated,
3573 )?;
3574SerdeErrorSpec::from_metas(&metas, list.span())
3575}
35763577/// Parse the tail of a `serde_error` option inside `parse_nested_meta`. Only
3578/// the option list `(shape = .., tag = "...", skip(...), as_character(...), ...)` is
3579/// accepted; the bare flag and `= true/false` are rejected with
3580/// [`SERDE_ERROR_BARE_HELP`], since the serde path is on for every eligible
3581/// error type under the `serde` feature.
3582pub(crate) fn parse_serde_error_nested(
3583 meta: &syn::meta::ParseNestedMeta,
3584) -> syn::Result<SerdeErrorSpec> {
3585use syn::spanned::Spanned;
3586let input = meta.input;
3587if input.peek(syn::token::Paren) {
3588let content;
3589match ::syn::__private::parse_parens(&input) {
::syn::__private::Ok(parens) => {
content = parens.content;
_ = content;
parens.token
}
::syn::__private::Err(error) => { return ::syn::__private::Err(error); }
};syn::parenthesized!(content in input);
3590let metas =
3591 content.parse_terminated(<syn::Meta as syn::parse::Parse>::parse, ::syn::token::Commasyn::Token![,])?;
3592return SerdeErrorSpec::from_metas(&metas, meta.path.span());
3593 }
3594if input.peek(::syn::token::Eqsyn::Token![=]) {
3595let _: ::syn::token::Eqsyn::Token![=] = input.parse()?;
3596let _: syn::LitBool = input.parse()?;
3597 }
3598Err(meta.error(SERDE_ERROR_BARE_HELP))
3599}
36003601/// Check the `NArgs` parameters of a signature (#1860): at most one, and none
3602/// that a per-parameter option names (`has_options`, keyed by Rust name). The
3603/// parameter is no R argument (the wrapper fills it with `nargs()`), so an
3604/// option would have nothing to act on.
3605///
3606/// Shared by standalone functions (`lib.rs`) and impl / trait methods
3607/// ([`finalize_method_param_attrs`]). Both errors point at the parameter,
3608/// also for a method, whose options are written on the method.
3609pub(crate) fn check_nargs_params(
3610 inputs: &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
3611 has_options: impl Fn(&str) -> bool,
3612) -> syn::Result<()> {
3613let mut first: Option<&syn::Ident> = None;
3614for arg in inputs {
3615let syn::FnArg::Typed(pt) = arg else {
3616continue;
3617 };
3618if !crate::type_inspect::is_nargs_marker(&pt.ty) {
3619continue;
3620 }
3621let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
3622continue;
3623 };
3624let ident = &pat_ident.ident;
3625if let Some(first) = first {
3626return Err(syn::Error::new_spanned(
3627 pt,
3628::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a `#[miniextendr]` function takes at most one `NArgs` parameter: `{0}` already receives `nargs()`, and `{1}` would receive the same count",
first, ident))
})format!(
3629"a `#[miniextendr]` function takes at most one `NArgs` parameter: `{first}` \
3630 already receives `nargs()`, and `{ident}` would receive the same count"
3631),
3632 ));
3633 }
3634if has_options(&crate::naming::ident_name(ident)) {
3635return Err(syn::Error::new_spanned(
3636 pt,
3637::alloc::__export::must_use({
::alloc::fmt::format(format_args!("per-parameter options (`coerce`, `match_arg`, `choices`, `several_ok`, `default`, `no_default`, `no_na`, `inherits`, `not_inherits`, `preconditions`, `formal`) do not apply to the `NArgs` parameter `{0}`: it is no R argument, the generated wrapper fills it with `nargs()`",
ident))
})format!(
3638"per-parameter options (`coerce`, `match_arg`, `choices`, `several_ok`, \
3639 `default`, `no_default`, `no_na`, `inherits`, `not_inherits`, \
3640 `preconditions`, `formal`) do not apply to the `NArgs` parameter \
3641 `{ident}`: it is no R argument, the generated wrapper fills it with \
3642 `nargs()`"
3643),
3644 ));
3645 }
3646 first = Some(ident);
3647 }
3648Ok(())
3649}
36503651/// Check the `LazyDots` parameters of a signature (#1892): `LazyDots` is the
3652/// parameter's whole type, taken by value (`&LazyDots`, `Option<LazyDots>`,
3653/// `Vec<LazyDots>` are refused; `Missing<LazyDots>` is refused by
3654/// [`validate_param_type`]), and no per-parameter option names it
3655/// (`has_options`, keyed by Rust name): the wrapper passes its frame, and
3656/// every option would force the dots or has nothing to act on.
3657///
3658/// Shared by standalone functions (`lib.rs`) and impl methods
3659/// ([`finalize_method_param_attrs`]). A function takes at most one `...`
3660/// either way ([`find_dots_param`]).
3661pub(crate) fn check_lazy_dots_params(
3662 inputs: &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
3663 has_options: impl Fn(&str) -> bool,
3664) -> syn::Result<()> {
3665for arg in inputs {
3666let syn::FnArg::Typed(pt) = arg else {
3667continue;
3668 };
3669if !crate::type_inspect::is_lazy_dots_marker(&pt.ty) {
3670if crate::type_inspect::mentions_lazy_dots(&pt.ty)
3671 && get_missing_inner_type(&pt.ty).is_none()
3672 {
3673return Err(syn::Error::new_spanned(
3674&pt.ty,
3675"`LazyDots` must be the parameter's whole type, taken by value \
3676 (`rest: LazyDots`): the wrapper passes the dots unforced only for that \
3677 shape, and they are always present",
3678 ));
3679 }
3680continue;
3681 }
3682let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
3683continue;
3684 };
3685let ident = &pat_ident.ident;
3686if has_options(&crate::naming::ident_name(ident)) {
3687return Err(syn::Error::new_spanned(
3688 pt,
3689::alloc::__export::must_use({
::alloc::fmt::format(format_args!("per-parameter options (`coerce`, `match_arg`, `choices`, `several_ok`, `default`, `no_default`, `no_na`, `inherits`, `not_inherits`, `preconditions`, `formal`) do not apply to the `LazyDots` parameter `{0}`: it is R\'s `...`, which the wrapper passes unforced",
ident))
})format!(
3690"per-parameter options (`coerce`, `match_arg`, `choices`, `several_ok`, \
3691 `default`, `no_default`, `no_na`, `inherits`, `not_inherits`, \
3692 `preconditions`, `formal`) do not apply to the `LazyDots` parameter \
3693 `{ident}`: it is R's `...`, which the wrapper passes unforced"
3694),
3695 ));
3696 }
3697 }
3698Ok(())
3699}
37003701/// Check the RNG guard parameters of a signature (#2002): `&RngGuard` is
3702/// filled by a `#[miniextendr(rng)]` wrapper (`rng`) with the guard it holds,
3703/// so it needs `rng`, takes no per-parameter option (`has_options`, keyed by
3704/// Rust name: it is no R argument) and appears at most once. Any other shape
3705/// that names `RngGuard` (`&mut RngGuard`, by value, inside another type) is
3706/// refused: the wrapper lends its guard for the call.
3707///
3708/// Shared by standalone functions (`lib.rs`) and inherent methods
3709/// (`ParsedMethod::from_impl_item`). Every error points at the parameter.
3710pub(crate) fn check_rng_guard_params(
3711 inputs: &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
3712 rng: bool,
3713 has_options: impl Fn(&str) -> bool,
3714) -> syn::Result<()> {
3715let mut first: Option<&syn::PatType> = None;
3716for arg in inputs {
3717let syn::FnArg::Typed(pt) = arg else {
3718continue;
3719 };
3720if !crate::type_inspect::is_rng_guard_param(&pt.ty) {
3721if crate::type_inspect::mentions_rng_guard(&pt.ty) {
3722return Err(syn::Error::new_spanned(
3723&pt.ty,
3724"take the RNG guard as `&RngGuard`: a `#[miniextendr(rng)]` wrapper lends \
3725 its guard for the call, so `&mut RngGuard`, `RngGuard` by value or a guard \
3726 inside another type is no parameter it can fill",
3727 ));
3728 }
3729continue;
3730 }
3731if first.is_some() {
3732return Err(syn::Error::new_spanned(
3733 pt,
3734"a `#[miniextendr]` function takes at most one `&RngGuard` parameter: every \
3735 one would receive the same guard",
3736 ));
3737 }
3738if !rng {
3739return Err(syn::Error::new_spanned(
3740 pt,
3741"a `&RngGuard` parameter needs `#[miniextendr(rng)]`: the `rng` wrapper loads \
3742 R's RNG state and passes its guard here. Add `rng` to the `#[miniextendr(...)]` \
3743 options, or call `with_rng(|rng| ...)` in the body",
3744 ));
3745 }
3746if let syn::Pat::Ident(pat_ident) = pt.pat.as_ref()
3747 && has_options(&crate::naming::ident_name(&pat_ident.ident))
3748 {
3749return Err(syn::Error::new_spanned(
3750 pt,
3751::alloc::__export::must_use({
::alloc::fmt::format(format_args!("per-parameter options (`coerce`, `match_arg`, `choices`, `several_ok`, `default`, `no_default`, `no_na`, `inherits`, `not_inherits`, `preconditions`) do not apply to the `&RngGuard` parameter `{0}`: it is no R argument, the `rng` wrapper passes its guard",
pat_ident.ident))
})format!(
3752"per-parameter options (`coerce`, `match_arg`, `choices`, `several_ok`, \
3753 `default`, `no_default`, `no_na`, `inherits`, `not_inherits`, \
3754 `preconditions`) do not apply to the `&RngGuard` parameter `{}`: it is no \
3755 R argument, the `rng` wrapper passes its guard",
3756 pat_ident.ident
3757 ),
3758 ));
3759 }
3760 first = Some(pt);
3761 }
3762Ok(())
3763}
37643765/// Refuse an `RngGuard` parameter on a trait method (#2002), in any shape:
3766/// the trait declaration and a trait impl. A trait method's arguments cross
3767/// the vtable as values its shim converts with `TryFromSexp`, and the guard is
3768/// no R value.
3769pub(crate) fn refuse_rng_guard_in_trait_method(
3770 inputs: &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
3771) -> syn::Result<()> {
3772for arg in inputs {
3773if let syn::FnArg::Typed(pt) = arg
3774 && crate::type_inspect::mentions_rng_guard(&pt.ty)
3775 {
3776return Err(syn::Error::new_spanned(
3777 arg,
3778"a trait method cannot take `&RngGuard`: its arguments cross the trait ABI as \
3779 R values, and the guard is none. Load the state in the body with \
3780 `with_rng(|rng| ...)` instead of the `rng` option, or take the guard on an \
3781 inherent impl method or a standalone function",
3782 ));
3783 }
3784 }
3785Ok(())
3786}
37873788/// Parse `rng(seed = <param>)` (#2198): the parameter, by its Rust name, whose
3789/// value the wrapper passes to `set.seed()`.
3790fn parse_rng_seed(list: &syn::MetaList) -> syn::Result<syn::Ident> {
3791let mut seed: Option<syn::Ident> = None;
3792 list.parse_nested_meta(|meta| {
3793if !meta.path.is_ident("seed") {
3794return Err(meta.error("unknown `rng(...)` option; expected `seed = <parameter>`"));
3795 }
3796let value = meta.value()?;
3797let ident: syn::Ident = value.parse().map_err(|err| {
3798 syn::Error::new(
3799 err.span(),
3800"`rng(seed = ..)` names the seed parameter by its Rust name, as an \
3801 identifier: `rng(seed = seed)`",
3802 )
3803 })?;
3804if seed.replace(ident).is_some() {
3805return Err(meta.error("`seed` is set more than once"));
3806 }
3807Ok(())
3808 })?;
3809seed.ok_or_else(|| {
3810 syn::Error::new_spanned(
3811list,
3812"`rng(...)` takes `seed = <parameter>`; write `rng` alone for the RNG state \
3813 without the seed contract",
3814 )
3815 })
3816}
38173818/// Check `rng(seed = <param>)` (#2198) against a standalone function's
3819/// signature and return the seed's R formal. Every problem is reported at
3820/// once:
3821/// - `seed` names a parameter of `all_inputs`, by its Rust name;
3822/// - the parameter is an R argument the wrapper evaluates: one of the formals
3823/// of `r_inputs` (the signature without the condition-call marker and the
3824/// RNG guard), not `...`, an `NArgs` or a `Quoted` / `Quosure` argument
3825/// (`unevaluated`, by R name), since `set.seed()` forces it;
3826/// - the return can carry the `seed` attribute: a unit return
3827/// (`unit_return`) is `NULL`, which has none.
3828///
3829/// The R name comes from the formal list (`r_formal_names` with `formals`),
3830/// so the prelude names the formal the wrapper has, a declared `formal`
3831/// included (#1842).
3832pub(crate) fn check_rng_seed(
3833 seed: &syn::Ident,
3834 all_inputs: &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
3835 r_inputs: &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
3836 formals: &crate::r_wrapper_builder::Formals,
3837 unevaluated: &[String],
3838 unit_return: bool,
3839) -> syn::Result<String> {
3840let rust_name = crate::naming::ident_name(seed);
3841let is_param = all_inputs.iter().any(|arg| {
3842#[allow(non_exhaustive_omitted_patterns)] match arg {
syn::FnArg::Typed(pt) if
#[allow(non_exhaustive_omitted_patterns)] match pt.pat.as_ref() {
syn::Pat::Ident(p) if
crate::naming::ident_name(&p.ident) == rust_name => true,
_ => false,
} => true,
_ => false,
}matches!(arg, syn::FnArg::Typed(pt) if matches!(
3843 pt.pat.as_ref(),
3844 syn::Pat::Ident(p) if crate::naming::ident_name(&p.ident) == rust_name
3845 ))3846 });
3847let formal = crate::r_wrapper_builder::r_formal_names(r_inputs, formals)
3848 .find(|(_, ident)| crate::naming::ident_name(ident) == rust_name)
3849 .map(|(r_name, _)| r_name)
3850 .filter(|r_name| !unevaluated.contains(r_name));
38513852let mut errors: Vec<syn::Error> = Vec::new();
3853if !is_param {
3854errors.push(syn::Error::new_spanned(
3855seed,
3856::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`rng(seed = {0})` names no parameter of this function; name the parameter whose value goes to `set.seed()`, by its Rust name",
rust_name))
})format!(
3857"`rng(seed = {rust_name})` names no parameter of this function; name the \
3858 parameter whose value goes to `set.seed()`, by its Rust name"
3859),
3860 ));
3861 } else if formal.is_none() {
3862errors.push(syn::Error::new_spanned(
3863seed,
3864::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`rng(seed = {0})` needs an R argument the wrapper evaluates: it passes the value to `set.seed()`. `{0}` is not one (`...`, `NArgs`, a `Call` marker, the `&RngGuard` or a `Quoted` / `Quosure` argument)",
rust_name))
})format!(
3865"`rng(seed = {rust_name})` needs an R argument the wrapper evaluates: it passes \
3866 the value to `set.seed()`. `{rust_name}` is not one (`...`, `NArgs`, a `Call` \
3867 marker, the `&RngGuard` or a `Quoted` / `Quosure` argument)"
3868),
3869 ));
3870 }
3871if unit_return {
3872errors.push(syn::Error::new_spanned(
3873seed,
3874"`rng(seed = ..)` records the seed in the result's `seed` attribute, and a unit \
3875 return is `NULL`, which can't carry one; return the simulated values",
3876 ));
3877 }
3878match errors.into_iter().reduce(|mut all, error| {
3879all.combine(error);
3880all3881 }) {
3882Some(error) => Err(error),
3883None => Ok(formal.expect("checked above")),
3884 }
3885}
38863887/// Refuse `rng(seed = ..)` on an impl or trait method (#2198), spanned on the
3888/// option: the seed contract is written in the R wrapper of a standalone
3889/// function or an `s3(...)` method. `meta` is `rng`, followed by its
3890/// parenthesized options.
3891pub(crate) fn refuse_rng_seed_on_method(
3892 meta: &syn::meta::ParseNestedMeta<'_>,
3893 method: &str,
3894) -> syn::Result<()> {
3895let content;
3896match ::syn::__private::parse_parens(&meta.input) {
::syn::__private::Ok(parens) => {
content = parens.content;
_ = content;
parens.token
}
::syn::__private::Err(error) => { return ::syn::__private::Err(error); }
};syn::parenthesized!(content in meta.input);
3897let _: proc_macro2::TokenStream = content.parse()?;
3898Err(meta.error(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`rng(seed = ..)` is for standalone functions and their `s3(...)` methods, not {0}; write `rng` here, or give the seeded draws a standalone function (`#[miniextendr(rng(seed = seed), s3(generic = \"stats::simulate\", class = \"..\"))]`)",
method))
})format!(
3899"`rng(seed = ..)` is for standalone functions and their `s3(...)` methods, not {method}; \
3900 write `rng` here, or give the seeded draws a standalone function \
3901 (`#[miniextendr(rng(seed = seed), s3(generic = \"stats::simulate\", class = \"..\"))]`)"
3902)))
3903}
39043905/// Refuse a `LazyDots` parameter on a trait method (#1892), in any shape:
3906/// the trait declaration (`#[miniextendr_trait]`) and a trait impl. A trait
3907/// method's arguments cross the vtable as values its shim converts with
3908/// `TryFromSexp`, as for `&Dots`, which trait methods don't take either;
3909/// `LazyDots` is the generated wrapper's frame, which has no such value.
3910pub(crate) fn refuse_lazy_dots_in_trait_method(
3911 inputs: &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
3912) -> syn::Result<()> {
3913for arg in inputs {
3914if let syn::FnArg::Typed(pt) = arg
3915 && crate::type_inspect::mentions_lazy_dots(&pt.ty)
3916 {
3917return Err(syn::Error::new_spanned(
3918&pt.ty,
3919"a trait method cannot take `LazyDots`: its arguments cross the trait ABI as \
3920 converted values, and `LazyDots` is the generated wrapper's frame. Take it on \
3921 an inherent impl method or a standalone function",
3922 ));
3923 }
3924 }
3925Ok(())
3926}
39273928/// The error for `dots = typed_list!(..)` on a function whose `...` is a
3929/// `LazyDots` parameter (#1892): `typed_list!` validates the forced
3930/// `list(...)` of a `&Dots` parameter, and `LazyDots` forces nothing. `None`
3931/// when the dots are `&Dots` (or absent). `span` is the attribute's, else the
3932/// parameter's.
3933pub(crate) fn typed_list_on_lazy_dots(
3934 inputs: &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
3935 span: Option<proc_macro2::Span>,
3936) -> Option<syn::Error> {
3937use syn::spanned::Spanned;
39383939let pt = inputs.iter().find_map(|arg| match arg {
3940 syn::FnArg::Typed(pt) if crate::type_inspect::is_lazy_dots_marker(&pt.ty) => Some(pt),
3941_ => None,
3942 })?;
3943Some(syn::Error::new(
3944span.unwrap_or_else(|| pt.span()),
3945"`dots = typed_list!(..)` validates the forced `list(...)` of a `&Dots` parameter; a \
3946 `LazyDots` parameter passes the dots unforced. Take `&Dots` (or `name: ...`) to \
3947 validate them, or read the `LazyDots` elements yourself",
3948 ))
3949}
39503951/// Check that an S3 method for a replacement generic takes the new value last,
3952/// as `value`.
3953///
3954/// A replacement generic is one whose name ends in `<-` (`$<-`, `[[<-`,
3955/// `names<-`). R calls it with the new value as a named argument
3956/// (`x$f <- v` runs `` `$<-`(x, "f", value = v) ``), and `R CMD check`
3957/// (`tools::checkReplaceFuns()`) requires the last formal of every replacement
3958/// function, registered S3 methods included, to be `value`. The last
3959/// non-receiver parameter of `inputs` that is an R formal (an `NArgs`
3960/// parameter is none, #1860) must therefore become the R formal `value`
3961/// (`_value` does too, as does a declared `formal = "value"`, `formals`); a
3962/// trailing `&Dots` is `...`, so it can't be last. Any
3963/// other generic passes. `fallback` spans the error when there is no
3964/// parameter to point at.
3965///
3966/// Used by standalone `s3(generic = ..., class = ...)` functions (`lib.rs`,
3967/// once the condition-call markers have left the R formals) and by S3
3968/// impl-block instance methods (`miniextendr_impl.rs`).
3969pub(crate) fn check_replacement_value_param(
3970 generic: &str,
3971 inputs: &syn::punctuated::Punctuated<syn::FnArg, syn::token::Comma>,
3972 formals: &crate::r_wrapper_builder::Formals,
3973 fallback: proc_macro2::Span,
3974) -> syn::Result<()> {
3975use syn::spanned::Spanned;
39763977if !generic.ends_with("<-") {
3978return Ok(());
3979 }
3980// The last R formal: an `NArgs` parameter is none (#1860), so `value`
3981 // may come before it.
3982let last = inputs3983 .iter()
3984 .enumerate()
3985 .rev()
3986 .find_map(|(idx, arg)| match arg {
3987 syn::FnArg::Typed(pat_type) if !crate::type_inspect::is_nargs_marker(&pat_type.ty) => {
3988Some((idx, pat_type))
3989 }
3990_ => None,
3991 });
3992let found = match last {
3993Some((idx, _)) if Some(idx) == dots_index(inputs) => "the last R argument is `...`".into(),
3994Some((_, pat_type)) => match pat_type.pat.as_ref() {
3995 syn::Pat::Ident(pat_ident) => {
3996let formal = formals.of_ident(&pat_ident.ident);
3997if formal == "value" {
3998return Ok(());
3999 }
4000::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the last R argument is `{0}`",
formal))
})format!("the last R argument is `{formal}`")4001 }
4002_ => "the last parameter is not a plain name".into(),
4003 },
4004None => "it takes no new-value parameter".to_string(),
4005 };
4006let span = last.map_or(fallback, |(_, pat_type)| pat_type.span());
4007Err(syn::Error::new(
4008span,
4009::alloc::__export::must_use({
::alloc::fmt::format(format_args!("an S3 method for the replacement generic `{0}` must take the new value as its last parameter, named `value`, but {1}. R passes the new value as `value = ` (`x$f <- v` calls `` `$<-`(x, \"f\", value = v) ``), and `R CMD check` requires the last argument of a replacement function to be named `value`.",
generic, found))
})format!(
4010"an S3 method for the replacement generic `{generic}` must take the new value as \
4011 its last parameter, named `value`, but {found}. R passes the new value as \
4012 `value = ` (`x$f <- v` calls `` `$<-`(x, \"f\", value = v) ``), and `R CMD check` \
4013 requires the last argument of a replacement function to be named `value`."
4014),
4015 ))
4016}
40174018#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for ReturnPref {
}
#[automatically_derived]impl ::core::clone::Clone for ReturnPref {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ReturnPref { }Copy, #[automatically_derived]impl ::core::default::Default for ReturnPref {
#[inline]
fn default() -> Self { Self::Auto }
}Default)]
4019/// Preferred return-conversion path for `IntoR`.
4020pub(crate) enum ReturnPref {
4021/// Use the default `IntoR` implementation for the type.
4022#[default]
4023Auto,
4024/// Force list conversion via the `AsList` wrapper.
4025List,
4026/// Force external pointer conversion via the `AsExternalPtr` wrapper.
4027ExternalPtr,
4028/// Force native vector/scalar conversion via the `AsRNative` wrapper.
4029Native,
4030}
40314032/// Parses the comma-separated option list inside `#[miniextendr(...)]`.
4033///
4034/// Supports three syntactic forms for each option:
4035/// - **Bare identifier**: `#[miniextendr(invisible)]`
4036/// - **Name-value**: `#[miniextendr(prefer = "list")]` or `#[miniextendr(invisible = true)]`
4037/// - **Nested list**: `#[miniextendr(s3(generic = "...", class = "..."))]`
4038///
4039/// Options with negated forms (`no_coerce`, `no_strict`, `no_preconditions`) explicitly
4040/// disable the corresponding flag, which is useful for overriding feature-based
4041/// defaults.
4042///
4043/// An empty input (plain `#[miniextendr]`) resolves all options to their feature-based
4044/// defaults (e.g., `coerce-default`, `strict-default`).
4045///
4046/// # Errors
4047///
4048/// Returns a compile error for:
4049/// - Unknown option names (prevents silent typos)
4050/// - Mutually exclusive options (`internal` + `noexport`)
4051/// - Invalid values for key-value options (e.g., bad `prefer` or `c_symbol`)
4052/// - Missing required sub-options (e.g., `s3(...)` without `class`)
4053impl syn::parse::Parsefor MiniextendrFnAttrs {
4054fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
4055use syn::spanned::Spanned;
4056// Use Option<bool> for fields that support feature defaults.
4057 // None = not explicitly set → resolve from cfg!(feature = "...") at end.
4058let mut force_invisible: Option<bool> = None;
4059let mut check_interrupt = false;
4060let mut coerce_all: Option<bool> = None;
4061let mut rng = false;
4062let mut rng_seed = None;
4063let mut unwrap_in_r = false;
4064let mut serialize = false;
4065let mut wrap = None;
4066let mut serde_error: Option<SerdeErrorSpec> = None;
4067let mut preconditions: Option<bool> = None;
4068let mut return_pref = ReturnPref::Auto;
4069let mut return_pref_span: Option<proc_macro2::Span> = None;
4070let mut s3_generic = None;
4071let mut s3_class = None;
4072let mut dots_spec = None;
4073let mut dots_policy = None;
4074let mut dots_span = None;
4075let mut lifecycle = None;
4076let mut strict: Option<bool> = None;
4077let mut internal = false;
4078let mut noexport = false;
4079let mut export = false;
4080let mut doc = None;
4081let mut c_symbol = None;
4082let mut r_name = None;
4083let mut postfix = None;
4084let mut call_attr: Option<crate::r_wrapper_builder::CallAttribution> = None;
4085let mut call_arg = false;
4086let mut r_entry = None;
4087let mut r_post_checks = None;
4088let mut r_on_exit = None;
40894090// Empty input (`#[miniextendr]`) → skip the parse loop and fall through
4091 // to the single Ok(Self {...}) at the bottom; every local is already
4092 // seeded with its default value above.
4093let metas = if input.is_empty() {
4094 syn::punctuated::Punctuated::new()
4095 } else {
4096 syn::punctuated::Punctuated::<syn::Meta, ::syn::token::Commasyn::Token![,]>::parse_terminated(input)?
4097};
40984099for meta in metas {
4100match meta {
4101// Simple identifiers: invisible, visible, check_interrupt, coerce, rng, ...
4102syn::Meta::Path(path) => {
4103if let Some(ident) = path.get_ident() {
4104if ident == "invisible" {
4105 force_invisible = Some(true);
4106 } else if ident == "visible" {
4107 force_invisible = Some(false);
4108 } else if ident == "check_interrupt" {
4109 check_interrupt = true;
4110 } else if ident == "coerce" {
4111 coerce_all = Some(true);
4112 } else if ident == "no_coerce" {
4113 coerce_all = Some(false);
4114 } else if ident == "rng" {
4115 rng = true;
4116 } else if ident == "unwrap_in_r" {
4117 unwrap_in_r = true;
4118 } else if ident == "serialize" {
4119 serialize = true;
4120 } else if ident == "serde_error" {
4121return Err(syn::Error::new_spanned(&path, SERDE_ERROR_BARE_HELP));
4122 } else if ident == "strict" {
4123 strict = Some(true);
4124 } else if ident == "no_strict" {
4125 strict = Some(false);
4126 } else if ident == "preconditions" {
4127 preconditions = Some(true);
4128 } else if ident == "no_preconditions" {
4129 preconditions = Some(false);
4130 } else if ident == "internal" {
4131 internal = true;
4132 } else if ident == "noexport" {
4133 noexport = true;
4134 } else if ident == "export" {
4135 export = true;
4136 } else if ident == "call_arg" {
4137 call_arg = true;
4138 } else {
4139return Err(syn::Error::new_spanned(
4140 ident,
4141::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unknown `#[miniextendr]` option; expected one of: {0}",
FN_BOOL_FLAGS_HELP))
})format!(
4142"unknown `#[miniextendr]` option; expected one of: {FN_BOOL_FLAGS_HELP}"
4143),
4144 ));
4145 }
4146 }
4147 }
4148 syn::Meta::NameValue(nv) => {
4149if nv.path.is_ident("wrap") {
4150let value = parse_lit_str(&nv, "wrap")?;
4151 wrap = Some(crate::return_wrap::parse_system(&syn::LitStr::new(
4152&value,
4153 nv.path.span(),
4154 ))?);
4155continue;
4156 }
4157// Check for boolean flag options: option = true / option = false
4158if let syn::Expr::Lit(syn::ExprLit {
4159 lit: syn::Lit::Bool(lit_bool),
4160 ..
4161 }) = &nv.value
4162 {
4163let val = lit_bool.value;
4164if let Some(ident) = nv.path.get_ident() {
4165if ident == "invisible" {
4166 force_invisible = Some(val);
4167 } else if ident == "visible" {
4168 force_invisible = Some(!val);
4169 } else if ident == "check_interrupt" {
4170 check_interrupt = val;
4171 } else if ident == "coerce" {
4172 coerce_all = Some(val);
4173 } else if ident == "no_coerce" {
4174 coerce_all = Some(!val);
4175 } else if ident == "rng" {
4176 rng = val;
4177 } else if ident == "unwrap_in_r" {
4178 unwrap_in_r = val;
4179 } else if ident == "serialize" {
4180 serialize = val;
4181 } else if ident == "serde_error" {
4182return Err(syn::Error::new_spanned(&nv, SERDE_ERROR_BARE_HELP));
4183 } else if ident == "strict" {
4184 strict = Some(val);
4185 } else if ident == "no_strict" {
4186 strict = Some(!val);
4187 } else if ident == "preconditions" {
4188 preconditions = Some(val);
4189 } else if ident == "no_preconditions" {
4190 preconditions = Some(!val);
4191 } else if ident == "internal" {
4192 internal = val;
4193 } else if ident == "noexport" {
4194 noexport = val;
4195 } else if ident == "export" {
4196 export = val;
4197 } else if ident == "call_arg" {
4198 call_arg = val;
4199 } else {
4200return Err(syn::Error::new_spanned(
4201 ident,
4202::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unknown `#[miniextendr]` option `{0}`; expected one of: {1}",
ident, FN_BOOL_FLAGS_HELP))
})format!(
4203"unknown `#[miniextendr]` option `{ident}`; expected one of: \
4204 {FN_BOOL_FLAGS_HELP}"
4205),
4206 ));
4207 }
4208continue;
4209 }
4210 }
42114212if nv.path.is_ident("prefer") {
4213let v = parse_lit_str(&nv, "prefer")?;
4214 return_pref_span = Some(nv.span());
4215 return_pref = match v.as_str() {
4216"list" => ReturnPref::List,
4217"externalptr" => ReturnPref::ExternalPtr,
4218"vector" | "native" => ReturnPref::Native,
4219"auto" => ReturnPref::Auto,
4220_ => {
4221return Err(syn::Error::new_spanned(
4222&nv.value,
4223"prefer must be one of: auto, list, externalptr, vector/native",
4224 ));
4225 }
4226 };
4227 } else if nv.path.is_ident("dots") {
4228// `dots = typed_list!(...)`, or the role of `...`
4229 // (#2157). The span is kept for the signature checks.
4230dots_span = Some(nv.path.span());
4231match crate::dots_policy::parse_dots_attr(&nv.value)? {
4232crate::dots_policy::DotsAttr::TypedList(spec) => {
4233 dots_spec = Some(spec);
4234 }
4235crate::dots_policy::DotsAttr::Policy(policy) => {
4236 dots_policy = Some(policy);
4237 }
4238 }
4239 } else if nv.path.is_ident("lifecycle") {
4240// lifecycle = "stage"
4241if let Some(spec) = crate::lifecycle::parse_lifecycle_attr(
4242&syn::Meta::NameValue(nv.clone()),
4243 )? {
4244 lifecycle = Some(spec);
4245 }
4246 } else if nv.path.is_ident("doc") {
4247 doc = Some(parse_lit_str(&nv, "doc")?);
4248 } else if nv.path.is_ident("c_symbol") {
4249let val = parse_lit_str(&nv, "c_symbol")?;
4250if val.is_empty()
4251 || (!val.starts_with(|c: char| c.is_ascii_alphabetic())
4252 && !val.starts_with('_'))
4253 {
4254return Err(syn::Error::new_spanned(
4255&nv.value,
4256"c_symbol must be a valid C identifier",
4257 ));
4258 }
4259if !val.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
4260return Err(syn::Error::new_spanned(
4261&nv.value,
4262"c_symbol must be a valid C identifier (alphanumeric and underscore only)",
4263 ));
4264 }
4265 c_symbol = Some(val);
4266 } else if nv.path.is_ident("r_name") {
4267let val = parse_lit_str(&nv, "r_name")?;
4268if val.is_empty() {
4269return Err(syn::Error::new_spanned(
4270&nv.value,
4271"r_name must not be empty",
4272 ));
4273 }
4274 r_name = Some(val);
4275 } else if nv.path.is_ident("postfix") {
4276let val = parse_lit_str(&nv, "postfix")?;
4277 validate_postfix(&val, &nv.value)?;
4278 postfix = Some(val);
4279 } else if nv.path.is_ident("call") {
4280let name = match &nv.value {
4281 syn::Expr::Path(p) => p.path.get_ident().map(|i| i.to_string()),
4282 syn::Expr::Lit(syn::ExprLit {
4283 lit: syn::Lit::Str(s),
4284 ..
4285 }) => Some(s.value()),
4286_ => None,
4287 };
4288let Some(attribution) = name
4289 .as_deref()
4290 .and_then(crate::r_wrapper_builder::CallAttribution::parse_name)
4291else {
4292return Err(syn::Error::new_spanned(
4293&nv.value,
4294"`call = ...` accepts `wrapper` (the call as written, the \
4295 default), `caller` (attribute conditions to the wrapper's \
4296 caller) or `none` (conditions carry no call)",
4297 ));
4298 };
4299if call_attr.is_some() {
4300return Err(syn::Error::new_spanned(
4301&nv,
4302"`call = ...` is set more than once",
4303 ));
4304 }
4305 call_attr = Some(attribution);
4306 } else if nv.path.is_ident("r_entry") {
4307 r_entry = Some(parse_lit_str(&nv, "r_entry")?);
4308 } else if nv.path.is_ident("r_post_checks") {
4309 r_post_checks = Some(parse_lit_str(&nv, "r_post_checks")?);
4310 } else if nv.path.is_ident("r_on_exit") {
4311// Short form: r_on_exit = "expr" → on.exit(expr, add = TRUE)
4312r_on_exit = Some(ROnExit {
4313 expr: parse_lit_str(&nv, "r_on_exit")?,
4314 add: true,
4315 after: true,
4316 });
4317 } else {
4318let key_name = nv
4319 .path
4320 .get_ident()
4321 .map(|i| i.to_string())
4322 .unwrap_or_default();
4323return Err(syn::Error::new_spanned(
4324 nv,
4325::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unknown `#[miniextendr]` key-value option `{0}`. Key-value options are: `prefer = \"...\"`, `dots = typed_list!(...)`, `lifecycle = \"...\"`, `doc = \"...\"`, `c_symbol = \"...\"`, `r_name = \"...\"`, `postfix = \"...\"`, `call = wrapper | caller | none`, `r_entry = \"...\"`, `r_post_checks = \"...\"`, `r_on_exit = \"...\"`",
key_name))
})format!(
4326"unknown `#[miniextendr]` key-value option `{}`. \
4327 Key-value options are: `prefer = \"...\"`, `dots = typed_list!(...)`, \
4328 `lifecycle = \"...\"`, `doc = \"...\"`, `c_symbol = \"...\"`, \
4329 `r_name = \"...\"`, `postfix = \"...\"`, `call = wrapper | caller | none`, `r_entry = \"...\"`, \
4330 `r_post_checks = \"...\"`, \
4331 `r_on_exit = \"...\"`",
4332 key_name,
4333 ),
4334 ));
4335 }
4336 }
4337 syn::Meta::List(list) => {
4338if list.path.is_ident("defaults") {
4339// Ignore defaults(...) - it's handled by impl method parsing
4340 // This allows #[miniextendr(defaults(...))] on impl methods
4341} else if list.path.is_ident("lifecycle") {
4342// lifecycle(stage = "deprecated", when = "0.4.0", ...)
4343if let Some(spec) =
4344crate::lifecycle::parse_lifecycle_attr(&syn::Meta::List(list.clone()))?
4345{
4346 lifecycle = Some(spec);
4347 }
4348 } else if list.path.is_ident("s3") {
4349// Parse s3(generic = "...", class = "...")
4350list.parse_nested_meta(|meta| {
4351if meta.path.is_ident("generic") {
4352let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
4353let value: syn::LitStr = meta.input.parse()?;
4354 s3_generic = Some(crate::naming::parse_generic(&value)?);
4355 } else if meta.path.is_ident("class") {
4356let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
4357let value: syn::LitStr = meta.input.parse()?;
4358 s3_class = Some(value.value());
4359 } else {
4360return Err(
4361 meta.error("unknown s3 option; expected `generic` or `class`")
4362 );
4363 }
4364Ok(())
4365 })?;
4366// Validate: s3 requires class (generic can default to function name)
4367if s3_class.is_none() {
4368return Err(syn::Error::new_spanned(
4369&list,
4370"s3(...) requires `class = \"...\"` to specify the S3 class suffix; \
4371 `generic` is optional and defaults to the function name",
4372 ));
4373 }
4374 } else if list.path.is_ident("r_on_exit") {
4375// Long form: r_on_exit(expr = "...", add = false, after = false)
4376let mut expr = None;
4377let mut add = true;
4378let mut after = true;
4379 list.parse_nested_meta(|meta| {
4380if meta.path.is_ident("expr") {
4381let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
4382let value: syn::LitStr = meta.input.parse()?;
4383 expr = Some(value.value());
4384 } else if meta.path.is_ident("add") {
4385let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
4386let value: syn::LitBool = meta.input.parse()?;
4387 add = value.value;
4388 } else if meta.path.is_ident("after") {
4389let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
4390let value: syn::LitBool = meta.input.parse()?;
4391 after = value.value;
4392 } else {
4393return Err(meta.error(
4394"unknown r_on_exit option; expected `expr`, `add`, or `after`",
4395 ));
4396 }
4397Ok(())
4398 })?;
4399let expr = expr.ok_or_else(|| {
4400 syn::Error::new_spanned(
4401&list,
4402"r_on_exit(...) requires `expr = \"...\"` specifying the R expression",
4403 )
4404 })?;
4405 r_on_exit = Some(ROnExit { expr, add, after });
4406 } else if list.path.is_ident("serde_error") {
4407 serde_error = Some(parse_serde_error_list(&list)?);
4408 } else if list.path.is_ident("rng") {
4409 rng_seed = Some(parse_rng_seed(&list)?);
4410 } else if let Some(ident) = list.path.get_ident() {
4411// Bool-flag parenthesized form (e.g. `strict(true)`) is not
4412 // supported — write `strict` alone or `strict = true` instead.
4413let opt_name = ident.to_string();
4414return Err(syn::Error::new_spanned(
4415&list,
4416::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` does not accept parenthesized arguments. Use `{0}` alone or `{0} = true/false`.",
opt_name))
})format!(
4417"`{opt_name}` does not accept parenthesized arguments. \
4418 Use `{opt_name}` alone or `{opt_name} = true/false`.",
4419 ),
4420 ));
4421 } else {
4422// path(something) where path is not a single ident
4423return Err(syn::Error::new_spanned(
4424 list,
4425::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unrecognized nested option. Nested options are: {0}",
FN_NESTED_OPTIONS_HELP))
})format!(
4426"unrecognized nested option. Nested options are: {FN_NESTED_OPTIONS_HELP}"
4427),
4428 ));
4429 }
4430 }
4431 }
4432 }
44334434// Validate: `internal` and `noexport` are redundant together
4435if internal && noexport {
4436return Err(syn::Error::new(
4437 proc_macro2::Span::call_site(),
4438"`internal` and `noexport` cannot be used together. \
4439 `internal` already suppresses @export and also adds @keywords internal. \
4440 Use `internal` alone to mark as internal, or `noexport` alone to only suppress export.",
4441 ));
4442 }
44434444// Validate: `export` conflicts with `noexport` and `internal`
4445if export && noexport {
4446return Err(syn::Error::new(
4447 proc_macro2::Span::call_site(),
4448"`export` and `noexport` are contradictory.",
4449 ));
4450 }
4451if export && internal {
4452return Err(syn::Error::new(
4453 proc_macro2::Span::call_site(),
4454"`export` and `internal` are contradictory.",
4455 ));
4456 }
44574458// Validate: `r_name` is incompatible with S3 naming (`s3(generic/class)`)
4459 // Validate: `postfix` derives the wrapper name from the Rust name; it
4460 // cannot combine with another naming source.
4461if postfix.is_some() && r_name.is_some() {
4462return Err(syn::Error::new(
4463 proc_macro2::Span::call_site(),
4464"`postfix` and `r_name` both set the R wrapper name; use one of them.",
4465 ));
4466 }
4467if postfix.is_some() && (s3_generic.is_some() || s3_class.is_some()) {
4468return Err(syn::Error::new(
4469 proc_macro2::Span::call_site(),
4470"`postfix` cannot be used with `s3(generic = ..., class = ...)`. \
4471 S3 method names are always `generic.class`.",
4472 ));
4473 }
44744475// Validate: `call = caller` is for internal entry points only.
4476use crate::r_wrapper_builder::CallAttribution;
4477if call_attr == Some(CallAttribution::Caller) && !(noexport || internal) {
4478return Err(syn::Error::new(
4479 proc_macro2::Span::call_site(),
4480"`call = caller` attributes conditions to the wrapper's caller, which is only \
4481 meaningful for a package-internal entry point; add `noexport` or `internal`.",
4482 ));
4483 }
4484// `call_arg` (#1834): a `.call` formal whose default is the wrapper's
4485 // own call. A `caller` wrapper already has the formal, defaulting to
4486 // the caller's call, and an S3 method can't take a formal its generic
4487 // lacks.
4488if call_arg && call_attr == Some(CallAttribution::Caller) {
4489return Err(syn::Error::new(
4490 proc_macro2::Span::call_site(),
4491"`call_arg` cannot be combined with `call = caller`: a `caller` wrapper already \
4492 takes `.call`, where NULL means the caller's call. Keep `call = caller`, or drop \
4493 it so that NULL means this function's own call.",
4494 ));
4495 }
4496// `call = none` (#1851) passes no call, so there is nothing for a
4497 // `.call` argument to replace.
4498if call_arg && call_attr == Some(CallAttribution::NoCall) {
4499return Err(syn::Error::new(
4500 proc_macro2::Span::call_site(),
4501"`call_arg` cannot be combined with `call = none`: `.call` names the call the \
4502 conditions report, and `none` reports none. Keep one of them.",
4503 ));
4504 }
4505if call_arg && (s3_generic.is_some() || s3_class.is_some()) {
4506return Err(syn::Error::new(
4507 proc_macro2::Span::call_site(),
4508"`call_arg` cannot be used with `s3(...)`: it adds a `.call` formal, and an S3 \
4509 method can't take a formal its generic lacks.",
4510 ));
4511 }
4512if r_name.is_some() && (s3_generic.is_some() || s3_class.is_some()) {
4513return Err(syn::Error::new(
4514 proc_macro2::Span::call_site(),
4515"`r_name` cannot be used with `s3(generic = ..., class = ...)`. \
4516 S3 method names are always `generic.class`. Use `generic` and `class` instead.",
4517 ));
4518 }
45194520if serialize && (unwrap_in_r || serde_error.is_some()) {
4521return Err(syn::Error::new(
4522 proc_macro2::Span::call_site(),
4523"`serialize` cannot be combined with `unwrap_in_r` or `serde_error`: it serializes the complete return value, including any Result variant",
4524 ));
4525 }
45264527// Validate: `serde_error` classes the raised condition; `unwrap_in_r`
4528 // never raises (the Result is returned as a value), so combining them
4529 // is a contradiction.
4530if serde_error.is_some() && unwrap_in_r {
4531return Err(syn::Error::new(
4532 proc_macro2::Span::call_site(),
4533"`serde_error` cannot be used with `unwrap_in_r`: `unwrap_in_r` returns the \
4534 `Result` to R as a value, so there is no raised condition to class.",
4535 ));
4536 }
45374538Ok(Self {
4539force_invisible,
4540check_interrupt,
4541 coerce_all: coerce_all.unwrap_or(falsecfg!(feature = "coerce-default")),
4542 rng: rng || rng_seed.is_some(),
4543rng_seed,
4544unwrap_in_r,
4545serialize,
4546wrap,
4547serde_error,
4548preconditions,
4549 call_attribution: call_attr,
4550call_arg,
4551return_pref,
4552return_pref_span,
4553s3_generic,
4554s3_class,
4555dots_spec,
4556dots_policy,
4557dots_span,
4558lifecycle,
4559 strict: strict.unwrap_or(falsecfg!(feature = "strict-default")),
4560internal,
4561noexport,
4562export,
4563doc,
4564c_symbol,
4565r_name,
4566postfix,
4567r_entry,
4568r_post_checks,
4569r_on_exit,
4570 })
4571 }
4572}
4573// endregion