Skip to main content

miniextendr_macros/
r_preconditions.rs

1//! R-side precondition generation for type checking.
2//!
3//! Generates argument checks in R wrapper functions that run BEFORE the `.Call()` boundary.
4//! This gives users clear, idiomatic R error messages with proper stack traces instead of
5//! Rust panic messages.
6//!
7//! Each check tests ONE thing and names the requirement it enforces:
8//!
9//! ```r
10//! add <- function(a, b) {
11//!   if (!isTRUE(is.integer(a))) .miniextendr_arg_error("a", "must be integer")
12//!   if (!isTRUE(length(a) == 1L)) .miniextendr_arg_error("a", "must have length 1")
13//!   if (!isTRUE(is.integer(b))) .miniextendr_arg_error("b", "must be integer")
14//!   if (!isTRUE(length(b) == 1L)) .miniextendr_arg_error("b", "must have length 1")
15//!   .Call(C_add, .call = sys.call(), a, b)
16//! }
17//! ```
18//!
19//! A failing check calls the preamble helper `.miniextendr_arg_error`
20//! (`miniextendr-api/src/registry.rs`), which raises the same condition as a
21//! failed Rust conversion: the crate's `conversion_error_class`, `rust_error`,
22//! `kind = "conversion"` and `e$param`, with the message `'a' must be integer`
23//! (#1591). A passing check costs one `isTRUE()` test; the condition is only
24//! built on failure. `isTRUE()` keeps `stopifnot()`'s failure semantics (`NA`
25//! fails too), and the guards are cheaper than the `stopifnot()` call they
26//! replace. [`conversion_expectation`] gives the Rust conversion the same
27//! vocabulary for its messages.
28
29use std::collections::{HashMap, HashSet};
30
31use crate::naming::r_string_escape;
32
33/// A single R-side check on one parameter: a requirement and the R condition
34/// enforcing it.
35///
36/// Formatted as a guard (see [`RAssertion::to_guard`]):
37/// `if (!isTRUE(is.numeric(x))) .miniextendr_arg_error("x", "must be numeric")`.
38struct RAssertion {
39    /// R name of the checked parameter (`e$param` on failure).
40    param: String,
41    /// What the parameter must satisfy, without the parameter name
42    /// (`must be numeric`). The condition message is `'<param>' <requirement>`.
43    requirement: String,
44    /// R expression that must evaluate to `TRUE` for the check to pass.
45    condition: String,
46    /// The author's own condition message (`message = "..."` on `inherits` /
47    /// `not_inherits` / `no_na`; an `inherits` message also on the
48    /// parameter's type checks),
49    /// used verbatim instead of `'<param>' <requirement>`.
50    message: Option<String>,
51}
52
53impl RAssertion {
54    /// Create a new assertion on `param` with its requirement and R condition expression.
55    fn new(
56        param: impl Into<String>,
57        requirement: impl Into<String>,
58        condition: impl Into<String>,
59    ) -> Self {
60        Self {
61            param: param.into(),
62            requirement: requirement.into(),
63            condition: condition.into(),
64            message: None,
65        }
66    }
67
68    /// Use `message` verbatim as the condition message of a failure.
69    fn with_message(mut self, message: Option<&String>) -> Self {
70        self.message = message.cloned();
71        self
72    }
73
74    /// The condition message a failure raises: the author's message, else
75    /// `'<param>' <requirement>`.
76    #[cfg(test)]
77    fn message(&self) -> String {
78        match &self.message {
79            Some(message) => message.clone(),
80            None => format!("'{}' {}", self.param, self.requirement),
81        }
82    }
83
84    /// Format as a guard that raises an argument error on failure:
85    /// `if (!isTRUE(condition)) .miniextendr_arg_error("param", "requirement")`,
86    /// or with the author's message
87    /// `if (!isTRUE(condition)) .miniextendr_arg_error("param", message = "...")`.
88    ///
89    /// `call` is the call the error is attributed to. `None` leaves the
90    /// helper's default, the wrapper's own call (what `stopifnot()` reported);
91    /// a `call = caller` wrapper passes `.mx_call` (#1548). Next to a named
92    /// `message` the call is named too: positionally it would bind to `what`.
93    fn to_guard(&self, call: Option<&str>) -> String {
94        match &self.message {
95            None => {
96                let call_arg = call.map(|c| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", {0}", c))
    })format!(", {c}")).unwrap_or_default();
97                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if (!isTRUE({0})) .miniextendr_arg_error(\"{1}\", \"{2}\"{3})",
                self.condition, self.param, self.requirement, call_arg))
    })format!(
98                    "if (!isTRUE({})) .miniextendr_arg_error(\"{}\", \"{}\"{})",
99                    self.condition, self.param, self.requirement, call_arg
100                )
101            }
102            Some(message) => {
103                let call_arg = call.map(|c| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", call = {0}", c))
    })format!(", call = {c}")).unwrap_or_default();
104                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if (!isTRUE({0})) .miniextendr_arg_error(\"{1}\", message = \"{2}\"{3})",
                self.condition, self.param, r_string_escape(message),
                call_arg))
    })format!(
105                    "if (!isTRUE({})) .miniextendr_arg_error(\"{}\", message = \"{}\"{})",
106                    self.condition,
107                    self.param,
108                    r_string_escape(message),
109                    call_arg
110                )
111            }
112        }
113    }
114
115    /// Wrap for nullable: prepend `is.null(param) || ` to the condition,
116    /// and adjust the requirement to mention NULL. With `plain_na` (an
117    /// optional scalar, #2305) a plain `NA` passes too
118    /// ([`plain_na_check`]): the Rust conversion reads either as `None`.
119    /// The requirement keeps naming the type a value must have.
120    fn nullable(self, plain_na: bool) -> Self {
121        let requirement = if let Some(rest) = self.requirement.strip_prefix("must be ") {
122            // "must be character" → "must be NULL or character"
123            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("must be NULL or {0}", rest))
    })format!("must be NULL or {rest}")
124        } else if let Some(rest) = self.requirement.strip_prefix("must have ") {
125            // "must have length 1" → "must be NULL or have length 1"
126            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("must be NULL or have {0}", rest))
    })format!("must be NULL or have {rest}")
127        } else {
128            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} (or NULL)", self.requirement))
    })format!("{} (or NULL)", self.requirement)
129        };
130        let absent = if plain_na {
131            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("is.null({1}) || {0}",
                plain_na_check(&self.param), self.param))
    })format!(
132                "is.null({p}) || {}",
133                plain_na_check(&self.param),
134                p = self.param
135            )
136        } else {
137            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("is.null({0})", self.param))
    })format!("is.null({})", self.param)
138        };
139        Self {
140            condition: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1} || {0}", self.condition,
                absent))
    })format!("{absent} || {}", self.condition),
141            param: self.param,
142            requirement,
143            message: self.message,
144        }
145    }
146}
147
148/// The R test for a plain `NA`, R's untyped missing value, as the argument
149/// `param`: `(is.logical(p) && length(p) == 1L && is.na(p))`. An optional
150/// scalar argument (`Option<T>` / `Nullable<T>` of a scalar `T`, a scalar
151/// `match_arg` / `choices` choice under `Option`) reads it as "no value",
152/// like `NULL` (#2305): the type checks pass it ([`RAssertion::nullable`])
153/// and the choice prelude skips it
154/// ([`crate::r_wrapper_builder::CallAttribution::match_arg_statement`]),
155/// as the Rust conversions read it as `None`
156/// (`miniextendr_api::from_r::is_null_or_plain_na`). `&&` stops before
157/// `is.na()` for a value of another type or length, so the test is always
158/// `TRUE` or `FALSE`. An optional vector keeps `is.null()` alone: there a
159/// plain `NA` is a logical vector of length one.
160pub(crate) fn plain_na_check(param: &str) -> String {
161    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("(is.logical({0}) && length({0}) == 1L && is.na({0}))",
                param))
    })format!("(is.logical({param}) && length({param}) == 1L && is.na({param}))")
