Skip to main content

miniextendr_macros/
miniextendr_fn.rs

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
9
10use crate::r_wrapper_const_ident_for;
11
12// region: Coercion analysis
13
14/// 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.
18    Numeric,
19    /// Keep logical scalars and additionally accept integer zero or one.
20    Bool,
21    /// Keep logical vectors and additionally accept integer zeros and ones.
22    BoolVec,
23    /// Native `i32`: keep `INTSXP`, additionally accept whole-valued doubles,
24    /// logicals, and raws.
25    NativeInt,
26    /// Native `Vec<i32>`: element-wise form of [`Self::NativeInt`].
27    NativeIntVec,
28    /// Native `f64`: keep `REALSXP`, additionally accept integers, logicals, and raws.
29    NativeReal,
30    /// Native `Vec<f64>`: element-wise form of [`Self::NativeReal`].
31    NativeRealVec,
32    /// `Option<bool>`: `NULL` and `NA` read `None`, any other value converts
33    /// as [`Self::Bool`] (#2274).
34    OptionBool,
35    /// `Vec<Option<bool>>`: element-wise form of [`Self::OptionBool`].
36    OptionBoolVec,
37    /// `Option<i32>`: `NULL` and `NA` read `None`, any other value converts
38    /// as [`Self::NativeInt`].
39    OptionNativeInt,
40    /// `Vec<Option<i32>>`: element-wise form of [`Self::OptionNativeInt`].
41    OptionNativeIntVec,
42    /// `Option<f64>`: `NULL` and `NA` read `None`, any other value converts
43    /// as [`Self::NativeReal`].
44    OptionNativeReal,
45    /// `Vec<Option<f64>>`: element-wise form of [`Self::OptionNativeReal`].
46    OptionNativeRealVec,
47}
48
49impl 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`.
64    pub(crate) fn from_type(ty: &syn::Type) -> Option<Self> {
65        let ty = get_missing_inner_type(ty).unwrap_or(ty);
66        let (ty, top_optional) = match crate::type_inspect::optional_inner_type(ty) {
67            Some(inner) => (inner, true),
68            None => (ty, false),
69        };
70        let syn::Type::Path(type_path) = ty else {
71            return None;
72        };
73        let mut seg = type_path.path.segments.last()?;
74        let is_vec = !top_optional && seg.ident == "Vec";
75        if is_vec {
76            seg = type_argument_segment(seg)?;
77        }
78        let is_option = top_optional || seg.ident == "Option";
79        if is_vec && is_option {
80            seg = type_argument_segment(seg)?;
81        }
82        match (seg.ident.to_string().as_str(), is_vec, is_option) {
83            ("i8" | "i16" | "u16" | "u32" | "i64" | "u64" | "isize" | "usize" | "f32", _, _) => {
84                Some(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    }
101
102    /// The `miniextendr_api::from_r` helper this mapping converts through,
103    /// or `None` for [`Self::Numeric`], whose `TryFromSexp` impls already read
104    /// every source.
105    pub(crate) fn converter(&self) -> Option<&'static str> {
106        Some(match self {
107            Self::Numeric => return None,
108            Self::Bool => "try_from_sexp_coerced_bool",
109            Self::BoolVec => "try_from_sexp_coerced_bool_vec",
110            Self::NativeInt => "try_from_sexp_coerced_i32",
111            Self::NativeIntVec => "try_from_sexp_coerced_i32_vec",
112            Self::NativeReal => "try_from_sexp_coerced_f64",
113            Self::NativeRealVec => "try_from_sexp_coerced_f64_vec",
114            Self::OptionBool => "try_from_sexp_coerced_option_bool",
115            Self::OptionBoolVec => "try_from_sexp_coerced_option_bool_vec",
116            Self::OptionNativeInt => "try_from_sexp_coerced_option_i32",
117            Self::OptionNativeIntVec => "try_from_sexp_coerced_option_i32_vec",
118            Self::OptionNativeReal => "try_from_sexp_coerced_option_f64",
119            Self::OptionNativeRealVec => "try_from_sexp_coerced_option_f64_vec",
120        })
121    }
122}
123
124/// 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> {
127    let syn::PathArguments::AngleBracketed(args) = &seg.arguments else {
128        return None;
129    };
130    let syn::GenericArgument::Type(syn::Type::Path(inner)) = args.args.first()? else {
131        return None;
132    };
133    inner.path.segments.last()
134}
135
136/// 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 {
141    let 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(
149        pat_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}",
156            crate::type_inspect::type_display(&pat_type.ty)
157        ),
158    )
159}
160
161// endregion
162
163// region: Type inspection helpers
164
165/// 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<()> {
170    if let Some(unsafety) = sig.unsafety {
171        return Err(syn::Error::new_spanned(
172            unsafety,
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    }
180    Ok(())
181}
182
183/// 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 {
188    match ty {
189        syn::Type::Path(tp) => tp
190            .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}
199
200/// 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.
204    Forced,
205    /// `LazyDots`: the wrapper passes its own frame, `environment()`, and
206    /// nothing is forced (#1892).
207    Lazy,
208}
209
210impl DotsKind {
211    /// The parameter type as written, for diagnostics.
212    pub(crate) fn type_name(self) -> &'static str {
213        match self {
214            Self::Forced => "&Dots",
215            Self::Lazy => "LazyDots",
216        }
217    }
218
219    /// The `.Call()` argument the R wrapper passes for the dots.
220    pub(crate) fn r_call_arg(self) -> &'static str {
221        match self {
222            Self::Forced => "list(...)",
223            Self::Lazy => "environment()",
224        }
225    }
226}
227
228/// 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> {
233    if crate::type_inspect::is_lazy_dots_marker(ty) {
234        Some(DotsKind::Lazy)
235    } else if type_ends_with(ty, "Dots") {
236        Some(DotsKind::Forced)
237    } else {
238        None
239    }
240}
241
242/// 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 {
245    dots_kind(ty).is_some()
246}
247
248/// 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<()> {
262    use syn::spanned::Spanned;
263
264    let Some(variadic) = sig.variadic.take() else {
265        return Ok(());
266    };
267    if let Some(syn::FnArg::Typed(existing)) = dots_index(&sig.inputs).map(|idx| &sig.inputs[idx]) {
268        let kind = dots_kind(existing.ty.as_ref()).map_or("&Dots", DotsKind::type_name);
269        let 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        };
273        return Err(syn::Error::new(
274            variadic.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    }
278    let ident = match variadic.pat.map(|(pat, _)| *pat) {
279        Some(syn::Pat::Ident(pat_ident)) => pat_ident.ident,
280        // `_: ...` (rustc's fix for a bare `...`) and a bare `...`.
281        Some(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.
284            for arg in &sig.inputs {
285                let syn::FnArg::Typed(pat_type) = arg else {
286                    continue;
287                };
288                if let syn::Pat::Ident(pat_ident) = pat_type.pat.as_ref()
289                    && pat_ident.ident == "__miniextendr_dots"
290                {
291                    return 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        }
300        Some(pat) => {
301            return Err(syn::Error::new(
302                pat.span(),
303                "variadic pattern must be a simple identifier (`args: ...`) or `_` (`_: ...`)",
304            ));
305        }
306    };
307    sig.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));
309    Ok(())
310}
311
312/// 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> {
320    inputs
321        .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}
324
325/// 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>> {
340    use syn::spanned::Spanned;
341
342    let mut found: Option<(syn::Ident, DotsKind)> = None;
343    for arg in inputs {
344        let syn::FnArg::Typed(pat_type) = arg else {
345            continue;
346        };
347        let Some(kind) = dots_kind(pat_type.ty.as_ref()) else {
348            continue;
349        };
350        let syn::Pat::Ident(pat_ident) = pat_type.pat.as_ref() else {
351            return 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        };
359        let ident = &pat_ident.ident;
360        if let Some((first, first_kind)) = &found {
361            let 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            };
374            return Err(syn::Error::new(ident.span(), msg));
375        }
376        found = Some((ident.clone(), kind));
377    }
378    Ok(found.map(|(ident, _)| ident))
379}
380
381/// Check if a type is `Missing<T>`.
382pub(crate) fn is_missing_type(ty: &syn::Type) -> bool {
383    type_ends_with(ty, "Missing")
384}
385
386/// 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 {
394    match ty {
395        syn::Type::Path(tp) => {
396            let Some(seg) = tp.path.segments.last() else {
397                return false;
398            };
399            if seg.ident == "Vec" {
400                return true;
401            }
402            if seg.ident == "Box" {
403                let syn::PathArguments::AngleBracketed(args) = &seg.arguments else {
404                    return false;
405                };
406                return #[allow(non_exhaustive_omitted_patterns)] match args.args.first() {
    Some(syn::GenericArgument::Type(syn::Type::Slice(_))) => true,
    _ => false,
}matches!(
407                    args.args.first(),
408                    Some(syn::GenericArgument::Type(syn::Type::Slice(_)))
409                );
410            }
411            false
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}
419
420/// 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> {
424    let syn::Type::Path(tp) = ty else {
425        return None;
426    };
427    let seg = tp.path.segments.last()?;
428    if seg.ident != "Missing" {
429        return None;
430    }
431    let syn::PathArguments::AngleBracketed(args) = &seg.arguments else {
432        return None;
433    };
434    if let Some(syn::GenericArgument::Type(inner)) = args.args.first() {
435        Some(inner)
436    } else {
437        None
438    }
439}
440
441/// 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<()> {
447    if crate::return_wrap::contains_marker(ty) {
448        return Err(syn::Error::new_spanned(
449            ty,
450            "class return markers are return-position only",
451        ));
452    }
453    if let Some(err) = crate::type_inspect::visibility_marker_error(ty, "argument") {
454        return Err(err);
455    }
456    if let Some(inner) = get_missing_inner_type(ty) {
457        if is_missing_type(inner) {
458            return Err(syn::Error::new(
459                span,
460                "Missing<T> cannot be nested; use Missing<T> with the inner type directly",
461            ));
462        }
463        if crate::type_inspect::is_lazy_dots_marker(inner) {
464            return Err(syn::Error::new(
465                span,
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        }
470        if is_dots_type(inner) {
471            return Err(syn::Error::new(
472                span,
473                "Missing<T> cannot wrap Dots; variadic parameters (...) are always present when called",
474            ));
475        }
476    }
477    Ok(())
478}
479
480/// 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<()> {
502    if attr.has_convert {
503        validate_convert_param(
504            ty,
505            attr.has_coerce || attr.has_match_arg || attr.choices.is_some(),
506        )?;
507    }
508    if attr.has_no_default
509        && let Some(msg) = no_default_conflict(
510            param_name,
511            attr.has_match_arg || attr.choices.is_some(),
512            attr.default_value.is_some(),
513            false,
514        )
515    {
516        return Err(syn::Error::new(span, msg));
517    }
518    if attr.has_coerce && attr.has_match_arg {
519        return Err(syn::Error::new(
520            span,
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    }
528    if attr.has_coerce && attr.choices.is_some() {
529        return Err(syn::Error::new(
530            span,
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    }
538    if attr.choices.is_some() && attr.default_value.is_some() {
539        return Err(syn::Error::new(
540            span,
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    }
548    if attr.has_match_arg && attr.choices.is_some() {
549        return Err(syn::Error::new(
550            span,
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    }
559    if attr.has_several_ok && attr.choices.is_none() && !attr.has_match_arg {
560        return Err(syn::Error::new(
561            span,
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    }
569    if is_dots && !attr.checks.is_empty() {
570        return Err(syn::Error::new(
571            span,
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    }
579    for check in [ClassCheck::Inherits, ClassCheck::NotInherits] {
580        if let Some(classes) = check.classes(&attr.checks)
581            && (classes.is_empty() || classes.iter().any(String::is_empty))
582        {
583            let key = check.keyword();
584            return 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    }
593    if let Some(msg) = attr.checks.class_conflict(param_name) {
594        return Err(syn::Error::new(span, msg));
595    }
596    if is_dots && attr.default_value.is_some() {
597        return Err(syn::Error::new(
598            span,
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    }
605    if is_dots && let Some(formal) = &attr.formal {
606        return Err(dots_formal_error(formal, param_name));
607    }
608    Ok(())
609}
610
611/// 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> {
623    let (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    };
634    if !is_choice {
635        return 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    }
641    if has_default {
642        return 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    }
647    None
648}
649
650/// 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(
653        formal.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}
660
661// endregion
662
663// region: Per-parameter attribute parsing
664
665/// 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";
673
674/// 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\"`";
677
678/// 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";
681
682/// 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`).
691    pub has_coerce: bool,
692    /// Use the reference type's conversion instead of borrowing an ExternalPtr.
693    pub has_convert: bool,
694    /// Whether `match_arg` was present, generating R `match.arg()` validation for
695    /// string parameters against a set of allowed values.
696    pub 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).
699    pub default_value: Option<(String, proc_macro2::Span)>,
700    /// Choices for string parameters: `#[miniextendr(choices("a", "b", "c"))]`.
701    pub 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`.
704    pub 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`.
708    pub 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`]).
713    pub 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.
717    pub preconditions: Option<bool>,
718    /// `formal = "conf.int"`: the parameter's R formal (#1842), checked by
719    /// [`crate::r_wrapper_builder::check_r_formals`].
720    pub formal: Option<syn::LitStr>,
721}
722
723impl 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.
729    pub(crate) fn merge(&mut self, other: PerParamMiniextendrAttr) -> Result<(), String> {
730        if let Some(formal) = other.formal {
731            if self.formal.is_some() {
732                return Err(FORMAL_TWICE.to_string());
733            }
734            self.formal = Some(formal);
735        }
736        if other.preconditions.is_some() {
737            self.preconditions = other.preconditions;
738        }
739        self.has_coerce |= other.has_coerce;
740        self.has_convert |= other.has_convert;
741        self.has_match_arg |= other.has_match_arg;
742        self.has_several_ok |= other.has_several_ok;
743        self.has_no_default |= other.has_no_default;
744        if self.default_value.is_none() {
745            self.default_value = other.default_value;
746        }
747        if self.choices.is_none() {
748            self.choices = other.choices;
749        }
750        self.checks.merge(other.checks)
751    }
752}
753
754/// 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>> {
774    use syn::spanned::Spanned;
775    if !attr.path().is_ident("miniextendr") {
776        return Ok(None);
777    }
778
779    let syn::Meta::List(meta_list) = &attr.meta else {
780        return Ok(None);
781    };
782
783    let mut result = PerParamMiniextendrAttr::default();
784    let mut is_per_param = false;
785
786    let Ok(metas) = meta_list.parse_args_with(
787        syn::punctuated::Punctuated::<syn::Meta, ::syn::token::Commasyn::Token![,]>::parse_terminated,
788    ) else {
789        return Ok(None);
790    };
791
792    for meta in &metas {
793        match meta {
794            syn::Meta::Path(path) => {
795                if 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) => {
823                if 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.
833                    let syn::Expr::Lit(syn::ExprLit {
834                        lit: syn::Lit::Str(lit_str),
835                        ..
836                    }) = &nv.value
837                    else {
838                        return Err(syn::Error::new_spanned(&nv.value, FORMAL_NOT_STRING));
839                    };
840                    if result.formal.replace(lit_str.clone()).is_some() {
841                        return 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                {
859                    return 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) => {
871                if list.path.is_ident("choices") {
872                    // Parse choices("a", "b", "c") — a comma-separated list of string literals
873                    let choice_lits = match list.parse_args_with(
874                        syn::punctuated::Punctuated::<syn::LitStr, ::syn::token::Commasyn::Token![,]>::parse_terminated,
875                    ) {
876                        Ok(lits) => lits,
877                        Err(_) => continue,
878                    };
879                    let 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.
885                    let 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 = "...")
893                    let 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    }
904
905    if !is_per_param {
906        return Ok(None);
907    }
908    Ok(Some(result))
909}
910
911/// 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}
920
921impl ClassCheck {
922    /// The check `path` names, if it is `inherits` or `not_inherits`.
923    pub(crate) fn of(path: &syn::Path) -> Option<Self> {
924        if path.is_ident("inherits") {
925            Some(Self::Inherits)
926        } else if path.is_ident("not_inherits") {
927            Some(Self::NotInherits)
928        } else {
929            None
930        }
931    }
932
933    /// The attribute keyword, for error messages.
934    fn keyword(self) -> &'static str {
935        match self {
936            Self::Inherits => "inherits",
937            Self::NotInherits => "not_inherits",
938        }
939    }
940
941    /// The `when(...)` hints in this check's list of options, for errors:
942    /// only `inherits` takes them.
943    fn hints_option(self) -> &'static str {
944        match self {
945            Self::Inherits => ", `when(...)` hints",
946            Self::NotInherits => "",
947        }
948    }
949
950    /// The error for an unknown option `key` in a parameter-level
951    /// `inherits(...)` / `not_inherits(...)`.
952    fn 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 = \"...\"`",
956            self.keyword(),
957            self.hints_option()
958        )
959    }
960
961    /// The error for an unknown option in a method-level
962    /// `inherits(p(...))` / `not_inherits(p(...))`.
963    fn 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 = \"...\"`",
967            self.keyword(),
968            self.hints_option()
969        )
970    }
971
972    /// This check's classes in `checks`, if it is requested.
973    fn classes(self, checks: &crate::r_preconditions::ExplicitChecks) -> Option<&[String]> {
974        match self {
975            Self::Inherits => checks.inherits.as_deref(),
976            Self::NotInherits => checks.not_inherits.as_deref(),
977        }
978    }
979
980    /// This check's classes in `checks`, to add to.
981    fn classes_mut(
982        self,
983        checks: &mut crate::r_preconditions::ExplicitChecks,
984    ) -> &mut Option<Vec<String>> {
985        match self {
986            Self::Inherits => &mut checks.inherits,
987            Self::NotInherits => &mut checks.not_inherits,
988        }
989    }
990
991    /// The checks holding this check with `classes` and `message`.
992    fn checks(
993        self,
994        classes: Vec<String>,
995        message: Option<String>,
996    ) -> crate::r_preconditions::ExplicitChecks {
997        let mut checks = crate::r_preconditions::ExplicitChecks::default();
998        *self.classes_mut(&mut checks) = Some(classes);
999        match self {
1000            Self::Inherits => checks.inherits_message = message,
1001            Self::NotInherits => checks.not_inherits_message = message,
1002        }
1003        checks
1004    }
1005}
1006
1007/// `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> {
1021    use syn::parse::Parser as _;
1022    let key_word = check.keyword();
1023    let mut classes = Vec::new();
1024    let mut message = None;
1025    let mut hints = Vec::new();
1026    let parser = |input: syn::parse::ParseStream| -> syn::Result<()> {
1027        while !input.is_empty() {
1028            if input.peek(syn::LitStr) {
1029                let class: syn::LitStr = input.parse()?;
1030                classes.push(class.value());
1031            } else {
1032                let key: syn::Ident = input.parse()?;
1033                if key == "when" && input.peek(syn::token::Paren) {
1034                    if check != ClassCheck::Inherits {
1035                        return Err(syn::Error::new_spanned(&key, WHEN_ON_NOT_INHERITS));
1036                    }
1037                    let content;
1038                    match ::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![=]>()?;
1042                    let value: syn::LitStr = input.parse()?;
1043                    if key == "class" {
1044                        classes.push(value.value());
1045                    } else if key == "message" {
1046                        set_check_message(&mut message, &value, key_word)?;
1047                    } else {
1048                        return Err(syn::Error::new_spanned(&key, check.unknown_option(&key)));
1049                    }
1050                }
1051            }
1052            if input.is_empty() {
1053                break;
1054            }
1055            input.parse::<::syn::token::Commasyn::Token![,]>()?;
1056        }
1057        Ok(())
1058    };
1059    parser.parse2(list.tokens.clone())?;
1060    if message.is_some() && classes.is_empty() {
1061        return Err(syn::Error::new_spanned(
1062            list,
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    }
1069    if !hints.is_empty() && classes.is_empty() {
1070        return Err(syn::Error::new_spanned(
1071            list,
1072            "`when(...)` in `inherits(...)` needs a class to check, e.g. \
1073             `inherits(class = \"pkg_obj\", when(class = \"data.frame\", message = \"...\"))`",
1074        ));
1075    }
1076    let mut checks = check.checks(classes, message);
1077    checks.inherits_hints = hints;
1078    Ok(checks)
1079}
1080
1081/// 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";
1085
1086/// 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> {
1094    let mut classes = Vec::new();
1095    let mut message = None;
1096    while !content.is_empty() {
1097        if content.peek(syn::LitStr) {
1098            let class: syn::LitStr = content.parse()?;
1099            classes.push(hint_class(&class)?);
1100        } else {
1101            let opt: syn::Ident = content.parse()?;
1102            content.parse::<::syn::token::Eqsyn::Token![=]>()?;
1103            let value: syn::LitStr = content.parse()?;
1104            if opt == "class" {
1105                classes.push(hint_class(&value)?);
1106            } else if opt == "message" {
1107                set_hint_message(&mut message, &value)?;
1108            } else {
1109                return 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        }
1118        if content.is_empty() {
1119            break;
1120        }
1121        content.parse::<::syn::token::Commasyn::Token![,]>()?;
1122    }
1123    inherits_hint(classes, message).map_err(|msg| syn::Error::new_spanned(key, msg))
1124}
1125
1126/// One class name of a parameter-level `when(...)` hint: not empty.
1127fn hint_class(value: &syn::LitStr) -> syn::Result<String> {
1128    let class = value.value();
1129    if class.is_empty() {
1130        return Err(syn::Error::new(
1131            value.span(),
1132            "a class name in `when(...)` must not be empty",
1133        ));
1134    }
1135    Ok(class)
1136}
1137
1138/// 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> {
1143    if classes.is_empty() {
1144        return Err("`when(...)` needs the classes it is for, e.g. \
1145             `when(class = \"data.frame\", message = \"...\")`");
1146    }
1147    let Some(message) = message else {
1148        return Err(
1149            "`when(...)` needs a `message = \"...\"`: the hint a value of its classes gets, \
1150             e.g. `when(class = \"data.frame\", message = \"...\")`",
1151        );
1152    };
1153    Ok(crate::r_preconditions::InheritsHint { classes, message })
1154}
1155
1156/// `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> {
1159    let mut message = None;
1160    list.parse_nested_meta(|opt| parse_no_na_option(&opt, &mut message))?;
1161    Ok(crate::r_preconditions::ExplicitChecks {
1162        no_na: true,
1163        no_na_message: message,
1164        ..Default::default()
1165    })
1166}
1167
1168/// 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<()> {
1174    if opt.path.is_ident("message") {
1175        let value: syn::LitStr = opt.value()?.parse()?;
1176        set_check_message(message, &value, "no_na")
1177    } else {
1178        Err(opt.error("unknown `no_na` option; expected `message = \"...\"`"))
1179    }
1180}
1181
1182/// 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<()> {
1190    set_message(
1191        slot,
1192        value,
1193        check,
1194        "leave it out to get the generated message",
1195    )
1196}
1197
1198/// 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<()> {
1202    set_message(
1203        slot,
1204        value,
1205        "when",
1206        "it is the message a value of those classes gets",
1207    )
1208}
1209
1210/// 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<()> {
1218    let text = value.value();
1219    if slot.is_some() {
1220        return Err(syn::Error::new(
1221            value.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    }
1225    if text.trim().is_empty() {
1226        return Err(syn::Error::new(
1227            value.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    }
1231    if text.contains('\0') {
1232        return Err(syn::Error::new(
1233            value.span(),
1234            "`message` must not contain a NUL character: an R string cannot hold one",
1235        ));
1236    }
1237    *slot = Some(text);
1238    Ok(())
1239}
1240
1241/// 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> {
1246    Ok(crate::naming::ident_name(
1247        entry
1248            .path
1249            .get_ident()
1250            .ok_or_else(|| entry.error("expected parameter name"))?,
1251    ))
1252}
1253
1254/// 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<()> {
1262    meta.parse_nested_meta(|entry| {
1263        let name = method_check_param(&entry)?;
1264        let mut message = None;
1265        if entry.input.peek(syn::token::Paren) {
1266            entry.parse_nested_meta(|opt| parse_no_na_option(&opt, &mut message))?;
1267        }
1268        let checks = crate::r_preconditions::ExplicitChecks {
1269            no_na: true,
1270            no_na_message: message,
1271            ..Default::default()
1272        };
1273        per_param
1274            .entry(name)
1275            .or_default()
1276            .checks
1277            .merge(checks)
1278            .map_err(|msg| entry.error(msg))
1279    })
1280}
1281
1282/// 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<()> {
1296    let key_word = check.keyword();
1297    meta.parse_nested_meta(|entry| {
1298        let name = method_check_param(&entry)?;
1299        let mut classes = Vec::new();
1300        let mut message = None;
1301        let mut hints = Vec::new();
1302        if entry.input.peek(::syn::token::Eqsyn::Token![=]) {
1303            let value: syn::LitStr = entry.value()?.parse()?;
1304            classes = method_class_list(&value, check)?;
1305        } else if entry.input.peek(syn::token::Paren) {
1306            entry.parse_nested_meta(|opt| {
1307                if opt.path.is_ident("class") {
1308                    let value: syn::LitStr = opt.value()?.parse()?;
1309                    classes.extend(method_class_list(&value, check)?);
1310                    Ok(())
1311                } else if opt.path.is_ident("message") {
1312                    let value: syn::LitStr = opt.value()?.parse()?;
1313                    set_check_message(&mut message, &value, key_word)
1314                } else if opt.path.is_ident("when") {
1315                    if check != ClassCheck::Inherits {
1316                        return Err(opt.error(WHEN_ON_NOT_INHERITS));
1317                    }
1318                    hints.push(parse_method_when(&opt)?);
1319                    Ok(())
1320                } else {
1321                    Err(opt.error(check.unknown_method_option()))
1322                }
1323            })?;
1324            if classes.is_empty() {
1325                return 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 {
1331            return 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        }
1335        let mut checks = check.checks(classes, message);
1336        checks.inherits_hints = hints;
1337        per_param
1338            .entry(name)
1339            .or_default()
1340            .checks
1341            .merge(checks)
1342            .map_err(|msg| entry.error(msg))
1343    })
1344}
1345
1346/// 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> {
1352    let mut classes = Vec::new();
1353    let mut message = None;
1354    opt.parse_nested_meta(|hint| {
1355        if hint.path.is_ident("class") {
1356            let value: syn::LitStr = hint.value()?.parse()?;
1357            let names = crate::r_wrapper_builder::split_choice_list(&value.value());
1358            if names.is_empty() {
1359                return Err(syn::Error::new(
1360                    value.span(),
1361                    "`when(class = \"...\")` needs one or more class names",
1362                ));
1363            }
1364            classes.extend(names);
1365            Ok(())
1366        } else if hint.path.is_ident("message") {
1367            let value: syn::LitStr = hint.value()?.parse()?;
1368            set_hint_message(&mut message, &value)
1369        } else {
1370            Err(hint
1371                .error("unknown `when` option; expected `class = \"...\"` and `message = \"...\"`"))
1372        }
1373    })?;
1374    inherits_hint(classes, message).map_err(|msg| opt.error(msg))
1375}
1376
1377/// 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<()> {
1386    meta.parse_nested_meta(|entry| {
1387        let name = method_check_param(&entry)?;
1388        per_param.entry(name).or_default().no_default = true;
1389        Ok(())
1390    })
1391}
1392
1393/// 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<()> {
1404    meta.parse_nested_meta(|entry| {
1405        let name = method_check_param(&entry)?;
1406        let value = entry.value()?;
1407        let value: syn::LitStr = value
1408            .parse()
1409            .map_err(|e| syn::Error::new(e.span(), FORMAL_NOT_STRING))?;
1410        let attrs = per_param.entry(name).or_default();
1411        if attrs.formal.replace(value).is_some() {
1412            return Err(entry.error(FORMAL_TWICE));
1413        }
1414        Ok(())
1415    })
1416}
1417
1418/// 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>> {
1421    let classes = crate::r_wrapper_builder::split_choice_list(&value.value());
1422    if classes.is_empty() {
1423        return Err(syn::Error::new(
1424            value.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    }
1431    Ok(classes)
1432}
1433// endregion
1434
1435// region: per-parameter preconditions (#1566 §2)
1436
1437/// 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<()> {
1448    meta.parse_nested_meta(|entry| {
1449        let name = method_check_param(&entry)?;
1450        per_param.entry(name).or_default().preconditions = Some(keep);
1451        Ok(())
1452    })
1453}
1454
1455/// 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 {
1459    let key = if keep {
1460        "preconditions"
1461    } else {
1462        "no_preconditions"
1463    };
1464    if 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}
1470
1471/// 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>> {
1485    let marker = crate::type_inspect::marker_in_family(
1486        markers,
1487        crate::type_inspect::ParamMarkerFamily::Preconditions,
1488    );
1489    let Some(marker) = marker else {
1490        return Ok(keyword);
1491    };
1492    let from_marker = marker.preconditions();
1493    if let Some(keep) = keyword
1494        && Some(keep) != from_marker
1495    {
1496        let (marker_does, keyword_does) = if keep {
1497            ("drops", "keeps")
1498        } else {
1499            ("keeps", "drops")
1500        };
1501        return Err(syn::Error::new_spanned(
1502            ty,
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    }
1511    Ok(from_marker)
1512}
1513
1514/// 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<()> {
1528    let Some(keep) = attrs.preconditions else {
1529        return Ok(());
1530    };
1531    let marker = crate::type_inspect::marker_in_family(
1532        markers,
1533        crate::type_inspect::ParamMarkerFamily::Preconditions,
1534    );
1535    let spelling = match marker {
1536        Some(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)),
1537        None => preconditions_keyword(keep, param, method_list),
1538    };
1539    if attrs.is_choice() {
1540        return Err(syn::Error::new_spanned(
1541            ty,
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    }
1549    if !crate::r_preconditions::has_type_check(ty) {
1550        return Err(syn::Error::new_spanned(
1551            ty,
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",
1554                crate::type_inspect::type_display(ty)
1555            ),
1556        ));
1557    }
1558    Ok(())
1559}
1560
1561/// `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![,]>> {
1568    let mut peeled = inputs.clone();
1569    for arg in peeled.iter_mut() {
1570        let syn::FnArg::Typed(pt) = arg else {
1571            continue;
1572        };
1573        let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
1574            continue;
1575        };
1576        let name = crate::naming::ident_name(&pat_ident.ident);
1577        if markers.iter().any(|(n, _)| *n == name) {
1578            let (_, inner) = crate::type_inspect::peel_param_markers(pt.ty.as_ref())?;
1579            *pt.ty = inner.clone();
1580        }
1581    }
1582    Ok(peeled)
1583}
1584
1585/// 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>)>> {
1591    let mut out = Vec::new();
1592    for arg in inputs {
1593        let syn::FnArg::Typed(pt) = arg else {
1594            continue;
1595        };
1596        let (markers, _) = crate::type_inspect::peel_param_markers(pt.ty.as_ref())?;
1597        if markers.is_empty() {
1598            continue;
1599        }
1600        let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
1601            continue;
1602        };
1603        out.push((crate::naming::ident_name(&pat_ident.ident), markers));
1604    }
1605    Ok(out)
1606}
1607// endregion
1608
1609// region: Function parsing
1610
1611/// 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.
1621    item: 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.
1628    param_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`]).
1632    dots: 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.
1636    per_param: std::collections::HashMap<String, ParamAttrs>,
1637}
1638
1639/// 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 {
1647    pub coerce: bool,
1648    pub convert: bool,
1649    pub match_arg: bool,
1650    pub several_ok: bool,
1651    pub choices: Option<Vec<String>>,
1652    pub 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.
1660    pub 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`].
1666    pub 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)`.
1673    pub 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`].
1681    pub either_noun: Option<String>,
1682    /// R-side checks named by the author: `inherits` / `not_inherits` /
1683    /// `no_na`.
1684    pub 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.
1691    pub 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.
1696    pub formal: Option<syn::LitStr>,
1697}
1698
1699impl 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).
1705    pub(crate) fn leaves_argument_unforced(&self, default_ok: bool) -> bool {
1706        let 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            && !coerce
1723            && !convert
1724            && !match_arg
1725            && !several_ok
1726            && choices.is_none()
1727            && !optional
1728            && !omittable
1729            && !no_default
1730            && either_noun.is_none()
1731            && checks.is_empty()
1732            && preconditions.is_none()
1733    }
1734
1735    /// Whether this is a `match_arg` / `choices` parameter.
1736    pub(crate) fn is_choice(&self) -> bool {
1737        self.match_arg || self.choices.is_some()
1738    }
1739
1740    /// 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.
1747    pub(crate) fn choice_formal(&self, choices: &str) -> Option<String> {
1748        if self.no_default {
1749            None
1750        } else if self.optional && !self.omittable {
1751            Some("NULL".to_string())
1752        } else {
1753            Some(choices.to_string())
1754        }
1755    }
1756
1757    /// 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.
1769    pub(crate) fn reads_formal_as_absent(&self) -> bool {
1770        self.is_choice() && self.omittable && !self.several_ok && !self.no_default
1771    }
1772
1773    /// 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.
1786    pub(crate) fn choice_doc_suffix(&self) -> String {
1787        let null_word = if self.omittable {
1788            "NULL"
1789        } else {
1790            "NULL for no choice"
1791        };
1792        let mut suffix =
1793            choice_alternatives_suffix(self.either_noun.as_deref(), self.optional, null_word);
1794        if self.omittable && !self.no_default {
1795            suffix.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        }
1801        suffix
1802    }
1803
1804    /// 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).
1809    pub(crate) fn literal_choices_doc(&self) -> Option<String> {
1810        let choices = self.choices.as_ref()?;
1811        let quoted: Vec<String> = choices.iter().map(|c| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"", c))
    })format!("\"{c}\"")).collect();
