Skip to main content

miniextendr_api/
match_arg.rs

1//! `match.arg`-style enum conversion for R string arguments.
2//!
3//! This module provides the [`MatchArg`] trait for converting between Rust
4//! fieldless enums and R character strings with `match.arg` semantics
5//! (exact match or unique partial matching).
6//!
7//! # Usage
8//!
9//! ```ignore
10//! use miniextendr_api::MatchArg;
11//!
12//! #[derive(Copy, Clone, MatchArg)]
13//! #[match_arg(rename_all = "snake_case")]
14//! enum Mode {
15//!     Fast,
16//!     Safe,
17//!     Debug,
18//! }
19//!
20//! #[miniextendr]
21//! fn run(#[miniextendr(match_arg)] mode: Mode) -> String {
22//!     format!("{mode:?}")
23//! }
24//! ```
25//!
26//! The generated R wrapper uses `base::match.arg()` for validation before
27//! the main `.Call()`, giving users familiar R error messages and partial
28//! matching.
29//!
30//! An `Option<T>` parameter (`#[miniextendr(match_arg)] mode: Option<Mode>`)
31//! is the optional form: the R formal defaults to `NULL`, `NULL` and a plain
32//! `NA` convert to `None` (#2305), and any other value is matched as usual.
33//! The generated C wrapper decodes it with [`match_arg_option_from_sexp`]
34//! (there is no `TryFromSexp for Option<T>` blanket: that slot belongs to the
35//! newtype forwarding impls in [`crate::newtype`], and a downstream crate
36//! cannot add one for its own enum under the orphan rule), so a hand-written
37//! `MatchArg` impl needs nothing extra.
38//!
39//! A `Missing<..>` around the parameter type (`Missing<T>`,
40//! `Missing<Option<T>>`, `Missing<Vec<T>>` for `several_ok`) keeps the choice
41//! vector as the R formal and reports an omitted argument as
42//! `Missing::Absent` (#1551), as it does that formal passed whole for a
43//! single choice (#2152); the C wrapper decodes it with
44//! [`match_arg_missing_or`] around the decoder of the inner type.
45//!
46//! With the `either` feature, `Either<T, R>` takes a choice or a value of
47//! another kind: character or factor input is matched and becomes `Left(T)`,
48//! anything else converts to `R` (`match_arg_either_or`). A `several_ok` list
49//! takes the same split as `Either<Vec<T>, R>` or `Either<Box<[T]>, R>`
50//! (#1612): character or factor input is matched element by element and
51//! becomes `Left(Vec<T>)`, anything else converts to `R`.
52//!
53//! [`MatchArg::ALIASES`] (`#[match_arg(alias = "grey")]` on a variant) adds
54//! other spellings of a choice, matched only when typed in full, by every
55//! matcher on both sides. An error that lists the choices names them after
56//! the choices (`(or "grey" for "gray")`), unless an alias opts out with
57//! `listed = false`; the formal, the usage and the `@param` line list the
58//! choices only.
59//!
60//! `several_ok` parameters are validated strictly on the R side: every element
61//! has to match a choice, and `NULL` selects every choice (the same fallback
62//! [`match_arg_vec_from_sexp`] applies). Under `Either`, `NULL` is not a
63//! choice: it goes to `R` (or is `None` under `Option<Either<..>>`).
64
65use crate::condition::ArgError;
66use crate::from_r::{NativeBorrow, SexpError, TryFromSexp, charsxp_to_cow_lossy};
67use crate::gc_protect::ProtectScope;
68use crate::{R_xlen_t, SEXP, SEXPTYPE, SexpExt};
69
70/// Trait for enum types that support `match.arg`-style string conversion.
71///
72/// Implementors provide a fixed set of choice strings and bidirectional
73/// conversion between enum variants and their string representations.
74///
75/// Use `#[derive(MatchArg)]` to auto-generate this implementation.
76pub trait MatchArg: Sized + Copy + 'static {
77    /// The canonical choice strings, in variant declaration order.
78    ///
79    /// The first choice is the default when the R argument is `NULL`.
80    const CHOICES: &'static [&'static str];
81
82    /// Other spellings of a choice: [`MatchArgAlias::new("grey",
83    /// "gray")`](MatchArgAlias::new) lets a user write `"grey"` for the choice
84    /// `"gray"` (#1843).
85    ///
86    /// An alias selects its choice only when typed in full: a prefix matches
87    /// the choices alone, so `"gr"` stays the prefix of `"gray"` it was. Every
88    /// matcher reads it, the generated wrapper's check and the Rust side
89    /// alike ([`match_arg_from_sexp`], [`match_arg_param`],
90    /// [`match_arg_vec_from_sexp`] element by element, the `Either` arm).
91    ///
92    /// Every error that lists the choices names the listed aliases after
93    /// them, `'color' should be one of "red", "gray", "blue" (or "grey" for
94    /// "gray")`, on both sides (#2148). An alias built with
95    /// [`MatchArgAlias::unlisted`] is matched the same way and named by no
96    /// error. The R formal, the usage and the `@param` line list `CHOICES`
97    /// only.
98    ///
99    /// `#[derive(MatchArg)]` fills it from `#[match_arg(alias = "...")]` on a
100    /// variant (`listed = false` for an unlisted one). A hand-written impl
101    /// lists its aliases here, not in [`from_choice`](Self::from_choice),
102    /// which the R-side check never reaches. The wrappers writer refuses, for
103    /// a type used as a `match_arg` parameter, an alias that is empty, `"NA"`,
104    /// a choice, repeated, or a prefix of a choice other than its own, and a
105    /// target that is not a choice.
106    const ALIASES: &'static [MatchArgAlias] = &[];
107
108    /// Convert a choice string to the corresponding enum variant.
109    ///
110    /// Returns `None` if the string doesn't match any choice exactly. An
111    /// alias is not a choice: [`ALIASES`](Self::ALIASES) maps it.
112    fn from_choice(choice: &str) -> Option<Self>;
113
114    /// Convert the enum variant to its canonical choice string.
115    fn to_choice(self) -> &'static str;
116}
117
118/// One entry of [`MatchArg::ALIASES`]: `alias`, another spelling of the
119/// choice `choice`, and whether the errors that list the choices name it.
120///
121/// ```ignore
122/// const ALIASES: &'static [MatchArgAlias] = &[
123///     MatchArgAlias::new("oral", "extravascular"),
124///     MatchArgAlias::unlisted("ev", "extravascular"),
125/// ];
126/// ```
127#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for MatchArgAlias {
}
#[automatically_derived]impl ::core::clone::Clone for MatchArgAlias {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<&'static str>;
        let _: ::core::clone::AssertParamIsClone<&'static str>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for MatchArgAlias { }Copy, #[automatically_derived]impl ::core::fmt::Debug for MatchArgAlias {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "MatchArgAlias alias choice listed", &self.alias, &self.choice,
            &&self.listed)
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    MatchArgAlias {
}
#[automatically_derived]impl ::core::cmp::PartialEq for MatchArgAlias {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.listed == other.listed && self.alias == other.alias &&
            self.choice == other.choice
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for MatchArgAlias {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<&'static str>;
        let _: ::core::cmp::AssertParamIsEq<&'static str>;
        let _: ::core::cmp::AssertParamIsEq<bool>;
    }
}Eq)]
128pub struct MatchArgAlias {
129    /// The other spelling, matched only when typed in full.
130    pub alias: &'static str,
131    /// The choice it selects, one of [`MatchArg::CHOICES`].
132    pub choice: &'static str,
133    /// Whether an error that lists the choices names this alias after them
134    /// (`(or "oral" for "extravascular")`, #2148).
135    pub listed: bool,
136}
137
138impl MatchArgAlias {
139    /// A listed alias, what `#[match_arg(alias = "...")]` makes: the errors
140    /// that list the choices name it.
141    pub const fn new(alias: &'static str, choice: &'static str) -> Self {
142        Self {
143            alias,
144            choice,
145            listed: true,
146        }
147    }
148
149    /// An unlisted alias, what `#[match_arg(alias = "...", listed = false)]`
150    /// makes: matched like any alias, named by no error.
151    pub const fn unlisted(alias: &'static str, choice: &'static str) -> Self {
152        Self {
153            alias,
154            choice,
155            listed: false,
156        }
157    }
158}
159
160/// The words of a `match_arg` argument error, shared by the wrappers
161/// preamble's `.miniextendr_match_arg` / `.miniextendr_match_arg_several`
162/// ([`crate::registry::ARG_CHECK_HELPERS`], built with `concat!`) and
163/// [`MatchArgError::arg_error`], so R and Rust word these errors from one
164/// source (#1741). The generated conversion of a `match_arg` type words its
165/// error with `arg_error` too (#1767). `or` and `alias_for` are the words of
166/// the clause naming the listed aliases ([`listed_aliases_clause`], #2148),
167/// which the wrappers writer renders in Rust and passes to the R helpers as
168/// their `listed` argument. `is_na` is the error of an `NA` that matches no
169/// choice, and of a non-character value holding `NA`, as `no_na` words it.
170/// It expands to string literals.
171macro_rules! match_arg_wording {
172    (not_character) => {
173        "must be NULL or a character vector"
174    };
175    (not_scalar) => {
176        "must be of length 1"
177    };
178    (not_a_choice) => {
179        "should be one of"
180    };
181    (is_na) => {
182        "must not be NA"
183    };
184    (or) => {
185        "or"
186    };
187    (alias_for) => {
188        "for"
189    };
190}
191// The R helpers (host-only) read it from here; this module uses it in place.
192#[cfg(not(target_arch = "wasm32"))]
193pub(crate) use match_arg_wording;
194
195/// Error type for `MatchArg` conversion failures.
196///
197/// Every variant carries the type's choices and aliases, so an error can say
198/// what the value must be (`'mode' should be one of "fast", "slow" (or
199/// "quick" for "fast")`) whichever way it was wrong.
200#[derive(#[automatically_derived]impl ::core::fmt::Debug for MatchArgError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::InvalidType {
                actual: __self_0, choices: __self_1, aliases: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "InvalidType actual choices aliases", __self_0, __self_1,
                    &__self_2),
            Self::InvalidLength {
                actual: __self_0, choices: __self_1, aliases: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "InvalidLength actual choices aliases", __self_0, __self_1,
                    &__self_2),
            Self::IsNa { choices: __self_0, aliases: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "IsNa choices aliases", __self_0, &__self_1),
            Self::NoMatch {
                input: __self_0, choices: __self_1, aliases: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "NoMatch input choices aliases", __self_0, __self_1,
                    &__self_2),
        }
    }
}Debug, #[automatically_derived]impl ::core::clone::Clone for MatchArgError {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::InvalidType {
                actual: __self_0, choices: __self_1, aliases: __self_2 } =>
                MatchArgError::InvalidType {
                    actual: ::core::clone::Clone::clone(__self_0),
                    choices: ::core::clone::Clone::clone(__self_1),
                    aliases: ::core::clone::Clone::clone(__self_2),
                },
            Self::InvalidLength {
                actual: __self_0, choices: __self_1, aliases: __self_2 } =>
                MatchArgError::InvalidLength {
                    actual: ::core::clone::Clone::clone(__self_0),
                    choices: ::core::clone::Clone::clone(__self_1),
                    aliases: ::core::clone::Clone::clone(__self_2),
                },
            Self::IsNa { choices: __self_0, aliases: __self_1 } =>
                MatchArgError::IsNa {
                    choices: ::core::clone::Clone::clone(__self_0),
                    aliases: ::core::clone::Clone::clone(__self_1),
                },
            Self::NoMatch {
                input: __self_0, choices: __self_1, aliases: __self_2 } =>
                MatchArgError::NoMatch {
                    input: ::core::clone::Clone::clone(__self_0),
                    choices: ::core::clone::Clone::clone(__self_1),
                    aliases: ::core::clone::Clone::clone(__self_2),
                },
        }
    }
}Clone)]
201pub enum MatchArgError {
202    /// The SEXP was not a character or factor type.
203    InvalidType {
204        /// The SEXPTYPE that was given.
205        actual: SEXPTYPE,
206        /// The valid choices.
207        choices: &'static [&'static str],
208        /// The type's aliases ([`MatchArg::ALIASES`]).
209        aliases: &'static [MatchArgAlias],
210    },
211    /// The input had length != 1.
212    InvalidLength {
213        /// The length that was given.
214        actual: usize,
215        /// The valid choices.
216        choices: &'static [&'static str],
217        /// The type's aliases ([`MatchArg::ALIASES`]).
218        aliases: &'static [MatchArgAlias],
219    },
220    /// The input was NA.
221    IsNa {
222        /// The valid choices.
223        choices: &'static [&'static str],
224        /// The type's aliases ([`MatchArg::ALIASES`]).
225        aliases: &'static [MatchArgAlias],
226    },
227    /// No choice matched the input.
228    NoMatch {
229        /// The input string that didn't match.
230        input: String,
231        /// The valid choices.
232        choices: &'static [&'static str],
233        /// The type's aliases ([`MatchArg::ALIASES`]).
234        aliases: &'static [MatchArgAlias],
235    },
236}
237
238impl MatchArgError {
239    /// [`InvalidType`](Self::InvalidType) for the choices of `T`.
240    fn invalid_type<T: MatchArg>(actual: SEXPTYPE) -> Self {
241        MatchArgError::InvalidType {
242            actual,
243            choices: T::CHOICES,
244            aliases: T::ALIASES,
245        }
246    }
247
248    /// [`InvalidLength`](Self::InvalidLength) for the choices of `T`.
249    fn invalid_length<T: MatchArg>(actual: usize) -> Self {
250        MatchArgError::InvalidLength {
251            actual,
252            choices: T::CHOICES,
253            aliases: T::ALIASES,
254        }
255    }
256
257    /// [`IsNa`](Self::IsNa) for the choices of `T`.
258    fn is_na<T: MatchArg>() -> Self {
259        MatchArgError::IsNa {
260            choices: T::CHOICES,
261            aliases: T::ALIASES,
262        }
263    }
264
265    /// [`NoMatch`](Self::NoMatch) of `input` for the choices of `T`.
266    fn no_match<T: MatchArg>(input: &str) -> Self {
267        MatchArgError::NoMatch {
268            input: input.to_string(),
269            choices: T::CHOICES,
270            aliases: T::ALIASES,
271        }
272    }
273
274    /// The choices the value should have been one of.
275    pub fn choices(&self) -> &'static [&'static str] {
276        match self {
277            MatchArgError::InvalidType { choices, .. }
278            | MatchArgError::InvalidLength { choices, .. }
279            | MatchArgError::IsNa { choices, .. }
280            | MatchArgError::NoMatch { choices, .. } => choices,
281        }
282    }
283
284    /// The aliases of the choices, listed and unlisted.
285    pub fn aliases(&self) -> &'static [MatchArgAlias] {
286        match self {
287            MatchArgError::InvalidType { aliases, .. }
288            | MatchArgError::InvalidLength { aliases, .. }
289            | MatchArgError::IsNa { aliases, .. }
290            | MatchArgError::NoMatch { aliases, .. } => aliases,
291        }
292    }
293
294    /// What the value must be, in R terms: `one of "fast", "slow"`, with the
295    /// listed aliases after the choices (`one of "fast", "slow" (or "quick"
296    /// for "fast")`). An `Either` whose arms both refused a value names a
297    /// `match_arg` arm with it (`'x' must be one of "oral", "bolus", or a
298    /// single double: got logical`, #1594).
299    pub fn expectation(&self) -> String {
300        one_of(self.choices(), self.aliases())
301    }
302
303    /// The argument error the generated wrapper's `match_arg` check
304    /// (`.miniextendr_match_arg`) raises for this value of parameter `param`
305    /// (its R name), word for word (#1741):
306    ///
307    /// - [`InvalidType`](Self::InvalidType): `'mode' must be NULL or a character vector`
308    /// - [`InvalidLength`](Self::InvalidLength): `'mode' must be of length 1`
309    /// - [`IsNa`](Self::IsNa): `'mode' must not be NA`, the message a `no_na`
310    ///   parameter gives an `NA`
311    /// - [`NoMatch`](Self::NoMatch): `'mode' should be one of "fast",
312    ///   "safe"`, then the listed aliases (`'mode' should be one of "fast",
313    ///   "safe" (or "quick" for "fast")`, #2148)
314    ///
315    /// The choices and the aliases are quoted as R's `dQuote(choices,
316    /// FALSE)` quotes them, without escapes. [`match_arg_param`] returns it;
317    /// [`ArgError::raise`] raises it as that condition. The generated conversion of a `match_arg`
318    /// type, with or without `#[miniextendr(match_arg)]`, raises its message
319    /// too (#1767).
320    pub fn arg_error(&self, param: &str) -> ArgError {
321        ArgError::new(param, self.arg_message(param, self.choices()))
322    }
323
324    /// The message of [`arg_error`](Self::arg_error), with the choices listed
325    /// in the order of `formal`, the choices of the parameter's R formal:
326    /// `T::CHOICES`, or those of a `default = "..."` parameter, which lists
327    /// its default first ([`match_arg_param_with_default`]). The listed
328    /// aliases follow in the order of `T::CHOICES` whatever the formal, as
329    /// the wrappers writer renders them for the R check.
330    pub(crate) fn arg_message(&self, param: &str, formal: &[&str]) -> String {
331        let what = match self {
332            MatchArgError::InvalidType { .. } => "must be NULL or a character vector"match_arg_wording!(not_character).to_string(),
333            MatchArgError::InvalidLength { .. } => "must be of length 1"match_arg_wording!(not_scalar).to_string(),
334            MatchArgError::IsNa { .. } => "must not be NA"match_arg_wording!(is_na).to_string(),
335            MatchArgError::NoMatch { .. } => {
336                let quoted: Vec<String> = formal.iter().map(|c| r_quote(c)).collect();
337                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1}{2}", "should be one of",
                quoted.join(", "),
                listed_aliases_clause(self.choices(), self.aliases(),
                    r_quote)))
    })format!(
338                    "{} {}{}",
339                    match_arg_wording!(not_a_choice),
340                    quoted.join(", "),
341                    listed_aliases_clause(self.choices(), self.aliases(), r_quote)
342                )
343            }
344        };
345        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}\' {1}", param, what))
    })format!("'{param}' {what}")