162}
163
164/// Per-function knobs that influence precondition codegen.
165///
166/// Coercion preserves numeric input types, extends `bool` / `Vec<bool>`
167/// checks to accept integers as well as logicals, widens the native
168/// `i32` / `Vec<i32>` gates to whole-number doubles and the native `f64` /
169/// `Vec<f64>` gates to every numeric source, in the `Option<T>` and
170/// `Vec<Option<T>>` forms too (see `coerce_widened`). Other types keep their checks.
171/// Strict input conversion remains enforced in Rust, where range and precision
172/// failures can carry contextual diagnostics.
173#[derive(#[automatically_derived]impl ::core::clone::Clone for PreconditionOptions {
    #[inline]
    fn clone(&self) -> Self {
        PreconditionOptions {
            coerce_all: ::core::clone::Clone::clone(&self.coerce_all),
            coerce_params: ::core::clone::Clone::clone(&self.coerce_params),
            explicit: ::core::clone::Clone::clone(&self.explicit),
            unchecked: ::core::clone::Clone::clone(&self.unchecked),
            formals: ::core::clone::Clone::clone(&self.formals),
        }
    }
}Clone, #[automatically_derived]impl ::core::default::Default for PreconditionOptions
    {
    #[inline]
    fn default() -> Self {
        PreconditionOptions {
            coerce_all: ::core::default::Default::default(),
            coerce_params: ::core::default::Default::default(),
            explicit: ::core::default::Default::default(),
            unchecked: ::core::default::Default::default(),
            formals: ::core::default::Default::default(),
        }
    }
}Default)]
174pub struct PreconditionOptions {
175    /// `coerce` knob is active for all parameters (`coerce_all`).
176    pub coerce_all: bool,
177    /// R-normalized names of parameters with a per-param `coerce` attribute.
178    pub coerce_params: HashSet<String>,
179    /// Checks the author named per parameter (`inherits`, `not_inherits`,
180    /// `no_na`), keyed by R-normalized parameter name.
181    pub explicit: HashMap<String, ExplicitChecks>,
182    /// R-normalized names of the parameters whose type-derived checks are
183    /// dropped (each one resolved by [`resolve_type_checks`]). Their
184    /// [`explicit`](Self::explicit) checks are still emitted.
185    pub unchecked: HashSet<String>,
186    /// The R formal of each parameter (#1842): the name every check, every
187    /// argument error and every map above uses. Without a declared formal,
188    /// the Rust name without leading underscores.
189    pub formals: crate::r_wrapper_builder::Formals,
190}
191
192impl PreconditionOptions {
193    /// Returns `true` if the parameter `r_name` is coerced (function-wide or
194    /// per-param).
195    fn is_coerced(&self, r_name: &str) -> bool {
196        self.coerce_all || self.coerce_params.contains(r_name)
197    }
198}
199
200// region: which parameters keep their type-derived checks (#1566 §2)
201
202/// Whether one parameter keeps its type-derived R-side checks, from every
203/// spelling that can decide it, most specific first; the first that speaks
204/// wins:
205///
206/// 1. `param`: a `Checked<T>` / `Unchecked<T>` marker, the per-parameter
207///    `preconditions` / `no_preconditions`, or a method's
208///    `preconditions(x)` / `no_preconditions(x)` list (merged at parse time,
209///    where a marker and a keyword that disagree are an error);
210/// 2. `item`: the function's or method's own `preconditions` /
211///    `no_preconditions`;
212/// 3. `impl_level`: the impl block's (`None` for a free function);
213/// 4. `crate_default`: `[package.metadata.miniextendr] preconditions`;
214/// 5. `no_preconditions_default`: the `no-preconditions-default` feature;
215/// 6. otherwise the checks are kept.
216///
217/// `Some(true)` everywhere means "keep".
218pub(crate) fn resolve_type_checks(
219    param: Option<bool>,
220    item: Option<bool>,
221    impl_level: Option<bool>,
222    crate_default: Option<bool>,
223    no_preconditions_default: bool,
224) -> bool {
225    param.unwrap_or_else(|| {
226        resolve_item_type_checks(item, impl_level, crate_default, no_preconditions_default)
227    })
228}
229
230/// [`resolve_type_checks`] without a per-parameter spelling: whether an item
231/// (function or method) keeps its type-derived checks by default, ranks 2 to
232/// 6. The condition-raise codegen keys on this item-level decision.
233pub(crate) fn resolve_item_type_checks(
234    item: Option<bool>,
235    impl_level: Option<bool>,
236    crate_default: Option<bool>,
237    no_preconditions_default: bool,
238) -> bool {
239    item.or(impl_level)
240        .or(crate_default)
241        .unwrap_or(!no_preconditions_default)
242}
243
244/// The R formals (`formals`) of the parameters of `inputs` whose
245/// type-derived checks are dropped, given each one's rank-1 decision
246/// (`param`, keyed by Rust name) and the item, impl and crate defaults
247/// ([`resolve_type_checks`]; the feature is this macro crate's
248/// `no-preconditions-default`).
249pub(crate) fn unchecked_params(
250    inputs: &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
251    formals: &crate::r_wrapper_builder::Formals,
252    param: impl Fn(&str) -> Option<bool>,
253    item: Option<bool>,
254    impl_level: Option<bool>,
255    crate_default: Option<bool>,
256) -> HashSet<String> {
257    inputs
258        .iter()
259        .filter_map(|arg| {
260            let syn::FnArg::Typed(pt) = arg else {
261                return None;
262            };
263            let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
264                return None;
265            };
266            let name = crate::naming::ident_name(&pat_ident.ident);
267            let keep = resolve_type_checks(
268                param(&name),
269                item,
270                impl_level,
271                crate_default,
272                falsecfg!(feature = "no-preconditions-default"),
273            );
274            (!keep).then(|| formals.of(&name))
275        })
276        .collect()
277}
278
279/// Whether a parameter type has type-derived R-side checks at all, i.e.
280/// whether `Checked` / `Unchecked` and the per-parameter keywords have
281/// anything to keep or drop (`SEXP`, `Missing<T>`, `ExternalPtr<T>`,
282/// `&Dots` and unknown types have none).
283pub(crate) fn has_type_check(ty: &syn::Type) -> bool {
284    r_check_for_type(ty).is_some()
285}
286
287// endregion
288
289/// R-side checks the author asked for by name on one parameter, rather than
290/// ones derived from its Rust type.
291///
292/// Spelled `#[miniextendr(inherits = "cls", not_inherits = "bad", no_na)]` on
293/// a standalone fn parameter, or `inherits(x = "cls")` /
294/// `not_inherits(x = "bad")` / `no_na(x)` on an impl or trait method. They
295/// are the same kind of guards as the type checks, raising the same argument
296/// error. The NA check runs first, so an argument holding `NA` gets its
297/// message (`'x' must not be NA`) whatever its class, type or range, the
298/// checks that would otherwise refuse a typed `NA` (an `NA` is logical, and
299/// fails a range check) before it. The class checks run next, before the
300/// parameter's type checks, so a value of the wrong class gets the class
301/// message whatever its type: `inherits` first, then `not_inherits` (#1815). That order matters for the classes a
302/// `not_inherits` typically refuses: `is.numeric()` is `FALSE` for a
303/// `difftime`, `Date` or `POSIXt`, so after an `AsNumeric` type check the
304/// refusal would never be reached. An `inherits` message also replaces the
305/// messages of the parameter's type checks; a `not_inherits` message does
306/// not, since a value that passes it is of none of the refused classes and is
307/// judged by its type. All survive `no_preconditions`: the Rust conversion does not
308/// repeat them, so dropping them would change what the function accepts.
309///
310/// `no_na` also has a Rust half. A type can read more inputs as missing than
311/// `anyNA()` sees (the reading markers `AsNumeric*` / `AsCharacter*` read the
312/// text `"NA"`, blank strings, a factor `NA` level as `NA`), so the C wrapper
313/// checks the converted value too (`TryFromSexp::__mx_has_na`, see
314/// `RustConversionBuilder::with_no_na`) and raises the same condition with
315/// the same message ([`no_na_message`]). An `Either` parameter has only the
316/// Rust half: the arm the value converted to checks the input
317/// ([`no_na_checked_after_conversion`]).
318///
319/// Each check can carry the author's own condition message
320/// (`inherits(class = "cls", message = "...")`,
321/// `not_inherits(class = "bad", message = "...")`, `no_na(message = "...")`;
322/// method level `inherits(x(class = "cls", message = "..."))`,
323/// `not_inherits(x(class = "bad", message = "..."))`,
324/// `no_na(x(message = "..."))`), used verbatim in place of the generated
325/// `'x' must inherit from 'cls'`. The condition is otherwise the same.
326///
327/// An `inherits` check can also give a value that fails it a message chosen
328/// by the value's class (#1824): `inherits(class = "cls",
329/// when(class = "data.frame", message = "..."))`, method level
330/// `inherits(x(class = "cls", when(class = "data.frame", message = "...")))`
331/// ([`InheritsHint`]).
332#[derive(#[automatically_derived]impl ::core::clone::Clone for ExplicitChecks {
    #[inline]
    fn clone(&self) -> Self {
        ExplicitChecks {
            inherits: ::core::clone::Clone::clone(&self.inherits),
            inherits_message: ::core::clone::Clone::clone(&self.inherits_message),
            inherits_hints: ::core::clone::Clone::clone(&self.inherits_hints),
            not_inherits: ::core::clone::Clone::clone(&self.not_inherits),
            not_inherits_message: ::core::clone::Clone::clone(&self.not_inherits_message),
            no_na: ::core::clone::Clone::clone(&self.no_na),
            no_na_message: ::core::clone::Clone::clone(&self.no_na_message),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for ExplicitChecks {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            "ExplicitChecks inherits inherits_message inherits_hints not_inherits not_inherits_message no_na no_na_message";
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.inherits, &self.inherits_message, &self.inherits_hints,
                        &self.not_inherits, &self.not_inherits_message, &self.no_na,
                        &&self.no_na_message];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, names, values)
    }
}Debug, #[automatically_derived]impl ::core::default::Default for ExplicitChecks {
    #[inline]
    fn default() -> Self {
        ExplicitChecks {
            inherits: ::core::default::Default::default(),
            inherits_message: ::core::default::Default::default(),
            inherits_hints: ::core::default::Default::default(),
            not_inherits: ::core::default::Default::default(),
            not_inherits_message: ::core::default::Default::default(),
            no_na: ::core::default::Default::default(),
            no_na_message: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    ExplicitChecks {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ExplicitChecks {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.no_na == other.no_na && self.inherits == other.inherits &&
                            self.inherits_message == other.inherits_message &&
                        self.inherits_hints == other.inherits_hints &&
                    self.not_inherits == other.not_inherits &&
                self.not_inherits_message == other.not_inherits_message &&
            self.no_na_message == other.no_na_message
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ExplicitChecks {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Option<Vec<String>>>;
        let _: ::core::cmp::AssertParamIsEq<Option<String>>;
        let _: ::core::cmp::AssertParamIsEq<Vec<InheritsHint>>;
        let _: ::core::cmp::AssertParamIsEq<Option<Vec<String>>>;
        let _: ::core::cmp::AssertParamIsEq<Option<String>>;
        let _: ::core::cmp::AssertParamIsEq<bool>;
        let _: ::core::cmp::AssertParamIsEq<Option<String>>;
    }
}Eq)]
333pub struct ExplicitChecks {
334    /// `inherits = "cls"` / `inherits("a", "b")`: the argument must inherit
335    /// from at least one of these classes (`inherits(x, c(...))`).
336    pub inherits: Option<Vec<String>>,
337    /// `message = "..."` in `inherits(...)`: the message of a failed class
338    /// check, for all of its classes, and of that parameter's R type checks.
339    /// Only set together with `inherits`.
340    pub inherits_message: Option<String>,
341    /// `when(class = "...", message = "...")` in `inherits(...)`: the
342    /// messages a value that fails the `inherits` check gets for its class,
343    /// in the order written. Only set together with `inherits`.
344    pub inherits_hints: Vec<InheritsHint>,
345    /// `not_inherits = "cls"` / `not_inherits("a", "b")`: the argument must
346    /// inherit from none of these classes (`!inherits(x, c(...))`, #1815).
347    pub not_inherits: Option<Vec<String>>,
348    /// `message = "..."` in `not_inherits(...)`: the message of a failed
349    /// `not_inherits` check, for all of its classes. Unlike the `inherits`
350    /// message it leaves the type checks' messages alone. Only set together
351    /// with `not_inherits`.
352    pub not_inherits_message: Option<String>,
353    /// `no_na`: the argument must not contain `NA` (`!anyNA(x)`, so `NaN`
354    /// is refused too, as `is.na()` does), nor a value its type reads as `NA`
355    /// (checked in Rust after the conversion). For an `Either`, both checks
356    /// run in Rust, by the arm the value converted to.
357    pub no_na: bool,
358    /// `no_na(message = "...")`: the message of a failed NA check. Only set
359    /// together with `no_na`.
360    pub no_na_message: Option<String>,
361}
362
363impl ExplicitChecks {
364    /// Whether any check is requested.
365    pub fn is_empty(&self) -> bool {
366        self.inherits.is_none() && self.not_inherits.is_none() && !self.no_na
367    }
368
369    /// Merge `other` into `self` (a parameter may carry several attributes).
370    /// The `inherits` hints of `other` follow those of `self`, so the hints
371    /// keep the order they are written in.
372    ///
373    /// Fails when both give a message for the same check; the error names
374    /// the check.
375    pub fn merge(&mut self, other: ExplicitChecks) -> Result<(), String> {
376        merge_message(
377            &mut self.inherits_message,
378            other.inherits_message,
379            "inherits",
380        )?;
381        merge_message(
382            &mut self.not_inherits_message,
383            other.not_inherits_message,
384            "not_inherits",
385        )?;
386        merge_message(&mut self.no_na_message, other.no_na_message, "no_na")?;
387        if let Some(classes) = other.inherits {
388            self.inherits.get_or_insert_with(Vec::new).extend(classes);
389        }
390        self.inherits_hints.extend(other.inherits_hints);
391        if let Some(classes) = other.not_inherits {
392            self.not_inherits
393                .get_or_insert_with(Vec::new)
394                .extend(classes);
395        }
396        self.no_na |= other.no_na;
397        Ok(())
398    }
399
400    /// The error for a parameter whose checks contradict each other: a class
401    /// both in `inherits` and in `not_inherits`, which no argument could
402    /// satisfy through that class, or an `inherits` class in a `when(...)`
403    /// hint, whose message could never be shown (a value of that class
404    /// passes `inherits`). `None` when they agree.
405    ///
406    /// A hint class may also be a `not_inherits` class: a value of that
407    /// class alone gets the hint, and one that also inherits from a required
408    /// class passes the hint and `inherits` and is refused by `not_inherits`.
409    ///
410    /// Run once every attribute of the parameter is merged: the
411    /// `inherits = "cls"` spelling adds its class without a merge, and a
412    /// hint can name a class that another attribute requires.
413    pub fn class_conflict(&self, param: &str) -> Option<String> {
414        let required = self.inherits.as_deref().unwrap_or_default();
415        if let Some(class) = self
416            .not_inherits
417            .iter()
418            .flatten()
419            .find(|c| required.contains(c))
420        {
421            return Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("class `{0}` is in both `inherits` and `not_inherits` on parameter `{1}`; name it in only one of them",
                class, param))
    })format!(
422                "class `{class}` is in both `inherits` and `not_inherits` on parameter `{param}`; \
423                 name it in only one of them"
424            ));
425        }
426        let class = self
427            .inherits_hints
428            .iter()
429            .flat_map(|hint| &hint.classes)
430            .find(|c| required.contains(c))?;
431        Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("class `{0}` is in both `inherits` and a `when(...)` hint on parameter `{1}`; a value of that class passes `inherits`, so the hint would never be shown: drop it from `when(...)`",
                class, param))
    })format!(
432            "class `{class}` is in both `inherits` and a `when(...)` hint on parameter \
433             `{param}`; a value of that class passes `inherits`, so the hint would never be \
434             shown: drop it from `when(...)`"
435        ))
436    }
437
438    /// The class checks (`inherits`, then `not_inherits`) for parameter
439    /// `param` of type `ty`, which run before the parameter's type checks.
440    /// Empty without either.
441    ///
442    /// The `inherits` hints come first, one check each in the order written,
443    /// so a refused value gets the first hint naming one of its classes:
444    /// `inherits(p, <required>) || !inherits(p, <hint classes>)`, failing
445    /// with the hint's message. A value that passes `inherits` passes every
446    /// hint, so a hint changes the message of a refusal, never what is
447    /// accepted.
448    ///
449    /// An `Option<T>` / `Missing<T>` parameter passes `NULL` / an omitted
450    /// argument (see [`guarded`]).
451    fn class_assertions(&self, param: &str, ty: &syn::Type) -> Vec<RAssertion> {
452        let mut out = Vec::new();
453        if let Some(classes) = &self.inherits {
454            let (what, class_arg) = class_list_r(classes);
455            for hint in &self.inherits_hints {
456                let (_, hint_arg) = class_list_r(&hint.classes);
457                out.push(
458                    RAssertion::new(
459                        param,
460                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("must inherit from {0}", what))
    })format!("must inherit from {what}"),
461                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("inherits({0}, {1}) || !inherits({0}, {2})",
                param, class_arg, hint_arg))
    })format!("inherits({param}, {class_arg}) || !inherits({param}, {hint_arg})"),