1812        let prefix = if self.several_ok {
1813            "One or more of"
1814        } else {
1815            "One of"
1816        };
1817        Some(::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(", "),
1820            self.choice_doc_suffix()
1821        ))
1822    }
1823
1824    /// 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).
1832    pub(crate) fn layered_leaf(&self) -> Option<crate::rust_conversion_builder::ChoiceLeaf> {
1833        use crate::rust_conversion_builder::ChoiceLeaf;
1834        let either = self.either_noun.is_some();
1835        if self.match_arg && (self.optional || self.omittable || either) {
1836            return Some(if self.several_ok {
1837                ChoiceLeaf::MatchArgSeveral
1838            } else {
1839                ChoiceLeaf::MatchArg
1840            });
1841        }
1842        let choices = self.choices.as_ref().filter(|_| either)?;
1843        Some(ChoiceLeaf::Literal {
1844            choices: choices.clone(),
1845            several: self.several_ok,
1846        })
1847    }
1848}
1849
1850/// 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 {
1862    match (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}
1869
1870/// 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<()> {
1895    use syn::spanned::Spanned;
1896    if !attrs.is_choice() {
1897        return Ok(());
1898    }
1899    let layers = crate::type_inspect::choice_layers(ty);
1900    if let Some(layer) = crate::type_inspect::choice_layer_name(layers.value) {
1901        return Err(syn::Error::new(
1902            ty.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    }
1910    if attrs.several_ok {
1911        let 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.
1914        if let Some(spelling) = layers.nullable
1915            && !either
1916        {
1917            return Err(syn::Error::new(
1918                ty.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        }
1927        if !is_vector_like_type(layers.value) {
1928            // Under `Missing` / `Either` only the owned containers decode.
1929            let containers = if layers.missing || either {
1930                "`Vec<T>` or `Box<[T]>`"
1931            } else {
1932                "`Vec<T>`, `Box<[T]>`, `&[T]`, or `[T; N]`"
1933            };
1934            return Err(syn::Error::new(
1935                ty.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        }
1943        let owned = #[allow(non_exhaustive_omitted_patterns)] match crate::classify_several_ok_container(layers.value)
    {
    Some((crate::SeveralOkContainer::Vec |
        crate::SeveralOkContainer::BoxedSlice, _)) => true,
    _ => false,
}matches!(
1944            crate::classify_several_ok_container(layers.value),
1945            Some((
1946                crate::SeveralOkContainer::Vec | crate::SeveralOkContainer::BoxedSlice,
1947                _
1948            ))
1949        );
1950        if either && !owned {
1951            return Err(syn::Error::new(
1952                ty.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        }
1959        if layers.missing && !owned {
1960            return Err(syn::Error::new(
1961                ty.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>>`.
1971    if let Some(spelling) = layers.nullable
1972        && !layers.missing
1973        && has_default
1974    {
1975        return Err(syn::Error::new(
1976            ty.span(),
1977            optional_choice_default_msg(param_name, spelling.name()),
1978        ));
1979    }
1980    if layers.missing && has_default {
1981        return Err(syn::Error::new(
1982            ty.span(),
1983            missing_choice_default_msg(param_name),
1984        ));
1985    }
1986    attrs.optional = layers.nullable.is_some();
1987    attrs.omittable = layers.missing;
1988    attrs.either_noun = layers.either_right.map(crate::type_inspect::r_value_noun);
1989    Ok(())
1990}
1991
1992/// 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)> {
2000    inputs.iter().filter_map(|arg| {
2001        let syn::FnArg::Typed(pt) = arg else {
2002            return None;
2003        };
2004        let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
2005            return None;
2006        };
2007        per_param.get_key_value(&crate::naming::ident_name(&pat_ident.ident))
2008    })
2009}
2010
2011/// 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> {
2017    let formals = crate::r_wrapper_builder::Formals::from_param_attrs(per_param);
2018    per_param
2019        .iter()
2020        .filter(|(_, a)| !a.checks.is_empty())
2021        .map(|(name, a)| (formals.of(name), a.checks.clone()))
2022        .collect()
2023}
2024
2025/// 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.";
2030
2031/// 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> {
2044    inputs
2045        .iter()
2046        .filter_map(|arg| {
2047            let syn::FnArg::Typed(pt) = arg else {
2048                return None;
2049            };
2050            let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
2051                return None;
2052            };
2053            let rust_name = crate::naming::ident_name(&pat_ident.ident);
2054            if !is_missing_type(pt.ty.as_ref())
2055                || per_param.get(&rust_name).is_some_and(ParamAttrs::is_choice)
2056            {
2057                return None;
2058            }
2059            defaults.contains_key(&rust_name).then(|| {
2060                (
2061                    formals.of(&rust_name),
2062                    MISSING_DEFAULT_PARAM_DOC.to_string(),
2063                )
2064            })
2065        })
2066        .collect()
2067}
2068
2069/// 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> {
2076    let formals = crate::r_wrapper_builder::Formals::from_param_attrs(per_param);
2077    per_param
2078        .iter()
2079        .filter(|(_, a)| a.reads_formal_as_absent())
2080        .map(|(name, _)| formals.of(name))
2081        .collect()
2082}
2083
2084/// 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<()> {
2089    meta.parse_nested_meta(|inner| {
2090        let name = method_check_param(&inner)?;
2091        per_param.entry(name).or_default().convert = true;
2092        Ok(())
2093    })
2094}
2095
2096/// 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<()> {
2099    let 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    })?;
2105    if 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    {
2108        return Err(syn::Error::new_spanned(
2109            ty,
2110            "`convert` cannot override Self or dots arguments",
2111        ));
2112    }
2113    if let Some(lifetime) = crate::type_inspect::static_lifetime(ty) {
2114        return Err(syn::Error::new_spanned(
2115            lifetime,
2116            "`convert` borrows only for the call; remove the `'static` lifetime",
2117        ));
2118    }
2119    if conflicting {
2120        return Err(syn::Error::new_spanned(
2121            ty,
2122            "`convert` cannot be combined with coerce, match_arg, or choices on the same parameter",
2123        ));
2124    }
2125    Ok(())
2126}
2127
2128/// 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<()> {
2154    let sig_names: std::collections::HashSet<String> = inputs
2155        .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();
2164    let mut unknown: Vec<&String> = per_param
2165        .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();
2177    unknown.sort();
2178    if let Some(first) = unknown.first() {
2179        if per_param[*first].convert {
2180            return Err(syn::Error::new(
2181                span,
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        }
2185        return Err(syn::Error::new(
2186            span,
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    }
2193    let mut unknown_formals: Vec<(&String, &syn::LitStr)> = per_param
2194        .iter()
2195        .filter(|(name, _)| !sig_names.contains(name.as_str()))
2196        .filter_map(|(name, a)| Some((name, a.formal.as_ref()?)))
2197        .collect();
2198    unknown_formals.sort_by_key(|(name, _)| *name);
2199    if let Some((name, formal)) = unknown_formals.first() {
2200        return Err(syn::Error::new(
2201            formal.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.
2212    check_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.
2216    check_lazy_dots_params(inputs, |name| {
2217        per_param.contains_key(name) || defaults.contains_key(name)
2218    })?;
2219    for arg in inputs {
2220        let syn::FnArg::Typed(pt) = arg else {
2221            continue;
2222        };
2223        let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
2224            continue;
2225        };
2226        let name = crate::naming::ident_name(&pat_ident.ident);
2227        let Some(attrs) = per_param.get_mut(&name) else {
2228            continue;
2229        };
2230        if let Some(formal) = &attrs.formal
2231            && is_dots_type(pt.ty.as_ref())
2232        {
2233            return Err(dots_formal_error(formal, &name));
2234        }
2235        if attrs.convert {
2236            validate_convert_param(&pt.ty, attrs.coerce || attrs.is_choice())?;
2237        }
2238        let has_default = attrs.default.is_some() || defaults.contains_key(&name);
2239        if attrs.no_default
2240            && let Some(msg) = no_default_conflict(&name, attrs.is_choice(), has_default, true)
2241        {
2242            return Err(syn::Error::new(span, msg));
2243        }
2244        classify_choice_param(attrs, &name, pt.ty.as_ref(), has_default)?;
2245        if let Some(msg) = attrs.checks.class_conflict(&name) {
2246            return Err(syn::Error::new(span, msg));
2247        }
2248        let 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    }
2254    Ok(())
2255}
2256
2257/// 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}
2270
2271/// 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}
2280
2281/// 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::Parse for MiniextendrFunctionParsed {
2302    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
2303        use syn::spanned::Spanned;
2304
2305        let mut item: syn::ItemFn = input.parse()?;
2306
2307        // dots support: replace `...` with `&Dots` (the dots parameter itself
2308        // is found by type once wildcard patterns have their names).
2309        rewrite_variadic_dots(&mut item.sig)?;
2310
2311        // 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].
2313        let is_extern = item.sig.abi.is_some();
2314        if !is_extern {
2315            require_safe_wrapper(&item.sig, "drop `#[miniextendr]`")?;
2316            for attr in &item.attrs {
2317                if attr.path().is_ident("export_name") {
2318                    return 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        }
2327
2328        // Transform `_` wildcard patterns to synthetic identifiers, and consume
2329        // per-parameter `#[miniextendr(coerce)]`, `#[miniextendr(default = "...")]`,
2330        // and `#[miniextendr(choices(...))]` attributes.
2331        let mut per_param: std::collections::HashMap<String, ParamAttrs> =
2332            std::collections::HashMap::new();
2333        let mut per_param_default_spans: std::collections::HashMap<String, proc_macro2::Span> =
2334            std::collections::HashMap::new();
2335        let mut unused_counter = 0usize;
2336        let mut pattern_destructures: Vec<(Box<syn::Pat>, syn::Ident)> = Vec::new();
2337        let mut param_markers: Vec<(String, Vec<crate::type_inspect::ParamMarker>)> = Vec::new();
2338        for arg in &mut item.sig.inputs {
2339            let 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.
2343                continue;
2344            };
2345
2346            // 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.
2350            let mut param_attr = PerParamMiniextendrAttr::default();
2351            let mut kept_attrs = Vec::with_capacity(pat_type.attrs.len());
2352            for attr in std::mem::take(&mut pat_type.attrs) {
2353                match parse_per_param_attr(&attr)? {
2354                    Some(parsed) => param_attr
2355                        .merge(parsed)
2356                        .map_err(|msg| syn::Error::new_spanned(&attr, msg))?,
2357                    None => kept_attrs.push(attr),
2358                }
2359            }
2360            pat_type.attrs = kept_attrs;
2361            let 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;
2373
2374            if is_extern && had_convert {
2375                return Err(syn::Error::new_spanned(
2376                    &pat_type.ty,
2377                    "`convert` requires a generated wrapper; remove `extern \"C-unwind\"`",
2378                ));
2379            }
2380
2381            // 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.
2385            let (markers, inner_ty) =
2386                crate::type_inspect::peel_param_markers(pat_type.ty.as_ref())?;
2387            let inner_ty = inner_ty.clone();
2388            if is_extern && let Some(marker) = markers.first() {
2389                return 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.
2401            if is_extern && crate::type_inspect::is_nargs_marker(&inner_ty) {
2402                return 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            }
2410
2411            // Validate type-based constraints (Missing nesting, Missing<Dots>)
2412            validate_param_type(&inner_ty, pat_type.ty.span())?;
2413
2414            // Resolve the Rust parameter name — either the user's identifier,
2415            // or a synthesized one for wildcard / destructuring patterns.
2416            let 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(_) => {
2419                    let synthetic_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__unused{0}", unused_counter))
    })format!("__unused{}", unused_counter);
2420                    unused_counter += 1;
2421                    let 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(_) => {
2432                    let synthetic_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__param_{0}", unused_counter))
    })format!("__param_{}", unused_counter);
2433                    unused_counter += 1;
2434                    let synthetic_ident = syn::Ident::new(&synthetic_name, pat_type.pat.span());
2435                    let 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                _ => {
2447                    return 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.
2456            let mut had_checks = had_checks;
2457            if 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.
2461            let preconditions = merge_param_policy(
2462                &markers,
2463                had_preconditions,
2464                &param_name,
2465                false,
2466                &pat_type.ty,
2467            )?;
2468
2469            // Validate per-parameter attribute conflicts (coerce+match_arg, coerce+choices, etc.)
2470            let 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                &param_name,
2485                is_dots_type(&inner_ty),
2486                &inner_ty,
2487                pat_type.ty.span(),
2488            )?;
2489
2490            // Record per-parameter attrs in one entry instead of five side-tables.
2491            if 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            {
2501                let 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;
2511                if 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).
2516                let has_default = entry.default.is_some();
2517                classify_choice_param(entry, &param_name, &inner_ty, has_default)?;
2518                check_param_preconditions(entry, &markers, &param_name, &inner_ty, false)?;
2519            }
2520            if !markers.is_empty() {
2521                param_markers.push((param_name, markers));
2522            }
2523        }
2524
2525        // Insert destructuring let-bindings for pattern parameters at the start of the function body
2526        for (pat, ident) in pattern_destructures.iter().rev() {
2527            item.block.stmts.insert(
2528                0,
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! {
2530                    let #pat = #ident;
2531                },
2532            );
2533        }
2534
2535        // Validate: all defaults reference existing parameters
2536        let param_names: std::collections::HashSet<String> = item
2537            .sig
2538            .inputs
2539            .iter()
2540            .filter_map(|input| {
2541                if let syn::FnArg::Typed(pat_type) = input
2542                    && let syn::Pat::Ident(pat_ident) = pat_type.pat.as_ref()
2543                {
2544                    Some(crate::naming::ident_name(&pat_ident.ident))
2545                } else {
2546                    None
2547                }
2548            })
2549            .collect();
2550
2551        let mut invalid_params: Vec<String> = per_param
2552            .iter()
2553            .filter_map(|(name, attrs)| {
2554                if attrs.default.is_some() && !param_names.contains(name) {
2555                    Some(name.clone())
2556                } else {
2557                    None
2558                }
2559            })
2560            .collect();
2561        invalid_params.sort();
2562
2563        if !invalid_params.is_empty() {
2564            // Use the span of the first invalid param's attribute for the error
2565            let error_span = invalid_params
2566                .first()
2567                .and_then(|p| per_param_default_spans.get(p).copied())
2568                .unwrap_or_else(|| item.sig.ident.span());
2569            return Err(syn::Error::new(
2570                error_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        }
2577
2578        let dots = find_dots_param(&item.sig.inputs)?;
2579        crate::r_wrapper_builder::check_r_formals(
2580            &item.sig.inputs,
2581            &crate::r_wrapper_builder::Formals::from_param_attrs(&per_param),
2582            &[],
2583        )?;
2584        let inputs = peeled_inputs(&item.sig.inputs, &param_markers)?;
2585
2586        Ok(Self {
2587            item,
2588            inputs,
2589            param_markers,
2590            dots,
2591            per_param,
2592        })
2593    }
2594}
2595
2596/// 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
2608
2609    /// Whether the function takes `...`: Rust `...` or an explicit `&Dots`
2610    /// parameter, at any position.
2611    pub(crate) fn has_dots(&self) -> bool {
2612        self.dots.is_some()
2613    }
2614
2615    /// The Rust binding of the dots: the user's name (`args: ...`,
2616    /// `rest: &Dots`), or `__miniextendr_dots` for `_: ...`.
2617    pub(crate) fn dots_ident(&self) -> Option<&syn::Ident> {
2618        self.dots.as_ref()
2619    }
2620
2621    /// Check if a parameter is the dots (`...`) param, whose R formal is `...`.
2622    pub(crate) fn is_dots_param(&self, ident: &syn::Ident) -> bool {
2623        self.dots_ident() == Some(ident)
2624    }
2625
2626    /// 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.
2629    pub(crate) fn has_param_attrs(&self, param_name: &str) -> bool {
2630        self.per_param.contains_key(param_name)
2631    }
2632
2633    /// Check if a parameter name had `#[miniextendr(coerce)]` attribute.
2634    pub(crate) fn has_coerce_attr(&self, param_name: &str) -> bool {
2635        self.per_param.get(param_name).is_some_and(|a| a.coerce)
2636    }
2637
2638    /// Check if a parameter name had `#[miniextendr(match_arg)]` attribute.
2639    pub(crate) fn has_match_arg_attr(&self, param_name: &str) -> bool {
2640        self.per_param.get(param_name).is_some_and(|a| a.match_arg)
2641    }
2642
2643    /// Iterator over parameter names annotated with `#[miniextendr(match_arg)]`,
2644    /// in signature order.
2645    pub(crate) fn match_arg_params(&self) -> impl Iterator<Item = &String> {
2646        per_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    }
2649
2650    /// Iterator over parameter names annotated with `#[miniextendr(choices(…))]`,
2651    /// together with their choice lists, in signature order.
2652    pub(crate) fn choices_params(&self) -> impl Iterator<Item = (&String, &Vec<String>)> {
2653        per_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    }
2656
2657    /// Check if a parameter has `several_ok` (multi-value match.arg).
2658    pub(crate) fn has_several_ok(&self, param_name: &str) -> bool {
2659        self.per_param.get(param_name).is_some_and(|a| a.several_ok)
2660    }
2661
2662    /// 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.
2665    pub(crate) fn param_attrs(&self, param_name: &str) -> Option<&ParamAttrs> {
2666        self.per_param.get(param_name)
2667    }
2668
2669    /// The R formal of each parameter (#1842), from the declared
2670    /// `formal = ".."` options.
2671    pub(crate) fn formals(&self) -> crate::r_wrapper_builder::Formals {
2672        crate::r_wrapper_builder::Formals::from_param_attrs(&self.per_param)
2673    }
2674
2675    /// The R formals of the parameters that read a value `identical()` to
2676    /// their formal as omitted (see [`absent_formals_by_r_name`]).
2677    pub(crate) fn absent_formals(&self) -> std::collections::HashSet<String> {
2678        absent_formals_by_r_name(&self.per_param)
2679    }
2680
2681    /// The generated `@param` text of each `Missing<..>` parameter with a
2682    /// default, keyed by R formal (see [`missing_default_param_docs`]).
2683    pub(crate) fn missing_default_param_docs(&self) -> std::collections::HashMap<String, String> {
2684        missing_default_param_docs(
2685            &self.item.sig.inputs,
2686            &self.per_param,
2687            &self.param_defaults(),
2688            &self.formals(),
2689        )
2690    }
2691
2692    /// The `inherits` / `not_inherits` / `no_na` checks of every parameter,
2693    /// keyed by R name (see [`explicit_checks_by_r_name`]).
2694    pub(crate) fn explicit_checks(
2695        &self,
2696    ) -> std::collections::HashMap<String, crate::r_preconditions::ExplicitChecks> {
2697        explicit_checks_by_r_name(&self.per_param)
2698    }
2699
2700    /// 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.
2703    pub(crate) fn precondition_skip_params(&self) -> std::collections::HashSet<String> {
2704        crate::r_class_formatter::match_arg_skip_set(&self.per_param)
2705    }
2706
2707    /// 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.
2712    pub(crate) fn param_defaults(&self) -> std::collections::HashMap<String, String> {
2713        self.per_param
2714            .iter()
2715            .filter_map(|(name, a)| a.default.as_ref().map(|d| (name.clone(), d.clone())))
2716            .collect()
2717    }
2718    // endregion
2719
2720    // region: Accessors for signature components
2721
2722    /// Original attributes on the function item (doc comments, cfgs, etc.).
2723    pub(crate) fn attrs(&self) -> &[syn::Attribute] {
2724        &self.item.attrs
2725    }
2726
2727    /// Visibility of the function (`pub`, `pub(crate)`, or private).
2728    pub(crate) fn vis(&self) -> &syn::Visibility {
2729        &self.item.vis
2730    }
2731
2732    /// Explicit ABI, if the function was declared `extern "C-unwind"`.
2733    pub(crate) fn abi(&self) -> Option<&syn::Abi> {
2734        self.item.sig.abi.as_ref()
2735    }
2736
2737    /// Function identifier after normalization.
2738    pub(crate) fn ident(&self) -> &syn::Ident {
2739        &self.item.sig.ident
2740    }
2741
2742    /// Generic parameters on the function signature.
2743    pub(crate) fn generics(&self) -> &syn::Generics {
2744        &self.item.sig.generics
2745    }
2746
2747    /// Function inputs after normalization (dots rewritten, wildcards
2748    /// renamed), with the parameter markers peeled (see [`Self::param_markers`]).
2749    pub(crate) fn inputs(&self) -> &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]> {
2750        &self.inputs
2751    }
2752
2753    /// The `Checked<T>` / `Unchecked<T>` markers peeled off the parameters
2754    /// (Rust name → markers, outermost first), in signature order.
2755    pub(crate) fn param_markers(&self) -> &[(String, Vec<crate::type_inspect::ParamMarker>)] {
2756        &self.param_markers
2757    }
2758
2759    /// Function return type.
2760    pub(crate) fn output(&self) -> &syn::ReturnType {
2761        &self.item.sig.output
2762    }
2763
2764    /// The normalized function item (with original doc comments).
2765    pub(crate) fn item(&self) -> &syn::ItemFn {
2766        &self.item
2767    }
2768
2769    /// 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.
2773    pub(crate) fn item_without_roxygen(&self) -> syn::ItemFn {
2774        let mut item = self.item.clone();
2775        item.attrs = crate::roxygen::strip_roxygen_from_attrs(&item.attrs);
2776        item
2777    }
2778    // endregion
2779
2780    // region: Codegen helpers
2781
2782    /// 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.
2787    pub(crate) fn uses_internal_c_wrapper(&self) -> bool {
2788        self.abi().is_none()
2789    }
2790
2791    /// 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.
2796    pub(crate) fn r_wrapper_const_ident(&self) -> syn::Ident {
2797        r_wrapper_const_ident_for(self.ident())
2798    }
2799
2800    /// 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.
2807    pub(crate) fn c_wrapper_ident(&self) -> syn::Ident {
2808        if self.uses_internal_c_wrapper() {
2809            crate::naming::bare_fn_c_wrapper_ident(self.ident())
2810        } else {
2811            // For extern functions, check for #[export_name = "..."]
2812            self.export_name_ident()
2813                .unwrap_or_else(|| self.ident().clone())
2814        }
2815    }
2816
2817    /// 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.
2821    pub(crate) fn export_name_ident(&self) -> Option<syn::Ident> {
2822        for attr in &self.item.attrs {
2823            if 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            {
2830                return Some(syn::Ident::new(&lit_str.value(), lit_str.span()));
2831            }
2832        }
2833        None
2834    }
2835
2836    /// 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
2843    pub(crate) fn add_inline_never_if_needed(&mut self) {
2844        let has_explicit_abi = self.item.sig.abi.is_some();
2845        let has_inline = self
2846            .item
2847            .attrs
2848            .iter()
2849            .any(|attr| attr.path().is_ident("inline"));
2850        if !has_inline && !has_explicit_abi {
2851            self.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
2857
2858// region: Attribute parsing
2859
2860/// 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<()> {
2868    if val.is_empty() {
2869        return Err(syn::Error::new_spanned(span, "postfix must not be empty"));
2870    }
2871    if !val
2872        .chars()
2873        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
2874    {
2875        return Err(syn::Error::new_spanned(
2876            span,
2877            "postfix must be a valid R identifier fragment (letters, digits, `_`, `.`)",
2878        ));
2879    }
2880    Ok(())
2881}
2882
2883fn parse_lit_str(nv: &syn::MetaNameValue, field: &str) -> syn::Result<String> {
2884    match &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(
2894            other,
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}
2899
2900/// 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";
2908
2909/// 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 = ...)`";
2912
2913/// 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.
2963    pub(crate) force_invisible: Option<bool>,
2964    /// Insert `R_CheckUserInterrupt()` before calling the Rust function.
2965    pub(crate) check_interrupt: bool,
2966    /// Enable automatic coercion for all parameters that support it.
2967    pub(crate) coerce_all: bool,
2968    /// Enable RNG state management (GetRNGstate/PutRNGstate). Also set by
2969    /// `rng(seed = ..)`.
2970    pub(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).
2975    pub(crate) rng_seed: Option<syn::Ident>,
2976    /// Return `Result<T, E>` to R without unwrapping.
2977    pub(crate) unwrap_in_r: bool,
2978    /// Serialize the complete return value through `AsSerialize<T>`.
2979    pub(crate) serialize: bool,
2980    pub(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 = .., ..))]`).
2983    pub(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`).
2999    pub(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`).
3005    pub(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`.
3011    pub(crate) call_arg: bool,
3012    /// Preferred return conversion: forces `AsList`/`AsExternalPtr`/`AsRNative` wrapping
3013    /// of the return value before `IntoR::into_sexp` is called.
3014    pub(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.
3018    pub(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).
3024    pub(crate) s3_generic: Option<String>,
3025    /// S3 class suffix for the method (e.g., "my_vctr" or "my_vctr.my_vctr" for double-dispatch).
3026    pub(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`.
3031    pub(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`]).
3034    pub(crate) dots_policy: Option<crate::dots_policy::DotsPolicy>,
3035    /// Span of the `dots = ...` attribute for error reporting.
3036    pub(crate) dots_span: Option<proc_macro2::Span>,
3037    /// Lifecycle specification for deprecation/experimental status.
3038    pub(crate) lifecycle: Option<crate::lifecycle::LifecycleSpec>,
3039    /// Strict output conversion: panic instead of lossy widening for i64/u64/isize/usize.
3040    pub(crate) strict: bool,
3041    /// Mark as internal: adds `@keywords internal`, suppresses `@export`.
3042    pub(crate) internal: bool,
3043    /// Suppress `@export` without adding `@keywords internal`.
3044    pub(crate) noexport: bool,
3045    /// Force `@export` even on non-pub functions. Antidote to `noexport`.
3046    pub(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.
3051    pub(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).
3057    pub(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.
3063    pub(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.
3069    pub(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.
3075    pub(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.
3081    pub(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.
3089    pub(crate) r_on_exit: Option<ROnExit>,
3090}
3091
3092/// 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 {
3101    pub expr: String,
3102    pub add: bool,
3103    pub after: bool,
3104}
3105
3106impl 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)`
3112    pub fn to_r_code(&self) -> String {
3113        if !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}
3122
3123/// `#[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.
3154    pub shape: Option<syn::Path>,
3155    /// Internally-tagged discriminator field name (`#[serde(tag = "...")]`).
3156    pub tag: Option<String>,
3157    /// Condition class prefix (family class).
3158    pub prefix: Option<String>,
3159    /// Payload fields dropped from the condition data.
3160    pub skip: Vec<String>,
3161    /// Payload fields spliced under another name: `(from, to)`.
3162    pub rename: Vec<(String, String)>,
3163    /// Payload fields given an atomic R type (`as_character(..)` & co.), in
3164    /// written order.
3165    pub types: Vec<(FieldType, String)>,
3166}
3167
3168/// 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}
3176
3177impl FieldType {
3178    const ALL: [FieldType; 4] = [
3179        FieldType::Logical,
3180        FieldType::Integer,
3181        FieldType::Double,
3182        FieldType::Character,
3183    ];
3184
3185    /// The option's name, which is also the `SerdeErrorShape` method's.
3186    pub(crate) fn option(self) -> &'static str {
3187        match self {
3188            FieldType::Logical => "as_logical",
3189            FieldType::Integer => "as_integer",
3190            FieldType::Double => "as_double",
3191            FieldType::Character => "as_character",
3192        }
3193    }
3194
3195    fn from_path(path: &syn::Path) -> Option<Self> {
3196        Self::ALL.into_iter().find(|ty| path.is_ident(ty.option()))
3197    }
3198}
3199
3200/// 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"];
3204
3205const 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(...)`";
3208
3209const SERDE_ERROR_SHAPE_HELP: &str = "serde_error shape takes the path of a `SerdeErrorShape` \
3210    const: `shape = ENGINE`";
3211
3212/// 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";
3218
3219impl SerdeErrorSpec {
3220    /// Parse `serde_error(...)` contents: a comma-separated list of options.
3221    /// Every problem is reported at once.
3222    fn from_metas<'a>(
3223        metas: impl IntoIterator<Item = &'a syn::Meta>,
3224        span: proc_macro2::Span,
3225    ) -> syn::Result<Self> {
3226        let mut spec = SerdeErrorSpec::default();
3227        let mut errors = Vec::new();
3228        let mut any = false;
3229        for meta in metas {
3230            any = true;
3231            spec.apply(meta, &mut errors);
3232        }
3233        if !any {
3234            return Err(syn::Error::new(span, SERDE_ERROR_BARE_HELP));
3235        }
3236        let mut errors = errors.into_iter();
3237        match errors.next() {
3238            None => Ok(spec),
3239            Some(mut first) => {
3240                first.extend(errors);
3241                Err(first)
3242            }
3243        }
3244    }
3245
3246    fn apply(&mut self, meta: &syn::Meta, errors: &mut Vec<syn::Error>) {
3247        match 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") => {
3258                match non_empty_lit_str(nv, "tag") {
3259                    Ok(tag) => self.tag = Some(tag),
3260                    Err(err) => errors.push(err),
3261                }
3262            }
3263            syn::Meta::NameValue(nv) if nv.path.is_ident("prefix") => {
3264                match non_empty_lit_str(nv, "prefix") {
3265                    Ok(prefix) => self.prefix = Some(prefix),
3266                    Err(err) => errors.push(err),
3267                }
3268            }
3269            syn::Meta::List(list) if list.path.is_ident("skip") => {
3270                for lit in field_names(list, "skip", errors) {
3271                    let name = lit.value();
3272                    if 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 {
3292                        self.skip.push(name);
3293                    }
3294                }
3295            }
3296            syn::Meta::List(list) if list.path.is_ident("rename") => {
3297                let pairs = match list.parse_args_with(
3298                    syn::punctuated::Punctuated::<RenamePair, ::syn::token::Commasyn::Token![,]>::parse_terminated,
3299                ) {
3300                    Ok(pairs) => pairs,
3301                    Err(err) => return errors.push(err),
3302                };
3303                if pairs.is_empty() {
3304                    errors.push(syn::Error::new_spanned(
3305                        list,
3306                        "serde_error rename needs at least one pair: `rename(message = \"detail\")`",
3307                    ));
3308                }
3309                for RenamePair { from, to, span } in pairs {
3310                    let error = |message: String| syn::Error::new(span, message);
3311                    if 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 {
3331                        self.rename.push((from, to));
3332                    }
3333                }
3334            }
3335            syn::Meta::List(list) if FieldType::from_path(&list.path).is_some() => {
3336                let ty = FieldType::from_path(&list.path).expect("matched above");
3337                let option = ty.option();
3338                for lit in field_names(list, option, errors) {
3339                    let name = lit.value();
3340                    match self.field_type(&name) {
3341                        Some(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                        )),
3345                        Some(other) => errors.push(both(
3346                            &lit,
3347                            other.option(),
3348                            option,
3349                            "a field has one R type",
3350                        )),
3351                        None if self.skip.contains(&name) => {
3352                            errors.push(both(&lit, "skip", option, "a skipped field has no R type"))
3353                        }
3354                        None => self.types.push((ty, name)),
3355                    }
3356                }
3357            }
3358            syn::Meta::NameValue(nv) if nv.path.is_ident("skip") => {
3359                errors.push(syn::Error::new_spanned(
3360                    nv,
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") => {
3365                errors.push(syn::Error::new_spanned(
3366                    nv,
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() => {
3371                let option = FieldType::from_path(&nv.path)
3372                    .expect("matched above")
3373                    .option();
3374                errors.push(syn::Error::new_spanned(
3375                    nv,
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") => {
3382                errors.push(syn::Error::new_spanned(other, SERDE_ERROR_SHAPE_HELP));
3383            }
3384            other => {
3385                errors.push(syn::Error::new_spanned(
3386                    other.path(),
3387                    SERDE_ERROR_OPTIONS_HELP,
3388                ));
3389            }
3390        }
3391    }
3392
3393    /// 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.
3396    pub(crate) fn with_self_type(&self, ty: &syn::Ident) -> Self {
3397        let mut spec = self.clone();
3398        if 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        {
3404            first.ident = syn::Ident::new(&ty.to_string(), first.ident.span());
3405        }
3406        spec
3407    }
3408
3409    /// The `as_*` option that names `name`, if any.
3410    fn field_type(&self, name: &str) -> Option<FieldType> {
3411        self.types
3412            .iter()
3413            .find(|(_, n)| n == name)
3414            .map(|(ty, _)| *ty)
3415    }
3416
3417    /// The function's own options as a `SerdeErrorShape` builder chain;
3418    /// `None` when it only names a shape.
3419    pub(crate) fn own_shape(&self) -> Option<proc_macro2::TokenStream> {
3420        let mut calls = Vec::new();
3421        if let Some(tag) = &self.tag {
3422            calls.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        }
3424        if let Some(prefix) = &self.prefix {
3425            calls.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        }
3427        if !self.skip.is_empty() {
3428            let skip = &self.skip;
3429            calls.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        }
3431        if !self.rename.is_empty() {
3432            let (from, to): (Vec<&String>, Vec<&String>) =
3433                self.rename.iter().map(|(f, t)| (f, t)).unzip();
3434            calls.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        }
3436        for ty in FieldType::ALL {
3437            let names: Vec<&String> = self
3438                .types
3439                .iter()
3440                .filter(|(t, _)| *t == ty)
3441                .map(|(_, name)| name)
3442                .collect();
3443            if !names.is_empty() {
3444                let 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}
3452
3453/// 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> {
3460    let names = match list.parse_args_with(
3461        syn::punctuated::Punctuated::<syn::LitStr, ::syn::token::Commasyn::Token![,]>::parse_terminated,
3462    ) {
3463        Ok(names) => names,
3464        Err(err) => {
3465            errors.push(err);
3466            return Vec::new();
3467        }
3468    };
3469    if names.is_empty() {
3470        errors.push(syn::Error::new_spanned(
3471            list,
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    }
3475    names
3476        .into_iter()
3477        .filter(|lit| {
3478            let empty = lit.value().is_empty();
3479            if empty {
3480                errors.push(syn::Error::new_spanned(
3481                    lit,
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            !empty
3486        })
3487        .collect()
3488}
3489
3490/// 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(
3493        lit,
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}
3500
3501/// A `tag = "..."` / `prefix = "..."` value: a non-empty string literal.
3502fn non_empty_lit_str(nv: &syn::MetaNameValue, key: &str) -> syn::Result<String> {
3503    let val = parse_lit_str(nv, key)?;
3504    if val.is_empty() {
3505        return 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    }
3510    Ok(val)
3511}
3512
3513/// 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}
3520
3521impl syn::parse::Parse for RenamePair {
3522    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
3523        use syn::ext::IdentExt;
3524        let lookahead = input.lookahead1();
3525        let (from, span) = if lookahead.peek(syn::LitStr) {
3526            let lit: syn::LitStr = input.parse()?;
3527            (lit.value(), lit.span())
3528        } else if lookahead.peek(syn::Ident::peek_any) {
3529            let ident = input.call(syn::Ident::parse_any)?;
3530            (ident.to_string(), ident.span())
3531        } else {
3532            return Err(lookahead.error());
3533        };
3534        let _: ::syn::token::Eqsyn::Token![=] = input.parse()?;
3535        let to: syn::LitStr = input.parse()?;
3536        Ok(RenamePair {
3537            from,
3538            to: to.value(),
3539            span,
3540        })
3541    }
3542}
3543
3544/// 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 {
3548    let 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}
3551
3552/// 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}
3558
3559/// `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 {
3563    let 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}
3566
3567/// 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> {
3570    use syn::spanned::Spanned;
3571    let metas = list.parse_args_with(
3572        syn::punctuated::Punctuated::<syn::Meta, ::syn::token::Commasyn::Token![,]>::parse_terminated,
3573    )?;
3574    SerdeErrorSpec::from_metas(&metas, list.span())
3575}
3576
3577/// 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> {
3585    use syn::spanned::Spanned;
3586    let input = meta.input;
3587    if input.peek(syn::token::Paren) {
3588        let content;
3589        match ::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);
3590        let metas =
3591            content.parse_terminated(<syn::Meta as syn::parse::Parse>::parse, ::syn::token::Commasyn::Token![,])?;
3592        return SerdeErrorSpec::from_metas(&metas, meta.path.span());
3593    }
3594    if input.peek(::syn::token::Eqsyn::Token![=]) {
3595        let _: ::syn::token::Eqsyn::Token![=] = input.parse()?;
3596        let _: syn::LitBool = input.parse()?;
3597    }
3598    Err(meta.error(SERDE_ERROR_BARE_HELP))
3599}
3600
3601/// 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<()> {
3613    let mut first: Option<&syn::Ident> = None;
3614    for arg in inputs {
3615        let syn::FnArg::Typed(pt) = arg else {
3616            continue;
3617        };
3618        if !crate::type_inspect::is_nargs_marker(&pt.ty) {
3619            continue;
3620        }
3621        let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
3622            continue;
3623        };
3624        let ident = &pat_ident.ident;
3625        if let Some(first) = first {
3626            return 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        }
3634        if has_options(&crate::naming::ident_name(ident)) {
3635            return 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    }
3648    Ok(())
3649}
3650
3651/// 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<()> {
3665    for arg in inputs {
3666        let syn::FnArg::Typed(pt) = arg else {
3667            continue;
3668        };
3669        if !crate::type_inspect::is_lazy_dots_marker(&pt.ty) {
3670            if crate::type_inspect::mentions_lazy_dots(&pt.ty)
3671                && get_missing_inner_type(&pt.ty).is_none()
3672            {
3673                return 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            }
3680            continue;
3681        }
3682        let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
3683            continue;
3684        };
3685        let ident = &pat_ident.ident;
3686        if has_options(&crate::naming::ident_name(ident)) {
3687            return 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    }
3698    Ok(())
3699}
3700
3701/// 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<()> {
3715    let mut first: Option<&syn::PatType> = None;
3716    for arg in inputs {
3717        let syn::FnArg::Typed(pt) = arg else {
3718            continue;
3719        };
3720        if !crate::type_inspect::is_rng_guard_param(&pt.ty) {
3721            if crate::type_inspect::mentions_rng_guard(&pt.ty) {
3722                return 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            }
3729            continue;
3730        }
3731        if first.is_some() {
3732            return 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        }
3738        if !rng {
3739            return 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        }
3746        if let syn::Pat::Ident(pat_ident) = pt.pat.as_ref()
3747            && has_options(&crate::naming::ident_name(&pat_ident.ident))
3748        {
3749            return 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    }
3762    Ok(())
3763}
3764
3765/// 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<()> {
3772    for arg in inputs {
3773        if let syn::FnArg::Typed(pt) = arg
3774            && crate::type_inspect::mentions_rng_guard(&pt.ty)
3775        {
3776            return 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    }
3785    Ok(())
3786}
3787
3788/// 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> {
3791    let mut seed: Option<syn::Ident> = None;
3792    list.parse_nested_meta(|meta| {
3793        if !meta.path.is_ident("seed") {
3794            return Err(meta.error("unknown `rng(...)` option; expected `seed = <parameter>`"));
3795        }
3796        let value = meta.value()?;
3797        let 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        })?;
3804        if seed.replace(ident).is_some() {
3805            return Err(meta.error("`seed` is set more than once"));
3806        }
3807        Ok(())
3808    })?;
3809    seed.ok_or_else(|| {
3810        syn::Error::new_spanned(
3811            list,
3812            "`rng(...)` takes `seed = <parameter>`; write `rng` alone for the RNG state \
3813             without the seed contract",
3814        )
3815    })
3816}
3817
3818/// 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> {
3840    let rust_name = crate::naming::ident_name(seed);
3841    let 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    });
3847    let 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));
3851
3852    let mut errors: Vec<syn::Error> = Vec::new();
3853    if !is_param {
3854        errors.push(syn::Error::new_spanned(
3855            seed,
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() {
3862        errors.push(syn::Error::new_spanned(
3863            seed,
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    }
3871    if unit_return {
3872        errors.push(syn::Error::new_spanned(
3873            seed,
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    }
3878    match errors.into_iter().reduce(|mut all, error| {
3879        all.combine(error);
3880        all
3881    }) {
3882        Some(error) => Err(error),
3883        None => Ok(formal.expect("checked above")),
3884    }
3885}
3886
3887/// 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<()> {
3895    let content;
3896    match ::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);
3897    let _: proc_macro2::TokenStream = content.parse()?;
3898    Err(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}
3904
3905/// 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<()> {
3913    for arg in inputs {
3914        if let syn::FnArg::Typed(pt) = arg
3915            && crate::type_inspect::mentions_lazy_dots(&pt.ty)
3916        {
3917            return 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    }
3925    Ok(())
3926}
3927
3928/// 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> {
3937    use syn::spanned::Spanned;
3938
3939    let 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    })?;
3943    Some(syn::Error::new(
3944        span.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}
3950
3951/// 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<()> {
3975    use syn::spanned::Spanned;
3976
3977    if !generic.ends_with("<-") {
3978        return Ok(());
3979    }
3980    // The last R formal: an `NArgs` parameter is none (#1860), so `value`
3981    // may come before it.
3982    let last = inputs
3983        .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) => {
3988                Some((idx, pat_type))
3989            }
3990            _ => None,
3991        });
3992    let found = match last {
3993        Some((idx, _)) if Some(idx) == dots_index(inputs) => "the last R argument is `...`".into(),
3994        Some((_, pat_type)) => match pat_type.pat.as_ref() {
3995            syn::Pat::Ident(pat_ident) => {
3996                let formal = formals.of_ident(&pat_ident.ident);
3997                if formal == "value" {
3998                    return 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        },
4004        None => "it takes no new-value parameter".to_string(),
4005    };
4006    let span = last.map_or(fallback, |(_, pat_type)| pat_type.span());
4007    Err(syn::Error::new(
4008        span,
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}
4017
4018#[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]
4023    Auto,
4024    /// Force list conversion via the `AsList` wrapper.
4025    List,
4026    /// Force external pointer conversion via the `AsExternalPtr` wrapper.
4027    ExternalPtr,
4028    /// Force native vector/scalar conversion via the `AsRNative` wrapper.
4029    Native,
4030}
4031
4032/// 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::Parse for MiniextendrFnAttrs {
4054    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
4055        use syn::spanned::Spanned;
4056        // Use Option<bool> for fields that support feature defaults.
4057        // None = not explicitly set → resolve from cfg!(feature = "...") at end.
4058        let mut force_invisible: Option<bool> = None;
4059        let mut check_interrupt = false;
4060        let mut coerce_all: Option<bool> = None;
4061        let mut rng = false;
4062        let mut rng_seed = None;
4063        let mut unwrap_in_r = false;
4064        let mut serialize = false;
4065        let mut wrap = None;
4066        let mut serde_error: Option<SerdeErrorSpec> = None;
4067        let mut preconditions: Option<bool> = None;
4068        let mut return_pref = ReturnPref::Auto;
4069        let mut return_pref_span: Option<proc_macro2::Span> = None;
4070        let mut s3_generic = None;
4071        let mut s3_class = None;
4072        let mut dots_spec = None;
4073        let mut dots_policy = None;
4074        let mut dots_span = None;
4075        let mut lifecycle = None;
4076        let mut strict: Option<bool> = None;
4077        let mut internal = false;
4078        let mut noexport = false;
4079        let mut export = false;
4080        let mut doc = None;
4081        let mut c_symbol = None;
4082        let mut r_name = None;
4083        let mut postfix = None;
4084        let mut call_attr: Option<crate::r_wrapper_builder::CallAttribution> = None;
4085        let mut call_arg = false;
4086        let mut r_entry = None;
4087        let mut r_post_checks = None;
4088        let mut r_on_exit = None;
4089
4090        // 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.
4093        let 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        };
4098
4099        for meta in metas {
4100            match meta {
4101                // Simple identifiers: invisible, visible, check_interrupt, coerce, rng, ...
4102                syn::Meta::Path(path) => {
4103                    if let Some(ident) = path.get_ident() {
4104                        if 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" {
4121                            return 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 {
4139                            return 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) => {
4149                    if nv.path.is_ident("wrap") {
4150                        let value = parse_lit_str(&nv, "wrap")?;
4151                        wrap = Some(crate::return_wrap::parse_system(&syn::LitStr::new(
4152                            &value,
4153                            nv.path.span(),
4154                        ))?);
4155                        continue;
4156                    }
4157                    // Check for boolean flag options: option = true / option = false
4158                    if let syn::Expr::Lit(syn::ExprLit {
4159                        lit: syn::Lit::Bool(lit_bool),
4160                        ..
4161                    }) = &nv.value
4162                    {
4163                        let val = lit_bool.value;
4164                        if let Some(ident) = nv.path.get_ident() {
4165                            if 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" {
4182                                return 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 {
4200                                return 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                            }
4208                            continue;
4209                        }
4210                    }
4211
4212                    if nv.path.is_ident("prefer") {
4213                        let 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                            _ => {
4221                                return 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.
4230                        dots_span = Some(nv.path.span());
4231                        match crate::dots_policy::parse_dots_attr(&nv.value)? {
4232                            crate::dots_policy::DotsAttr::TypedList(spec) => {
4233                                dots_spec = Some(spec);
4234                            }
4235                            crate::dots_policy::DotsAttr::Policy(policy) => {
4236                                dots_policy = Some(policy);
4237                            }
4238                        }
4239                    } else if nv.path.is_ident("lifecycle") {
4240                        // lifecycle = "stage"
4241                        if 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") {
4249                        let val = parse_lit_str(&nv, "c_symbol")?;
4250                        if val.is_empty()
4251                            || (!val.starts_with(|c: char| c.is_ascii_alphabetic())
4252                                && !val.starts_with('_'))
4253                        {
4254                            return Err(syn::Error::new_spanned(
4255                                &nv.value,
4256                                "c_symbol must be a valid C identifier",
4257                            ));
4258                        }
4259                        if !val.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
4260                            return 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") {
4267                        let val = parse_lit_str(&nv, "r_name")?;
4268                        if val.is_empty() {
4269                            return 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") {
4276                        let val = parse_lit_str(&nv, "postfix")?;
4277                        validate_postfix(&val, &nv.value)?;
4278                        postfix = Some(val);
4279                    } else if nv.path.is_ident("call") {
4280                        let 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                        };
4288                        let Some(attribution) = name
4289                            .as_deref()
4290                            .and_then(crate::r_wrapper_builder::CallAttribution::parse_name)
4291                        else {
4292                            return 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                        };
4299                        if call_attr.is_some() {
4300                            return 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)
4312                        r_on_exit = Some(ROnExit {
4313                            expr: parse_lit_str(&nv, "r_on_exit")?,
4314                            add: true,
4315                            after: true,
4316                        });
4317                    } else {
4318                        let key_name = nv
4319                            .path
4320                            .get_ident()
4321                            .map(|i| i.to_string())
4322                            .unwrap_or_default();
4323                        return 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) => {
4338                    if 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", ...)
4343                        if let Some(spec) =
4344                            crate::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 = "...")
4350                        list.parse_nested_meta(|meta| {
4351                            if meta.path.is_ident("generic") {
4352                                let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
4353                                let value: syn::LitStr = meta.input.parse()?;
4354                                s3_generic = Some(crate::naming::parse_generic(&value)?);
4355                            } else if meta.path.is_ident("class") {
4356                                let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
4357                                let value: syn::LitStr = meta.input.parse()?;
4358                                s3_class = Some(value.value());
4359                            } else {
4360                                return Err(
4361                                    meta.error("unknown s3 option; expected `generic` or `class`")
4362                                );
4363                            }
4364                            Ok(())
4365                        })?;
4366                        // Validate: s3 requires class (generic can default to function name)
4367                        if s3_class.is_none() {
4368                            return 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)
4376                        let mut expr = None;
4377                        let mut add = true;
4378                        let mut after = true;
4379                        list.parse_nested_meta(|meta| {
4380                            if meta.path.is_ident("expr") {
4381                                let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
4382                                let value: syn::LitStr = meta.input.parse()?;
4383                                expr = Some(value.value());
4384                            } else if meta.path.is_ident("add") {
4385                                let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
4386                                let value: syn::LitBool = meta.input.parse()?;
4387                                add = value.value;
4388                            } else if meta.path.is_ident("after") {
4389                                let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
4390                                let value: syn::LitBool = meta.input.parse()?;
4391                                after = value.value;
4392                            } else {
4393                                return Err(meta.error(
4394                                    "unknown r_on_exit option; expected `expr`, `add`, or `after`",
4395                                ));
4396                            }
4397                            Ok(())
4398                        })?;
4399                        let 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.
4413                        let opt_name = ident.to_string();
4414                        return 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
4423                        return 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        }
4433
4434        // Validate: `internal` and `noexport` are redundant together
4435        if internal && noexport {
4436            return 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        }
4443
4444        // Validate: `export` conflicts with `noexport` and `internal`
4445        if export && noexport {
4446            return Err(syn::Error::new(
4447                proc_macro2::Span::call_site(),
4448                "`export` and `noexport` are contradictory.",
4449            ));
4450        }
4451        if export && internal {
4452            return Err(syn::Error::new(
4453                proc_macro2::Span::call_site(),
4454                "`export` and `internal` are contradictory.",
4455            ));
4456        }
4457
4458        // 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.
4461        if postfix.is_some() && r_name.is_some() {
4462            return 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        }
4467        if postfix.is_some() && (s3_generic.is_some() || s3_class.is_some()) {
4468            return 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        }
4474
4475        // Validate: `call = caller` is for internal entry points only.
4476        use crate::r_wrapper_builder::CallAttribution;
4477        if call_attr == Some(CallAttribution::Caller) && !(noexport || internal) {
4478            return 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.
4488        if call_arg && call_attr == Some(CallAttribution::Caller) {
4489            return 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.
4498        if call_arg && call_attr == Some(CallAttribution::NoCall) {
4499            return 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        }
4505        if call_arg && (s3_generic.is_some() || s3_class.is_some()) {
4506            return 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        }
4512        if r_name.is_some() && (s3_generic.is_some() || s3_class.is_some()) {
4513            return 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        }
4519
4520        if serialize && (unwrap_in_r || serde_error.is_some()) {
4521            return 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        }
4526
4527        // 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.
4530        if serde_error.is_some() && unwrap_in_r {
4531            return 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        }
4537
4538        Ok(Self {
4539            force_invisible,
4540            check_interrupt,
4541            coerce_all: coerce_all.unwrap_or(falsecfg!(feature = "coerce-default")),
4542            rng: rng || rng_seed.is_some(),
4543            rng_seed,
4544            unwrap_in_r,
4545            serialize,
4546            wrap,
4547            serde_error,
4548            preconditions,
4549            call_attribution: call_attr,
4550            call_arg,
4551            return_pref,
4552            return_pref_span,
4553            s3_generic,
4554            s3_class,
4555            dots_spec,
4556            dots_policy,
4557            dots_span,
4558            lifecycle,
4559            strict: strict.unwrap_or(falsecfg!(feature = "strict-default")),
4560            internal,
4561            noexport,
4562            export,
4563            doc,
4564            c_symbol,
4565            r_name,
4566            postfix,
4567            r_entry,
4568            r_post_checks,
4569            r_on_exit,
4570        })
4571    }
4572}
4573// endregion