346    }
347
348    /// The reason of this error in R terms, after `<expected>: ` when an
349    /// `Either` names this arm in an argument error (#1591): `got "zzz"`,
350    /// `got numeric`, `got length 2`, `NA is not allowed`. With
351    /// `expected_known = false` (nothing before the reason names the choices)
352    /// it is the `Display` text, which says what was expected.
353    pub(crate) fn r_reason(&self, expected_known: bool) -> String {
354        if !expected_known {
355            return self.to_string();
356        }
357        match self {
358            MatchArgError::InvalidType { actual, .. } => {
359                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("got {0}",
                crate::typed_list::sexptype_name(*actual)))
    })format!("got {}", crate::typed_list::sexptype_name(*actual))
360            }
361            MatchArgError::InvalidLength { actual, .. } => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("got length {0}", actual))
    })format!("got length {actual}"),
362            MatchArgError::IsNa { .. } => "NA is not allowed".to_string(),
363            MatchArgError::NoMatch { input, .. } => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("got {0:?}", input))
    })format!("got {input:?}"),
364        }
365    }
366}
367
368/// `one of "fast", "slow"`: what a `match_arg` / `choices` value must be, in
369/// the words of a conversion's argument error that names it beside other
370/// accepted values (`'x' must be one of "oral", "bolus", or a single double:
371/// got logical`, #1594). The listed `aliases` follow the choices (`one of
372/// "fast", "slow" (or "quick" for "fast")`).
373pub fn one_of(choices: &[&str], aliases: &[MatchArgAlias]) -> String {
374    choice_expectation(choices, aliases, false, "")
375}
376
377/// `one of "fast", "slow"<suffix>`, or `one or more of "fast", "slow"<suffix>`
378/// for a `several_ok` parameter (`several`), quoted as [`one_of`] quotes, the
379/// listed `aliases` between the choices and the suffix (`one of "fast",
380/// "slow" (or "quick" for "fast"), or a number`).
381/// The generated argument error of a `match_arg` / `choices` parameter on
382/// `Either<T, R>` passes the other accepted values as `suffix`
383/// (`, or a data frame`), in the words of its `@param` line; an `Either`
384/// whose arms both refused a value joins them with it too.
385#[doc(hidden)]
386pub fn choice_expectation(
387    choices: &[&str],
388    aliases: &[MatchArgAlias],
389    several: bool,
390    suffix: &str,
391) -> String {
392    let quoted: Vec<String> = choices.iter().map(|c| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", c))
    })format!("{c:?}")).collect();