462                    )
463                    .with_message(Some(&hint.message)),
464                );
465            }
466            out.push(
467                RAssertion::new(
468                    param,
469                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("must inherit from {0}", what))
    })format!("must inherit from {what}"),
470                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("inherits({0}, {1})", param,
                class_arg))
    })format!("inherits({param}, {class_arg})"),
471                )
472                .with_message(self.inherits_message.as_ref()),
473            );
474        }
475        if let Some(classes) = &self.not_inherits {
476            let (what, class_arg) = class_list_r(classes);
477            out.push(
478                RAssertion::new(
479                    param,
480                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("must not inherit from {0}", what))
    })format!("must not inherit from {what}"),
481                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("!inherits({0}, {1})", param,
                class_arg))
    })format!("!inherits({param}, {class_arg})"),
482                )
483                .with_message(self.not_inherits_message.as_ref()),
484            );
485        }
486        guarded(param, ty, out)
487    }
488
489    /// The NA check (`no_na`) for parameter `param` of type `ty`, which runs
490    /// before the parameter's other checks, with its own message. Empty without
491    /// `no_na`, and for an `Either` parameter that is not a choice parameter
492    /// (`choice`: `match_arg` / `choices`), whose NA check runs in Rust after
493    /// the conversion ([`no_na_checked_after_conversion`]).
494    ///
495    /// An `Option<T>` / `Missing<T>` parameter passes `NULL` / an omitted
496    /// argument (see [`guarded`]).
497    fn value_assertions(&self, param: &str, ty: &syn::Type, choice: bool) -> Vec<RAssertion> {
498        let mut out = Vec::new();
499        if self.no_na && (choice || !no_na_checked_after_conversion(ty)) {
500            out.push(
501                RAssertion::new(param, no_na_requirement(ty), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("!anyNA({0})", param))
    })format!("!anyNA({param})"))
502                    .with_message(self.no_na_message.as_ref()),
503            );
504        }
505        guarded(param, ty, out)
506    }
507
508    /// The message of the parameter's R type checks: the `inherits` message,
509    /// when there is one. Without it the type checks keep their generated
510    /// messages. A `not_inherits` message is not one: a value that passed
511    /// `not_inherits` is of none of the refused classes, so its type check
512    /// keeps its own wording.
513    fn type_check_message(&self) -> Option<&String> {
514        self.inherits_message.as_ref()
515    }
516}
517
518/// One `when(class = "...", message = "...")` hint of an `inherits` check
519/// (#1824): the message a value gets when it fails the check and inherits
520/// from one of `classes`, in place of the check's own. A `data.frame` passed
521/// where a model object is expected can be told which function takes a data
522/// frame, while `NULL` or a number gets the plain refusal.
523#[derive(#[automatically_derived]impl ::core::clone::Clone for InheritsHint {
    #[inline]
    fn clone(&self) -> Self {
        InheritsHint {
            classes: ::core::clone::Clone::clone(&self.classes),
            message: ::core::clone::Clone::clone(&self.message),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for InheritsHint {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "InheritsHint classes message", &self.classes, &&self.message)
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    InheritsHint {
}
#[automatically_derived]impl ::core::cmp::PartialEq for InheritsHint {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.classes == other.classes && self.message == other.message
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for InheritsHint {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Vec<String>>;
        let _: ::core::cmp::AssertParamIsEq<String>;
    }
}Eq)]
524pub struct InheritsHint {
525    /// The classes the hint is for (any one of them).
526    pub classes: Vec<String>,
527    /// The condition message, used verbatim.
528    pub message: String,
529}
530
531/// A class check's classes in R: the quoted list for its message
532/// (`'a', 'b' or 'c'`) and the argument of `inherits()` (`"a"` or
533/// `c("a", "b", "c")`), each class escaped as an R string.
534fn class_list_r(classes: &[String]) -> (String, String) {
535    let quoted: Vec<String> = classes
536        .iter()
537        .map(|c| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}\'", r_string_escape(c)))
    })format!("'{}'", r_string_escape(c)))
538        .collect();
539    let literals: Vec<String> = classes
540        .iter()
541        .map(|c| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"", r_string_escape(c)))
    })format!("\"{}\"", r_string_escape(c)))
542        .collect();
543    let what = match quoted.as_slice() {
544        [one] => one.clone(),
545        [init @ .., last] => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} or {1}", init.join(", "),
                last))
    })format!("{} or {last}", init.join(", ")),
546        [] => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("a class check is parsed as a non-empty class list")));
}unreachable!("a class check is parsed as a non-empty class list"),
547    };
548    let class_arg = match literals.as_slice() {
549        [one] => one.clone(),
550        _ => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("c({0})", literals.join(", ")))
    })format!("c({})", literals.join(", ")),
551    };
552    (what, class_arg)
553}
554
555/// Let an `Option<T>` (or `Nullable<T>`) parameter pass `NULL`, and a
556/// `Missing<T>` parameter an omitted argument, in the named checks `out` on
557/// parameter `param` of type `ty`: each condition gains an
558/// `is.null(param) || ` / `missing(param) || ` prefix. The failure message
559/// names only the failed requirement: it is shown only for a present,
560/// non-`NULL` value.
561fn guarded(param: &str, ty: &syn::Type, mut out: Vec<RAssertion>) -> Vec<RAssertion> {
562    let guard = if crate::miniextendr_fn::is_missing_type(ty) {
563        Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("missing({0})", param))
    })format!("missing({param})"))
564    } else if crate::type_inspect::is_optional_type(ty) {
565        Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("is.null({0})", param))
    })format!("is.null({param})"))
566    } else {
567        None
568    };
569    if let Some(guard) = guard {
570        for a in &mut out {
571            a.condition = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1} || {0}", a.condition, guard))
    })format!("{guard} || {}", a.condition);
572        }
573    }
574    out
575}
576
577/// Whether a `no_na` parameter of Rust type `ty` is checked for `NA` only
578/// in Rust, after the conversion, with no R guard: an `Either<L, R>`, also
579/// under `Missing` and `Option`. The layers are peeled as for a choice
580/// parameter ([`crate::type_inspect::choice_layers`]). A plain
581/// `Option<Either<..>>` converts through `TryFromSexp`, which reads `NULL` as
582/// `None` (no `NA`) and asks the `Either` otherwise; a choice
583/// `Option<Either<Mode, X>>` keeps the guard (see below). The type is read
584/// as written: an alias, a newtype or a `Result<Either<..>, ()>` keeps the
585/// guard.
586///
587/// One `!anyNA(x)` on the whole argument is wrong for an arm with its own
588/// reading of `NA` (a data frame arm whose cells may be missing), and it
589/// scans the input a second time. So the C wrapper asks the arm the value
590/// converted to (`TryFromSexp::__mx_input_has_na`): by default the arm runs
591/// `anyNA()`'s check on the input in Rust, and a `DataFrame` arm refuses
592/// nothing. A choice parameter (`match_arg` / `choices`) keeps the R guard:
593/// its conversion does not go through `TryFromSexp`, so no Rust check follows.
594pub(crate) fn no_na_checked_after_conversion(ty: &syn::Type) -> bool {
595    crate::type_inspect::choice_layers(ty)
596        .either_right
597        .is_some()
598}
599
600/// What a `no_na` parameter of Rust type `ty` must satisfy, without the
601/// parameter name: `must not contain NA` for a value holding several values
602/// ([`no_na_holds_several`]), else `must not be NA`.
603///
604/// Shared by the R guard and the Rust check that the C wrapper runs after the
605/// conversion (see [`no_na_message`]), so both word a failure alike.
606pub(crate) fn no_na_requirement(ty: &syn::Type) -> String {
607    let verb = if no_na_holds_several(ty) {
608        "contain"
609    } else {
610        "be"
611    };
612    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("must not {0} NA", verb))
    })format!("must not {verb} NA")
613}
614
615/// Whether a `no_na` value of Rust type `ty` holds several values, looking
616/// through the layers `no_na` checks through: `Missing`, `Option` (or
617/// `Nullable`), `Result<T, _>` (its `T`) and `Either<L, R>`, which holds
618/// several when either arm does. The text is fixed at compile time, before
619/// the conversion picks an arm, and `contain` also reads right for one value.
620fn no_na_holds_several(ty: &syn::Type) -> bool {
621    let ty = crate::miniextendr_fn::get_missing_inner_type(ty).unwrap_or(ty);
622    let ty = crate::type_inspect::optional_inner_type(ty).unwrap_or(ty);
623    if let Some((left, right)) = crate::type_inspect::either_arms(ty) {
624        return no_na_holds_several(left) || no_na_holds_several(right);
625    }
626    if let syn::Type::Path(tp) = ty
627        && let Some(seg) = tp.path.segments.last()
628        && seg.ident == "Result"
629        && let Some(ok) = crate::type_inspect::first_type_argument(seg)
630    {
631        return no_na_holds_several(ok);
632    }
633    is_vector_valued(ty)
634}
635
636/// The condition message of a failed `no_na` check on parameter `param` of
637/// type `ty`: the author's `no_na(message = "...")` verbatim (`custom`), else
638/// `'<param>' must not be NA` / `'<param>' must not contain NA`
639/// ([`no_na_requirement`]). The R guard builds the same text in R
640/// (`.miniextendr_arg_error`); the C wrapper's post-conversion check passes
641/// this one to `arg_check_condition_value`.
642pub(crate) fn no_na_message(param: &str, ty: &syn::Type, custom: Option<&str>) -> String {
643    match custom {
644        Some(message) => message.to_string(),
645        None => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{1}\' {0}",
                no_na_requirement(ty), param))
    })format!("'{param}' {}", no_na_requirement(ty)),