393    let lead = if several { "one or more of" } else { "one of" };
394    let listed = listed_aliases_clause(choices, aliases, |s| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", s))
    })format!("{s:?}"));
395    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1} {0}{2}{3}", quoted.join(", "),
                lead, listed, suffix))
    })format!("{lead} {}{listed}{suffix}", quoted.join(", "))
396}
397
398/// `"x"`: a string quoted as R's `dQuote(x, FALSE)` quotes it, without
399/// escapes, as the `match_arg` check's message quotes the choices.
400pub(crate) fn r_quote(s: &str) -> String {
401    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"", s))
    })format!("\"{s}\"")
402}
403
404/// The text that names the listed aliases after the choices of a message: a
405/// space, then `(or "oral" for "extravascular", "grey" for "gray")`; `""`
406/// when no alias is listed (#2148). The aliases follow the order of their
407/// choices in `choices` (`MatchArg::CHOICES`, the order of the variants),
408/// then their order in `aliases`. `quote` quotes each alias and choice, as
409/// the message quotes the choices before it.
410///
411/// Every error that lists the choices appends it: [`MatchArgError`]'s
412/// messages, [`choice_expectation`], and the wrappers preamble's checks, to
413/// which the wrappers writer passes it as their `listed` argument
414/// ([`crate::registry::match_arg_aliases_arg`]), so R and Rust word it alike.
415pub(crate) fn listed_aliases_clause(
416    choices: &[&str],
417    aliases: &[MatchArgAlias],
418    quote: impl Fn(&str) -> String,
419) -> String {
420    let mut listed: Vec<&MatchArgAlias> = aliases.iter().filter(|a| a.listed).collect();
421    if listed.is_empty() {
422        return String::new();
423    }
424    // Stable: aliases of one choice keep their order. A target that is no
425    // choice (a hand-written impl the writer refuses) goes last.
426    listed.sort_by_key(|a| {
427        choices
428            .iter()
429            .position(|choice| *choice == a.choice)
430            .unwrap_or(usize::MAX)
431    });
432    let pairs: Vec<String> = listed
433        .iter()
434        .map(|a| {
435            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1} {2}", quote(a.alias),
                "for", quote(a.choice)))
    })format!(
436                "{} {} {}",
437                quote(a.alias),
438                match_arg_wording!(alias_for),
439                quote(a.choice)
440            )
441        })
442        .collect();
443    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" ({0} {1})", "or",
                pairs.join(", ")))
    })format!(" ({} {})", match_arg_wording!(or), pairs.join(", "))
444}
445
446/// The text is complete on its own, for a conversion outside an argument:
447/// `expected one of "fast", "slow", got "zzz"`, `expected a string or factor,
448/// got numeric`.
449impl std::fmt::Display for MatchArgError {
450    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
451        let expected = self.expectation();
452        match self {
453            MatchArgError::InvalidType { actual, .. } => f.write_fmt(format_args!("expected {1} (a string or factor), got {0}",
        crate::typed_list::sexptype_name(*actual), expected))write!(
454                f,
455                "expected {expected} (a string or factor), got {}",
456                crate::typed_list::sexptype_name(*actual)
457            ),
458            MatchArgError::InvalidLength { actual, .. } => {
459                f.write_fmt(format_args!("expected {0}, got length {1}", expected, actual))write!(f, "expected {expected}, got length {actual}")
460            }
461            MatchArgError::IsNa { .. } => f.write_fmt(format_args!("expected {0}, got NA", expected))write!(f, "expected {expected}, got NA"),
462            MatchArgError::NoMatch { input, .. } => {
463                f.write_fmt(format_args!("expected {0}, got {1:?}", expected, input))write!(f, "expected {expected}, got {input:?}")
464            }
465        }
466    }
467}
468
469impl std::error::Error for MatchArgError {}
470
471/// Kept whole, so a `TryFromSexp` whose error is `SexpError` (the one
472/// `#[derive(MatchArg)]` emits) still reports the choices.
473impl From<MatchArgError> for crate::from_r::SexpError {
474    fn from(e: MatchArgError) -> Self {
475        crate::from_r::SexpError::MatchArg(e)
476    }
477}
478
479/// Escape a Rust `&str` for embedding inside an R double-quoted string literal.
480///
481/// Handles `\`, `"`, newline, carriage return, and tab — the characters R
482/// recognises as escape sequences inside `"..."`. Used when formatting
483/// `MatchArg::CHOICES` into the default of a generated R wrapper formal, so
484/// that a choice like `say "hi"` or `c:\path` cannot produce syntactically
485/// invalid R code.
486pub fn escape_r_string(s: &str) -> String {
487    let mut out = String::with_capacity(s.len());
488    for ch in s.chars() {
489        match ch {
490            '\\' => out.push_str(r"\\"),
491            '"' => out.push_str(r#"\""#),
492            '\n' => out.push_str(r"\n"),
493            '\r' => out.push_str(r"\r"),
494            '\t' => out.push_str(r"\t"),
495            c => out.push(c),
496        }
497    }
498    out
499}
500
501/// What is wrong with the aliases of a type whose choices are `choices`, one
502/// sentence per bad alias, in order (empty when they are fine): an alias that
503/// is empty or `"NA"`, a choice, given twice, or a prefix of a choice other
504/// than its own (typing it would select something else than without the
505/// alias), and a target that is not a choice. `#[derive(MatchArg)]` refuses
506/// the same at compile time, with the same words; the wrappers writer checks
507/// a hand-written impl with this ([`crate::registry::match_arg_aliases_arg`]).
508#[cfg(not(target_arch = "wasm32"))]
509pub(crate) fn alias_problems(choices: &[&str], aliases: &[MatchArgAlias]) -> Vec<String> {
510    let mut problems = Vec::new();
511    let mut seen = std::collections::HashSet::new();
512    for &MatchArgAlias {
513        alias,
514        choice: target,
515        ..
516    } in aliases
517    {
518        if alias.is_empty() {
519            problems
520                .push("an alias can't be empty: the empty string matches no choice".to_string());
521        } else if alias == "NA" {
522            problems.push("alias \"NA\" would read as a missing value".to_string());
523        } else if choices.contains(&alias) {
524            problems.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("alias {0:?} is already a choice",
                alias))
    })format!("alias {alias:?} is already a choice"));
525        } else if !seen.insert(alias) {
526            problems.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("alias {0:?} is given more than once",
                alias))
    })format!("alias {alias:?} is given more than once"));