646    }
647}
648
649/// Whether an argument of Rust type `ty` holds several values, so a `no_na`
650/// failure reads `must not contain NA` rather than `must not be NA`.
651///
652/// The type table decides when it knows the type ([`RTypeCheck::is_vector`]):
653/// `Vec<T>` and slices, the vector markers (`AsNumericVec`, `AsCharacterVec`,
654/// any marker whose table entry is a vector check), maps and lists. For a type the
655/// table does not know, the shape decides: `Vec<T>`, `Box<[T]>`, slices and
656/// arrays, and a type named `...Vec` (the vector half of a marker family such
657/// as `AsFromStrVec` / `AsDisplayVec`, or a vector type like `BitVec`).
658fn is_vector_valued(ty: &syn::Type) -> bool {
659    if let Some(check) = r_check_for_type(ty) {
660        return check.is_vector();
661    }
662    crate::miniextendr_fn::is_vector_like_type(ty)
663        || #[allow(non_exhaustive_omitted_patterns)] match ty {
    syn::Type::Path(tp) if
        tp.path.segments.last().is_some_and(|s|
                s.ident.to_string().ends_with("Vec")) => true,
    _ => false,
}matches!(
664            ty,
665            syn::Type::Path(tp)
666                if tp.path.segments.last().is_some_and(|s| s.ident.to_string().ends_with("Vec"))
667        )
668}
669
670/// Record `from` as the message of `check`, which may have only one.
671fn merge_message(
672    into: &mut Option<String>,
673    from: Option<String>,
674    check: &str,
675) -> Result<(), String> {
676    match (into.is_some(), from) {
677        (true, Some(_)) => Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is given more than one `message` on this parameter; give it once",
                check))
    })format!(
678            "`{check}` is given more than one `message` on this parameter; give it once"
679        )),
680        (false, Some(message)) => {
681            *into = Some(message);
682            Ok(())
683        }
684        (_, None) => Ok(()),
685    }
686}
687
688/// Classification of an R-side type check for a function parameter.
689///
690/// Each variant maps to a specific set of R-side checks. Numeric checks
691/// use a broad predicate (`is.numeric || is.logical || is.raw`) because R coerces
692/// logical to numeric freely and raw to integer is valid for byte-sized types.
693/// Borderline cases (e.g., raw to i64 in strict mode) pass the precondition and
694/// reach Rust's strict checker, which produces better contextual error messages.
695enum RTypeCheck {
696    /// Numeric scalar: type check + length-1 check (2 assertions).
697    /// Used for the multi-source scalars `f32`, `i8`, `i16`, `i64`, `isize`, and
698    /// for a coerced native `f64`. Native `i32` / `f64` without coerce use
699    /// [`RTypeCheck::Scalar`] with `"integer"` / `"double"`.
700    ScalarNumeric,
701    /// Coerced bool: logical or integer, with length one.
702    ScalarLogicalOrInteger,
703    /// Coerced bool vector: logical or integer.
704    VectorLogicalOrInteger,
705    /// Coerced native `i32` scalar: integer, logical, raw, or a whole-number
706    /// double, with length one. The vector form is [`RTypeCheck::VectorIntegerWide`].
707    ScalarIntegerWide,
708    /// Non-negative numeric scalar: type + length-1 + `>= 0` (3 assertions).
709    /// Used for `u16`, `u32`, `u64`, `usize`. The vector form is
710    /// [`RTypeCheck::VectorNonNegIntegerWide`].
711    ScalarNonNeg,
712    /// Non-numeric scalar: `is.<type>(x)` + length-1 check (2 assertions).
713    /// The string is the R type predicate name (e.g., `"logical"`, `"character"`).
714    Scalar(&'static str),
715    /// Floating-point numeric vector: loose `is.numeric || is.logical || is.raw`
716    /// (1 assertion). Used for `Vec<f32>` (multi-source converter) and for a
717    /// coerced native `Vec<f64>`; `Vec<f64>` / `&[f64]` without coerce use
718    /// [`RTypeCheck::Vector`] with `"double"` because the native path reads
719    /// REALSXP only.
720    VectorNumeric,
721    /// **INTSXP-only** integer vector: `is.integer(x)` (1 assertion). Used *only*
722    /// for `Vec<i32>` / `&[i32]` (issue #616). These use the native `RNativeType`
723    /// inbound path (`impl_vec_try_from_sexp_native!(i32)`), which requires
724    /// `INTSXP` and rejects `REALSXP` outright. The loose `is.numeric` predicate
725    /// previously let a `double` like `c(1, 2)` pass the R gate only to fail with
726    /// a cryptic "expected INTSXP, got REALSXP". `is.integer(x)` rejects every
727    /// `double` (whole or fractional) at the boundary with a clean message,
728    /// matching the actual Rust behaviour and closing the silent-truncation gap.
729    VectorIntegerStrict,
730    /// **Wide** integer vector accepting `REALSXP` whole-number values: the
731    /// lossless whole-number predicate (1 assertion). Used for every non-`i32`
732    /// integer element type — `Vec<i8>` / `Vec<i16>` / `Vec<u16>` / `Vec<u32>`
733    /// and the 64-bit family `Vec<i64>` / `Vec<u64>` / `Vec<isize>` / `Vec<usize>`
734    /// (issue #616). These use the coercing inbound path
735    /// (`impl_vec_try_from_sexp_numeric!` → `from_numeric_vec_with`) which accepts
736    /// INTSXP/REALSXP/RAWSXP/LGLSXP and rejects fractional doubles element-wise
737    /// (`f64: TryCoerce<T>` checks `self.fract() != 0`). We accept
738    /// integer/logical/raw **and** whole-number doubles, and reject genuinely
739    /// lossy fractional doubles (`1.5`) at the boundary. The unsigned element
740    /// types use [`RTypeCheck::VectorNonNegIntegerWide`].
741    VectorIntegerWide,
742    /// Unsigned integer vector (`Vec<u16>` / `Vec<u32>` / `Vec<u64>` /
743    /// `Vec<usize>`, their slices and `Vec<Option<_>>` forms): the
744    /// [`RTypeCheck::VectorIntegerWide`] predicate, then every non-`NA` element
745    /// `>= 0` (2 assertions), as [`RTypeCheck::ScalarNonNeg`] checks its value
746    /// (#2290). Without it a negative element passed the R gate and failed in
747    /// Rust as "value out of range", under the whole-number requirement it met.
748    VectorNonNegIntegerWide,
749    /// Non-numeric vector: `is.<type>(x)` only (1 assertion).
750    /// The string is the R type predicate name.
751    Vector(&'static str),
752    /// `AsNumeric` scalar: numeric, logical, character, or factor, with length
753    /// one (2 assertions). The marker parses character and factor labels the way
754    /// `as.numeric()` does, so the gate admits exactly the types it reads.
755    ScalarNumericOrText,
756    /// `AsNumericVec`: numeric, logical, character, or factor (1 assertion).
757    VectorNumericOrText,
758    /// Nullable wrapper around an inner check: prepends `is.null(x) ||` to each assertion
759    /// and adjusts messages to mention NULL. Around a scalar check a plain
760    /// `NA` passes too (`is.null(x) || (is.logical(x) && length(x) == 1L &&
761    /// is.na(x)) ||`, [`plain_na_check`], #2305); around a vector check it
762    /// does not.
763    Nullable(Box<RTypeCheck>),
764    /// List check: `is.list(x)` (1 assertion).
765    /// Used for `HashMap`, `BTreeMap`, `NamedList`, `List`, `ListMut`.
766    List,
767}
768
769/// Build the R expression for the numeric type predicate.
770///
771/// Returns `"is.numeric(p) || is.logical(p) || is.raw(p)"` for a given parameter `p`.
772/// This broad predicate matches R's coercion rules: logical coerces to numeric freely,
773/// and raw is accepted because it represents byte-level data.
774fn numeric_type_check(param: &str) -> String {
775    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("is.numeric({0}) || is.logical({0}) || is.raw({0})",
                param))
    })format!(
776        "is.numeric({p}) || is.logical({p}) || is.raw({p})",
777        p = param
778    )
779}
780
781/// Build the lossless whole-number predicate for a `REALSXP`-accepting integer
782/// vector (the `i64` / `u64` / `isize` / `usize` family).
783///
784/// Accepts integer/logical/raw and whole-number doubles, rejects fractional
785/// doubles. The whole-number test is NA-safe (`is.na(p) | p == trunc(p)`):
786/// `NA_real_` passes (maps to `NA_integer_`), `1.5` fails. `Inf`/`NaN` satisfy
787/// `x == trunc(x)` in R but are caught by the Rust-side range/NaN conversion
788/// check instead.
789fn integer_vector_wide_check(param: &str) -> String {
790    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("is.integer({0}) || is.logical({0}) || is.raw({0}) || (is.numeric({0}) && all(is.na({0}) | {0} == trunc({0})))",
                param))
    })format!(
791        "is.integer({p}) || is.logical({p}) || is.raw({p}) || \
792         (is.numeric({p}) && all(is.na({p}) | {p} == trunc({p})))",
793        p = param
794    )
795}
796
797/// Build the predicate for the `AsNumeric` / `AsNumericVec` markers.
798///
799/// `is.numeric()` is `FALSE` for a factor, so `is.factor()` is listed on its
800/// own: the marker reads a factor by its labels. Raw and complex stay out, as
801/// the marker refuses them.
802fn numeric_or_text_check(param: &str) -> String {
803    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("is.numeric({0}) || is.logical({0}) || is.character({0}) || is.factor({0})",
                param))
    })format!(
804        "is.numeric({p}) || is.logical({p}) || is.character({p}) || is.factor({p})",
805        p = param
806    )
807}
808
809impl RTypeCheck {
810    /// Produce the individual checks for this type check.
811    ///
812    /// Returns one or more `RAssertion` values, each one requirement on
813    /// `param` (the R parameter name used in the conditions and messages).
814    fn assertions(&self, param: &str) -> Vec<RAssertion> {
815        let length_one = || {
816            RAssertion::new(
817                param,
818                "must have length 1",
819                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("length({0}) == 1L", param))
    })format!("length({param}) == 1L"),
820            )
821        };
822        match self {
823            RTypeCheck::ScalarNumeric => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [RAssertion::new(param, "must be numeric, logical, or raw",
                    numeric_type_check(param)), length_one()]))vec![
824                RAssertion::new(
825                    param,
826                    "must be numeric, logical, or raw",
827                    numeric_type_check(param),
828                ),
829                length_one(),
830            ],
831            RTypeCheck::ScalarLogicalOrInteger => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [RAssertion::new(param, "must be logical or integer",
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("is.logical({0}) || is.integer({0})",
                                    param))
                        })), length_one()]))vec![
832                RAssertion::new(
833                    param,
834                    "must be logical or integer",
835                    format!("is.logical({p}) || is.integer({p})", p = param),
836                ),
837                length_one(),
838            ],
839            RTypeCheck::VectorLogicalOrInteger => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [RAssertion::new(param, "must be logical or integer",
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("is.logical({0}) || is.integer({0})",
                                    param))
                        }))]))vec![RAssertion::new(
840                param,
841                "must be logical or integer",
842                format!("is.logical({p}) || is.integer({p})", p = param),
843            )],
844            RTypeCheck::ScalarIntegerWide => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [RAssertion::new(param, "must be integer or whole-number numeric",
                    integer_vector_wide_check(param)), length_one()]))vec![
845                RAssertion::new(
846                    param,
847                    "must be integer or whole-number numeric",
848                    integer_vector_wide_check(param),
849                ),
850                length_one(),
851            ],
852            RTypeCheck::ScalarNonNeg => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [RAssertion::new(param, "must be numeric, logical, or raw",
                    numeric_type_check(param)), length_one(),
                RAssertion::new(param, "must be non-negative",
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("is.raw({0}) || {0} >= 0",
                                    param))
                        }))]))vec![
853                RAssertion::new(
854                    param,
855                    "must be numeric, logical, or raw",
856                    numeric_type_check(param),
857                ),
858                length_one(),
859                RAssertion::new(
860                    param,
861                    "must be non-negative",
862                    // raw is always non-negative; guard with is.raw() to avoid
863                    // "comparison not implemented" error for raw values
864                    format!("is.raw({p}) || {p} >= 0", p = param),
865                ),
866            ],
867            RTypeCheck::Scalar(r_type) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [RAssertion::new(param,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("must be {0}", r_type))
                        }),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("is.{0}({1})", r_type,
                                    param))
                        })), length_one()]))vec![
868                RAssertion::new(
869                    param,
870                    format!("must be {r_type}"),
871                    format!("is.{r_type}({param})"),
872                ),
873                length_one(),
874            ],
875            RTypeCheck::VectorNumeric => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [RAssertion::new(param, "must be numeric, logical, or raw",
                    numeric_type_check(param))]))vec![RAssertion::new(
876                param,
877                "must be numeric, logical, or raw",
878                numeric_type_check(param),
879            )],
880            RTypeCheck::VectorIntegerStrict => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [RAssertion::new(param, "must be an integer vector",
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("is.integer({0})", param))
                        }))]))vec![RAssertion::new(
881                param,
882                "must be an integer vector",
883                format!("is.integer({param})"),
884            )],
885            RTypeCheck::VectorIntegerWide => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [RAssertion::new(param, "must be integer or whole-number numeric",
                    integer_vector_wide_check(param))]))vec![RAssertion::new(
886                param,
887                "must be integer or whole-number numeric",
888                integer_vector_wide_check(param),
889            )],
890            RTypeCheck::VectorNonNegIntegerWide => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [RAssertion::new(param, "must be integer or whole-number numeric",
                    integer_vector_wide_check(param)),
                RAssertion::new(param, "must be non-negative",
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("is.raw({0}) || all({0} >= 0, na.rm = TRUE)",
                                    param))
                        }))]))vec![
891                RAssertion::new(
892                    param,
893                    "must be integer or whole-number numeric",
894                    integer_vector_wide_check(param),
895                ),
896                RAssertion::new(
897                    param,
898                    "must be non-negative",
899                    // Raw is never negative and has no `>=`; an `NA` element is
900                    // left to the conversion, which reads it as `None` or
901                    // refuses it.
902                    format!("is.raw({p}) || all({p} >= 0, na.rm = TRUE)", p = param),
903                ),
904            ],
905            RTypeCheck::Vector(r_type) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [RAssertion::new(param,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("must be {0}", r_type))
                        }),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("is.{0}({1})", r_type,
                                    param))
                        }))]))vec![RAssertion::new(
906                param,
907                format!("must be {r_type}"),
908                format!("is.{r_type}({param})"),
909            )],
910            RTypeCheck::ScalarNumericOrText => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [RAssertion::new(param,
                    "must be numeric, logical, character, or factor",
                    numeric_or_text_check(param)), length_one()]))vec![
911                RAssertion::new(
912                    param,
913                    "must be numeric, logical, character, or factor",
914                    numeric_or_text_check(param),
915                ),
916                length_one(),
917            ],
918            RTypeCheck::VectorNumericOrText => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [RAssertion::new(param,
                    "must be numeric, logical, character, or factor",
                    numeric_or_text_check(param))]))vec![RAssertion::new(
919                param,
920                "must be numeric, logical, character, or factor",
921                numeric_or_text_check(param),
922            )],
923            RTypeCheck::Nullable(inner) => {
924                // An optional scalar reads a plain `NA` as `None` (#2305).
925                let plain_na = !inner.is_vector();
926                inner
927                    .assertions(param)
928                    .into_iter()
929                    .map(|a| a.nullable(plain_na))
930                    .collect()
931            }
932            RTypeCheck::List => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [RAssertion::new(param, "must be a list",
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("is.list({0})", param))
                        }))]))vec![RAssertion::new(
933                param,
934                "must be a list",
935                format!("is.list({param})"),
936            )],
937        }
938    }
939
940    /// Whether the check admits several values: the vector checks and
941    /// [`RTypeCheck::List`], through [`RTypeCheck::Nullable`]. Matched
942    /// exhaustively, so a new check has to say which it is.
943    fn is_vector(&self) -> bool {
944        match self {
945            RTypeCheck::VectorLogicalOrInteger
946            | RTypeCheck::VectorNumeric
947            | RTypeCheck::VectorIntegerStrict
948            | RTypeCheck::VectorIntegerWide
949            | RTypeCheck::VectorNonNegIntegerWide
950            | RTypeCheck::Vector(_)
951            | RTypeCheck::VectorNumericOrText
952            | RTypeCheck::List => true,
953            RTypeCheck::ScalarNumeric
954            | RTypeCheck::ScalarLogicalOrInteger
955            | RTypeCheck::ScalarIntegerWide
956            | RTypeCheck::ScalarNonNeg
957            | RTypeCheck::Scalar(_)
958            | RTypeCheck::ScalarNumericOrText => false,
959            RTypeCheck::Nullable(inner) => inner.is_vector(),
960        }
961    }
962
963    /// What an argument of this type must be, in R terms: the `<expected>` of
964    /// a Rust conversion failure's message, `'<p>' must be <expected>: <reason>`
965    /// (#1591).
966    ///
967    /// The R-side checks test one requirement at a time (type, then length);
968    /// a conversion failure names the whole expectation once. Scalars read
969    /// `a single <noun>` (`a single integer`, `a single string`, `TRUE or
970    /// FALSE`), vectors name the R type (`numeric`, `character`, `a list`).
971    /// `AsNumeric` / `AsNumericVec` say `a single number` / `numeric`, the
972    /// value they produce, rather than the inputs they read. `AsCharacter` /
973    /// `AsCharacterVec` likewise say `coercible to a single string` /
974    /// `coercible to character`: their R-side check has already required an
975    /// atomic argument, so what is left to fail is the `as.character()` step
976    /// (a failing method, a non-character or wrong-length result).
977    fn expectation(&self) -> String {
978        match self {
979            RTypeCheck::ScalarNumeric | RTypeCheck::ScalarNumericOrText => "a single number".into(),
980            RTypeCheck::ScalarLogicalOrInteger => "a single logical or integer".into(),
981            RTypeCheck::VectorLogicalOrInteger => "logical or integer".into(),
982            RTypeCheck::ScalarIntegerWide => "a single whole number".into(),
983            RTypeCheck::ScalarNonNeg => "a single non-negative number".into(),
984            RTypeCheck::Scalar(r_type) => match *r_type {
985                "logical" => "TRUE or FALSE".into(),
986                "character" => "a single string".into(),
987                "integer" | "double" => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a single {0}", r_type))
    })format!("a single {r_type}"),
988                "atomic" => "coercible to a single string".into(),
989                // `raw`, `complex`.
990                other => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a single {0} value", other))
    })format!("a single {other} value"),
991            },
992            RTypeCheck::VectorNumeric | RTypeCheck::VectorNumericOrText => "numeric".into(),
993            RTypeCheck::VectorIntegerStrict => "integer".into(),
994            RTypeCheck::VectorIntegerWide => "integer or whole-number numeric".into(),
995            RTypeCheck::VectorNonNegIntegerWide => {
996                "non-negative integer or whole-number numeric".into()
997            }
998            RTypeCheck::Vector("atomic") => "coercible to character".into(),
999            RTypeCheck::Vector(r_type) => (*r_type).into(),
1000            RTypeCheck::Nullable(inner) => match inner.expectation().as_str() {
1001                "TRUE or FALSE" => "NULL, TRUE or FALSE".into(),
1002                inner => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("NULL or {0}", inner))
    })format!("NULL or {inner}"),
1003            },
1004            RTypeCheck::List => "a list".into(),
1005        }
1006    }
1007}
1008
1009/// The R-facing expectation for a parameter of Rust type `ty`, for the
1010/// message of its Rust conversion failure: `'<p>' must be <expected>: ...`
1011/// (see [`RTypeCheck::expectation`]).
1012///
1013/// Derived from the same type classification as the R-side checks, including
1014/// the `coerce` widening (`coerced`) and the `Missing<T>` / `Option<T>`
1015/// wrappers (`Nullable<T>` reads as `Option<T>`, #2294), so the two paths
1016/// describe an argument the same way. A few types
1017/// without an R-side check still have an R-facing expectation
1018/// ([`unchecked_expectation`]): `Either<L, R>`, the `AsFromStr` markers and
1019/// tuples. `None` only for an opaque type (a custom `TryFromSexp` type, or an
1020/// `Either` with such an arm): the wrapper then asks the type at run time
1021/// (`rust_conversion_builder::declared_expectation`: a derived newtype's
1022/// declared expectation, an `Either` side by side), else reports
1023/// `invalid '<p>' argument: <reason>`.
1024pub(crate) fn conversion_expectation(ty: &syn::Type, coerced: bool) -> Option<String> {
1025    let ty = crate::miniextendr_fn::get_missing_inner_type(ty).unwrap_or(ty);
1026    let Some(check) = r_check_for_type(ty) else {
1027        return unchecked_expectation(ty);
1028    };
1029    let check = if coerced {
1030        coerce_widened(check, ty)
1031    } else {
1032        check
1033    };
1034    Some(check.expectation())
1035}
1036
1037/// The R-facing expectation of a type that has no R-side check, so its
1038/// conversion alone says what it accepts (#1594):
1039///
1040/// | type | `<expected>` |
1041/// |------|--------------|
1042/// | `AsFromStr<T>` / `AsFromStrVec<T>` | `a single string` / `character` (the input `T` is parsed from) |
1043/// | `Either<L, R>` | `<L> or <R>`, when both sides have one (`a single integer or a single string`) |
1044/// | `(A, B, ...)` | `a list of length N` |
1045/// | `DataFrame` | `a data frame` |
1046/// | `Option<T>` / `Nullable<T>` of the above | `NULL or <T>` |
1047fn unchecked_expectation(ty: &syn::Type) -> Option<String> {
1048    if let Some(inner) = crate::type_inspect::optional_inner_type(ty) {
1049        return Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("NULL or {0}",
                unchecked_expectation(inner)?))
    })format!("NULL or {}", unchecked_expectation(inner)?));
1050    }
1051    match ty {
1052        syn::Type::Tuple(tuple) if !tuple.elems.is_empty() => {
1053            Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a list of length {0}",
                tuple.elems.len()))
    })format!("a list of length {}", tuple.elems.len()))