527        } else if !choices.contains(&target) {
528            problems.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("alias {0:?} names {1:?}, which is not a choice",
                alias, target))
    })format!(
529                "alias {alias:?} names {target:?}, which is not a choice"
530            ));
531        } else if let Some(other) = choices
532            .iter()
533            .find(|choice| **choice != target && choice.starts_with(alias))
534        {
535            problems.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("alias {0:?} for {1:?} is a prefix of the choice {2:?}, so it would change what typing {0:?} selects",
                alias, target, other))
    })format!(
536                "alias {alias:?} for {target:?} is a prefix of the choice {other:?}, \
537                 so it would change what typing {alias:?} selects"
538            ));
539        }
540    }
541    problems
542}
543
544/// Build an R character vector (STRSXP) from the choices of a `MatchArg` type.
545///
546/// This is called by generated choices-helper C wrappers to provide the
547/// choice list to `base::match.arg()` in the R wrapper.
548pub fn choices_sexp<T: MatchArg>() -> SEXP {
549    let choices = <T as MatchArg>::CHOICES;
550    unsafe {
551        let scope = ProtectScope::new();
552        // Preserve the R_BlankString short-circuit: skips hash-lookup on the
553        // interned empty CHARSXP for any empty choice strings.
554        let vec = scope.alloc_strsxp(choices.len()).into_raw();
555        for (i, s) in choices.iter().enumerate() {
556            let charsxp = if s.is_empty() {
557                SEXP::blank_string()
558            } else {
559                SEXP::charsxp(s)
560            };
561            vec.set_string_elt(i as R_xlen_t, charsxp);
562        }
563        vec
564    }
565}
566
567/// Map a `SexpError` from a string `TryFromSexp` conversion into a `MatchArgError`.
568///
569/// Only `Type` and `Length` are produced by the `&str`/`Option<&str>`/
570/// `Vec<Option<&str>>` conversions we delegate to — other variants are
571/// unreachable in this context.
572fn sexp_err_to_match_arg_err<T: MatchArg>(e: SexpError) -> MatchArgError {
573    match e {
574        SexpError::Type(t) => MatchArgError::invalid_type::<T>(t.actual),
575        SexpError::Length(l) => MatchArgError::invalid_length::<T>(l.actual),
576        other => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("unexpected SexpError from string conversion: {0}",
                other)));
}unreachable!("unexpected SexpError from string conversion: {other}"),
577    }
578}
579
580/// The choices of a `match_arg` parameter's R formal: `choices` with the
581/// default moved to the front and the others after it in their order
582/// (`"Safe"` in `"Fast", "Safe", "Debug"` gives `"Safe", "Fast", "Debug"`),
583/// or `None` when `is_default` holds for no choice.
584///
585/// `.miniextendr_match_arg()` takes the first element of the formal for
586/// `NULL` and for the formal itself, so this order is what makes a
587/// `default = "..."` the default, and the order its message lists. The
588/// wrappers writer builds such a formal with it
589/// ([`crate::registry::match_arg_formal`]) and
590/// [`match_arg_param_with_default`] matches against it, so the two cannot
591/// disagree (#1767).
592pub(crate) fn default_first<'a>(
593    choices: &[&'a str],
594    is_default: impl Fn(&str) -> bool,
595) -> Option<Vec<&'a str>> {
596    let at = choices.iter().position(|choice| is_default(choice))?;
597    let mut formal = Vec::with_capacity(choices.len());
598    formal.push(choices[at]);
599    formal.extend(
600        choices
601            .iter()
602            .enumerate()
603            .filter(|&(i, _)| i != at)
604            .map(|(_, choice)| *choice),
605    );
606    Some(formal)
607}
608
609/// The first choice of the formal: what `NULL` and the formal itself select.
610fn first_choice<T: MatchArg>(formal: &[&str]) -> Result<T, MatchArgError> {
611    formal
612        .first()
613        .and_then(|choice| T::from_choice(choice))
614        .ok_or_else(|| MatchArgError::no_match::<T>(""))
615}
616
617/// `NA` as a choice: `pmatch()`, and so the wrapper's check, matches it as
618/// the string `"NA"`, so a choice that is `"NA"` or the only one starting
619/// with it is selected. Anything else is [`MatchArgError::IsNa`]. No alias
620/// maps it: the wrapper looks aliases up with `match()`, which never matches
621/// `NA` to `"NA"`.
622fn match_na<T: MatchArg>() -> Result<T, MatchArgError> {
623    match_string::<T>("NA", &[]).map_err(|_| MatchArgError::is_na::<T>())
624}
625
626/// The error of a choice value that is not a character vector (nor a
627/// factor or `NULL`): [`MatchArgError::IsNa`] when it is an atomic vector
628/// holding an `NA` (`anyNA()`'s reading), else
629/// [`MatchArgError::InvalidType`]. The R helpers decide the same way.
630fn not_character<T: MatchArg>(sexp: SEXP) -> MatchArgError {
631    let atomic = #[allow(non_exhaustive_omitted_patterns)] match sexp.type_of() {
    SEXPTYPE::LGLSXP | SEXPTYPE::INTSXP | SEXPTYPE::REALSXP |
        SEXPTYPE::CPLXSXP => true,
    _ => false,
}matches!(
632        sexp.type_of(),
633        SEXPTYPE::LGLSXP | SEXPTYPE::INTSXP | SEXPTYPE::REALSXP | SEXPTYPE::CPLXSXP
634    );
635    if atomic && crate::from_r::any_na(sexp) {
636        MatchArgError::is_na::<T>()
637    } else {
638        MatchArgError::invalid_type::<T>(sexp.type_of())
639    }
640}
641
642/// The text of one string of a choice value.
643type Label = std::borrow::Cow<'static, str>;
644
645/// The text of the non-`NA` CHARSXP `charsxp` of a choice value. A Latin-1
646/// string is translated. One marked as bytes is compared by its bytes, as
647/// `pmatch()` and so the wrapper's check compare it: read lossily, it matches
648/// a choice only when its bytes are that choice's UTF-8, and a `NoMatch`
649/// shows it with `U+FFFD` for the bytes that are not UTF-8.
650fn choice_label(charsxp: SEXP) -> Label {
651    // SAFETY: a non-NA CHARSXP of the choice value, which the caller roots.
652    unsafe { charsxp_to_cow_lossy(charsxp) }
653}
654
655/// The error of a choice value of `len` strings `label(i)` (`None` for `NA`)
656/// that is not one string: [`MatchArgError::IsNa`] when it holds an `NA` that
657/// matches no choice (see [`match_na`]), else
658/// [`MatchArgError::InvalidLength`]. The R helper decides the same way.
659fn not_scalar<T: MatchArg>(len: usize, label: impl Fn(isize) -> Option<Label>) -> MatchArgError {
660    let has_na = (0isize..).take(len).any(|i| label(i).is_none());
661    if has_na && match_na::<T>().is_err() {
662        MatchArgError::is_na::<T>()
663    } else {
664        MatchArgError::invalid_length::<T>(len)
665    }
666}
667
668/// Whether the `len` strings `label(i)` (`None` for `NA`) are `formal`, in
669/// order: the formal default of a choice parameter, which an omitted argument
670/// evaluates to.
671fn is_formal(formal: &[&str], len: usize, label: impl Fn(isize) -> Option<Label>) -> bool {
672    len == formal.len()
673        && formal
674            .iter()
675            .zip(0..)
676            .all(|(choice, i)| label(i).as_deref() == Some(*choice))
677}
678
679/// The label of element `i` of a factor (`None` for a missing code or one
680/// outside the levels).
681fn factor_label(codes: SEXP, levels: SEXP, i: isize) -> Option<Label> {
682    let code = codes.integer_elt(i);
683    // R factor codes are 1-based; NA_integer_ is i32::MIN.
684    let level = isize::try_from(code).ok()?.checked_sub(1)?;
685    if level < 0 || level >= isize::try_from(levels.len()).ok()? {
686        return None;
687    }
688    let charsxp = levels.string_elt(level);
689    if charsxp.is_na_string() {
690        return None;
691    }
692    Some(choice_label(charsxp))
693}
694
695/// A factor as a choice: read as its labels, like `as.character()`.
696fn factor_to_choice<T: MatchArg>(sexp: SEXP, formal: &[&str]) -> Result<T, MatchArgError> {
697    let levels = sexp.get_levels();
698    let len = sexp.len();
699    if is_formal(formal, len, |i| factor_label(sexp, levels, i)) {
700        return first_choice::<T>(formal);
701    }
702    if len != 1 {
703        return Err(not_scalar::<T>(len, |i| factor_label(sexp, levels, i)));
704    }
705    match factor_label(sexp, levels, 0) {
706        Some(label) => match_choice::<T>(&label),
707        None => match_na::<T>(),
708    }
709}
710
711/// Match one choice argument with the semantics of the generated wrapper's
712/// `match_arg` check (`.miniextendr_match_arg`), which are those of
713/// `base::match.arg(arg, choices)`:
714///
715/// - `NULL` is the first choice;
716/// - a factor is read as its labels;
717/// - any other value that is not a character vector is
718///   [`MatchArgError::IsNa`] when it holds an `NA` (a logical `NA`,
719///   `NA_real_`), else [`MatchArgError::InvalidType`];
720/// - the full choices vector, `T::CHOICES` in order and without attributes
721///   (what an omitted argument evaluates to when the choices are its formal
722///   default), is the first choice;
723/// - otherwise the value must have length 1 ([`MatchArgError::InvalidLength`],
724///   or [`MatchArgError::IsNa`] when it holds an `NA` that matches no choice)
725///   and match a choice exactly, an alias exactly ([`MatchArg::ALIASES`]),
726///   or a choice as a unique prefix ([`MatchArgError::NoMatch`]). The empty
727///   string matches nothing, and `NA` is matched as the string `"NA"`, as
728///   `pmatch()` does ([`MatchArgError::IsNa`] when that matches nothing).
729///
730/// Used by the generated `TryFromSexp for T` implementation, and by the
731/// generated C wrapper of a `#[miniextendr(match_arg)]` parameter, which only
732/// sees the single choice the R wrapper already matched. A body matching a raw
733/// `SEXP` argument wants [`match_arg_param`], which words its errors as the
734/// wrapper does.
735pub fn match_arg_from_sexp<T: MatchArg>(sexp: SEXP) -> Result<T, MatchArgError> {
736    match_formal::<T>(sexp, <T as MatchArg>::CHOICES)
737}
738
739/// [`match_arg_from_sexp`] for a parameter whose R formal is `formal`, a
740/// permutation of `T::CHOICES`: its first element is what `NULL` and the
741/// formal itself select. Matching a string does not depend on the order.
742fn match_formal<T: MatchArg>(sexp: SEXP, formal: &[&str]) -> Result<T, MatchArgError> {
743    let sexptype = sexp.type_of();
744    if sexptype == SEXPTYPE::NILSXP {
745        return first_choice::<T>(formal);
746    }
747    if sexp.is_factor() {
748        return factor_to_choice::<T>(sexp, formal);
749    }
750    if sexptype != SEXPTYPE::STRSXP {
751        return Err(not_character::<T>(sexp));
752    }
753    let len = sexp.len();
754    // `identical(arg, choices)` compares attributes too: a named vector of
755    // the choices is not the formal default.
756    let label = |i: isize| {
757        let charsxp = sexp.string_elt(i);
758        (!charsxp.is_na_string()).then(|| choice_label(charsxp))
759    };
760    if is_formal(formal, len, label) && !sexp.has_attributes() {
761        return first_choice::<T>(formal);
762    }
763    if len != 1 {
764        return Err(not_scalar::<T>(len, label));
765    }
766    match label(0) {
767        Some(input) => match_choice::<T>(&input),
768        None => match_na::<T>(),
769    }
770}
771
772/// Match a choice argument a body received as a raw `SEXP` exactly as the
773/// generated wrapper matches a `#[miniextendr(match_arg)]` parameter, and
774/// with the same error.
775///
776/// The result is [`match_arg_from_sexp`]'s (`NULL` and the full choices
777/// vector select the first choice, a factor is read as its labels, one string
778/// matches a choice exactly, an alias exactly, or a choice as a unique
779/// prefix). The error is the argument error
780/// the wrapper raises for parameter `param` (its R name), word for word:
781///
782/// - `'mode' must be NULL or a character vector`
783/// - `'mode' must be of length 1`
784/// - `'mode' must not be NA`
785/// - `'mode' should be one of "fast", "safe"`
786///
787/// [`ArgError::raise`] raises it as that condition (`kind = "conversion"`,
788/// the crate's `conversion_error_class`, `e$param`; see
789/// [`crate::arg_error!`]):
790///
791/// ```ignore
792/// use miniextendr_api::{SEXP, match_arg_param, miniextendr};
793///
794/// #[miniextendr]
795/// pub fn run(data: SEXP, mode: SEXP) -> String {
796///     if is_data_frame(data) {
797///         // Checked on this path only.
798///         let mode: Mode = match_arg_param(mode, "mode").unwrap_or_else(|e| e.raise());
799///         return format!("{mode:?}");
800///     }
801///     String::new()
802/// }
803/// ```
804///
805/// The choices are `T::CHOICES` in declaration order, the formal of a
806/// `#[miniextendr(match_arg)]` parameter. A value forwarded from a parameter
807/// with `default = "..."` wants [`match_arg_param_with_default`].
808pub fn match_arg_param<T: MatchArg>(sexp: SEXP, param: &str) -> Result<T, ArgError> {
809    match_arg_from_sexp::<T>(sexp).map_err(|e| e.arg_error(param))
810}
811
812/// [`match_arg_param`] for a choice argument whose R formal lists `default`
813/// first: the formal of a `#[miniextendr(match_arg, default = "...")]`
814/// parameter, which moves its default to the front and keeps the other
815/// choices in their order (#1767).
816///
817/// The formal's order decides three things, and here they follow the formal
818/// rather than `T::CHOICES`: the choice `NULL` selects, the vector that counts
819/// as the formal itself (what an omitted argument evaluates to), and the
820/// order of the choices in the message. For
821/// `#[miniextendr(match_arg, default = "\"Safe\"")] mode: Mode` with
822/// `Mode::CHOICES` `"Fast", "Safe", "Debug"`, the formal is
823/// `c("Safe", "Fast", "Debug")`:
824///
825/// | Input | `match_arg_param` | `match_arg_param_with_default(.., Mode::Safe)` |
826/// |---|---|---|
827/// | `NULL` | `Fast` | `Safe` |
828/// | `c("Safe", "Fast", "Debug")` | `'mode' must be of length 1` | `Safe` |
829/// | `c("Fast", "Safe", "Debug")` | `Fast` | `'mode' must be of length 1` |
830/// | `"zzz"` | `'mode' should be one of "Fast", "Safe", "Debug"` | `'mode' should be one of "Safe", "Fast", "Debug"` |
831///
832/// Matching a string is the same either way. The wrappers writer orders the
833/// formal with the same code, so the two agree on every input.
834///
835/// `default` is a `T`, not its string or its position: it is always one of
836/// the choices, a misspelled default does not compile, and a renamed or
837/// reordered choice moves with it.
838///
839/// ```ignore
840/// #[miniextendr]
841/// pub fn run(mode: SEXP) -> String {
842///     let mode: Mode = match_arg_param_with_default(mode, "mode", Mode::Safe)
843///         .unwrap_or_else(|e| e.raise());
844///     format!("{mode:?}")
845/// }
846/// ```
847pub fn match_arg_param_with_default<T: MatchArg>(
848    sexp: SEXP,
849    param: &str,
850    default: T,
851) -> Result<T, ArgError> {
852    let default = default.to_choice();
853    let formal = default_first(<T as MatchArg>::CHOICES, |choice| choice == default)
854        .expect("MatchArg::to_choice returns one of MatchArg::CHOICES");
855    match_formal::<T>(sexp, &formal)
856        .map_err(|e| ArgError::new(param, e.arg_message(param, &formal)))
857}
858
859/// Optional form of [`match_arg_from_sexp`] for `Option<T>` parameters (#1473).
860///
861/// `NULL` is `None` (the R formal of an `Option<T>` choice parameter defaults
862/// to `NULL`, meaning no choice was made), and so is a plain `NA`, R's
863/// untyped missing value (#2305), which the R wrapper's check lets through
864/// unmatched; anything else goes through the same exact-or-partial matching
865/// as the plain type and becomes `Some`. A typed `NA` (`NA_character_`) is
866/// matched, and refused as `NA`.
867///
868/// Used by the generated C wrapper for `#[miniextendr(match_arg)] x: Option<T>`
869/// parameters instead of `TryFromSexp`, because `Option<T>` cannot carry a
870/// `TryFromSexp` impl for a downstream enum (orphan rule) and a `T: MatchArg`
871/// blanket would collide with the newtype blanket in [`crate::newtype`].
872pub fn match_arg_option_from_sexp<T: MatchArg>(sexp: SEXP) -> Result<Option<T>, MatchArgError> {
873    if crate::from_r::is_null_or_plain_na(sexp) {
874        return Ok(None);
875    }
876    match_arg_from_sexp(sexp).map(Some)
877}
878
879/// The `Option<_>` layer of a choice parameter: `NULL` is `None`, anything
880/// else is decoded by `inner` and becomes `Some`.
881///
882/// Unlike [`match_arg_option_from_sexp`], it reads a plain `NA` as a value:
883/// it is the layer over a `several_ok` list and over an `Either`, where a
884/// plain `NA` is a logical vector, not "no value" (#2305).
885///
886/// Generated C wrappers compose this with the other layer helpers
887/// ([`match_arg_missing_or`]) around the decoder of the choice itself;
888/// [`match_arg_option_from_sexp`] is the scalar case.
889pub fn match_arg_null_or<U, E>(
890    sexp: SEXP,
891    inner: impl FnOnce(SEXP) -> Result<U, E>,
892) -> Result<Option<U>, E> {
893    if sexp.type_of() == SEXPTYPE::NILSXP {
894        Ok(None)
895    } else {
896        inner(sexp).map(Some)
897    }
898}
899
900/// The `Missing<_>` layer of a choice parameter (#1551): the missing-argument
901/// sentinel is [`Missing::Absent`](crate::Missing::Absent), anything else
902/// (`NULL` included) is decoded by `inner` and becomes `Missing::Present`.
903///
904/// The generated R wrapper keeps the choice vector as the formal default,
905/// skips the `match.arg()` check for an omitted argument and forwards R's
906/// missing-argument sentinel (`if (missing(x)) quote(expr=) else x`), so
907/// `#[miniextendr(match_arg)] mode: Missing<Option<Mode>>` reaches Rust as
908/// `Absent` when omitted, `Present(None)` for `NULL`, and
909/// `Present(Some(mode))` for a matched choice. A single-choice parameter
910/// treats its formal passed whole the same way (#2152): before the check the
911/// wrapper binds `.mx_absent_x <- missing(x) || identical(x, c(...))`, skips
912/// the check for it and forwards the sentinel
913/// (`if (.mx_absent_x) quote(expr=) else x`), so that value is `Absent` too,
914/// while a value the check matches is `Present` even when the choice vector
915/// has one element (#2182); a `several_ok` list reads that vector as every
916/// choice. The C wrapper decodes it with
917/// `match_arg_missing_or(sexp, match_arg_option_from_sexp::<Mode>)`.
918pub fn match_arg_missing_or<U, E>(
919    sexp: SEXP,
920    inner: impl FnOnce(SEXP) -> Result<U, E>,
921) -> Result<crate::Missing<U>, E> {
922    crate::missing::__mx_missing_or(sexp, inner)
923}
924
925/// The `Either<_, R>` layer of a choice parameter: a choice or a value of
926/// another kind. Character and factor input (the forms `match.arg()` reads)
927/// is decoded by `left` and becomes `Left`; anything else, `NULL` included, is
928/// converted to `R` and becomes `Right`.
929///
930/// The generated R wrapper applies the same split: its prelude matches the
931/// argument against the choices only when it is character or factor, so a
932/// misspelled choice fails there and never reaches `R`, and a data frame is
933/// never tried as a choice. For `#[miniextendr(match_arg)] route:
934/// Either<Route, DataFrame>` the C wrapper decodes with
935/// `match_arg_either_or::<_, DataFrame, _>(sexp, match_arg_from_sexp::<Route>)`;
936/// for a `several_ok` list, `Either<Vec<Route>, DataFrame>` (#1612), `left` is
937/// [`match_arg_vec_from_sexp::<Route>`](match_arg_vec_from_sexp); a
938/// `choices(...)` parameter on `Either<String, R>` (or `Either<Vec<String>, R>`
939/// with `several_ok`) passes the string type's `TryFromSexp` as `left`.
940///
941/// A value that `R` refuses is reported against the whole parameter:
942/// `'route' must be one of "oral", "bolus", "infusion", or a data frame: got
943/// integer`.
944///
945/// So `R` must read something other than character or factor input: an `R`
946/// whose [`TryFromSexp::CHARACTER_ONLY`] is `true` could receive at most
947/// `NULL`, and `#[miniextendr]` rejects the parameter at compile time.
948///
949/// This differs from `TryFromSexp for Either<L, R>`, which tries `L` first on
950/// every input and would decode `NULL` as the first choice.
951#[cfg(feature = "either")]
952pub fn match_arg_either_or<L, R, E>(
953    sexp: SEXP,
954    left: impl FnOnce(SEXP) -> Result<L, E>,
955) -> Result<either::Either<L, R>, SexpError>
956where
957    E: Into<SexpError>,
958    R: TryFromSexp,
959    R::Error: Into<SexpError>,
960{
961    if sexp.type_of() == SEXPTYPE::STRSXP || sexp.is_factor() {
962        left(sexp).map(either::Either::Left).map_err(Into::into)
963    } else {
964        R::try_from_sexp(sexp)
965            .map(either::Either::Right)
966            .map_err(Into::into)
967    }
968}
969
970/// Reads [`TryFromSexp::CHARACTER_ONLY`] of the `R` arm of an `Either<T, R>`
971/// choice parameter without requiring `R: TryFromSexp`.
972///
973/// `#[miniextendr]` emits, for each such arm (inside the generated C
974/// wrapper),
975///
976/// ```ignore
977/// {
978///     use ::miniextendr_api::match_arg::EitherArmProbeFallback as _;
979///     const _: () = ::core::assert!(
980///         !::miniextendr_api::match_arg::EitherArmProbe::<R>::CHARACTER_ONLY,
981///         "...",
982///     );
983/// }
984/// ```
985///
986/// The path resolves to the inherent const below when `R: TryFromSexp`
987/// holds. When it does not, path resolution rejects the inherent candidate
988/// (its impl bound fails) and falls back to the const of
989/// [`EitherArmProbeFallback`], which is `false`. So the check adds no error
990/// of its own for an `R` without a conversion: the decode's single "`R:
991/// TryFromSexp` is not satisfied" is the whole diagnostic. Naming
992/// `<R as TryFromSexp>::CHARACTER_ONLY` directly would report that missing
993/// impl a second time.
994#[doc(hidden)]
995pub struct EitherArmProbe<R>(core::marker::PhantomData<fn() -> R>);
996
997impl<R: TryFromSexp> EitherArmProbe<R> {
998    /// `R`'s [`TryFromSexp::CHARACTER_ONLY`].
999    pub const CHARACTER_ONLY: bool = R::CHARACTER_ONLY;
1000
1001    /// The native borrow of the choice parameter: none for character or
1002    /// factor input, which is the owned choice, else what `R` borrows
1003    /// ([`NativeBorrow::choice_or`]). The generated alias check reads it
1004    /// (#1504).
1005    pub const CHOICE_NATIVE_BORROW: Option<NativeBorrow> =
1006        NativeBorrow::choice_or(&R::NATIVE_BORROW);
1007}
1008
1009/// The fallback of [`EitherArmProbe`] for an `R` without `TryFromSexp`: the
1010/// check passes, and the decode reports the missing impl.
1011#[doc(hidden)]
1012pub trait EitherArmProbeFallback {
1013    /// Always `false`.
1014    const CHARACTER_ONLY: bool = false;
1015
1016    /// Always `None`: no conversion, nothing to check.
1017    const CHOICE_NATIVE_BORROW: Option<NativeBorrow> = None;
1018}
1019
1020impl<R> EitherArmProbeFallback for EitherArmProbe<R> {}
1021
1022/// Match a string against the choices of a `MatchArg` type: a choice typed
1023/// exactly, then an alias typed exactly ([`MatchArg::ALIASES`]), then a
1024/// unique prefix of a choice.
1025fn match_choice<T: MatchArg>(input: &str) -> Result<T, MatchArgError> {
1026    match_string::<T>(input, <T as MatchArg>::ALIASES)
1027}
1028
1029/// [`match_choice`] with the aliases `aliases`.
1030fn match_string<T: MatchArg>(input: &str, aliases: &[MatchArgAlias]) -> Result<T, MatchArgError> {
1031    let no_match = || MatchArgError::no_match::<T>(input);
1032    // `pmatch()` matches the empty string to nothing, not even to an empty
1033    // choice; without this every choice would be a partial match.
1034    if input.is_empty() {
1035        return Err(no_match());
1036    }
1037
1038    // Exact match
1039    if let Some(val) = T::from_choice(input) {
1040        return Ok(val);
1041    }
1042
1043    // An alias, typed in full only: a prefix of an alias is not one, so an
1044    // alias never makes a prefix of the choices ambiguous.
1045    if let Some(alias) = aliases.iter().find(|alias| alias.alias == input) {
1046        return T::from_choice(alias.choice).ok_or_else(no_match);
1047    }
1048
1049    // Unique partial match (like R's match.arg)
1050    let mut matches = <T as MatchArg>::CHOICES
1051        .iter()
1052        .filter(|choice| choice.starts_with(input));
1053    match (matches.next(), matches.next()) {
1054        (Some(choice), None) => T::from_choice(choice).ok_or_else(no_match),
1055        _ => Err(no_match()),
1056    }
1057}
1058
1059/// Convert a `Vec<T: MatchArg>` to an R character vector (STRSXP).
1060///
1061/// Each element is written as its canonical choice string via [`MatchArg::to_choice`].
1062/// Empty choice strings are stored as `R_BlankString` (parity with [`choices_sexp`]).
1063///
1064/// Called by the [`MatchArg`]→[`IntoRVecElement`](crate::newtype::IntoRVecElement)
1065/// bridge below, which backs `IntoR for Vec<MyEnum>`.
1066pub fn match_arg_vec_into_sexp<T: MatchArg>(values: Vec<T>) -> SEXP {
1067    unsafe {
1068        let scope = ProtectScope::new();
1069        // Preserve the R_BlankString short-circuit: skips hash-lookup on the
1070        // interned empty CHARSXP for any empty choice strings.
1071        let vec = scope.alloc_strsxp(values.len()).into_raw();
1072        for (i, v) in values.into_iter().enumerate() {
1073            let s = v.to_choice();
1074            let charsxp = if s.is_empty() {
1075                SEXP::blank_string()
1076            } else {
1077                SEXP::charsxp(s)
1078            };
1079            vec.set_string_elt(i as R_xlen_t, charsxp);
1080        }
1081        vec
1082    }
1083}
1084
1085/// Bridge: every [`MatchArg`] type is an [`IntoRVecElement`](crate::newtype::IntoRVecElement),
1086/// so `Vec<MyEnum>` converts to an R character vector (STRSXP) via
1087/// [`match_arg_vec_into_sexp`].
1088///
1089/// `IntoR for Vec<T>` has a single blanket slot (see [`crate::newtype`]). Routing
1090/// `MatchArg` through `IntoRVecElement` lets `#[derive(IntoR)]` newtypes share
1091/// that slot — a newtype implements `IntoRVecElement` concretely in its own crate,
1092/// which coexists with this bridge because a local newtype is provably not
1093/// `MatchArg` (deriving both `MatchArg` and `IntoR` on one type is an E0119
1094/// coherence error, by design). Stable Rust has no negative trait bounds, so a
1095/// *second* `impl<T: …> IntoR for Vec<T>` blanket would conflict directly; this
1096/// indirection is what avoids that.
1097impl<T: MatchArg> crate::newtype::IntoRVecElement for T {
1098    fn elements_into_sexp(values: Vec<Self>) -> SEXP {
1099        match_arg_vec_into_sexp(values)
1100    }
1101}
1102
1103/// Extract multiple strings from an R SEXP (STRSXP) and match each against
1104/// the choices of a `MatchArg` type.
1105///
1106/// Used by the generated C wrapper for `match_arg + several_ok` parameters
1107/// (`match.arg` with `several.ok = TRUE`).
1108///
1109/// NULL input returns all variants. The R prelude's strict `several_ok`
1110/// helper maps `NULL` the same way and rejects any element that matches no
1111/// choice before the value reaches this function, so the per-element check
1112/// here is the second line of defence, not the only one (#1472). Under an
1113/// `Either<Vec<T>, R>` parameter (#1612), `match_arg_either_or` calls it
1114/// only for character or factor input, so `NULL` never reaches it there.
1115///
1116/// Note: factors (INTSXP) are not handled here — the R wrapper coerces factors
1117/// to character before the `.Call()` boundary, on the `Either` path too.
1118pub fn match_arg_vec_from_sexp<T: MatchArg>(sexp: SEXP) -> Result<Vec<T>, MatchArgError> {
1119    // NIL → all choices (match.arg default with several.ok = TRUE).
1120    if sexp.type_of() == SEXPTYPE::NILSXP {
1121        return <T as MatchArg>::CHOICES
1122            .iter()
1123            .map(|c| T::from_choice(c).ok_or_else(|| MatchArgError::no_match::<T>(c)))
1124            .collect();
1125    }
1126
1127    if sexp.type_of() != SEXPTYPE::STRSXP {
1128        return Err(not_character::<T>(sexp));
1129    }
1130    // STRSXP path — `None` is NA_character_, matched as the string "NA" the
1131    // way `pmatch()` does (IsNa error when that matches no choice).
1132    <Vec<Option<&'static str>> as TryFromSexp>::try_from_sexp(sexp)
1133        .map_err(sexp_err_to_match_arg_err::<T>)?
1134        .into_iter()
1135        .map(|opt| match opt {
1136            Some(s) => match_choice::<T>(s),
1137            None => match_na::<T>(),
1138        })
1139        .collect()
1140}
1141
1142#[cfg(test)]
1143mod tests;