1054        }
1055        syn::Type::Path(type_path) => {
1056            let segment = type_path.path.segments.last()?;
1057            match segment.ident.to_string().as_str() {
1058                "AsFromStr" => Some("a single string".into()),
1059                "AsFromStrVec" => Some("character".into()),
1060                "DataFrame" => Some("a data frame".into()),
1061                "Either" => {
1062                    let left = crate::type_inspect::first_type_argument(segment)?;
1063                    let right = crate::type_inspect::second_type_argument(segment)?;
1064                    Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} or {1}",
                conversion_expectation(left, false)?,
                conversion_expectation(right, false)?))
    })format!(
1065                        "{} or {}",
1066                        conversion_expectation(left, false)?,
1067                        conversion_expectation(right, false)?
1068                    ))
1069                }
1070                _ => None,
1071            }
1072        }
1073        _ => None,
1074    }
1075}
1076
1077/// The R-facing expectation of a `strict` lossy-integer parameter (`i64`,
1078/// `u64`, `isize`, `usize` and their `Vec` / `Vec<Option<_>>` forms), whose
1079/// Rust conversion accepts only integer and whole-number double input
1080/// (#1594): `a single whole number` / `a single non-negative whole number`
1081/// for a scalar, the vector's usual `integer or whole-number numeric` (with
1082/// `non-negative` for the unsigned ones) otherwise.
1083pub(crate) fn strict_conversion_expectation(ty: &syn::Type) -> Option<String> {
1084    let scalar = match ty {
1085        syn::Type::Path(tp) => tp.path.segments.last().map(|s| s.ident.to_string()),
1086        _ => None,
1087    };
1088    match scalar.as_deref() {
1089        Some("i64" | "isize") => Some("a single whole number".into()),
1090        Some("u64" | "usize") => Some("a single non-negative whole number".into()),
1091        _ => conversion_expectation(ty, false),
1092    }
1093}
1094
1095/// Keep the R gate in sync with the conversion actually selected for this type.
1096///
1097/// Native `i32` widens to whole-number doubles (plus logical/raw), so its gate
1098/// becomes the lossless whole-number predicate; `Vec<i32>` moves from the
1099/// INTSXP-only gate (#616) to the same wide predicate the other integer vectors
1100/// use. Native `f64` / `Vec<f64>` move from the `is.double` gate to the loose
1101/// numeric predicate. `Option<T>` of these types takes its scalar's widened
1102/// check under [`RTypeCheck::Nullable`], and `Vec<Option<T>>` its vector's
1103/// (#2274): the vector checks already let `NA` elements through, and a
1104/// `Vec<Option<T>>` reads `NULL` no more than a `Vec<T>` does.
1105fn coerce_widened(check: RTypeCheck, ty: &syn::Type) -> RTypeCheck {
1106    use crate::miniextendr_fn::CoercionMapping;
1107    let nullable = |inner| RTypeCheck::Nullable(Box::new(inner));
1108    match CoercionMapping::from_type(ty) {
1109        Some(CoercionMapping::Bool) => RTypeCheck::ScalarLogicalOrInteger,
1110        Some(CoercionMapping::OptionBool) => nullable(RTypeCheck::ScalarLogicalOrInteger),
1111        Some(CoercionMapping::BoolVec | CoercionMapping::OptionBoolVec) => {
1112            RTypeCheck::VectorLogicalOrInteger
1113        }
1114        Some(CoercionMapping::NativeInt) => RTypeCheck::ScalarIntegerWide,
1115        Some(CoercionMapping::OptionNativeInt) => nullable(RTypeCheck::ScalarIntegerWide),
1116        Some(CoercionMapping::NativeIntVec | CoercionMapping::OptionNativeIntVec) => {
1117            RTypeCheck::VectorIntegerWide
1118        }
1119        Some(CoercionMapping::NativeReal) => RTypeCheck::ScalarNumeric,
1120        Some(CoercionMapping::OptionNativeReal) => nullable(RTypeCheck::ScalarNumeric),
1121        Some(CoercionMapping::NativeRealVec | CoercionMapping::OptionNativeRealVec) => {
1122            RTypeCheck::VectorNumeric
1123        }
1124        Some(CoercionMapping::Numeric) | None => check,
1125    }
1126}
1127
1128/// Map a Rust type to its R-side type check, if applicable.
1129///
1130/// `Option<T>` and `Nullable<T>` (#2294) are [`RTypeCheck::Nullable`] of
1131/// `T`'s check. Returns `None` for types that should skip precondition
1132/// checks (SEXP, Dots, ExternalPtr, etc.).
1133fn r_check_for_type(ty: &syn::Type) -> Option<RTypeCheck> {
1134    if let Some(inner) = crate::type_inspect::optional_inner_type(ty) {
1135        return r_check_for_type(inner).map(|inner| RTypeCheck::Nullable(Box::new(inner)));
1136    }
1137    match ty {
1138        syn::Type::Path(type_path) => r_check_for_type_path(type_path),
1139        syn::Type::Reference(type_ref) => r_check_for_reference(type_ref),
1140        _ => None,
1141    }
1142}
1143
1144/// Map a `syn::TypePath` to its R-side type check.
1145///
1146/// Handles the most common case: simple types (`i32`, `String`, `bool`),
1147/// `Vec<T>`, map types, and skip types (`Option<T>` is
1148/// [`r_check_for_type`]'s). Returns `None` for types that cannot be
1149/// prechecked from R.
1150fn r_check_for_type_path(type_path: &syn::TypePath) -> Option<RTypeCheck> {
1151    let segment = type_path.path.segments.last()?;
1152    let ident = segment.ident.to_string();
1153
1154    match ident.as_str() {
1155        // Native scalars convert from exactly one SEXPTYPE (`i32::try_from_sexp`
1156        // is INTSXP-only, `f64` REALSXP-only), so the R gate names that storage
1157        // instead of letting a double reach Rust and fail with "expected INTSXP,
1158        // got REALSXP" (#1112). Under `coerce` the gate widens with the conversion
1159        // (see `coerce_widened`).
1160        "i32" => Some(RTypeCheck::Scalar("integer")),
1161        "f64" => Some(RTypeCheck::Scalar("double")),
1162
1163        // Non-native numeric scalars use the multi-source converters (integer,
1164        // double, logical, raw), so the loose predicate matches what Rust accepts.
1165        "f32" | "i8" | "i16" | "i64" | "isize" => Some(RTypeCheck::ScalarNumeric),
1166
1167        // Unsigned numeric scalars (non-negative constraint)
1168        "u16" | "u32" | "u64" | "usize" => Some(RTypeCheck::ScalarNonNeg),
1169
1170        // Logical scalar
1171        "bool" | "Rbool" | "Rboolean" => Some(RTypeCheck::Scalar("logical")),
1172
1173        // Character scalar
1174        "String" | "char" | "PathBuf" => Some(RTypeCheck::Scalar("character")),
1175
1176        // Raw scalar
1177        "u8" => Some(RTypeCheck::Scalar("raw")),
1178
1179        // Complex scalar
1180        "Rcomplex" => Some(RTypeCheck::Scalar("complex")),
1181
1182        // `as.numeric()`-style markers: numbers, text, and factor labels.
1183        "AsNumeric" => Some(RTypeCheck::ScalarNumericOrText),
1184        "AsNumericVec" => Some(RTypeCheck::VectorNumericOrText),
1185
1186        // `as.character()`-style markers: any atomic vector (a list or data
1187        // frame is refused, as `as.character()` would flatten it), with length
1188        // one for the scalar. "'x' must be atomic" is base R's own wording.
1189        "AsCharacter" => Some(RTypeCheck::Scalar("atomic")),
1190        "AsCharacterVec" => Some(RTypeCheck::Vector("atomic")),
1191
1192        // `Cow<str>` converts as `&str` does, `Cow<[T]>` as `&[T]`. The first
1193        // generic argument is the lifetime, so look past it.
1194        "Cow" => match crate::type_inspect::first_type_argument(segment)? {
1195            syn::Type::Slice(slice) => r_check_for_vec_element(&slice.elem),
1196            inner if is_str(inner) => Some(RTypeCheck::Scalar("character")),
1197            _ => None,
1198        },
1199
1200        // Vec<T> → Vector (depends on element type)
1201        "Vec" => {
1202            let inner_ty = extract_single_generic_arg(segment)?;
1203            r_check_for_vec_element(inner_ty)
1204        }
1205
1206        // Map types and named list → List
1207        "HashMap" | "BTreeMap" | "NamedList" => Some(RTypeCheck::List),
1208
1209        // List (bare) → List
1210        "List" | "ListMut" => Some(RTypeCheck::List),
1211
1212        // Skip types: SEXP, Dots, Missing, ExternalPtr, RLogical, etc.
1213        // `LazyDots` is `...`, passed as the wrapper's frame (#1892).
1214        "SEXP" | "Dots" | "LazyDots" | "Missing" | "ExternalPtr" | "OwnedProtect" => None,
1215
1216        // Unknown type → skip (let Rust side validate)
1217        _ => None,
1218    }
1219}
1220
1221/// Map a reference type to its R-side type check.
1222///
1223/// Handles `&str` and `&Path` (character scalar), `&[T]` (vector based on element type),
1224/// and `&Dots` (skipped). Returns `None` for unrecognized reference types.
1225fn r_check_for_reference(type_ref: &syn::TypeReference) -> Option<RTypeCheck> {
1226    match type_ref.elem.as_ref() {
1227        // &str → character scalar
1228        syn::Type::Path(tp) => {
1229            let seg = tp.path.segments.last()?;
1230            match seg.ident.to_string().as_str() {
1231                "str" => Some(RTypeCheck::Scalar("character")),
1232                "Path" => Some(RTypeCheck::Scalar("character")),
1233                "Dots" => None,
1234                _ => None,
1235            }
1236        }
1237        // &[T] → vector check based on element type
1238        syn::Type::Slice(slice) => r_check_for_vec_element(&slice.elem),
1239        _ => None,
1240    }
1241}
1242
1243/// Map a `Vec<T>` or `&[T]` element type to the appropriate vector type check.
1244///
1245/// Numeric elements produce `VectorNumeric`, `bool` produces `Vector("logical")`,
1246/// `String` produces `Vector("character")`, etc. Handles nested `Option<T>` for
1247/// nullable element types (e.g., `Vec<Option<String>>` becomes character vector).
1248fn r_check_for_vec_element(elem_ty: &syn::Type) -> Option<RTypeCheck> {
1249    let tp = match elem_ty {
1250        syn::Type::Path(tp) => tp,
1251        // `Vec<&str>` reads a character vector, as `Vec<String>` does.
1252        syn::Type::Reference(type_ref) if is_str(&type_ref.elem) => {
1253            return Some(RTypeCheck::Vector("character"));
1254        }
1255        _ => return None,
1256    };
1257    let seg = tp.path.segments.last()?;
1258    let ident = seg.ident.to_string();
1259
1260    match ident.as_str() {
1261        // `Vec<f64>` / `&[f64]` read the REALSXP payload directly (native path),
1262        // so the gate is `is.double`; `Vec<f32>` coerces from every numeric source.
1263        "f64" => Some(RTypeCheck::Vector("double")),
1264        "f32" => Some(RTypeCheck::VectorNumeric),
1265
1266        // `Vec<i32>` / `&[i32]` is the *only* INTSXP-only integer vector (issue
1267        // #616): its inbound conversion uses the native `RNativeType` path
1268        // (`impl_vec_try_from_sexp_native!(i32)` in `from_r/collections.rs`),
1269        // which rejects REALSXP outright. So the R gate is `is.integer` — a
1270        // `double` like `c(1, 2)` fails cleanly at the boundary instead of
1271        // producing a cryptic "expected INTSXP, got REALSXP". `u8` is handled
1272        // below as a raw vector.
1273        "i32" => Some(RTypeCheck::VectorIntegerStrict),
1274
1275        // Every other integer-element vector (`i8`/`i16`/`u16`/`u32` and the
1276        // 64-bit family `i64`/`u64`/`isize`/`usize`) uses the coercing inbound
1277        // path (`impl_vec_try_from_sexp_numeric!` → `from_numeric_vec_with`),
1278        // which accepts INTSXP/REALSXP/RAWSXP/LGLSXP and rejects fractional
1279        // doubles element-wise via `f64: TryCoerce<T>` (the `self.fract() != 0`
1280        // check in `coerce.rs`). The R gate mirrors that: accept integer/logical/
1281        // raw + whole-number doubles, reject fractional. (64-bit ints also arrive
1282        // as REALSXP since R has no native 64-bit integer type.) The unsigned
1283        // ones also refuse a negative element, as their scalars do (#2290).
1284        "i8" | "i16" | "i64" | "isize" => Some(RTypeCheck::VectorIntegerWide),
1285        "u16" | "u32" | "u64" | "usize" => Some(RTypeCheck::VectorNonNegIntegerWide),
1286
1287        // Logical vector
1288        "bool" => Some(RTypeCheck::Vector("logical")),
1289
1290        // Character vector; `Vec<Cow<str>>` reads one as `Vec<String>` does.
1291        "String" => Some(RTypeCheck::Vector("character")),
1292        "Cow" if crate::type_inspect::first_type_argument(seg).is_some_and(is_str) => {
1293            Some(RTypeCheck::Vector("character"))
1294        }
1295
1296        // Raw vector
1297        "u8" => Some(RTypeCheck::Vector("raw")),
1298
1299        // Complex vector
1300        "Rcomplex" => Some(RTypeCheck::Vector("complex")),
1301
1302        // Vec<Option<T>> — e.g., Vec<Option<String>> for nullable strings
1303        "Option" => {
1304            let inner = extract_single_generic_arg(seg)?;
1305            // Vec<Option<String>> → character, Vec<Option<i32>> → numeric, etc.
1306            r_check_for_vec_element(inner)
1307        }
1308
1309        _ => None,
1310    }
1311}
1312
1313/// Whether `ty` is `str`.
1314fn is_str(ty: &syn::Type) -> bool {
1315    #[allow(non_exhaustive_omitted_patterns)] match ty {
    syn::Type::Path(tp) if tp.qself.is_none() && tp.path.is_ident("str") =>
        true,
    _ => false,
}matches!(ty, syn::Type::Path(tp) if tp.qself.is_none() && tp.path.is_ident("str"))
1316}
1317
1318/// Extract the single generic type argument from a path segment.
1319///
1320/// e.g., `Option<String>` → `String`, `Vec<i32>` → `i32`
1321fn extract_single_generic_arg(segment: &syn::PathSegment) -> Option<&syn::Type> {
1322    if let syn::PathArguments::AngleBracketed(ref args) = segment.arguments
1323        && let Some(syn::GenericArgument::Type(ty)) = args.args.first()
1324    {
1325        return Some(ty);
1326    }
1327    None
1328}
1329
1330/// A parameter whose Rust type is not in the static type table.
1331///
1332/// Currently, fallback params are recorded but no R-side validation is generated
1333/// for them -- the Rust-side conversion handles type errors with its own messages.
1334#[allow(dead_code)] // Read in tests
1335pub struct FallbackParam {
1336    /// R-normalized parameter name (e.g., `_dots` becomes `dots`).
1337    pub r_name: String,
1338}
1339
1340/// Output of precondition analysis for a function's parameters.
1341///
1342/// Holds the R-side checks for known types and a list of parameters with
1343/// unknown types that were not statically prechecked.
1344pub struct PreconditionOutput {
1345    /// The checks, in parameter order: each parameter's NA check, its class
1346    /// checks, then its type checks ([`ExplicitChecks`]). Rendered by
1347    /// [`PreconditionOutput::guards`].
1348    assertions: Vec<RAssertion>,
1349    /// Parameters with unknown custom types that were not prechecked.
1350    #[allow(dead_code)] // Read in tests
1351    pub fallback_params: Vec<FallbackParam>,
1352}
1353
1354impl PreconditionOutput {
1355    /// One guard line per check, raising an argument error through
1356    /// `.miniextendr_arg_error` when it fails (#1591); empty when there is
1357    /// nothing to check.
1358    ///
1359    /// `call` is the call every failure is attributed to: `None` for the
1360    /// wrapper's own call (the helper's default, the call `stopifnot()`
1361    /// reported), or `.mx_call` for a `call = caller` wrapper, which binds the
1362    /// caller's matched call before the checks run (#1548).
1363    pub fn guards(&self, call: Option<&str>) -> Vec<String> {
1364        self.assertions.iter().map(|a| a.to_guard(call)).collect()
1365    }
1366}
1367
1368/// Returns `true` for types that should never get a fallback precheck.
1369///
1370/// These types are either handled specially by the FFI layer (`SEXP`),
1371/// consumed by the macro infrastructure (`Dots`, `LazyDots`, `Missing`), or
1372/// managed internally (`ExternalPtr`, `OwnedProtect`).
1373fn is_skip_type(ident: &str) -> bool {
1374    #[allow(non_exhaustive_omitted_patterns)] match ident {
    "SEXP" | "Dots" | "LazyDots" | "Missing" | "ExternalPtr" | "OwnedProtect"
        => true,
    _ => false,
}matches!(
1375        ident,
1376        "SEXP" | "Dots" | "LazyDots" | "Missing" | "ExternalPtr" | "OwnedProtect"
1377    )
1378}
1379
1380/// Returns `true` if a type is unknown to the static type table and should
1381/// be recorded as a fallback parameter.
1382///
1383/// Returns `false` for skip types (SEXP, Dots, etc.) and reference types
1384/// (which are handled by the static table or skipped).
1385fn needs_fallback(ty: &syn::Type) -> bool {
1386    match ty {
1387        syn::Type::Path(tp) => {
1388            let Some(seg) = tp.path.segments.last() else {
1389                return false;
1390            };
1391            !is_skip_type(&seg.ident.to_string())
1392        }
1393        // References (&str, &[T], &Dots) are handled by static table or skipped
1394        syn::Type::Reference(_) => false,
1395        _ => false,
1396    }
1397}
1398
1399/// Build precondition checks for a function's parameters.
1400///
1401/// Returns the checks for known types (render them with
1402/// [`PreconditionOutput::guards`]) and the parameters with unknown custom
1403/// types (`fallback_params`). The guards read:
1404/// ```r
1405/// if (!isTRUE(is.integer(a))) .miniextendr_arg_error("a", "must be integer")
1406/// if (!isTRUE(length(a) == 1L)) .miniextendr_arg_error("a", "must have length 1")
1407/// ```
1408///
1409/// Skips:
1410/// - `self`/`&self`/`&mut self` (receiver args)
1411/// - Parameters in `skip_params` (e.g., match_arg params already validated)
1412/// - Skip types (SEXP, Dots, ExternalPtr, etc.)
1413/// - The type-derived checks of the parameters in `opts.unchecked`
1414///
1415/// A parameter's [`ExplicitChecks`] are never skipped: its NA check comes
1416/// first, then its class checks (`inherits`, then `not_inherits`), then its
1417/// type checks, which take the `inherits` message when there is one.
1418pub fn build_precondition_checks(
1419    inputs: &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
1420    skip_params: &HashSet<String>,
1421    opts: &PreconditionOptions,
1422) -> PreconditionOutput {
1423    let mut assertions = Vec::new();
1424    let mut fallback_params = Vec::new();
1425
1426    for arg in inputs {
1427        // Skip receiver (self/&self/&mut self)
1428        let syn::FnArg::Typed(pt) = arg else {
1429            continue;
1430        };
1431
1432        // `NArgs` is no R formal: the wrapper passes `nargs()`, which no
1433        // check needs to look at (#1860). Nor is a `LazyDots` parameter's name:
1434        // its formal is `...`, passed unforced as the wrapper's frame (#1892).
1435        if crate::type_inspect::is_nargs_marker(&pt.ty)
1436            || crate::type_inspect::is_lazy_dots_marker(&pt.ty)
1437        {
1438            continue;
1439        }
1440
1441        // Extract parameter name
1442        let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
1443            continue;
1444        };
1445
1446        // The parameter's R formal (#1842): what the checks read and name
1447        let r_name = opts.formals.of_ident(&pat_ident.ident);
1448        let explicit = opts.explicit.get(&r_name);
1449
1450        // The NA check first, so an `NA` gets its message whatever its class
1451        // or type, then the class checks, so a value of the wrong class gets
1452        // their message whatever its type.
1453        if let Some(checks) = explicit {
1454            assertions.extend(checks.value_assertions(
1455                &r_name,
1456                pt.ty.as_ref(),
1457                skip_params.contains(&r_name),
1458            ));
1459            assertions.extend(checks.class_assertions(&r_name, pt.ty.as_ref()));
1460        }
1461
1462        // Type-derived checks: skipped for match_arg params (already validated
1463        // by match.arg()) and for the parameters that drop them.
1464        if !opts.unchecked.contains(&r_name) && !skip_params.contains(&r_name) {
1465            // Preserve the ordinary input domain and include any coercion extensions.
1466            if let Some(mut check) = r_check_for_type(pt.ty.as_ref()) {
1467                if opts.is_coerced(&r_name) {
1468                    check = coerce_widened(check, pt.ty.as_ref());
1469                }
1470                let mut type_assertions = check.assertions(&r_name);
1471                // An `inherits` message covers the type checks too.
1472                if let Some(message) = explicit.and_then(ExplicitChecks::type_check_message) {
1473                    for a in &mut type_assertions {
1474                        a.message = Some(message.clone());
1475                    }
1476                }
1477                assertions.extend(type_assertions);
1478            } else if needs_fallback(pt.ty.as_ref()) {
1479                // Unknown type → record for potential future validation
1480                fallback_params.push(FallbackParam {
1481                    r_name: r_name.clone(),
1482                });
1483            }
1484        }
1485    }
1486
1487    PreconditionOutput {
1488        assertions,
1489        fallback_params,
1490    }
1491}
1492
1493#[cfg(test)]
1494mod tests;