Skip to main content

miniextendr_api/
from_r.rs

1#![allow(rustdoc::private_intra_doc_links)]
2//! Conversions from R SEXP to Rust types.
3//!
4//! This module provides [`TryFromSexp`] implementations for converting R values to Rust types:
5//!
6//! | R Type | Rust Type | Access Method |
7//! |--------|-----------|---------------|
8//! | INTSXP | `i32`, `&[i32]` | `INTEGER()` / `DATAPTR_RO` |
9//! | REALSXP | `f64`, `&[f64]` | `REAL()` / `DATAPTR_RO` |
10//! | LGLSXP | `RLogical`, `&[RLogical]` | `LOGICAL()` / `DATAPTR_RO` |
11//! | RAWSXP | `u8`, `&[u8]` | `RAW()` / `DATAPTR_RO` |
12//! | CPLXSXP | `Rcomplex` | `COMPLEX()` / `DATAPTR_RO` |
13//! | STRSXP | `&str`, `String` | `STRING_ELT()` + encoding-aware UTF-8 extraction |
14//!
15//! # Submodules
16//!
17//! | Module | Contents |
18//! |--------|----------|
19//! | [`logical`] | `Rboolean`.string_elt(`bool`, `Option<bool>` |
20//! | [`coerced_scalars`] | Multi-source numeric scalars (`i8`..`usize`) + large integers (`i64`, `u64`) |
21//! | [`references`] | Borrowed views: `&T`, `&mut T`, `&[T]`, `Vec<&T>` |
22//! | [`strings`] | `&str`, `String`, `char` from STRSXP |
23//! | [`na_vectors`] | `Vec<Option<T>>`, `Box<[Option<T>]>` with NA awareness |
24//! | [`collections`] | `HashMap`, `BTreeMap`, `HashSet`, `BTreeSet` |
25//! | [`cow_and_paths`] | `Cow<[T]>`, `PathBuf`, `OsString`, string sets |
26//!
27//! # Choosing the right inbound conversion
28//!
29//! [`TryFromSexp`] is the strict inbound path: it returns `Result<T, SexpError>`
30//! and rejects mismatched [`SEXPTYPE`]s outright (no silent coercion). When you
31//! need to *accept* arguments coming from multiple R native types, reach for
32//! the [`crate::coerce::Coerce`] / [`crate::coerce::TryCoerce`] traits instead
33//! — those are the looser inbound path and the entry point for the multi-source
34//! scalars handled in [`coerced_scalars`].
35//!
36//! The strict-vs-lax pairing for *outbound* conversion lives on
37//! [`crate::into_r::IntoR`] (lax, default) vs [`crate::strict`] (`#[miniextendr(strict)]`).
38//! There is intentionally no `TryFromSexpStrict` trait — inbound is already
39//! strict-by-default because it returns `Result`.
40//!
41//! # Thread Safety
42//!
43//! The trait provides two methods:
44//! - [`TryFromSexp::try_from_sexp`] - checked version with debug thread assertions
45//! - [`TryFromSexp::try_from_sexp_unchecked`] - unchecked version for performance-critical paths
46//!
47//! Use `try_from_sexp_unchecked` when you're certain you're on the main thread:
48//! - Inside ALTREP callbacks
49//! - Inside standalone `#[miniextendr]` functions (they run on the main thread)
50//! - Inside `extern "C-unwind"` functions called directly by R
51
52use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
53
54use crate::altrep_traits::NA_REAL;
55use crate::coerce::TryCoerce;
56use crate::{IsNA, RLogical, SEXP, SEXPTYPE, SexpExt};
57
58/// [`any_na`] for generated code: the C wrapper's check of a `NonNa<T>`
59/// argument before its conversion, which also covers a `.Call()` that skips
60/// the R wrapper's `!anyNA()` guard.
61#[doc(hidden)]
62#[inline]
63pub fn __mx_any_na(sexp: SEXP) -> bool {
64    any_na(sexp)
65}
66
67/// Whether R's `anyNA(sexp)` is `TRUE`: the check `no_na`'s R guard makes,
68/// done in Rust on an argument that the guard does not cover (see
69/// [`TryFromSexp::__mx_input_has_na`]).
70///
71/// It follows R's rules (`anyNA` / `is.na` in `src/main/coerce.c`). A double
72/// or complex value counts when it is `NaN` (`ISNAN`, so `NaN` counts as well
73/// as `NA`). A logical or integer counts when it is `NA_INTEGER`, and a string
74/// when it is `NA_STRING`. Raw vectors and `NULL` never count. A list counts
75/// when one of its elements is a length-1 atomic `NA` (`anyNA()` is not
76/// recursive by default), and a data frame when one of its columns counts
77/// (`anyNA.data.frame`). Any other type (an external pointer, an environment,
78/// ...) holds no `NA`. A classed value is read by its type. The one gap is a
79/// class with its own `is.na()` method, such as `POSIXlt`.
80///
81/// An ALTREP vector is read element by element (`*_ELT`), as R does: a data
82/// pointer would expand a compact sequence, and some classes have none.
83pub(crate) fn any_na(sexp: SEXP) -> bool {
84    if !sexp.is_vector() {
85        return false;
86    }
87    let n = sexp.xlength();
88    if sexp.is_data_frame() {
89        return (0..n).any(|i| any_na(sexp.vector_elt(i)));
90    }
91    let altrep = sexp.is_altrep();
92    // SAFETY: `sexp` is a live wrapper argument (or an element of one) for
93    // the whole check, and each slice is read at the SEXP's own type.
94    match sexp.type_of() {
95        SEXPTYPE::LGLSXP if altrep => {
96            (0..n).any(|i| RLogical::from_i32(sexp.logical_elt(i)).is_na())
97        }
98        SEXPTYPE::INTSXP if altrep => (0..n).any(|i| sexp.integer_elt(i).is_na()),
99        SEXPTYPE::REALSXP if altrep => (0..n).any(|i| sexp.real_elt(i).is_nan()),
100        SEXPTYPE::CPLXSXP if altrep => (0..n).any(|i| {
101            let v = sexp.complex_elt(i);
102            v.r.is_nan() || v.i.is_nan()
103        }),
104        SEXPTYPE::LGLSXP => unsafe { sexp.as_slice::<RLogical>() }
105            .iter()
106            .any(|v| v.is_na()),
107        SEXPTYPE::INTSXP => unsafe { sexp.as_slice::<i32>() }.iter().any(IsNA::is_na),
108        SEXPTYPE::REALSXP => unsafe { sexp.as_slice::<f64>() }.iter().any(|v| v.is_nan()),
109        SEXPTYPE::CPLXSXP => unsafe { sexp.as_slice::<crate::Rcomplex>() }
110            .iter()
111            .any(|v| v.r.is_nan() || v.i.is_nan()),
112        SEXPTYPE::STRSXP => (0..n).any(|i| sexp.string_elt(i).is_na_string()),
113        SEXPTYPE::VECSXP => (0..n).any(|i| {
114            let elt = sexp.vector_elt(i);
115            elt.is_vector_atomic() && elt.len() == 1 && any_na(elt)
116        }),
117        _ => false,
118    }
119}
120
121// region: CHARSXP to string conversion
122
123/// Why a string marked with R's `bytes` encoding is refused: its bytes are
124/// not text in any encoding, so it has no Rust `str`. Worded as the reason of
125/// an argument error (`'x' must be a single string: marked as bytes, not
126/// text`), and of each element of a batched one (`marked as bytes, not text
127/// (elements 2, 4)`).
128pub(crate) const BYTES_REASON: &str = "marked as bytes, not text";
129
130/// Why a string whose own bytes are not valid UTF-8 is refused: a UTF-8 string,
131/// or a native one R reads without translation (any native string in a UTF-8
132/// session).
133pub(crate) const INVALID_UTF8_REASON: &str = "not valid UTF-8";
134
135/// Read a CHARSXP as Rust text, translating it to UTF-8 when its encoding
136/// requires.
137///
138/// UTF-8 strings, ASCII strings and native strings in a UTF-8 session borrow
139/// directly from the CHARSXP via `R_CHAR` + `LENGTH`. Latin-1 strings, and
140/// native non-ASCII strings in a session whose locale isn't UTF-8, use
141/// `Rf_translateCharUTF8`; that buffer lives on R's memory stack for the
142/// enclosing `.Call`. The first native translation of the session queues a
143/// warning (`encoding::warn_native_translation`).
144///
145/// A string marked with R's `bytes` encoding is not text, and a string read
146/// without translation whose bytes are not valid UTF-8 has no `str`: both are
147/// an [`SexpError::InvalidValue`] ([`BYTES_REASON`], [`INVALID_UTF8_REASON`]),
148/// which an argument conversion reports as an argument error. Every caller
149/// that returns a `Result` reads strings through this;
150/// [`charsxp_to_str_or_panic`] is for the few that cannot.
151///
152/// # Safety
153///
154/// - `charsxp` must be a valid CHARSXP (not NA_STRING, not null).
155/// - The returned `&str` is only valid as long as R doesn't GC the CHARSXP,
156///   and, for a translated string, until the enclosing `.Call` returns.
157#[inline]
158pub(crate) unsafe fn try_charsxp_to_str(charsxp: SEXP) -> Result<&'static str, SexpError> {
159    unsafe {
160        let encoding = crate::sys::Rf_getCharCE(charsxp);
161        let text = utf8_text(encoding, charsxp.r_char(), charsxp.len(), || {
162            crate::sys::Rf_translateCharUTF8(charsxp)
163        })?;
164        text.warn_if_native();
165        Ok(text.as_str())
166    }
167}
168
169/// Unchecked version of [`try_charsxp_to_str`] (skips R thread checks on R
170/// API calls).
171#[inline]
172pub(crate) unsafe fn try_charsxp_to_str_unchecked(
173    charsxp: SEXP,
174) -> Result<&'static str, SexpError> {
175    unsafe {
176        let encoding = crate::sys::Rf_getCharCE_unchecked(charsxp);
177        let text = utf8_text(
178            encoding,
179            charsxp.r_char_unchecked(),
180            charsxp.len_unchecked(),
181            || crate::sys::Rf_translateCharUTF8_unchecked(charsxp),
182        )?;
183        text.warn_if_native();
184        Ok(text.as_str())
185    }
186}
187
188/// Where a CHARSXP's UTF-8 text lives.
189enum Utf8Text {
190    /// The CHARSXP's own bytes: UTF-8-marked, ASCII, or native in a UTF-8
191    /// session.
192    Own(&'static str),
193    /// R's translation, in a buffer on R's memory stack until the enclosing
194    /// `.Call` returns. `native` when the string was unmarked (in the
195    /// session's encoding) rather than marked Latin-1.
196    Translated { text: &'static str, native: bool },
197}
198
199impl Utf8Text {
200    #[inline]
201    fn as_str(&self) -> &'static str {
202        match *self {
203            Utf8Text::Own(text) | Utf8Text::Translated { text, .. } => text,
204        }
205    }
206
207    #[inline]
208    fn warn_if_native(&self) {
209        if let Utf8Text::Translated { native: true, .. } = self {
210            crate::encoding::warn_native_translation();
211        }
212    }
213}
214
215/// A CHARSXP's text as UTF-8, given its encoding mark, its bytes and R's
216/// `translateCharUTF8`.
217///
218/// R's translation returns the CHARSXP's own bytes when none is needed:
219/// UTF-8 or ASCII strings, and native strings while the session's locale is
220/// UTF-8 (R reads its current locale, so `Sys.setlocale()` is followed). The
221/// bytes are then borrowed and validated ([`INVALID_UTF8_REASON`]). A string
222/// marked as bytes is refused ([`BYTES_REASON`]) before `translate` runs,
223/// because `Rf_translateCharUTF8` raises an R error for it.
224///
225/// # Safety
226///
227/// `own` / `len` are the CHARSXP's `R_CHAR` and `LENGTH`; `translate` returns
228/// its `Rf_translateCharUTF8`.
229#[inline]
230unsafe fn utf8_text(
231    encoding: crate::cetype_t,
232    own: *const std::os::raw::c_char,
233    len: usize,
234    translate: impl FnOnce() -> *const std::os::raw::c_char,
235) -> Result<Utf8Text, SexpError> {
236    unsafe {
237        match encoding {
238            crate::cetype_t::CE_UTF8 => return charsxp_utf8_bytes(own, len).map(Utf8Text::Own),
239            crate::cetype_t::CE_BYTES => return Err(bytes_refusal()),
240            _ => {}
241        }
242        let utf8 = translate();
243        if std::ptr::eq(utf8, own) {
244            return charsxp_utf8_bytes(own, len).map(Utf8Text::Own);
245        }
246        Ok(Utf8Text::Translated {
247            text: translated_charsxp_to_str(utf8),
248            native: #[allow(non_exhaustive_omitted_patterns)] match encoding {
    crate::cetype_t::CE_NATIVE => true,
    _ => false,
}matches!(encoding, crate::cetype_t::CE_NATIVE),
249        })
250    }
251}
252
253/// [`try_charsxp_to_str`] as a `Cow`.
254///
255/// Strings whose bytes are their UTF-8 text borrow directly from R. Strings
256/// that require encoding translation become owned Rust strings so the
257/// translated buffer cannot be invalidated independently of the returned
258/// value.
259#[inline]
260pub(crate) unsafe fn try_charsxp_to_cow(
261    charsxp: SEXP,
262) -> Result<std::borrow::Cow<'static, str>, SexpError> {
263    unsafe {
264        let encoding = crate::sys::Rf_getCharCE(charsxp);
265        let text = utf8_text(encoding, charsxp.r_char(), charsxp.len(), || {
266            crate::sys::Rf_translateCharUTF8(charsxp)
267        })?;
268        text.warn_if_native();
269        Ok(match text {
270            Utf8Text::Own(text) => std::borrow::Cow::Borrowed(text),
271            Utf8Text::Translated { text, .. } => std::borrow::Cow::Owned(text.to_owned()),
272        })
273    }
274}
275
276/// [`try_charsxp_to_str`] for a caller that has no `Result` to return: an
277/// accessor that returns `Option<&str>`, a symbol's print name. **Panics**
278/// with the refusal's reason on a string marked as bytes or one that is not
279/// valid UTF-8; a caller that returns a `Result` uses [`try_charsxp_to_str`].
280///
281/// # Safety
282///
283/// As [`try_charsxp_to_str`].
284#[inline]
285pub(crate) unsafe fn charsxp_to_str_or_panic(charsxp: SEXP) -> &'static str {
286    unsafe { try_charsxp_to_str(charsxp) }.unwrap_or_else(|e| refuse_text(&e))
287}
288
289/// [`try_charsxp_to_cow`] for a caller that has no `Result` to return.
290/// **Panics** as [`charsxp_to_str_or_panic`] does.
291///
292/// # Safety
293///
294/// As [`try_charsxp_to_str`].
295#[inline]
296pub(crate) unsafe fn charsxp_to_cow_or_panic(charsxp: SEXP) -> std::borrow::Cow<'static, str> {
297    unsafe { try_charsxp_to_cow(charsxp) }.unwrap_or_else(|e| refuse_text(&e))
298}
299
300/// Borrow directly from a CHARSXP whose bytes are its UTF-8 text, for a caller
301/// that has no `Result` to return.
302///
303/// Unlike [`try_charsxp_to_str`], this never returns R's temporary translation
304/// buffer. Use it for views whose borrow may be tied to the source STRSXP
305/// rather than merely to the enclosing `.Call`. **Panics** on a string that
306/// needs translation (Latin-1, or native non-ASCII in a session whose locale
307/// isn't UTF-8), and as [`charsxp_to_str_or_panic`] does.
308#[inline]
309pub(crate) unsafe fn charsxp_to_borrowed_str_or_panic(charsxp: SEXP) -> &'static str {
310    unsafe {
311        let encoding = crate::sys::Rf_getCharCE(charsxp);
312        match utf8_text(encoding, charsxp.r_char(), charsxp.len(), || {
313            crate::sys::Rf_translateCharUTF8(charsxp)
314        })
315        .unwrap_or_else(|e| refuse_text(&e))
316        {
317            Utf8Text::Own(text) => text,
318            Utf8Text::Translated { .. } => {
    ::core::panicking::panic_fmt(format_args!("cannot borrow an R string that needs translation to UTF-8 (Latin-1, or native in a session whose locale isn\'t UTF-8); use Cow<str> or String to translate it"));
}panic!(
319                "cannot borrow an R string that needs translation to UTF-8 (Latin-1, or native \
320                 in a session whose locale isn't UTF-8); use Cow<str> or String to translate it"
321            ),
322        }
323    }
324}
325
326/// Read a CHARSXP as text whatever it holds, for a read that must not fail
327/// (a name in a message, a class attribute): as [`try_charsxp_to_str`], except
328/// that a string marked as bytes, or one whose bytes are not valid UTF-8, is
329/// decoded lossily (`U+FFFD` for each invalid sequence) instead of refused.
330///
331/// # Safety
332///
333/// As [`try_charsxp_to_str`].
334#[inline]
335pub(crate) unsafe fn charsxp_to_cow_lossy(charsxp: SEXP) -> std::borrow::Cow<'static, str> {
336    unsafe {
337        match try_charsxp_to_str(charsxp) {
338            Ok(text) => std::borrow::Cow::Borrowed(text),
339            Err(_) => {
340                String::from_utf8_lossy(r_slice(charsxp.r_char().cast::<u8>(), charsxp.len()))
341            }
342        }
343    }
344}
345
346/// The error for a string marked as bytes ([`BYTES_REASON`]).
347fn bytes_refusal() -> SexpError {
348    SexpError::InvalidValue(BYTES_REASON.to_string())
349}
350
351/// The error of a name that [`try_charsxp_to_str`] refused, for the element at
352/// 0-based `index`: `the name of element 3 is marked as bytes, not text`.
353pub(crate) fn name_refusal(index: usize, error: &SexpError) -> SexpError {
354    SexpError::InvalidValue(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the name of element {0} is {1}",
                index + 1, error.r_reason(false)))
    })format!(
355        "the name of element {} is {}",
356        index + 1,
357        error.r_reason(false)
358    ))
359}
360
361/// The panic of a `*_or_panic` read, with the refusal's reason.
362#[cold]
363fn refuse_text(error: &SexpError) -> ! {
364    {
    ::core::panicking::panic_fmt(format_args!("cannot read an R string as Rust text: {0}",
            error.r_reason(false)));
}panic!(
365        "cannot read an R string as Rust text: {}",
366        error.r_reason(false)
367    )
368}
369
370#[inline]
371unsafe fn charsxp_utf8_bytes(
372    ptr: *const std::os::raw::c_char,
373    len: usize,
374) -> Result<&'static str, SexpError> {
375    let bytes = unsafe { r_slice(ptr.cast::<u8>(), len) };
376    std::str::from_utf8(bytes).map_err(|_| SexpError::InvalidValue(INVALID_UTF8_REASON.to_string()))
377}
378
379#[inline]
380unsafe fn translated_charsxp_to_str(ptr: *const std::os::raw::c_char) -> &'static str {
381    if !!ptr.is_null() {
    {
        ::core::panicking::panic_fmt(format_args!("R returned a null UTF-8 translation"));
    }
};assert!(!ptr.is_null(), "R returned a null UTF-8 translation");
382    unsafe { std::ffi::CStr::from_ptr(ptr) }
383        .to_str()
384        .expect("R string translation produced invalid UTF-8")
385}
386
387/// Convert CHARSXP to an owned, lossy `String`.
388///
389/// NA/null-defensive: returns `None` for `NA_character_`, `R_NilValue`, or a
390/// null SEXP. Text is read as [`charsxp_to_cow_lossy`] reads it: Latin-1 is
391/// translated, and only a string marked as bytes or one that is not valid
392/// UTF-8 is decoded lossily (`U+FFFD`) rather than rejected. Unlike
393/// [`try_charsxp_to_str`] (the hot path for argument conversions), this is for
394/// defensive reads of *arbitrary* R objects — S4 class attributes,
395/// `geterrmessage()` output, vctrs field names, `tzone` attributes — where
396/// the CHARSXP's origin and encoding aren't guaranteed.
397///
398/// # Safety
399///
400/// `charsxp` must be a valid SEXP. It may be `R_NilValue` or a null SEXP
401/// (both map to `None`); if it is neither of those and not `NA_character_`,
402/// it must actually be a CHARSXP.
403#[inline]
404pub(crate) unsafe fn charsxp_to_string_lossy(charsxp: SEXP) -> Option<String> {
405    if charsxp.is_null_or_nil() || charsxp.is_na_string() {
406        return None;
407    }
408    Some(unsafe { charsxp_to_cow_lossy(charsxp) }.into_owned())
409}
410
411/// Create a slice from an R data pointer, handling the zero-length case.
412///
413/// R returns a sentinel pointer (`0x1`) instead of null for empty vectors
414/// (e.g., `LOGICAL(integer(0))` → `0x1`). Rust 1.93+ validates pointer
415/// alignment in `slice::from_raw_parts` even for `len == 0`, so passing
416/// R's sentinel directly causes a precondition-check abort.
417///
418/// This helper returns an empty slice for `len == 0` without touching the pointer.
419///
420/// # Safety
421///
422/// If `len > 0`, `ptr` must satisfy the requirements of [`std::slice::from_raw_parts`].
423#[inline(always)]
424pub(crate) unsafe fn r_slice<'a, T>(ptr: *const T, len: usize) -> &'a [T] {
425    if len == 0 {
426        &[]
427    } else {
428        unsafe { std::slice::from_raw_parts(ptr, len) }
429    }
430}
431
432/// Mutable version of [`r_slice`] for `from_raw_parts_mut`.
433///
434/// # Safety
435///
436/// If `len > 0`, `ptr` must satisfy the requirements of [`std::slice::from_raw_parts_mut`].
437#[inline(always)]
438pub(crate) unsafe fn r_slice_mut<'a, T>(ptr: *mut T, len: usize) -> &'a mut [T] {
439    if len == 0 {
440        &mut []
441    } else {
442        unsafe { std::slice::from_raw_parts_mut(ptr, len) }
443    }
444}
445
446#[derive(#[automatically_derived]impl ::core::fmt::Debug for SexpTypeError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "SexpTypeError expected actual", &self.expected, &&self.actual)
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for SexpTypeError {
}
#[automatically_derived]impl ::core::clone::Clone for SexpTypeError {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<SEXPTYPE>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for SexpTypeError { }Copy)]
447/// Error describing an unexpected R `SEXPTYPE`.
448pub struct SexpTypeError {
449    /// Expected R type.
450    pub expected: SEXPTYPE,
451    /// Actual R type encountered.
452    pub actual: SEXPTYPE,
453}
454
455impl std::fmt::Display for SexpTypeError {
456    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
457        f.write_fmt(format_args!("type mismatch: expected {0:?}, got {1:?}",
        self.expected, self.actual))write!(
458            f,
459            "type mismatch: expected {:?}, got {:?}",
460            self.expected, self.actual
461        )
462    }
463}
464
465impl std::error::Error for SexpTypeError {}
466
467#[derive(#[automatically_derived]impl ::core::fmt::Debug for SexpClassError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "SexpClassError expected actual", &self.expected, &&self.actual)
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for SexpClassError {
}
#[automatically_derived]impl ::core::clone::Clone for SexpClassError {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<&'static str>;
        let _: ::core::clone::AssertParamIsClone<SEXPTYPE>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for SexpClassError { }Copy)]
468/// Error describing a value that is not the kind of R object a conversion
469/// reads, where that kind is a class rather than a `SEXPTYPE` (a data frame
470/// is a list with a class).
471pub struct SexpClassError {
472    /// What the value should have been, in R terms, with its article:
473    /// `"a data frame"`.
474    pub expected: &'static str,
475    /// Actual R type encountered.
476    pub actual: SEXPTYPE,
477}
478
479impl std::fmt::Display for SexpClassError {
480    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
481        f.write_fmt(format_args!("class mismatch: expected {0}, got {1:?}",
        self.expected, self.actual))write!(
482            f,
483            "class mismatch: expected {}, got {:?}",
484            self.expected, self.actual
485        )
486    }
487}
488
489impl std::error::Error for SexpClassError {}
490
491#[derive(#[automatically_derived]impl ::core::fmt::Debug for SexpLengthError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "SexpLengthError expected actual", &self.expected, &&self.actual)
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for SexpLengthError {
}
#[automatically_derived]impl ::core::clone::Clone for SexpLengthError {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<usize>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for SexpLengthError { }Copy)]
492/// Error describing an unexpected R object length.
493pub struct SexpLengthError {
494    /// Required length.
495    pub expected: usize,
496    /// Actual length encountered.
497    pub actual: usize,
498}
499
500impl std::fmt::Display for SexpLengthError {
501    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
502        f.write_fmt(format_args!("length mismatch: expected {0}, got {1}",
        self.expected, self.actual))write!(
503            f,
504            "length mismatch: expected {}, got {}",
505            self.expected, self.actual
506        )
507    }
508}
509
510impl std::error::Error for SexpLengthError {}
511
512#[derive(#[automatically_derived]impl ::core::fmt::Debug for SexpNaError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "SexpNaError sexp_type", &&self.sexp_type)
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for SexpNaError {
}
#[automatically_derived]impl ::core::clone::Clone for SexpNaError {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<SEXPTYPE>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for SexpNaError { }Copy)]
513/// Error for NA values in conversions that require non-missing values.
514pub struct SexpNaError {
515    /// R type where an NA was found.
516    pub sexp_type: SEXPTYPE,
517}
518
519impl std::fmt::Display for SexpNaError {
520    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
521        f.write_fmt(format_args!("unexpected NA value in {0:?}", self.sexp_type))write!(f, "unexpected NA value in {:?}", self.sexp_type)
522    }
523}
524
525impl std::error::Error for SexpNaError {}
526
527#[derive(#[automatically_derived]impl ::core::fmt::Debug for SexpError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Type(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Type",
                    &__self_0),
            Self::Class(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Class",
                    &__self_0),
            Self::Length(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Length", &__self_0),
            Self::Na(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Na",
                    &__self_0),
            Self::InvalidValue(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "InvalidValue", &__self_0),
            Self::MissingField(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "MissingField", &__self_0),
            Self::DuplicateName(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "DuplicateName", &__self_0),
            Self::MatchArg(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "MatchArg", &__self_0),
            Self::Condition(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Condition", &__self_0),
        }
    }
}Debug, #[automatically_derived]impl ::core::clone::Clone for SexpError {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::Type(__self_0) =>
                SexpError::Type(::core::clone::Clone::clone(__self_0)),
            Self::Class(__self_0) =>
                SexpError::Class(::core::clone::Clone::clone(__self_0)),
            Self::Length(__self_0) =>
                SexpError::Length(::core::clone::Clone::clone(__self_0)),
            Self::Na(__self_0) =>
                SexpError::Na(::core::clone::Clone::clone(__self_0)),
            Self::InvalidValue(__self_0) =>
                SexpError::InvalidValue(::core::clone::Clone::clone(__self_0)),
            Self::MissingField(__self_0) =>
                SexpError::MissingField(::core::clone::Clone::clone(__self_0)),
            Self::DuplicateName(__self_0) =>
                SexpError::DuplicateName(::core::clone::Clone::clone(__self_0)),
            Self::MatchArg(__self_0) =>
                SexpError::MatchArg(::core::clone::Clone::clone(__self_0)),
            Self::Condition(__self_0) =>
                SexpError::Condition(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone)]
528/// Unified conversion error when decoding an R `SEXP`.
529pub enum SexpError {
530    /// `SEXPTYPE` did not match the expected one.
531    Type(SexpTypeError),
532    /// The value is not the kind of R object this conversion reads, where
533    /// that kind is a class (a data frame is a list with a class), not a
534    /// `SEXPTYPE`.
535    Class(SexpClassError),
536    /// Length did not match the expected one.
537    Length(SexpLengthError),
538    /// Missing value encountered where disallowed.
539    Na(SexpNaError),
540    /// Value is syntactically valid but semantically invalid (e.g. parse error).
541    InvalidValue(String),
542    /// A required field was missing from a named list.
543    MissingField(String),
544    /// A named list has duplicate non-empty names.
545    DuplicateName(String),
546    /// A `match_arg` choice did not match (from `#[derive(MatchArg)]`'s
547    /// `TryFromSexp`), kept whole so the argument error names the choices.
548    MatchArg(crate::match_arg::MatchArgError),
549    /// A value a check refused with its own message, classes and fields,
550    /// typically a [`TryFromSexpElement::check_sexp`](crate::TryFromSexpElement::check_sexp)
551    /// (`#[try_from_sexp(validate = ...)]`). Any
552    /// [`RConditionData`](crate::condition::RConditionData) type, an
553    /// [`RError`](crate::condition::RError) or a `#[derive(RCondition)]`
554    /// type, converts into it with `?`.
555    ///
556    /// As an argument error it keeps the parameter context: the message is
557    /// `'<p>' must be <expected>: <the RError's message>`, the classes come
558    /// before the crate's `conversion_error_class`, the fields are spliced in
559    /// next to `e$param` and `e$rust_type`, and the call is the wrapper's
560    /// ([`RError::without_call`](crate::condition::RError::without_call) has
561    /// no effect here, as for any argument error). Inside an `Either` it is
562    /// reported, classes and fields included, whenever the other arm refused
563    /// the kind of value.
564    Condition(crate::condition::RError),
565    /// Failed to convert to `Either<L, R>` - both branches failed.
566    ///
567    /// Contains the errors from attempting both conversions, so the argument
568    /// error can word them for R (see [`SexpError::r_reason`]).
569    #[cfg(feature = "either")]
570    EitherConversion {
571        /// Error from attempting to convert to the Left type
572        left_error: Box<SexpError>,
573        /// Error from attempting to convert to the Right type
574        right_error: Box<SexpError>,
575    },
576}
577
578impl SexpTypeError {
579    /// The reason of this type error in R terms (#1591): `got character`, or
580    /// `expected integer, got character` when `expected_known` is `false`
581    /// (nothing before the reason says what the value should be). The type
582    /// names are [`sexptype_name`](crate::typed_list::sexptype_name)'s
583    /// (`numeric` for a double, `list`, `NULL`, ...), not SEXPTYPE names.
584    ///
585    /// A pairlist where a list was expected says how to fix it: `got
586    /// pairlist, convert it with as.list()`. R's `is.list()` is `TRUE` for a
587    /// pairlist, but a list conversion refuses one (#1866).
588    pub(crate) fn r_reason(&self, expected_known: bool) -> String {
589        let got = crate::typed_list::sexptype_name(self.actual);
590        let hint = if self.expected == SEXPTYPE::VECSXP && self.actual == SEXPTYPE::LISTSXP {
591            ", convert it with as.list()"
592        } else {
593            ""
594        };
595        if expected_known {
596            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("got {0}{1}", got, hint))
    })format!("got {got}{hint}")
597        } else {
598            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}, got {1}{2}",
                crate::typed_list::sexptype_name(self.expected), got, hint))
    })format!(
599                "expected {}, got {got}{hint}",
600                crate::typed_list::sexptype_name(self.expected)
601            )
602        }
603    }
604}
605
606impl SexpClassError {
607    /// The reason of this class error in R terms: `got list`, or
608    /// `expected a data frame, got list` when `expected_known` is `false`.
609    pub(crate) fn r_reason(&self, expected_known: bool) -> String {
610        let got = crate::typed_list::sexptype_name(self.actual);
611        if expected_known {
612            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("got {0}", got))
    })format!("got {got}")
613        } else {
614            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}, got {1}",
                self.expected, got))
    })format!("expected {}, got {got}", self.expected)
615        }
616    }
617}
618
619impl SexpLengthError {
620    /// The reason of this length error in R terms: `got length 2`, or
621    /// `expected length 1, got length 2` when `expected_known` is `false`.
622    pub(crate) fn r_reason(&self, expected_known: bool) -> String {
623        if expected_known {
624            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("got length {0}", self.actual))
    })format!("got length {}", self.actual)
625        } else {
626            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected length {0}, got length {1}",
                self.expected, self.actual))
    })format!(
627                "expected length {}, got length {}",
628                self.expected, self.actual
629            )
630        }
631    }
632}
633
634/// What one arm of an `Either` expected, when the value was not of that arm's
635/// kind at all (see [`SexpError::kind_mismatch`]).
636#[cfg(feature = "either")]
637enum KindExpected {
638    /// A kind in R terms: `numeric`, `a data frame`, or the joined
639    /// expectation of a nested `Either`.
640    Noun(String),
641    /// A `match_arg` choice, which reads only a string or factor: the
642    /// type's choices and aliases, whose listed ones the expectation names
643    /// after the choices.
644    Choices(
645        &'static [&'static str],
646        &'static [crate::match_arg::MatchArgAlias],
647    ),
648}
649
650#[cfg(feature = "either")]
651impl KindExpected {
652    /// The expectation of an `Either` over this arm (left) and `right`:
653    /// `numeric or a data frame`, `one of "a", "b", or numeric`,
654    /// `numeric or one of "a", "b"`, and one `one of` over two choice lists
655    /// (and their aliases).
656    fn join(&self, right: &KindExpected) -> String {
657        use crate::match_arg::choice_expectation;
658        match (self, right) {
659            (KindExpected::Noun(l), KindExpected::Noun(r)) => format!("{l} or {r}"),
660            (KindExpected::Choices(l, aliases), KindExpected::Noun(r)) => {
661                choice_expectation(l, aliases, false, &format!(", or {r}"))
662            }
663            (KindExpected::Noun(l), KindExpected::Choices(r, aliases)) => {
664                format!("{l} or {}", choice_expectation(r, aliases, false, ""))
665            }
666            (KindExpected::Choices(l, l_aliases), KindExpected::Choices(r, r_aliases)) => {
667                let mut both: Vec<&str> = l.to_vec();
668                both.extend(r.iter().filter(|c| !l.contains(c)));
669                let mut aliases = l_aliases.to_vec();
670                aliases.extend(
671                    r_aliases
672                        .iter()
673                        .filter(|a| !l_aliases.iter().any(|seen| seen.alias == a.alias)),
674                );
675                choice_expectation(&both, &aliases, false, "")
676            }
677        }
678    }
679
680    /// This expectation on its own: the noun, or `one of "a", "b"`.
681    fn text(&self) -> String {
682        match self {
683            KindExpected::Noun(noun) => noun.clone(),
684            KindExpected::Choices(choices, aliases) => {
685                crate::match_arg::choice_expectation(choices, aliases, false, "")
686            }
687        }
688    }
689}
690
691/// What one side of an `Either` parameter accepts, as the generated wrapper
692/// knows it, for [`either_expectation`]. Not public API.
693#[cfg(feature = "either")]
694#[doc(hidden)]
695pub enum ExpectedArm<'a> {
696    /// The macro's text for a type it knows (`a single number`).
697    Known(&'a str),
698    /// A type the macro does not know: what its
699    /// [`TryFromSexp::__MX_EXPECTATION`] declares, else what the arm's own
700    /// error says it expected, else `noun`, the arm's `@param` noun (the
701    /// type's name in code format for a type without an R name).
702    Opaque {
703        /// `<T as TryFromSexp>::__MX_EXPECTATION`.
704        declared: Option<&'a str>,
705        /// The fallback name of the arm.
706        noun: &'a str,
707    },
708    /// An `Option<T>` or `Result<T, ()>` arm: `NULL or <T>`.
709    Nullable(&'a ExpectedArm<'a>),
710    /// A nested `Either`, matched with the two sides of its error.
711    Either(&'a ExpectedArm<'a>, &'a ExpectedArm<'a>),
712}
713
714#[cfg(feature = "either")]
715impl ExpectedArm<'_> {
716    /// This side's expectation against the error it gave, and whether
717    /// anything but a fallback noun named it.
718    fn resolve(&self, error: &SexpError) -> Option<(KindExpected, bool)> {
719        match self {
720            ExpectedArm::Known(text)
721            | ExpectedArm::Opaque {
722                declared: Some(text),
723                ..
724            } => Some((KindExpected::Noun((*text).to_string()), true)),
725            ExpectedArm::Opaque {
726                declared: None,
727                noun,
728            } => Some(match error.arm_expectation() {
729                Some(expected) => (expected, true),
730                None => (KindExpected::Noun((*noun).to_string()), false),
731            }),
732            ExpectedArm::Nullable(inner) => inner.resolve(error).map(|(expected, known)| {
733                (
734                    KindExpected::Noun(format!("NULL or {}", expected.text())),
735                    known,
736                )
737            }),
738            ExpectedArm::Either(left, right) => {
739                let SexpError::EitherConversion {
740                    left_error,
741                    right_error,
742                } = error
743                else {
744                    return None;
745                };
746                let (l, l_known) = left.resolve(left_error)?;
747                let (r, r_known) = right.resolve(right_error)?;
748                Some((KindExpected::Noun(l.join(&r)), l_known || r_known))
749            }
750        }
751    }
752}
753
754/// Internal: the expectation of an `Either` parameter whose conversion failed
755/// with `error`, from what the wrapper knows of each side (`arms`), for
756/// `'<p>' must be <expected>: <reason>`. Not public API.
757///
758/// Each side says what its type accepts whatever the input, so the text stays
759/// the same for every failure of the parameter: `a single number or a data
760/// frame` for `Either<Dose, DataFrame>`, where `Dose` is a
761/// `#[derive(TryFromSexp)]` newtype of `AsNumeric`. A side whose type says
762/// nothing is named by its own error when that knows (`numeric` for a type
763/// error, the choices of a `match_arg` enum), else by its fallback noun. `None`
764/// when no side is named by more than that noun: the wrapper then reports
765/// `invalid '<p>' argument`.
766#[cfg(feature = "either")]
767#[doc(hidden)]
768pub fn either_expectation(error: &SexpError, arms: &ExpectedArm<'_>) -> Option<String> {
769    match arms.resolve(error)? {
770        (expected, true) => Some(expected.text()),
771        (_, false) => None,
772    }
773}
774
775impl SexpError {
776    /// What the value should have been, in R terms, when the error itself
777    /// knows and the argument's Rust type does not tell the macro (#1594): a
778    /// `match_arg` choice (`one of "fast", "slow"`), a class (`a data
779    /// frame`), or an `Either` whose arms both refused the kind of value
780    /// (`one of "fast", "slow", or numeric`). The generated wrapper then
781    /// writes `'<p>' must be <this>: <reason>` instead of
782    /// `invalid '<p>' argument: <reason>`. A type error alone gives none: the
783    /// `SEXPTYPE` it expected is the storage the conversion reads, which for
784    /// an opaque type need not be all it accepts.
785    pub(crate) fn r_expectation(&self) -> Option<String> {
786        match self {
787            SexpError::MatchArg(e) => Some(e.expectation()),
788            SexpError::Class(e) => Some(e.expected.to_string()),
789            #[cfg(feature = "either")]
790            SexpError::EitherConversion {
791                left_error,
792                right_error,
793            } => both_kind_mismatches(left_error, right_error).map(|(expected, _)| expected),
794            _ => None,
795        }
796    }
797
798    /// What this error expected and the value's `SEXPTYPE`, when it means the
799    /// value was not of the conversion's kind at all: a type error, a class
800    /// error, a `match_arg` refusal of a value that is not a string or factor,
801    /// or an `Either` whose arms both mean that. `None` when the value was of
802    /// the right kind and failed later (length, NA, value, a choice that did
803    /// not match).
804    #[cfg(feature = "either")]
805    fn kind_mismatch(&self) -> Option<(KindExpected, SEXPTYPE)> {
806        match self {
807            SexpError::Type(e) => Some((
808                KindExpected::Noun(crate::typed_list::sexptype_name(e.expected)),
809                e.actual,
810            )),
811            SexpError::Class(e) => Some((KindExpected::Noun(e.expected.to_string()), e.actual)),
812            SexpError::MatchArg(crate::match_arg::MatchArgError::InvalidType {
813                actual,
814                choices,
815                aliases,
816            }) => Some((KindExpected::Choices(choices, aliases), *actual)),
817            SexpError::EitherConversion {
818                left_error,
819                right_error,
820            } => both_kind_mismatches(left_error, right_error)
821                .map(|(expected, actual)| (KindExpected::Noun(expected), actual)),
822            _ => None,
823        }
824    }
825
826    /// What this error says one `Either` side expected, whether or not the
827    /// value was of that side's kind: the kind it refused ([`Self::kind_mismatch`]),
828    /// or the choices of a `match_arg` refusal that got further (a string
829    /// that matched no choice). `None` for an error that names no
830    /// expectation (length, NA, an invalid value).
831    #[cfg(feature = "either")]
832    fn arm_expectation(&self) -> Option<KindExpected> {
833        match self {
834            SexpError::MatchArg(e) => Some(KindExpected::Choices(e.choices(), e.aliases())),
835            _ => self.kind_mismatch().map(|(expected, _)| expected),
836        }
837    }
838
839    /// The reason of this conversion error in R terms, the text after
840    /// `'<p>' must be <expected>: ` in an argument error (#1591). `Display`
841    /// is written for the package author (SEXPTYPE names, `invalid value: `);
842    /// this says what was wrong with the value:
843    ///
844    /// | error | `expected_known` | reason |
845    /// |-------|------------------|--------|
846    /// | type | yes | `got character` |
847    /// | type | no | `expected integer, got character` |
848    /// | class | yes | `got list` |
849    /// | class | no | `expected a data frame, got list` |
850    /// | length | yes | `got length 2` |
851    /// | length | no | `expected length 1, got length 2` |
852    /// | NA | either | `NA is not allowed` |
853    /// | invalid value | either | the value's own text, without `invalid value: ` |
854    /// | missing field / duplicate name | either | `missing field 'x'` / `duplicate name 'x'` |
855    /// | `match_arg` | yes | `got "zzz"`, `got numeric`, `got length 2`, `NA is not allowed` |
856    /// | `match_arg` | no | `expected one of "a", "b", got "zzz"` |
857    /// | a check's refusal ([`SexpError::Condition`]) | either | its own message |
858    /// | `Either` | either | see below |
859    ///
860    /// `expected_known` says whether the text before the reason already
861    /// states what the value should be (`'x' must be a single integer`); the
862    /// reason then does not repeat it. A per-element reason inside a batched
863    /// message is worded with `expected_known = false`.
864    ///
865    /// Both branches of an `Either` failed. A type or class error, or a
866    /// `match_arg` refusal of a value that is not a string or factor, means
867    /// the value was not of that branch's kind at all; any other error means
868    /// it was, and failed later (length, NA, value), which is the more useful
869    /// reason. So: when both branches refused the kind, one reason for the
870    /// value's type (`got numeric`, or `expected integer or character, got
871    /// numeric`, `expected one of "a", "b", or numeric, got logical`); when
872    /// exactly one did, the other branch's reason; otherwise both branches'
873    /// reasons, once if they agree, else joined with `; `.
874    pub(crate) fn r_reason(&self, expected_known: bool) -> String {
875        match self {
876            SexpError::Type(e) => e.r_reason(expected_known),
877            SexpError::Class(e) => e.r_reason(expected_known),
878            SexpError::Length(e) => e.r_reason(expected_known),
879            SexpError::Na(_) => "NA is not allowed".to_string(),
880            SexpError::InvalidValue(msg) => msg.clone(),
881            SexpError::MissingField(name) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("missing field \'{0}\'", name))
    })format!("missing field '{name}'"),
882            SexpError::DuplicateName(name) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("duplicate name \'{0}\'", name))
    })format!("duplicate name '{name}'"),
883            SexpError::MatchArg(e) => e.r_reason(expected_known),
884            SexpError::Condition(e) => e.message_str().to_string(),
885            #[cfg(feature = "either")]
886            SexpError::EitherConversion {
887                left_error,
888                right_error,
889            } => {
890                let (l, r) = (left_error.as_ref(), right_error.as_ref());
891                if let Some((expected, actual)) = both_kind_mismatches(l, r) {
892                    let got = crate::typed_list::sexptype_name(actual);
893                    if expected_known {
894                        format!("got {got}")
895                    } else {
896                        format!("expected {expected}, got {got}")
897                    }
898                } else if l.kind_mismatch().is_some() {
899                    r.r_reason(expected_known)
900                } else if r.kind_mismatch().is_some() {
901                    l.r_reason(expected_known)
902                } else {
903                    let (l, r) = (l.r_reason(expected_known), r.r_reason(expected_known));
904                    if l == r { l } else { format!("{l}; {r}") }
905                }
906            }
907        }
908    }
909
910    /// The [`SexpError::Condition`] refusals whose reasons
911    /// [`r_reason`](Self::r_reason) reports, left arm first: the error itself
912    /// when it is one, and inside an `Either` the refusals of the arm (or
913    /// arms) whose reason is reported. Their classes and fields go on the
914    /// argument error.
915    pub(crate) fn reported_conditions(&self) -> Vec<&crate::condition::RError> {
916        match self {
917            SexpError::Condition(e) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [e]))vec![e],
918            #[cfg(feature = "either")]
919            SexpError::EitherConversion {
920                left_error,
921                right_error,
922            } => {
923                let (l, r) = (left_error.as_ref(), right_error.as_ref());
924                if both_kind_mismatches(l, r).is_some() {
925                    Vec::new()
926                } else if l.kind_mismatch().is_some() {
927                    r.reported_conditions()
928                } else if r.kind_mismatch().is_some() {
929                    l.reported_conditions()
930                } else {
931                    let mut both = l.reported_conditions();
932                    both.extend(r.reported_conditions());
933                    both
934                }
935            }
936            _ => Vec::new(),
937        }
938    }
939}
940
941/// The joined expectation of an `Either` whose two branches both refused the
942/// kind of value, with the value's `SEXPTYPE`; `None` if either branch got
943/// further (see [`SexpError::r_reason`]).
944#[cfg(feature = "either")]
945fn both_kind_mismatches(left: &SexpError, right: &SexpError) -> Option<(String, SEXPTYPE)> {
946    let (l, actual) = left.kind_mismatch()?;
947    let (r, _) = right.kind_mismatch()?;
948    Some((l.join(&r), actual))
949}
950
951impl std::fmt::Display for SexpError {
952    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
953        match self {
954            SexpError::Type(e) => f.write_fmt(format_args!("{0}", e))write!(f, "{}", e),
955            SexpError::Class(e) => f.write_fmt(format_args!("{0}", e))write!(f, "{}", e),
956            SexpError::Length(e) => f.write_fmt(format_args!("{0}", e))write!(f, "{}", e),
957            SexpError::Na(e) => f.write_fmt(format_args!("{0}", e))write!(f, "{}", e),
958            SexpError::InvalidValue(msg) => f.write_fmt(format_args!("invalid value: {0}", msg))write!(f, "invalid value: {}", msg),
959            SexpError::MissingField(name) => f.write_fmt(format_args!("missing field: {0}", name))write!(f, "missing field: {}", name),
960            SexpError::DuplicateName(name) => f.write_fmt(format_args!("duplicate name in list: {0:?}", name))write!(f, "duplicate name in list: {:?}", name),
961            SexpError::MatchArg(e) => f.write_fmt(format_args!("{0}", e))write!(f, "{}", e),
962            SexpError::Condition(e) => f.write_fmt(format_args!("{0}", e))write!(f, "{}", e),
963            #[cfg(feature = "either")]
964            SexpError::EitherConversion {
965                left_error,
966                right_error,
967            } => write!(
968                f,
969                "failed to convert to Either: Left failed ({}), Right failed ({})",
970                left_error, right_error
971            ),
972        }
973    }
974}
975
976impl std::error::Error for SexpError {
977    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
978        match self {
979            SexpError::Type(e) => Some(e),
980            SexpError::Class(e) => Some(e),
981            SexpError::Length(e) => Some(e),
982            SexpError::Na(e) => Some(e),
983            SexpError::InvalidValue(_) => None,
984            SexpError::MissingField(_) => None,
985            SexpError::DuplicateName(_) => None,
986            SexpError::MatchArg(e) => Some(e),
987            // `RError` does not implement `Error` (see its docs).
988            SexpError::Condition(_) => None,
989            #[cfg(feature = "either")]
990            SexpError::EitherConversion { .. } => None,
991        }
992    }
993}
994
995impl From<SexpTypeError> for SexpError {
996    fn from(e: SexpTypeError) -> Self {
997        SexpError::Type(e)
998    }
999}
1000
1001impl From<SexpClassError> for SexpError {
1002    fn from(e: SexpClassError) -> Self {
1003        SexpError::Class(e)
1004    }
1005}
1006
1007impl From<SexpLengthError> for SexpError {
1008    fn from(e: SexpLengthError) -> Self {
1009        SexpError::Length(e)
1010    }
1011}
1012
1013impl From<SexpNaError> for SexpError {
1014    fn from(e: SexpNaError) -> Self {
1015        SexpError::Na(e)
1016    }
1017}
1018
1019pub mod borrow;
1020pub use borrow::NativeBorrow;
1021
1022#[doc(hidden)]
1023pub mod prepared;
1024
1025/// TryFrom-style trait for converting SEXP to Rust types.
1026///
1027/// Inbound counterpart of [`crate::into_r::IntoR`]. Strict by construction
1028/// (returns `Result`) — for a looser, multi-source coercion path use
1029/// [`crate::coerce::Coerce`] / [`crate::coerce::TryCoerce`].
1030///
1031/// # Examples
1032///
1033/// ```no_run
1034/// use miniextendr_api::SEXP;
1035/// use miniextendr_api::from_r::TryFromSexp;
1036///
1037/// fn example(sexp: SEXP) {
1038///     let value: i32 = TryFromSexp::try_from_sexp(sexp).unwrap();
1039///     let text: String = TryFromSexp::try_from_sexp(sexp).unwrap();
1040/// }
1041/// ```
1042pub trait TryFromSexp: Sized {
1043    /// Native vector storage retained by this conversion, if any.
1044    ///
1045    /// Generated wrappers use this before conversion to reject aliased mutable
1046    /// borrows. Owned and custom object conversions default to no native borrow.
1047    /// Conversions that retain native references must describe their leaf and
1048    /// forward this metadata through their containers.
1049    const NATIVE_BORROW: Option<NativeBorrow> = None;
1050
1051    /// Whether this conversion accepts only character input: every value it
1052    /// converts, other than `NULL` (and the plain `NA` an optional string
1053    /// reads as `None`, #2305), is a character vector or a factor.
1054    ///
1055    /// `#[miniextendr]` reads it for choice parameters (`match_arg` /
1056    /// `choices`) typed `Either<T, R>`. Their R wrapper sends all character
1057    /// and factor input to the choice `T`, so an `R` with
1058    /// `CHARACTER_ONLY = true` could receive at most `NULL`, and the macro
1059    /// rejects the signature at compile time.
1060    ///
1061    /// Defaults to `false`, which is always safe: the check is skipped. Set it
1062    /// to `true` in an implementation that reads only strings or factors, and
1063    /// forward it (`<Inner as TryFromSexp>::CHARACTER_ONLY`) in one that
1064    /// delegates to another conversion. Do not set it on a type that also
1065    /// converts numbers, logicals or lists: that would reject valid
1066    /// parameters.
1067    ///
1068    /// The built-in string and factor conversions (including the types given
1069    /// [`try_from_sexp_via_str_parse!`](crate::try_from_sexp_via_str_parse),
1070    /// such as uuid, url, regex and num-bigint), `#[derive(MatchArg)]` and
1071    /// `#[derive(RFactor)]` set it. `Option<T>`, `Vec<T>`, `Box<[T]>`,
1072    /// [`Missing<T>`](crate::Missing) and `#[derive(TryFromSexp)]` newtypes
1073    /// forward it. [`AsCharacter`](crate::AsCharacter) leaves it `false`,
1074    /// since it also converts numbers.
1075    ///
1076    /// # Examples
1077    ///
1078    /// ```no_run
1079    /// use miniextendr_api::SEXP;
1080    /// use miniextendr_api::from_r::{SexpError, TryFromSexp};
1081    ///
1082    /// pub struct Username(String);
1083    ///
1084    /// impl TryFromSexp for Username {
1085    ///     type Error = SexpError;
1086    ///     const CHARACTER_ONLY: bool = <String as TryFromSexp>::CHARACTER_ONLY;
1087    ///
1088    ///     fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1089    ///         String::try_from_sexp(sexp).map(Username)
1090    ///     }
1091    /// }
1092    /// ```
1093    const CHARACTER_ONLY: bool = false;
1094
1095    /// What an argument of this type must be, in R terms, when
1096    /// `#[miniextendr]` cannot tell from the type as written: the
1097    /// `<expected>` of a failed conversion's `'<p>' must be <expected>: ...`.
1098    ///
1099    /// `#[derive(TryFromSexp)]` sets it from the newtype's inner type
1100    /// (`struct Dose(AsNumeric)` says `a single number`, as `AsNumeric`
1101    /// does) or forwards the inner type's. The generated wrapper reads it on
1102    /// the failure path of a parameter whose type the macro does not know,
1103    /// alone or as an arm of an `Either`. `None` (the default) leaves the
1104    /// expectation to the conversion error, else `invalid '<p>' argument`.
1105    #[doc(hidden)]
1106    const __MX_EXPECTATION: Option<&'static str> = None;
1107
1108    /// The error type returned when conversion fails.
1109    type Error;
1110
1111    /// Attempt to convert an R SEXP to this Rust type.
1112    ///
1113    /// In debug builds, may assert that we're on R's main thread.
1114    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error>;
1115
1116    /// Convert from SEXP without thread safety checks.
1117    ///
1118    /// # Safety
1119    ///
1120    /// Must be called from R's main thread. In debug builds, this still
1121    /// calls the checked version by default, but implementations may
1122    /// skip thread assertions for performance.
1123    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1124        // Default: just call the checked version
1125        Self::try_from_sexp(sexp)
1126    }
1127
1128    /// Convert with a scope able to retain uncached ALTREP elements.
1129    /// Custom reference converters keep their existing behavior by default.
1130    ///
1131    /// # Safety
1132    /// R's main thread. Any R-backed references in the result must be narrowed
1133    /// to the lifetime of `root`; this hook does not change `Self`'s lifetime.
1134    #[doc(hidden)]
1135    unsafe fn __mx_try_from_rooted(root: crate::Root<'_>) -> Result<Self, Self::Error> {
1136        Self::try_from_sexp(root.get())
1137    }
1138
1139    /// Run this conversion up to the point where it would build a native
1140    /// reference, for a generated wrapper whose alias check must learn which
1141    /// arm of an `Either` the conversion takes (#1504, see [`prepared`]).
1142    ///
1143    /// The default runs a conversion with no `NATIVE_BORROW` now and keeps
1144    /// its result, value or error. A borrowing conversion stays
1145    /// [`Undecided`](prepared::Prepared::Undecided): only building its
1146    /// reference could tell whether it succeeds, so the check takes all it
1147    /// may borrow and it converts after the check. The native slice and
1148    /// scalar references validate without building one, `Either` picks its
1149    /// arm, and the types that wrap one conversion (`Option<Either<..>>`,
1150    /// `Missing`, `Result<_, ()>`, `Nullable`, `#[derive(TryFromSexp)]`
1151    /// newtypes) forward it, with [`__mx_materialize`](Self::__mx_materialize).
1152    /// Runs on R's main thread inside the wrapper's unwind protection; the
1153    /// argument is rooted by the call. Not public API.
1154    #[doc(hidden)]
1155    fn __mx_prepare(sexp: SEXP) -> prepared::Prepared<Self> {
1156        if Self::NATIVE_BORROW.is_none() {
1157            prepared::Prepared::from_result(Self::try_from_sexp(sexp))
1158        } else {
1159            prepared::Prepared::Undecided(Self::NATIVE_BORROW)
1160        }
1161    }
1162
1163    /// Build the value a preparation deferred, after the alias check: follow
1164    /// `arms` through each `Either` down to the borrowing conversion. An
1165    /// override of [`__mx_prepare`](Self::__mx_prepare) that wraps another
1166    /// type's preparation must forward this to that type. The default
1167    /// converts. Not public API.
1168    #[doc(hidden)]
1169    #[inline]
1170    fn __mx_materialize(sexp: SEXP, arms: prepared::Arms) -> Result<Self, Self::Error> {
1171        let _ = arms;
1172        Self::try_from_sexp(sexp)
1173    }
1174
1175    /// Whether the converted argument holds a value `#[miniextendr(no_na)]`
1176    /// refuses after the conversion.
1177    ///
1178    /// The default is `false`, because `no_na`'s R guard (`!anyNA(x)`) already
1179    /// refuses R's `NA` before the conversion runs. The reading markers
1180    /// (`AsNumeric*`, `AsCharacter*`) override it: they read more inputs as
1181    /// missing than `anyNA()` sees (the text `"NA"`, blank strings, a factor
1182    /// `NA` level, ...). The layers a marker can sit in (`Option`, `Missing`,
1183    /// the named-list maps, `Result<T, ()>`, `Either`, `#[derive(TryFromSexp)]`
1184    /// newtypes) forward it, so a type alias or a newtype of a marker is
1185    /// checked too. The generated C wrapper calls it on the value of every
1186    /// `no_na` parameter that has the R guard.
1187    #[doc(hidden)]
1188    #[inline]
1189    fn __mx_has_na(&self) -> bool {
1190        false
1191    }
1192
1193    /// Whether `#[miniextendr(no_na)]` refuses this converted argument, read
1194    /// from `input` (the R value it converted from), when no R guard ran.
1195    ///
1196    /// An `Either` parameter gets no `!anyNA(x)` guard: one test on the whole
1197    /// argument is wrong for an arm with its own reading of `NA`, such as a
1198    /// data frame whose cells may be missing. Its C wrapper calls this instead
1199    /// of [`__mx_has_na`](Self::__mx_has_na). The default makes the guard's
1200    /// check in Rust (R's `anyNA(input)`), then asks `__mx_has_na` for what a
1201    /// marker reads as `NA` beyond it. `Either` asks the arm the value
1202    /// converted to, `Missing` asks its value, and `DataFrame` refuses
1203    /// nothing, so the NA cells of a data frame arm get through. The wrappers
1204    /// `Result<T, ()>`, `Option<DataFrame>`, `Option<Either<L, R>>` and
1205    /// `#[derive(TryFromSexp)]` newtypes ask their value too, so a
1206    /// `Result<DataFrame, ()>` or `Option<DataFrame>` arm, a newtype of a
1207    /// `DataFrame`, or the data frame arm of an `Option<Either<..>>` keeps its
1208    /// NA cells as well. Their `Err(())` / `None` comes only from `NULL`,
1209    /// which holds no `NA`, so it passes.
1210    ///
1211    /// An `Option` arm over a scalar (`Either<Option<AsNumeric>, DataFrame>`)
1212    /// keeps the default, which reads the input rather than the value: `NULL`
1213    /// holds no `NA` and passes as `None`, while an `NA` the arm reads as
1214    /// `None` (`Option<f64>`, `Option<String>`) is still refused. An override
1215    /// that answered `false` for `None` would let that `NA` through; the
1216    /// overrides above can, since their `None` is never an `NA`.
1217    #[doc(hidden)]
1218    #[inline]
1219    fn __mx_input_has_na(&self, input: SEXP) -> bool {
1220        any_na(input) || self.__mx_has_na()
1221    }
1222
1223    /// Convert, running `check`, an element type's
1224    /// [`TryFromSexpElement::check_sexp`](crate::TryFromSexpElement::check_sexp),
1225    /// on the R value that carries an element's class (#1837).
1226    ///
1227    /// The newtype containers read `Vec<T>` through `Vec<T::Inner>` and
1228    /// `Vec<Option<T>>` through `Vec<Option<T::Inner>>` with this, passing
1229    /// `T::check_sexp`, so the inner container decides where the check runs:
1230    ///
1231    /// - The default runs it once, on the whole input, then converts. An
1232    ///   atomic vector carries its class on the vector.
1233    /// - A list of R objects runs it on each element instead, where each
1234    ///   object carries its own class: `Vec<List>` on every element,
1235    ///   `Vec<Option<List>>` on every element but `NULL`.
1236    /// - The newtype containers pass it on, with their own element's check
1237    ///   after it, so a newtype of a newtype checks outer then inner, as its
1238    ///   scalar does.
1239    ///
1240    /// An override must also override
1241    /// [`__mx_try_from_sexp_unchecked_with_check`](Self::__mx_try_from_sexp_unchecked_with_check).
1242    /// Not public API.
1243    #[doc(hidden)]
1244    #[inline]
1245    fn __mx_try_from_sexp_with_check(
1246        sexp: SEXP,
1247        check: &ElementCheck<'_>,
1248    ) -> Result<Self, SexpError>
1249    where
1250        Self::Error: Into<SexpError>,
1251    {
1252        check(sexp)?;
1253        Self::try_from_sexp(sexp).map_err(Into::into)
1254    }
1255
1256    /// [`__mx_try_from_sexp_with_check`](Self::__mx_try_from_sexp_with_check)
1257    /// through [`try_from_sexp_unchecked`](Self::try_from_sexp_unchecked).
1258    /// Not public API.
1259    ///
1260    /// # Safety
1261    ///
1262    /// As [`try_from_sexp_unchecked`](Self::try_from_sexp_unchecked).
1263    #[doc(hidden)]
1264    #[inline]
1265    unsafe fn __mx_try_from_sexp_unchecked_with_check(
1266        sexp: SEXP,
1267        check: &ElementCheck<'_>,
1268    ) -> Result<Self, SexpError>
1269    where
1270        Self::Error: Into<SexpError>,
1271    {
1272        check(sexp)?;
1273        unsafe { Self::try_from_sexp_unchecked(sexp) }.map_err(Into::into)
1274    }
1275}
1276
1277/// An element type's check on an R value, as the newtype containers pass it
1278/// to [`TryFromSexp::__mx_try_from_sexp_with_check`]: `T::check_sexp`, with
1279/// the checks of any enclosing newtypes before it. Not public API.
1280#[doc(hidden)]
1281pub type ElementCheck<'a> = dyn Fn(SEXP) -> Result<(), SexpError> + 'a;
1282
1283/// The [`ElementCheck`] that accepts every value: what a container starts
1284/// from when nothing encloses it. Not public API.
1285#[doc(hidden)]
1286#[inline]
1287pub fn no_element_check(_sexp: SEXP) -> Result<(), SexpError> {
1288    Ok(())
1289}
1290
1291// region: Box<[T]> delegates to Vec<T>
1292//
1293// A boxed slice converts exactly like the owned vector — read the vector, then
1294// `into_boxed_slice()` (an O(1), allocation-free shrink). This single blanket
1295// replaces every hand-rolled / macro-generated `Box<[X]>` impl: any element
1296// type whose `Vec<X>` is convertible gets `Box<[X]>` for free, inheriting the
1297// vector impl's error type and NA semantics by construction.
1298
1299impl<T> TryFromSexp for Box<[T]>
1300where
1301    Vec<T>: TryFromSexp,
1302{
1303    const NATIVE_BORROW: Option<NativeBorrow> = <Vec<T> as TryFromSexp>::NATIVE_BORROW;
1304    const CHARACTER_ONLY: bool = <Vec<T> as TryFromSexp>::CHARACTER_ONLY;
1305
1306    type Error = <Vec<T> as TryFromSexp>::Error;
1307
1308    #[inline]
1309    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1310        <Vec<T> as TryFromSexp>::try_from_sexp(sexp).map(|v| v.into_boxed_slice())
1311    }
1312
1313    #[inline]
1314    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1315        unsafe { <Vec<T> as TryFromSexp>::try_from_sexp_unchecked(sexp) }
1316            .map(|v| v.into_boxed_slice())
1317    }
1318}
1319// endregion
1320
1321macro_rules! impl_try_from_sexp_scalar_native {
1322    ($t:ty, $sexptype:ident) => {
1323        impl TryFromSexp for $t {
1324            type Error = SexpError;
1325
1326            #[inline]
1327            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1328                let actual = sexp.type_of();
1329                if actual != SEXPTYPE::$sexptype {
1330                    return Err(SexpTypeError {
1331                        expected: SEXPTYPE::$sexptype,
1332                        actual,
1333                    }
1334                    .into());
1335                }
1336                let len = sexp.len();
1337                if len != 1 {
1338                    return Err(SexpLengthError {
1339                        expected: 1,
1340                        actual: len,
1341                    }
1342                    .into());
1343                }
1344                unsafe { sexp.as_slice::<$t>() }
1345                    .first()
1346                    .cloned()
1347                    .ok_or_else(|| {
1348                        SexpLengthError {
1349                            expected: 1,
1350                            actual: 0,
1351                        }
1352                        .into()
1353                    })
1354            }
1355
1356            #[inline]
1357            unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1358                let actual = sexp.type_of();
1359                if actual != SEXPTYPE::$sexptype {
1360                    return Err(SexpTypeError {
1361                        expected: SEXPTYPE::$sexptype,
1362                        actual,
1363                    }
1364                    .into());
1365                }
1366                let len = unsafe { sexp.len_unchecked() };
1367                if len != 1 {
1368                    return Err(SexpLengthError {
1369                        expected: 1,
1370                        actual: len,
1371                    }
1372                    .into());
1373                }
1374                unsafe { sexp.as_slice_unchecked::<$t>() }
1375                    .first()
1376                    .cloned()
1377                    .ok_or_else(|| {
1378                        SexpLengthError {
1379                            expected: 1,
1380                            actual: 0,
1381                        }
1382                        .into()
1383                    })
1384            }
1385        }
1386    };
1387}
1388
1389// i32 has a bespoke impl that checks for NA_integer_ (i32::MIN).
1390// The shared macro is NOT used for i32 — it would silently pass NA through.
1391impl TryFromSexp for i32 {
1392    type Error = SexpError;
1393
1394    #[inline]
1395    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1396        let actual = sexp.type_of();
1397        if actual != SEXPTYPE::INTSXP {
1398            return Err(SexpTypeError {
1399                expected: SEXPTYPE::INTSXP,
1400                actual,
1401            }
1402            .into());
1403        }
1404        let len = sexp.len();
1405        if len != 1 {
1406            return Err(SexpLengthError {
1407                expected: 1,
1408                actual: len,
1409            }
1410            .into());
1411        }
1412        let v = unsafe { sexp.as_slice::<i32>() }
1413            .first()
1414            .cloned()
1415            .ok_or_else(|| {
1416                SexpError::from(SexpLengthError {
1417                    expected: 1,
1418                    actual: 0,
1419                })
1420            })?;
1421        if v.is_na() {
1422            return Err(SexpNaError {
1423                sexp_type: SEXPTYPE::INTSXP,
1424            }
1425            .into());
1426        }
1427        Ok(v)
1428    }
1429
1430    #[inline]
1431    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1432        let actual = sexp.type_of();
1433        if actual != SEXPTYPE::INTSXP {
1434            return Err(SexpTypeError {
1435                expected: SEXPTYPE::INTSXP,
1436                actual,
1437            }
1438            .into());
1439        }
1440        let len = unsafe { sexp.len_unchecked() };
1441        if len != 1 {
1442            return Err(SexpLengthError {
1443                expected: 1,
1444                actual: len,
1445            }
1446            .into());
1447        }
1448        let v = unsafe { sexp.as_slice_unchecked::<i32>() }
1449            .first()
1450            .cloned()
1451            .ok_or_else(|| {
1452                SexpError::from(SexpLengthError {
1453                    expected: 1,
1454                    actual: 0,
1455                })
1456            })?;
1457        if v.is_na() {
1458            return Err(SexpNaError {
1459                sexp_type: SEXPTYPE::INTSXP,
1460            }
1461            .into());
1462        }
1463        Ok(v)
1464    }
1465}
1466
1467impl TryFromSexp for f64 {
    type Error = SexpError;
    #[inline]
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let actual = sexp.type_of();
        if actual != SEXPTYPE::REALSXP {
            return Err(SexpTypeError {
                            expected: SEXPTYPE::REALSXP,
                            actual,
                        }.into());
        }
        let len = sexp.len();
        if len != 1 {
            return Err(SexpLengthError { expected: 1, actual: len }.into());
        }
        unsafe {
                        sexp.as_slice::<f64>()
                    }.first().cloned().ok_or_else(||
                { SexpLengthError { expected: 1, actual: 0 }.into() })
    }
    #[inline]
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        let actual = sexp.type_of();
        if actual != SEXPTYPE::REALSXP {
            return Err(SexpTypeError {
                            expected: SEXPTYPE::REALSXP,
                            actual,
                        }.into());
        }
        let len = unsafe { sexp.len_unchecked() };
        if len != 1 {
            return Err(SexpLengthError { expected: 1, actual: len }.into());
        }
        unsafe {
                        sexp.as_slice_unchecked::<f64>()
                    }.first().cloned().ok_or_else(||
                { SexpLengthError { expected: 1, actual: 0 }.into() })
    }
}impl_try_from_sexp_scalar_native!(f64, REALSXP);
1468impl TryFromSexp for u8 {
    type Error = SexpError;
    #[inline]
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let actual = sexp.type_of();
        if actual != SEXPTYPE::RAWSXP {
            return Err(SexpTypeError {
                            expected: SEXPTYPE::RAWSXP,
                            actual,
                        }.into());
        }
        let len = sexp.len();
        if len != 1 {
            return Err(SexpLengthError { expected: 1, actual: len }.into());
        }
        unsafe {
                        sexp.as_slice::<u8>()
                    }.first().cloned().ok_or_else(||
                { SexpLengthError { expected: 1, actual: 0 }.into() })
    }
    #[inline]
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        let actual = sexp.type_of();
        if actual != SEXPTYPE::RAWSXP {
            return Err(SexpTypeError {
                            expected: SEXPTYPE::RAWSXP,
                            actual,
                        }.into());
        }
        let len = unsafe { sexp.len_unchecked() };
        if len != 1 {
            return Err(SexpLengthError { expected: 1, actual: len }.into());
        }
        unsafe {
                        sexp.as_slice_unchecked::<u8>()
                    }.first().cloned().ok_or_else(||
                { SexpLengthError { expected: 1, actual: 0 }.into() })
    }
}impl_try_from_sexp_scalar_native!(u8, RAWSXP);
1469impl TryFromSexp for RLogical {
    type Error = SexpError;
    #[inline]
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let actual = sexp.type_of();
        if actual != SEXPTYPE::LGLSXP {
            return Err(SexpTypeError {
                            expected: SEXPTYPE::LGLSXP,
                            actual,
                        }.into());
        }
        let len = sexp.len();
        if len != 1 {
            return Err(SexpLengthError { expected: 1, actual: len }.into());
        }
        unsafe {
                        sexp.as_slice::<RLogical>()
                    }.first().cloned().ok_or_else(||
                { SexpLengthError { expected: 1, actual: 0 }.into() })
    }
    #[inline]
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        let actual = sexp.type_of();
        if actual != SEXPTYPE::LGLSXP {
            return Err(SexpTypeError {
                            expected: SEXPTYPE::LGLSXP,
                            actual,
                        }.into());
        }
        let len = unsafe { sexp.len_unchecked() };
        if len != 1 {
            return Err(SexpLengthError { expected: 1, actual: len }.into());
        }
        unsafe {
                        sexp.as_slice_unchecked::<RLogical>()
                    }.first().cloned().ok_or_else(||
                { SexpLengthError { expected: 1, actual: 0 }.into() })
    }
}impl_try_from_sexp_scalar_native!(RLogical, LGLSXP);
1470impl TryFromSexp for crate::Rcomplex {
    type Error = SexpError;
    #[inline]
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let actual = sexp.type_of();
        if actual != SEXPTYPE::CPLXSXP {
            return Err(SexpTypeError {
                            expected: SEXPTYPE::CPLXSXP,
                            actual,
                        }.into());
        }
        let len = sexp.len();
        if len != 1 {
            return Err(SexpLengthError { expected: 1, actual: len }.into());
        }
        unsafe {
                        sexp.as_slice::<crate::Rcomplex>()
                    }.first().cloned().ok_or_else(||
                { SexpLengthError { expected: 1, actual: 0 }.into() })
    }
    #[inline]
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        let actual = sexp.type_of();
        if actual != SEXPTYPE::CPLXSXP {
            return Err(SexpTypeError {
                            expected: SEXPTYPE::CPLXSXP,
                            actual,
                        }.into());
        }
        let len = unsafe { sexp.len_unchecked() };
        if len != 1 {
            return Err(SexpLengthError { expected: 1, actual: len }.into());
        }
        unsafe {
                        sexp.as_slice_unchecked::<crate::Rcomplex>()
                    }.first().cloned().ok_or_else(||
                { SexpLengthError { expected: 1, actual: 0 }.into() })
    }
}impl_try_from_sexp_scalar_native!(crate::Rcomplex, CPLXSXP);
1471
1472/// Pass-through conversion for raw SEXP values with ALTREP auto-materialization.
1473///
1474/// This allows `SEXP` to be used directly in `#[miniextendr]` function signatures.
1475/// When R passes an ALTREP vector (e.g., `1:10`, `seq_len(N)`),
1476/// [`ensure_materialized`](crate::altrep_sexp::ensure_materialized) is called
1477/// automatically to force materialization on the R main thread. After this,
1478/// the SEXP's data pointer is stable and safe to access from any thread.
1479///
1480/// # ALTREP handling
1481///
1482/// | Input | Result |
1483/// |---|---|
1484/// | Regular SEXP | Passed through unchanged |
1485/// | ALTREP SEXP | Materialized via `ensure_materialized`, then passed through |
1486///
1487/// To receive ALTREP without materializing, use
1488/// [`AltrepSexp`](crate::altrep_sexp::AltrepSexp) as the parameter type instead.
1489/// To receive the raw SEXP without any conversion (including no materialization),
1490/// use `extern "C-unwind"`.
1491///
1492/// # Safety
1493///
1494/// SEXP handles are only valid on R's main thread, where every
1495/// `#[miniextendr]` function runs.
1496impl TryFromSexp for SEXP {
1497    type Error = SexpError;
1498
1499    /// Converts a SEXP, auto-materializing ALTREP vectors.
1500    ///
1501    /// If the input is ALTREP, [`ensure_materialized`](crate::altrep_sexp::ensure_materialized)
1502    /// is called to force materialization on the R main thread. After
1503    /// materialization the data pointer is stable and the SEXP can be safely
1504    /// sent to other threads.
1505    #[inline]
1506    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1507        Ok(unsafe { crate::altrep_sexp::ensure_materialized(sexp) })
1508    }
1509
1510    #[inline]
1511    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1512        Ok(unsafe { crate::altrep_sexp::ensure_materialized(sexp) })
1513    }
1514}
1515
1516impl TryFromSexp for Option<SEXP> {
1517    type Error = SexpError;
1518
1519    #[inline]
1520    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1521        if sexp.type_of() == SEXPTYPE::NILSXP {
1522            Ok(None)
1523        } else {
1524            Ok(Some(unsafe {
1525                crate::altrep_sexp::ensure_materialized(sexp)
1526            }))
1527        }
1528    }
1529
1530    #[inline]
1531    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1532        Self::try_from_sexp(sexp)
1533    }
1534}
1535// endregion
1536
1537mod logical;
1538
1539mod coerced_scalars;
1540pub(crate) use coerced_scalars::{coerce_real_value, coerce_value};
1541
1542mod references;
1543
1544// region: Blanket implementations for slices with arbitrary lifetimes
1545
1546/// The one check of a native slice conversion: `sexp` has `T`'s R type.
1547/// Shared with its preparation, which defers the slice (#1504).
1548#[inline]
1549fn native_slice_type<T: crate::RNativeType>(sexp: SEXP) -> Result<(), SexpTypeError> {
1550    let actual = sexp.type_of();
1551    if actual == T::SEXP_TYPE {
1552        Ok(())
1553    } else {
1554        Err(SexpTypeError {
1555            expected: T::SEXP_TYPE,
1556            actual,
1557        })
1558    }
1559}
1560
1561/// Blanket impl for `&[T]` where T: RNativeType
1562///
1563/// This replaces the macro-generated `&'static [T]` impls with a more composable
1564/// blanket impl that works for any lifetime. This enables containers like TinyVec
1565/// to use blanket impls without needing helper functions.
1566impl<T> TryFromSexp for &[T]
1567where
1568    T: crate::RNativeType + Copy,
1569{
1570    const NATIVE_BORROW: Option<NativeBorrow> = Some(NativeBorrow::slice(T::SEXP_TYPE, false));
1571
1572    type Error = SexpTypeError;
1573
1574    #[inline]
1575    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1576        native_slice_type::<T>(sexp)?;
1577        Ok(unsafe { sexp.as_slice::<T>() })
1578    }
1579
1580    #[inline]
1581    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1582        native_slice_type::<T>(sexp)?;
1583        Ok(unsafe { sexp.as_slice_unchecked::<T>() })
1584    }
1585
1586    fn __mx_prepare(sexp: SEXP) -> prepared::Prepared<Self> {
1587        prepared::native_leaf(native_slice_type::<T>(sexp))
1588    }
1589}
1590
1591/// Blanket impl for `&mut [T]` where T: RNativeType
1592///
1593/// # Safety note (aliasing)
1594///
1595/// This impl hands out a `&mut` view over R's data pointer without copying, so
1596/// binding the same R vector to two slice parameters aliases one buffer. That is
1597/// undefined behavior whenever at least one borrow is mutable — two `&mut [T]`,
1598/// or a `&mut [T]` paired with a shared `&[T]` (which borrows the same buffer).
1599/// Generated wrappers reject repeated non-empty R vector identities before
1600/// conversion in every build, including scalar/slice pairs and borrowed leaves
1601/// inside optional, nested, and boxed containers (#1104, #1252, #1502). Direct callers of this conversion must ensure the
1602/// resulting borrow does not overlap another live mutable or shared borrow.
1603impl<T> TryFromSexp for &mut [T]
1604where
1605    T: crate::RNativeType + Copy,
1606{
1607    const NATIVE_BORROW: Option<NativeBorrow> = Some(NativeBorrow::slice(T::SEXP_TYPE, true));
1608
1609    type Error = SexpTypeError;
1610
1611    #[inline]
1612    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1613        native_slice_type::<T>(sexp)?;
1614        let len = sexp.len();
1615        let ptr = unsafe { T::dataptr_mut(sexp) };
1616        Ok(unsafe { r_slice_mut(ptr, len) })
1617    }
1618
1619    #[inline]
1620    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1621        native_slice_type::<T>(sexp)?;
1622        let len = unsafe { sexp.len_unchecked() };
1623        let ptr = unsafe { T::dataptr_mut(sexp) };
1624        Ok(unsafe { r_slice_mut(ptr, len) })
1625    }
1626
1627    fn __mx_prepare(sexp: SEXP) -> prepared::Prepared<Self> {
1628        prepared::native_leaf(native_slice_type::<T>(sexp))
1629    }
1630}
1631
1632/// Blanket impl for `Option<&[T]>` where T: RNativeType
1633impl<T> TryFromSexp for Option<&[T]>
1634where
1635    T: crate::RNativeType + Copy,
1636{
1637    const NATIVE_BORROW: Option<NativeBorrow> = <&[T] as TryFromSexp>::NATIVE_BORROW;
1638
1639    type Error = SexpError;
1640
1641    #[inline]
1642    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1643        if sexp.type_of() == SEXPTYPE::NILSXP {
1644            return Ok(None);
1645        }
1646        let slice: &[T] = TryFromSexp::try_from_sexp(sexp).map_err(SexpError::from)?;
1647        Ok(Some(slice))
1648    }
1649
1650    #[inline]
1651    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1652        if sexp.type_of() == SEXPTYPE::NILSXP {
1653            return Ok(None);
1654        }
1655        let slice: &[T] =
1656            unsafe { TryFromSexp::try_from_sexp_unchecked(sexp).map_err(SexpError::from)? };
1657        Ok(Some(slice))
1658    }
1659
1660    fn __mx_prepare(sexp: SEXP) -> prepared::Prepared<Self> {
1661        if sexp.type_of() == SEXPTYPE::NILSXP {
1662            return prepared::Prepared::Ready(None);
1663        }
1664        prepared::native_leaf(native_slice_type::<T>(sexp).map_err(SexpError::from))
1665    }
1666}
1667
1668/// Blanket impl for `Option<&mut [T]>` where T: RNativeType
1669impl<T> TryFromSexp for Option<&mut [T]>
1670where
1671    T: crate::RNativeType + Copy,
1672{
1673    const NATIVE_BORROW: Option<NativeBorrow> = <&mut [T] as TryFromSexp>::NATIVE_BORROW;
1674
1675    type Error = SexpError;
1676
1677    #[inline]
1678    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1679        if sexp.type_of() == SEXPTYPE::NILSXP {
1680            return Ok(None);
1681        }
1682        let slice: &mut [T] = TryFromSexp::try_from_sexp(sexp).map_err(SexpError::from)?;
1683        Ok(Some(slice))
1684    }
1685
1686    #[inline]
1687    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1688        if sexp.type_of() == SEXPTYPE::NILSXP {
1689            return Ok(None);
1690        }
1691        let slice: &mut [T] =
1692            unsafe { TryFromSexp::try_from_sexp_unchecked(sexp).map_err(SexpError::from)? };
1693        Ok(Some(slice))
1694    }
1695
1696    fn __mx_prepare(sexp: SEXP) -> prepared::Prepared<Self> {
1697        if sexp.type_of() == SEXPTYPE::NILSXP {
1698            return prepared::Prepared::Ready(None);
1699        }
1700        prepared::native_leaf(native_slice_type::<T>(sexp).map_err(SexpError::from))
1701    }
1702}
1703// endregion
1704
1705mod strings;
1706
1707mod str_parse;
1708pub use str_parse::{ParseRStr, ParsedRStr};
1709
1710// region: Result conversions (NULL -> Err(()))
1711
1712impl<T> TryFromSexp for Result<T, ()>
1713where
1714    T: TryFromSexp,
1715    T::Error: Into<SexpError>,
1716{
1717    const NATIVE_BORROW: Option<crate::from_r::NativeBorrow> = T::NATIVE_BORROW;
1718
1719    type Error = SexpError;
1720    // `NULL` (`Err(())`) is "not given" and passes `no_na`.
1721    #[inline]
1722    fn __mx_has_na(&self) -> bool {
1723        self.as_ref().is_ok_and(T::__mx_has_na)
1724    }
1725
1726    // As an `Either` arm, a given value is read by `T` (a
1727    // `Result<DataFrame, ()>` arm keeps its `NA` cells); `NULL` holds no `NA`.
1728    #[inline]
1729    fn __mx_input_has_na(&self, input: SEXP) -> bool {
1730        match self {
1731            Ok(v) => T::__mx_input_has_na(v, input),
1732            Err(()) => false,
1733        }
1734    }
1735
1736    #[inline]
1737    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1738        if sexp.type_of() == SEXPTYPE::NILSXP {
1739            return Ok(Err(()));
1740        }
1741        let value = T::try_from_sexp(sexp).map_err(Into::into)?;
1742        Ok(Ok(value))
1743    }
1744
1745    #[inline]
1746    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1747        if sexp.type_of() == SEXPTYPE::NILSXP {
1748            return Ok(Err(()));
1749        }
1750        let value = unsafe { T::try_from_sexp_unchecked(sexp).map_err(Into::into)? };
1751        Ok(Ok(value))
1752    }
1753
1754    fn __mx_prepare(sexp: SEXP) -> prepared::Prepared<Self> {
1755        if sexp.type_of() == SEXPTYPE::NILSXP {
1756            return prepared::Prepared::Ready(Err(()));
1757        }
1758        T::__mx_prepare(sexp).map(Ok, Into::into)
1759    }
1760
1761    fn __mx_materialize(sexp: SEXP, arms: prepared::Arms) -> Result<Self, Self::Error> {
1762        T::__mx_materialize(sexp, arms).map(Ok).map_err(Into::into)
1763    }
1764}
1765// endregion
1766
1767mod na_vectors;
1768
1769mod collections;
1770
1771mod tuples;
1772
1773// region: Fixed-size array conversions
1774
1775/// Blanket impl: Convert R vector to `[T; N]` where T: RNativeType.
1776///
1777/// Returns an error if the R vector length doesn't match N.
1778/// Useful for SHA hashes ([u8; 32]), fixed-size patterns, etc.
1779impl<T, const N: usize> TryFromSexp for [T; N]
1780where
1781    T: crate::RNativeType + Copy,
1782{
1783    type Error = SexpError;
1784
1785    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1786        let slice: &[T] = TryFromSexp::try_from_sexp(sexp)?;
1787        if slice.len() != N {
1788            return Err(SexpLengthError {
1789                expected: N,
1790                actual: slice.len(),
1791            }
1792            .into());
1793        }
1794
1795        // T: Copy, length verified above. Use MaybeUninit + copy_from_slice.
1796        let mut arr = std::mem::MaybeUninit::<[T; N]>::uninit();
1797        unsafe {
1798            // SAFETY: MaybeUninit<[T; N]> and [T; N] have the same layout.
1799            // We write all N elements via copy_from_slice, so assume_init is safe.
1800            let dst: &mut [T] = std::slice::from_raw_parts_mut(arr.as_mut_ptr().cast::<T>(), N);
1801            dst.copy_from_slice(&slice[..N]);
1802            Ok(arr.assume_init())
1803        }
1804    }
1805
1806    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1807        Self::try_from_sexp(sexp)
1808    }
1809}
1810// endregion
1811
1812// region: VecDeque conversions
1813
1814use std::collections::VecDeque;
1815
1816/// Blanket impl: Convert R vector to `VecDeque<T>` where T: RNativeType.
1817impl<T> TryFromSexp for VecDeque<T>
1818where
1819    T: crate::RNativeType + Copy,
1820{
1821    type Error = SexpTypeError;
1822
1823    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1824        let slice: &[T] = TryFromSexp::try_from_sexp(sexp)?;
1825        Ok(VecDeque::from(slice.to_vec()))
1826    }
1827
1828    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1829        let slice: &[T] = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
1830        Ok(VecDeque::from(slice.to_vec()))
1831    }
1832}
1833// endregion
1834
1835// region: BinaryHeap conversions
1836
1837use std::collections::BinaryHeap;
1838
1839/// Blanket impl: Convert R vector to `BinaryHeap<T>` where T: RNativeType + Ord.
1840///
1841/// Creates a binary heap from the R vector elements.
1842impl<T> TryFromSexp for BinaryHeap<T>
1843where
1844    T: crate::RNativeType + Copy + Ord,
1845{
1846    type Error = SexpTypeError;
1847
1848    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1849        let slice: &[T] = TryFromSexp::try_from_sexp(sexp)?;
1850        Ok(BinaryHeap::from(slice.to_vec()))
1851    }
1852
1853    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1854        let slice: &[T] = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
1855        Ok(BinaryHeap::from(slice.to_vec()))
1856    }
1857}
1858// endregion
1859
1860mod cow_and_paths;
1861mod rooted;
1862pub use rooted::TryFromRoot;
1863
1864// region: Option<Collection> conversions
1865//
1866// These convert NULL → None, and non-NULL to Some(collection).
1867// This differs from Option<scalar> which converts NA → None.
1868
1869/// Convert R value to `Option<Vec<T>>`: NULL → None, otherwise Some(vec).
1870impl<T> TryFromSexp for Option<Vec<T>>
1871where
1872    Vec<T>: TryFromSexp,
1873    <Vec<T> as TryFromSexp>::Error: Into<SexpError>,
1874{
1875    const NATIVE_BORROW: Option<NativeBorrow> = <Vec<T> as TryFromSexp>::NATIVE_BORROW;
1876    const CHARACTER_ONLY: bool = <Vec<T> as TryFromSexp>::CHARACTER_ONLY;
1877
1878    type Error = SexpError;
1879
1880    #[inline]
1881    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1882        if sexp.type_of() == SEXPTYPE::NILSXP {
1883            Ok(None)
1884        } else {
1885            Vec::<T>::try_from_sexp(sexp).map(Some).map_err(Into::into)
1886        }
1887    }
1888
1889    #[inline]
1890    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1891        if sexp.type_of() == SEXPTYPE::NILSXP {
1892            Ok(None)
1893        } else {
1894            unsafe {
1895                Vec::<T>::try_from_sexp_unchecked(sexp)
1896                    .map(Some)
1897                    .map_err(Into::into)
1898            }
1899        }
1900    }
1901}
1902
1903macro_rules! impl_option_map_try_from_sexp {
1904    ($(#[$meta:meta])* $map_ty:ident) => {
1905        $(#[$meta])*
1906        impl<V: TryFromSexp> TryFromSexp for Option<$map_ty<String, V>>
1907        where
1908            V::Error: Into<SexpError>,
1909        {
1910            const NATIVE_BORROW: Option<NativeBorrow> =
1911                <$map_ty<String, V> as TryFromSexp>::NATIVE_BORROW;
1912
1913            type Error = SexpError;
1914            #[inline]
1915            fn __mx_has_na(&self) -> bool {
1916                self.as_ref()
1917                    .is_some_and(<$map_ty<String, V> as TryFromSexp>::__mx_has_na)
1918            }
1919
1920            #[inline]
1921            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1922                if sexp.type_of() == SEXPTYPE::NILSXP {
1923                    Ok(None)
1924                } else {
1925                    $map_ty::<String, V>::try_from_sexp(sexp).map(Some)
1926                }
1927            }
1928        }
1929    };
1930}
1931
1932#[doc =
r" Convert R value to `Option<HashMap<String, V>>`: NULL -> None, otherwise Some(map)."]
impl<V: TryFromSexp> TryFromSexp for Option<HashMap<String, V>> where
    V::Error: Into<SexpError> {
    const NATIVE_BORROW: Option<NativeBorrow> =
        <HashMap<String, V> as TryFromSexp>::NATIVE_BORROW;
    type Error = SexpError;
    #[inline]
    fn __mx_has_na(&self) -> bool {
        self.as_ref().is_some_and(<HashMap<String, V> as
                TryFromSexp>::__mx_has_na)
    }
    #[inline]
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        if sexp.type_of() == SEXPTYPE::NILSXP {
            Ok(None)
        } else { HashMap::<String, V>::try_from_sexp(sexp).map(Some) }
    }
}impl_option_map_try_from_sexp!(
1933    /// Convert R value to `Option<HashMap<String, V>>`: NULL -> None, otherwise Some(map).
1934    HashMap
1935);
1936#[doc =
r" Convert R value to `Option<BTreeMap<String, V>>`: NULL -> None, otherwise Some(map)."]
impl<V: TryFromSexp> TryFromSexp for Option<BTreeMap<String, V>> where
    V::Error: Into<SexpError> {
    const NATIVE_BORROW: Option<NativeBorrow> =
        <BTreeMap<String, V> as TryFromSexp>::NATIVE_BORROW;
    type Error = SexpError;
    #[inline]
    fn __mx_has_na(&self) -> bool {
        self.as_ref().is_some_and(<BTreeMap<String, V> as
                TryFromSexp>::__mx_has_na)
    }
    #[inline]
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        if sexp.type_of() == SEXPTYPE::NILSXP {
            Ok(None)
        } else { BTreeMap::<String, V>::try_from_sexp(sexp).map(Some) }
    }
}impl_option_map_try_from_sexp!(
1937    /// Convert R value to `Option<BTreeMap<String, V>>`: NULL -> None, otherwise Some(map).
1938    BTreeMap
1939);
1940
1941macro_rules! impl_option_set_try_from_sexp {
1942    ($(#[$meta:meta])* $set_ty:ident) => {
1943        $(#[$meta])*
1944        impl<T> TryFromSexp for Option<$set_ty<T>>
1945        where
1946            $set_ty<T>: TryFromSexp,
1947            <$set_ty<T> as TryFromSexp>::Error: Into<SexpError>,
1948        {
1949            const CHARACTER_ONLY: bool = <$set_ty<T> as TryFromSexp>::CHARACTER_ONLY;
1950
1951            type Error = SexpError;
1952
1953            #[inline]
1954            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1955                if sexp.type_of() == SEXPTYPE::NILSXP {
1956                    Ok(None)
1957                } else {
1958                    $set_ty::<T>::try_from_sexp(sexp)
1959                        .map(Some)
1960                        .map_err(Into::into)
1961                }
1962            }
1963        }
1964    };
1965}
1966
1967#[doc =
r" Convert R value to `Option<HashSet<T>>`: NULL -> None, otherwise Some(set)."]
impl<T> TryFromSexp for Option<HashSet<T>> where HashSet<T>: TryFromSexp,
    <HashSet<T> as TryFromSexp>::Error: Into<SexpError> {
    const CHARACTER_ONLY: bool = <HashSet<T> as TryFromSexp>::CHARACTER_ONLY;
    type Error = SexpError;
    #[inline]
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        if sexp.type_of() == SEXPTYPE::NILSXP {
            Ok(None)
        } else {
            HashSet::<T>::try_from_sexp(sexp).map(Some).map_err(Into::into)
        }
    }
}impl_option_set_try_from_sexp!(
1968    /// Convert R value to `Option<HashSet<T>>`: NULL -> None, otherwise Some(set).
1969    HashSet
1970);
1971#[doc =
r" Convert R value to `Option<BTreeSet<T>>`: NULL -> None, otherwise Some(set)."]
impl<T> TryFromSexp for Option<BTreeSet<T>> where BTreeSet<T>: TryFromSexp,
    <BTreeSet<T> as TryFromSexp>::Error: Into<SexpError> {
    const CHARACTER_ONLY: bool = <BTreeSet<T> as TryFromSexp>::CHARACTER_ONLY;
    type Error = SexpError;
    #[inline]
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        if sexp.type_of() == SEXPTYPE::NILSXP {
            Ok(None)
        } else {
            BTreeSet::<T>::try_from_sexp(sexp).map(Some).map_err(Into::into)
        }
    }
}impl_option_set_try_from_sexp!(
1972    /// Convert R value to `Option<BTreeSet<T>>`: NULL -> None, otherwise Some(set).
1973    BTreeSet
1974);
1975// endregion
1976
1977// region: Nested vector conversions (list of vectors)
1978
1979/// Convert R list (VECSXP) to `Vec<Vec<T>>`.
1980///
1981/// Each element of the R list must be convertible to `Vec<T>`.
1982impl<T> TryFromSexp for Vec<Vec<T>>
1983where
1984    Vec<T>: TryFromSexp,
1985    <Vec<T> as TryFromSexp>::Error: Into<SexpError>,
1986{
1987    const NATIVE_BORROW: Option<NativeBorrow> =
1988        NativeBorrow::in_list(<Vec<T> as TryFromSexp>::NATIVE_BORROW);
1989
1990    type Error = SexpError;
1991
1992    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1993        map_vecsxp_with(sexp, |_i, elem| {
1994            Vec::<T>::try_from_sexp(elem).map_err(Into::into)
1995        })
1996    }
1997
1998    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1999        unsafe {
2000            map_vecsxp_with_unchecked(sexp, |_i, elem| {
2001                Vec::<T>::try_from_sexp_unchecked(elem).map_err(Into::into)
2002            })
2003        }
2004    }
2005}
2006// endregion
2007
2008// region: Coerced wrapper - bridge between TryFromSexp and TryCoerce
2009
2010use crate::coerce::Coerced;
2011
2012/// Convert R value to `Coerced<T, R>` by reading `R` and coercing to `T`.
2013///
2014/// This enables reading non-native Rust types from R with coercion:
2015///
2016/// ```ignore
2017/// // Read i64 from R integer (i32)
2018/// let val: Coerced<i64, i32> = TryFromSexp::try_from_sexp(sexp)?;
2019/// let i64_val: i64 = val.into_inner();
2020///
2021/// // Works with collections too:
2022/// let vec: Vec<Coerced<i64, i32>> = ...;
2023/// let set: HashSet<Coerced<NonZeroU32, i32>> = ...;
2024/// ```
2025impl<T, R> TryFromSexp for Coerced<T, R>
2026where
2027    R: TryFromSexp,
2028    R: TryCoerce<T>,
2029    <R as TryFromSexp>::Error: Into<SexpError>,
2030    <R as TryCoerce<T>>::Error: std::fmt::Display,
2031{
2032    type Error = SexpError;
2033
2034    #[inline]
2035    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
2036        let r_val: R = R::try_from_sexp(sexp).map_err(Into::into)?;
2037        let value: T = r_val
2038            .try_coerce()
2039            .map_err(|e| SexpError::InvalidValue(::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("{0}", e)) })format!("{e}")))?;
2040        Ok(Coerced::new(value))
2041    }
2042
2043    #[inline]
2044    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
2045        let r_val: R = unsafe { R::try_from_sexp_unchecked(sexp).map_err(Into::into)? };
2046        let value: T = r_val
2047            .try_coerce()
2048            .map_err(|e| SexpError::InvalidValue(::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("{0}", e)) })format!("{e}")))?;
2049        Ok(Coerced::new(value))
2050    }
2051}
2052// endregion
2053
2054/// Convert a `coerce` boolean parameter from a logical or integer zero/one.
2055/// Numeric parameters already have multi-source `TryFromSexp` implementations;
2056/// bool needs this extension while its ordinary conversion stays logical-only.
2057#[doc(hidden)]
2058pub fn try_from_sexp_coerced_bool(sexp: SEXP) -> Result<bool, SexpError> {
2059    if sexp.type_of() == SEXPTYPE::INTSXP {
2060        Coerced::<bool, i32>::try_from_sexp(sexp).map(Coerced::into_inner)
2061    } else {
2062        bool::try_from_sexp(sexp)
2063    }
2064}
2065
2066/// Convert a `coerce` boolean vector, retaining indexed, batched diagnostics.
2067#[doc(hidden)]
2068pub fn try_from_sexp_coerced_bool_vec(sexp: SEXP) -> Result<Vec<bool>, SexpError> {
2069    if sexp.type_of() == SEXPTYPE::INTSXP {
2070        let slice: &[i32] = TryFromSexp::try_from_sexp(sexp)?;
2071        coerce_slice_to_vec(slice)
2072    } else {
2073        Vec::<bool>::try_from_sexp(sexp)
2074    }
2075}
2076
2077/// Convert a `coerce` native `i32` parameter.
2078///
2079/// `INTSXP` takes exactly the bare conversion (NA rejected, as always for a
2080/// scalar `i32`). Whole-valued doubles, logicals, and raws go through the
2081/// checked multi-source path the non-native integers use, so `3` reaches an
2082/// `i32` parameter as `3L` while `3.5`, `NA`, and out-of-range values are errors.
2083#[doc(hidden)]
2084pub fn try_from_sexp_coerced_i32(sexp: SEXP) -> Result<i32, SexpError> {
2085    if sexp.type_of() == SEXPTYPE::INTSXP {
2086        i32::try_from_sexp(sexp)
2087    } else {
2088        coerced_scalars::try_from_sexp_numeric_scalar(sexp)
2089    }
2090}
2091
2092/// Convert a `coerce` native `f64` parameter.
2093///
2094/// `REALSXP` takes exactly the bare conversion (`NA_real_` passes through).
2095/// Integers, logicals, and raws widen losslessly, and an integer or logical NA
2096/// becomes `NA_real_` as `as.numeric()` would produce it: the declared type can
2097/// carry NA, so coercion propagates it rather than inventing an error.
2098#[doc(hidden)]
2099pub fn try_from_sexp_coerced_f64(sexp: SEXP) -> Result<f64, SexpError> {
2100    match sexp.type_of() {
2101        SEXPTYPE::INTSXP => {
2102            let v: Option<i32> = TryFromSexp::try_from_sexp(sexp)?;
2103            Ok(v.map_or(NA_REAL, f64::from))
2104        }
2105        SEXPTYPE::LGLSXP => {
2106            let v: RLogical = TryFromSexp::try_from_sexp(sexp)?;
2107            Ok(if v.is_na() {
2108                NA_REAL
2109            } else {
2110                f64::from(v.to_i32())
2111            })
2112        }
2113        SEXPTYPE::RAWSXP => {
2114            let v: u8 = TryFromSexp::try_from_sexp(sexp)?;
2115            Ok(f64::from(v))
2116        }
2117        _ => f64::try_from_sexp(sexp),
2118    }
2119}
2120
2121/// Convert a `coerce` `Vec<i32>` parameter.
2122///
2123/// `INTSXP` takes the bare conversion. Whole-valued doubles, logicals, and raws
2124/// widen element-wise with indexed, batched diagnostics. `NA_real_` and a
2125/// logical NA become `NA_integer_` (the vector can carry NA, unlike the scalar);
2126/// any other NaN, fractional, or out-of-range double is an error.
2127#[doc(hidden)]
2128pub fn try_from_sexp_coerced_i32_vec(sexp: SEXP) -> Result<Vec<i32>, SexpError> {
2129    if sexp.type_of() == SEXPTYPE::INTSXP {
2130        return Vec::<i32>::try_from_sexp(sexp).map_err(SexpError::from);
2131    }
2132    from_numeric_vec_with(
2133        sexp,
2134        Ok,
2135        |v: f64| {
2136            if v.is_na() {
2137                Ok(crate::altrep_traits::NA_INTEGER)
2138            } else {
2139                coerced_scalars::coerce_value(v)
2140            }
2141        },
2142        |v: u8| Ok(i32::from(v)),
2143        // `NA_LOGICAL` and `NA_INTEGER` share the `i32::MIN` sentinel.
2144        |v: RLogical| Ok(v.to_i32()),
2145    )
2146}
2147
2148/// Convert a `coerce` `Vec<f64>` parameter.
2149///
2150/// `REALSXP` takes the bare conversion. Integers, logicals, and raws widen
2151/// element-wise; an integer or logical NA becomes `NA_real_`.
2152#[doc(hidden)]
2153pub fn try_from_sexp_coerced_f64_vec(sexp: SEXP) -> Result<Vec<f64>, SexpError> {
2154    if sexp.type_of() == SEXPTYPE::REALSXP {
2155        return Vec::<f64>::try_from_sexp(sexp).map_err(SexpError::from);
2156    }
2157    from_numeric_vec_with(
2158        sexp,
2159        |v: i32| Ok(if v.is_na() { NA_REAL } else { f64::from(v) }),
2160        Ok,
2161        |v: u8| Ok(f64::from(v)),
2162        |v: RLogical| {
2163            Ok(if v.is_na() {
2164                NA_REAL
2165            } else {
2166                f64::from(v.to_i32())
2167            })
2168        },
2169    )
2170}
2171
2172// region: Optional scalars: `NULL` or a plain `NA` (#2305)
2173
2174/// Whether `sexp` is `NULL` or a plain `NA`, R's untyped missing value: a
2175/// logical vector of length one holding `NA`. Its attributes are not looked
2176/// at, as the R-side check `is.null(x) || (is.logical(x) && length(x) == 1L
2177/// && is.na(x))` does not look at them.
2178///
2179/// An optional scalar argument reads either as "no value" (#2305), since R
2180/// users write `f(NA)` for that. The `Option<T>` conversions of the scalars
2181/// (integer, double, string, logical, complex and raw values, the
2182/// `match_arg` choice through
2183/// [`match_arg_option_from_sexp`](crate::match_arg_option_from_sexp), and
2184/// the scalar types of the optional features) start with this test, so a
2185/// `.Call()` that skips the R wrapper reads an argument as the wrapper's
2186/// own check does. An optional vector (`Option<Vec<T>>`) does not: there a
2187/// plain `NA` is a logical vector of length one, converted or refused as
2188/// such.
2189#[inline]
2190pub(crate) fn is_null_or_plain_na(sexp: SEXP) -> bool {
2191    match sexp.type_of() {
2192        SEXPTYPE::NILSXP => true,
2193        SEXPTYPE::LGLSXP => sexp.len() == 1 && RLogical::from_i32(sexp.logical_elt(0)).is_na(),
2194        _ => false,
2195    }
2196}
2197
2198/// [`is_null_or_plain_na`] through the unchecked FFI variants, for the
2199/// `try_from_sexp_unchecked` bodies.
2200///
2201/// # Safety
2202///
2203/// As for [`TryFromSexp::try_from_sexp_unchecked`]: `sexp` is a live SEXP
2204/// and the caller is on R's main thread.
2205#[inline]
2206pub(crate) unsafe fn is_null_or_plain_na_unchecked(sexp: SEXP) -> bool {
2207    match sexp.type_of() {
2208        SEXPTYPE::NILSXP => true,
2209        SEXPTYPE::LGLSXP => unsafe {
2210            sexp.len_unchecked() == 1
2211                && RLogical::from_i32(crate::sys::LOGICAL_ELT_unchecked(sexp, 0)).is_na()
2212        },
2213        _ => false,
2214    }
2215}
2216
2217// endregion
2218
2219// region: Coerced optional parameters (`Option<T>` / `Vec<Option<T>>`, #2274)
2220
2221/// The `Option` form of a `coerce` scalar: `NULL` reads `None`, any other
2222/// input goes through `read`, the type's coerced scalar helper, and an `NA`
2223/// that helper refuses reads `None`, as it does for the bare `Option<i32>`.
2224#[inline]
2225fn coerced_option<T>(
2226    sexp: SEXP,
2227    read: impl FnOnce(SEXP) -> Result<T, SexpError>,
2228) -> Result<Option<T>, SexpError> {
2229    if sexp.type_of() == SEXPTYPE::NILSXP {
2230        return Ok(None);
2231    }
2232    match read(sexp) {
2233        Ok(value) => Ok(Some(value)),
2234        Err(SexpError::Na(_)) => Ok(None),
2235        Err(e) => Err(e),
2236    }
2237}
2238
2239/// Convert a `coerce` `Option<bool>` parameter.
2240///
2241/// `NULL` and a logical or integer `NA` read `None`. Any other input converts
2242/// as [`try_from_sexp_coerced_bool`] does: a logical, or integer `0` / `1`.
2243#[doc(hidden)]
2244pub fn try_from_sexp_coerced_option_bool(sexp: SEXP) -> Result<Option<bool>, SexpError> {
2245    coerced_option(sexp, try_from_sexp_coerced_bool)
2246}
2247
2248/// Convert a `coerce` `Option<i32>` parameter.
2249///
2250/// `NULL` and an integer, double, or logical `NA` read `None`. Any other input
2251/// converts as [`try_from_sexp_coerced_i32`] does: whole-valued doubles,
2252/// logicals, and raws widen, while `NaN`, `3.5`, and out-of-range values are
2253/// errors.
2254#[doc(hidden)]
2255pub fn try_from_sexp_coerced_option_i32(sexp: SEXP) -> Result<Option<i32>, SexpError> {
2256    coerced_option(sexp, try_from_sexp_coerced_i32)
2257}
2258
2259/// Convert a `coerce` `Option<f64>` parameter.
2260///
2261/// `NULL` reads `None`. Any other input converts as
2262/// [`try_from_sexp_coerced_f64`] does, and the `NA_real_` it gives for an
2263/// integer, double, or logical `NA` reads `None`. `NaN` stays a value, as for
2264/// the bare `Option<f64>`.
2265#[doc(hidden)]
2266pub fn try_from_sexp_coerced_option_f64(sexp: SEXP) -> Result<Option<f64>, SexpError> {
2267    coerced_option(sexp, try_from_sexp_coerced_f64).map(|v| v.filter(|x| !x.is_na()))
2268}
2269
2270/// Convert a `coerce` `Vec<Option<bool>>` parameter.
2271///
2272/// A logical vector takes the bare conversion. An integer vector reads
2273/// `NA_integer_` as `None` and `0` / `1` as booleans; every other element is
2274/// an error, all of them reported in one diagnostic by reason and position.
2275#[doc(hidden)]
2276pub fn try_from_sexp_coerced_option_bool_vec(sexp: SEXP) -> Result<Vec<Option<bool>>, SexpError> {
2277    if sexp.type_of() != SEXPTYPE::INTSXP {
2278        return Vec::<Option<bool>>::try_from_sexp(sexp);
2279    }
2280    let slice: &[i32] = TryFromSexp::try_from_sexp(sexp)?;
2281    collect_coerced(
2282        slice.len(),
2283        slice.iter().map(|&v| {
2284            if v.is_na() {
2285                Ok(None)
2286            } else {
2287                coerced_scalars::coerce_value(v).map(Some)
2288            }
2289        }),
2290    )
2291}
2292
2293/// Convert a `coerce` `Vec<Option<i32>>` parameter.
2294///
2295/// An integer vector takes the bare conversion (`NA_integer_` reads `None`).
2296/// Whole-valued doubles, logicals, and raws widen element-wise; `NA_real_` and
2297/// a logical `NA` read `None`, and every `NaN`, fractional, or out-of-range
2298/// double is reported in one batched diagnostic.
2299#[doc(hidden)]
2300pub fn try_from_sexp_coerced_option_i32_vec(sexp: SEXP) -> Result<Vec<Option<i32>>, SexpError> {
2301    if sexp.type_of() == SEXPTYPE::INTSXP {
2302        return Vec::<Option<i32>>::try_from_sexp(sexp);
2303    }
2304    from_numeric_vec_with(
2305        sexp,
2306        |v: i32| Ok(if v.is_na() { None } else { Some(v) }),
2307        |v: f64| {
2308            if v.is_na() {
2309                Ok(None)
2310            } else {
2311                coerced_scalars::coerce_value(v).map(Some)
2312            }
2313        },
2314        |v: u8| Ok(Some(i32::from(v))),
2315        |v: RLogical| Ok(if v.is_na() { None } else { Some(v.to_i32()) }),
2316    )
2317}
2318
2319/// Convert a `coerce` `Vec<Option<f64>>` parameter.
2320///
2321/// A double vector takes the bare conversion (`NA_real_` reads `None`).
2322/// Integers, logicals, and raws widen element-wise; an integer or logical `NA`
2323/// reads `None`.
2324#[doc(hidden)]
2325pub fn try_from_sexp_coerced_option_f64_vec(sexp: SEXP) -> Result<Vec<Option<f64>>, SexpError> {
2326    if sexp.type_of() == SEXPTYPE::REALSXP {
2327        return Vec::<Option<f64>>::try_from_sexp(sexp);
2328    }
2329    from_numeric_vec_with(
2330        sexp,
2331        |v: i32| Ok(if v.is_na() { None } else { Some(f64::from(v)) }),
2332        |v: f64| Ok(if v.is_na() { None } else { Some(v) }),
2333        |v: u8| Ok(Some(f64::from(v))),
2334        |v: RLogical| {
2335            Ok(if v.is_na() {
2336                None
2337            } else {
2338                Some(f64::from(v.to_i32()))
2339            })
2340        },
2341    )
2342}
2343
2344// endregion
2345
2346// region: Direct Vec coercion conversions
2347//
2348// These provide direct `TryFromSexp for Vec<T>` where T is not an R native type
2349// but can be coerced from one. This mirrors the `impl_into_r_via_coerce!` pattern
2350// in into_r.rs for the reverse direction.
2351
2352/// Helper to coerce a slice element-wise into a Vec.
2353///
2354/// Walks the whole slice, accumulating every per-element coercion failure into
2355/// one batched [`SexpError::InvalidValue`] via [`BatchedErrors`]
2356/// (`value out of range (elements 2, 3)`) instead of bailing on the first
2357/// `Err`. The happy path allocates nothing for diagnostics, and a large
2358/// all-failing slice never builds more than [`BATCHED_ERROR_CAP`] messages.
2359#[inline]
2360fn coerce_slice_to_vec<R, T>(slice: &[R]) -> Result<Vec<T>, SexpError>
2361where
2362    R: Copy + TryCoerce<T>,
2363    <R as TryCoerce<T>>::Error: std::fmt::Display,
2364{
2365    let mut result = Vec::with_capacity(slice.len());
2366    let mut errors = BatchedErrors::default();
2367    for (i, v) in slice.iter().copied().enumerate() {
2368        match v.try_coerce() {
2369            Ok(x) => result.push(x),
2370            Err(e) => errors.push(i, || e.to_string()),
2371        }
2372    }
2373    if errors.is_empty() {
2374        Ok(result)
2375    } else {
2376        Err(errors.into_element_error())
2377    }
2378}
2379
2380/// Drive a per-element coercion, batching every failure into one diagnostic.
2381///
2382/// Backs [`from_numeric_vec_with`]'s four SEXP-type branches: successes go into
2383/// the output `Vec`, failures accumulate by reason and position via
2384/// [`BatchedErrors`] (`value out of range (elements 2, 3)`, the grammar of
2385/// `Vec<T>` for a string-parsed type, see [`ParsedRStr`]). Each failure's reason is
2386/// [`SexpError::r_reason`]: an `InvalidValue`'s own text, `NA is not allowed`
2387/// for an NA. The happy path allocates nothing for diagnostics, and a large
2388/// all-failing vector never builds more than [`BATCHED_ERROR_CAP`] messages.
2389#[inline]
2390fn collect_coerced<U>(
2391    len: usize,
2392    iter: impl Iterator<Item = Result<U, SexpError>>,
2393) -> Result<Vec<U>, SexpError> {
2394    let mut result = Vec::with_capacity(len);
2395    let mut errors = BatchedErrors::default();
2396    for (i, item) in iter.enumerate() {
2397        match item {
2398            Ok(v) => result.push(v),
2399            Err(e) => errors.push(i, || e.r_reason(false)),
2400        }
2401    }
2402    if errors.is_empty() {
2403        Ok(result)
2404    } else {
2405        Err(errors.into_element_error())
2406    }
2407}
2408
2409/// Shared SEXP-dispatch shell for coerced numeric/logical/raw vectors.
2410///
2411/// Reads INTSXP/REALSXP/RAWSXP/LGLSXP and applies the per-element map. The only
2412/// behavioural axis (NA policy) lives entirely in the four closures the caller
2413/// passes, so the NA-rejecting [`try_from_sexp_numeric_vec`] and the NA-aware
2414/// `try_from_sexp_numeric_option_vec` (in [`na_vectors`]) share one dispatch.
2415/// LGLSXP NA (`NA_LOGICAL`) and INTSXP NA (`i32::MIN`) round through as raw
2416/// sentinels here; any NA-to-`None` policy is the caller's closure to encode.
2417///
2418/// Per-element coercion failures are accumulated (not short-circuited) and
2419/// reported as one batched diagnostic, by reason and 1-based position (see
2420/// [`collect_coerced`]). Any other SEXPTYPE is a type error naming `numeric`,
2421/// as the `AsNumeric` markers do.
2422#[inline]
2423pub(crate) fn from_numeric_vec_with<U, FI, FD, FR, FL>(
2424    sexp: SEXP,
2425    map_i32: FI,
2426    map_f64: FD,
2427    map_u8: FR,
2428    map_lgl: FL,
2429) -> Result<Vec<U>, SexpError>
2430where
2431    FI: Fn(i32) -> Result<U, SexpError>,
2432    FD: Fn(f64) -> Result<U, SexpError>,
2433    FR: Fn(u8) -> Result<U, SexpError>,
2434    FL: Fn(RLogical) -> Result<U, SexpError>,
2435{
2436    let actual = sexp.type_of();
2437    match actual {
2438        SEXPTYPE::INTSXP => {
2439            let slice: &[i32] = unsafe { sexp.as_slice() };
2440            collect_coerced(slice.len(), slice.iter().copied().map(map_i32))
2441        }
2442        SEXPTYPE::REALSXP => {
2443            let slice: &[f64] = unsafe { sexp.as_slice() };
2444            collect_coerced(slice.len(), slice.iter().copied().map(map_f64))
2445        }
2446        SEXPTYPE::RAWSXP => {
2447            let slice: &[u8] = unsafe { sexp.as_slice() };
2448            collect_coerced(slice.len(), slice.iter().copied().map(map_u8))
2449        }
2450        SEXPTYPE::LGLSXP => {
2451            let slice: &[RLogical] = unsafe { sexp.as_slice() };
2452            collect_coerced(slice.len(), slice.iter().copied().map(map_lgl))
2453        }
2454        _ => Err(SexpTypeError {
2455            expected: SEXPTYPE::REALSXP,
2456            actual,
2457        }
2458        .into()),
2459    }
2460}
2461
2462/// Shared SEXP-dispatch shell for the STRSXP (character vector) walk.
2463///
2464/// String-side counterpart of [`from_numeric_vec_with`]: checks `STRSXP`,
2465/// walks each element via `string_elt`, and applies the per-element `map`
2466/// closure to the raw CHARSXP. NA/blank-string policy (`""` vs `None` vs
2467/// error) and the target representation (`String` vs `&str` vs `Cow`) are
2468/// entirely the caller's closure to encode — this only centralizes the type
2469/// check and the walk.
2470///
2471/// Every element is read: the failures are reported in one error
2472/// ([`ElementErrors`]), each reason followed by the positions of the elements
2473/// that failed with it, numbered as R counts them (`marked as bytes, not text
2474/// (elements 2, 4)`).
2475///
2476/// Mirrors `from_numeric_vec_with`'s choice to route both the checked and
2477/// unchecked `TryFromSexp` paths through the same (checked-FFI) walk — none
2478/// of the current STRSXP vector impls define a distinct unchecked fast path
2479/// (they fall back to `TryFromSexp`'s default `try_from_sexp_unchecked`, which
2480/// just calls the checked version), so there is no unchecked-FFI twin here.
2481#[inline]
2482pub(crate) fn map_strsxp_with<U>(
2483    sexp: SEXP,
2484    mut map: impl FnMut(SEXP /* charsxp */, usize) -> Result<U, SexpError>,
2485) -> Result<Vec<U>, SexpError> {
2486    let actual = sexp.type_of();
2487    if actual != SEXPTYPE::STRSXP {
2488        return Err(SexpTypeError {
2489            expected: SEXPTYPE::STRSXP,
2490            actual,
2491        }
2492        .into());
2493    }
2494
2495    let len = sexp.len();
2496    let mut result = Vec::with_capacity(len);
2497    let mut errors = ElementErrors::default();
2498    for i in 0..len {
2499        let charsxp = sexp.string_elt(i as crate::R_xlen_t);
2500        match map(charsxp, i) {
2501            Ok(value) => result.push(value),
2502            Err(e) => errors.push(i, e),
2503        }
2504    }
2505    errors.into_result(result)
2506}
2507
2508/// Why a value that `Rf_asInteger` / `Rf_asReal` / `Rf_asLogical` (or a raw
2509/// coercion) could not reduce to one non-`NA` scalar was refused, in R terms:
2510/// `got NULL`, `got length 0`, `got "abc"` (a string that does not parse),
2511/// `NA is not allowed`, or `got <type>` for a value of another kind.
2512///
2513/// The reason of a sidecar scalar setter's argument error
2514/// (`'value' must be a number: got "abc"`, #1594). Those setters read the
2515/// value with the `Rf_as*` coercions, which report failure as `NA` with no
2516/// error value, so the reason is worded from the rejected value itself.
2517#[doc(hidden)]
2518pub fn scalar_rejection_reason(value: SEXP) -> String {
2519    let ty = value.type_of();
2520    if ty == SEXPTYPE::NILSXP {
2521        return "got NULL".to_string();
2522    }
2523    let atomic = #[allow(non_exhaustive_omitted_patterns)] match ty {
    SEXPTYPE::LGLSXP | SEXPTYPE::INTSXP | SEXPTYPE::REALSXP |
        SEXPTYPE::CPLXSXP | SEXPTYPE::STRSXP | SEXPTYPE::RAWSXP => true,
    _ => false,
}matches!(
2524        ty,
2525        SEXPTYPE::LGLSXP
2526            | SEXPTYPE::INTSXP
2527            | SEXPTYPE::REALSXP
2528            | SEXPTYPE::CPLXSXP
2529            | SEXPTYPE::STRSXP
2530            | SEXPTYPE::RAWSXP
2531    );
2532    if !atomic {
2533        return ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("got {0}",
                crate::typed_list::sexptype_name(ty)))
    })format!("got {}", crate::typed_list::sexptype_name(ty));
2534    }
2535    if value.len() == 0 {
2536        return "got length 0".to_string();
2537    }
2538    if ty == SEXPTYPE::STRSXP {
2539        let charsxp = value.string_elt(0);
2540        if charsxp != SEXP::na_string() {
2541            // SAFETY: a non-NA CHARSXP of a live STRSXP.
2542            return ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("got {0:?}",
                unsafe { charsxp_to_cow_lossy(charsxp) }))
    })format!("got {:?}", unsafe { charsxp_to_cow_lossy(charsxp) });
2543        }
2544    }
2545    "NA is not allowed".to_string()
2546}
2547
2548/// Shared scalar-STRSXP prologue: type-check + `len == 1` + `string_elt(0)`.
2549///
2550/// Returns the raw CHARSXP; NA (`SEXP::na_string()`) and blank-string
2551/// (`SEXP::blank_string()`) policy stay the caller's decision — some sites
2552/// error on NA, some map it to `""`, some to `None`, and `String`'s blank
2553/// handling has historically differed from `&str`'s (see audit D6 finding
2554/// #3), so this helper does not paper over that divergence.
2555#[inline]
2556pub(crate) fn scalar_charsxp(sexp: SEXP) -> Result<SEXP, SexpError> {
2557    let actual = sexp.type_of();
2558    if actual != SEXPTYPE::STRSXP {
2559        return Err(SexpTypeError {
2560            expected: SEXPTYPE::STRSXP,
2561            actual,
2562        }
2563        .into());
2564    }
2565
2566    let len = sexp.len();
2567    if len != 1 {
2568        return Err(SexpLengthError {
2569            expected: 1,
2570            actual: len,
2571        }
2572        .into());
2573    }
2574
2575    Ok(sexp.string_elt(0))
2576}
2577
2578/// Unchecked-FFI variant of [`scalar_charsxp`] — uses `len_unchecked` /
2579/// `string_elt_unchecked`.
2580///
2581/// # Safety
2582///
2583/// Must be called from R's main thread (same contract as
2584/// [`TryFromSexp::try_from_sexp_unchecked`]).
2585#[inline]
2586pub(crate) unsafe fn scalar_charsxp_unchecked(sexp: SEXP) -> Result<SEXP, SexpError> {
2587    let actual = sexp.type_of();
2588    if actual != SEXPTYPE::STRSXP {
2589        return Err(SexpTypeError {
2590            expected: SEXPTYPE::STRSXP,
2591            actual,
2592        }
2593        .into());
2594    }
2595
2596    let len = unsafe { sexp.len_unchecked() };
2597    if len != 1 {
2598        return Err(SexpLengthError {
2599            expected: 1,
2600            actual: len,
2601        }
2602        .into());
2603    }
2604
2605    Ok(unsafe { sexp.string_elt_unchecked(0) })
2606}
2607
2608/// Shared SEXP-dispatch shell for the VECSXP (list) walk.
2609///
2610/// List-side counterpart of [`from_numeric_vec_with`] / [`map_strsxp_with`]:
2611/// checks `VECSXP`, walks each element via `vector_elt`, and applies the
2612/// per-element `map` closure (which receives the element's index and SEXP).
2613/// Per-element policy (recursion, `NILSXP` → `None`, duplicate-pointer
2614/// aliasing checks, …) lives entirely in the closure.
2615#[inline]
2616pub(crate) fn map_vecsxp_with<U>(
2617    sexp: SEXP,
2618    mut map: impl FnMut(usize, SEXP) -> Result<U, SexpError>,
2619) -> Result<Vec<U>, SexpError> {
2620    let actual = sexp.type_of();
2621    if actual != SEXPTYPE::VECSXP {
2622        return Err(SexpTypeError {
2623            expected: SEXPTYPE::VECSXP,
2624            actual,
2625        }
2626        .into());
2627    }
2628
2629    let len = sexp.len();
2630    let mut result = Vec::with_capacity(len);
2631    for i in 0..len {
2632        let elem = sexp.vector_elt(i as crate::R_xlen_t);
2633        result.push(map(i, elem)?);
2634    }
2635    Ok(result)
2636}
2637
2638/// Unchecked-FFI variant of [`map_vecsxp_with`] — uses `len_unchecked` /
2639/// `vector_elt_unchecked` for the type-check and walk.
2640///
2641/// # Safety
2642///
2643/// Must be called from R's main thread (same contract as
2644/// [`TryFromSexp::try_from_sexp_unchecked`]).
2645#[inline]
2646pub(crate) unsafe fn map_vecsxp_with_unchecked<U>(
2647    sexp: SEXP,
2648    mut map: impl FnMut(usize, SEXP) -> Result<U, SexpError>,
2649) -> Result<Vec<U>, SexpError> {
2650    let actual = sexp.type_of();
2651    if actual != SEXPTYPE::VECSXP {
2652        return Err(SexpTypeError {
2653            expected: SEXPTYPE::VECSXP,
2654            actual,
2655        }
2656        .into());
2657    }
2658
2659    let len = unsafe { sexp.len_unchecked() };
2660    let mut result = Vec::with_capacity(len);
2661    for i in 0..len {
2662        let elem = unsafe { sexp.vector_elt_unchecked(i as crate::R_xlen_t) };
2663        result.push(map(i, elem)?);
2664    }
2665    Ok(result)
2666}
2667
2668/// Convert numeric/logical/raw vectors to `Vec<T>` with element-wise coercion.
2669///
2670/// An R `NA` is an error at its index, whichever storage carries it: `NA_integer_`
2671/// and a logical `NA` are caught here (the `i32::MIN` sentinel would otherwise
2672/// coerce to a finite number), and `NA_real_`, which an integer target refuses
2673/// as a NaN, is reported as NA by [`coerce_real_value`]. Bind
2674/// `Vec<Option<T>>` (see [`na_vectors`]) when the caller can pass NA. Per-element
2675/// failures batch into one diagnostic, by reason and 1-based position.
2676#[inline]
2677fn try_from_sexp_numeric_vec<T>(sexp: SEXP) -> Result<Vec<T>, SexpError>
2678where
2679    i32: TryCoerce<T>,
2680    f64: TryCoerce<T>,
2681    u8: TryCoerce<T>,
2682    <i32 as TryCoerce<T>>::Error: std::fmt::Display,
2683    <f64 as TryCoerce<T>>::Error: std::fmt::Display,
2684    <u8 as TryCoerce<T>>::Error: std::fmt::Display,
2685{
2686    from_numeric_vec_with(
2687        sexp,
2688        |v: i32| {
2689            if v.is_na() {
2690                Err(SexpNaError {
2691                    sexp_type: SEXPTYPE::INTSXP,
2692                }
2693                .into())
2694            } else {
2695                coerce_value(v)
2696            }
2697        },
2698        // `NA_real_` fails an integer target's coercion as NaN; say NA, as for
2699        // the other storages. (A float target keeps it, as NaN.)
2700        coerce_real_value,
2701        coerce_value,
2702        |v: RLogical| {
2703            if v.is_na() {
2704                Err(SexpNaError {
2705                    sexp_type: SEXPTYPE::LGLSXP,
2706                }
2707                .into())
2708            } else {
2709                coerce_value(v.to_i32())
2710            }
2711        },
2712    )
2713}
2714
2715/// Implement `TryFromSexp for Vec<$target>` by coercing from integer/real/logical/raw.
2716macro_rules! impl_vec_try_from_sexp_numeric {
2717    ($target:ty) => {
2718        impl TryFromSexp for Vec<$target> {
2719            type Error = SexpError;
2720
2721            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
2722                try_from_sexp_numeric_vec(sexp)
2723            }
2724
2725            unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
2726                try_from_sexp_numeric_vec(sexp)
2727            }
2728        }
2729    };
2730}
2731
2732impl TryFromSexp for Vec<i8> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_vec(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_vec(sexp)
    }
}impl_vec_try_from_sexp_numeric!(i8);
2733impl TryFromSexp for Vec<i16> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_vec(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_vec(sexp)
    }
}impl_vec_try_from_sexp_numeric!(i16);
2734impl TryFromSexp for Vec<i64> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_vec(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_vec(sexp)
    }
}impl_vec_try_from_sexp_numeric!(i64);
2735impl TryFromSexp for Vec<isize> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_vec(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_vec(sexp)
    }
}impl_vec_try_from_sexp_numeric!(isize);
2736impl TryFromSexp for Vec<u16> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_vec(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_vec(sexp)
    }
}impl_vec_try_from_sexp_numeric!(u16);
2737impl TryFromSexp for Vec<u32> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_vec(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_vec(sexp)
    }
}impl_vec_try_from_sexp_numeric!(u32);
2738impl TryFromSexp for Vec<u64> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_vec(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_vec(sexp)
    }
}impl_vec_try_from_sexp_numeric!(u64);
2739impl TryFromSexp for Vec<usize> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_vec(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_vec(sexp)
    }
}impl_vec_try_from_sexp_numeric!(usize);
2740impl TryFromSexp for Vec<f32> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_vec(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_vec(sexp)
    }
}impl_vec_try_from_sexp_numeric!(f32);
2741
2742/// Convert R logical vector (LGLSXP) to `Vec<bool>` (errors on NA).
2743impl TryFromSexp for Vec<bool> {
2744    type Error = SexpError;
2745
2746    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
2747        let actual = sexp.type_of();
2748        if actual != SEXPTYPE::LGLSXP {
2749            return Err(SexpTypeError {
2750                expected: SEXPTYPE::LGLSXP,
2751                actual,
2752            }
2753            .into());
2754        }
2755        let slice: &[RLogical] = unsafe { sexp.as_slice() };
2756        coerce_slice_to_vec(slice)
2757    }
2758
2759    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
2760        Self::try_from_sexp(sexp)
2761    }
2762}
2763// endregion
2764
2765// region: Direct HashSet / BTreeSet coercion conversions
2766
2767/// Convert numeric/logical/raw vectors to a set type with element-wise coercion.
2768///
2769/// Inherits [`try_from_sexp_numeric_vec`]'s batching.
2770#[inline]
2771fn try_from_sexp_numeric_set<T, S>(sexp: SEXP) -> Result<S, SexpError>
2772where
2773    S: std::iter::FromIterator<T>,
2774    i32: TryCoerce<T>,
2775    f64: TryCoerce<T>,
2776    u8: TryCoerce<T>,
2777    <i32 as TryCoerce<T>>::Error: std::fmt::Display,
2778    <f64 as TryCoerce<T>>::Error: std::fmt::Display,
2779    <u8 as TryCoerce<T>>::Error: std::fmt::Display,
2780{
2781    let vec = try_from_sexp_numeric_vec(sexp)?;
2782    Ok(vec.into_iter().collect())
2783}
2784
2785macro_rules! impl_set_try_from_sexp_numeric {
2786    ($set_ty:ident, $target:ty) => {
2787        impl TryFromSexp for $set_ty<$target> {
2788            type Error = SexpError;
2789
2790            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
2791                try_from_sexp_numeric_set(sexp)
2792            }
2793
2794            unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
2795                try_from_sexp_numeric_set(sexp)
2796            }
2797        }
2798    };
2799}
2800
2801impl TryFromSexp for HashSet<i8> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
}impl_set_try_from_sexp_numeric!(HashSet, i8);
2802impl TryFromSexp for HashSet<i16> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
}impl_set_try_from_sexp_numeric!(HashSet, i16);
2803impl TryFromSexp for HashSet<i64> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
}impl_set_try_from_sexp_numeric!(HashSet, i64);
2804impl TryFromSexp for HashSet<isize> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
}impl_set_try_from_sexp_numeric!(HashSet, isize);
2805impl TryFromSexp for HashSet<u16> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
}impl_set_try_from_sexp_numeric!(HashSet, u16);
2806impl TryFromSexp for HashSet<u32> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
}impl_set_try_from_sexp_numeric!(HashSet, u32);
2807impl TryFromSexp for HashSet<u64> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
}impl_set_try_from_sexp_numeric!(HashSet, u64);
2808impl TryFromSexp for HashSet<usize> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
}impl_set_try_from_sexp_numeric!(HashSet, usize);
2809
2810impl TryFromSexp for BTreeSet<i8> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
}impl_set_try_from_sexp_numeric!(BTreeSet, i8);
2811impl TryFromSexp for BTreeSet<i16> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
}impl_set_try_from_sexp_numeric!(BTreeSet, i16);
2812impl TryFromSexp for BTreeSet<i64> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
}impl_set_try_from_sexp_numeric!(BTreeSet, i64);
2813impl TryFromSexp for BTreeSet<isize> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
}impl_set_try_from_sexp_numeric!(BTreeSet, isize);
2814impl TryFromSexp for BTreeSet<u16> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
}impl_set_try_from_sexp_numeric!(BTreeSet, u16);
2815impl TryFromSexp for BTreeSet<u32> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
}impl_set_try_from_sexp_numeric!(BTreeSet, u32);
2816impl TryFromSexp for BTreeSet<u64> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
}impl_set_try_from_sexp_numeric!(BTreeSet, u64);
2817impl TryFromSexp for BTreeSet<usize> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        try_from_sexp_numeric_set(sexp)
    }
}impl_set_try_from_sexp_numeric!(BTreeSet, usize);
2818
2819macro_rules! impl_set_try_from_sexp_bool {
2820    ($set_ty:ident) => {
2821        impl TryFromSexp for $set_ty<bool> {
2822            type Error = SexpError;
2823
2824            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
2825                let vec: Vec<bool> = TryFromSexp::try_from_sexp(sexp)?;
2826                Ok(vec.into_iter().collect())
2827            }
2828
2829            unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
2830                Self::try_from_sexp(sexp)
2831            }
2832        }
2833    };
2834}
2835
2836impl TryFromSexp for HashSet<bool> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let vec: Vec<bool> = TryFromSexp::try_from_sexp(sexp)?;
        Ok(vec.into_iter().collect())
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        Self::try_from_sexp(sexp)
    }
}impl_set_try_from_sexp_bool!(HashSet);
2837impl TryFromSexp for BTreeSet<bool> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let vec: Vec<bool> = TryFromSexp::try_from_sexp(sexp)?;
        Ok(vec.into_iter().collect())
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        Self::try_from_sexp(sexp)
    }
}impl_set_try_from_sexp_bool!(BTreeSet);
2838// endregion
2839
2840// region: ExternalPtr conversions
2841
2842use crate::externalptr::{ExternalPtr, TypeMismatchError, TypedExternal};
2843
2844/// Map a downcast [`TypeMismatchError`] to the [`SexpError`] surfaced from
2845/// `ExternalPtr<T>` argument conversion. Shared by the checked and unchecked
2846/// `TryFromSexp` paths below.
2847fn type_mismatch_to_sexp_error(e: TypeMismatchError) -> SexpError {
2848    match e {
2849        TypeMismatchError::NullPointer => {
2850            SexpError::InvalidValue("external pointer is null".to_string())
2851        }
2852        TypeMismatchError::InvalidTypeId => {
2853            SexpError::InvalidValue("external pointer has no valid type id".to_string())
2854        }
2855        TypeMismatchError::Mismatch { expected, found } => SexpError::InvalidValue(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("type mismatch: expected `{0}`, found `{1}`",
                expected, found))
    })format!(
2856            "type mismatch: expected `{}`, found `{}`",
2857            expected, found
2858        )),
2859        // A pointer restored from a saved session: the classed error, with
2860        // its message as the whole argument error.
2861        TypeMismatchError::Restored { .. } | TypeMismatchError::OtherVersion { .. } => {
2862            let message = e.to_string();
2863            let classes: Vec<String> = e
2864                .restored_classes()
2865                .map(|classes| classes.iter().map(|&class| class.to_owned()).collect())
2866                .unwrap_or_default();
2867            let mut error = crate::condition::RError::new(message.clone())
2868                .class(classes)
2869                .argument_message(message);
2870            if let TypeMismatchError::OtherVersion { saved, current, .. } = e {
2871                error = error
2872                    .data("saved_version", saved)
2873                    .data("current_version", current);
2874            }
2875            SexpError::Condition(error)
2876        }
2877    }
2878}
2879
2880/// Error for an `ExternalPtr<T>` argument that is neither a bare `EXTPTRSXP`
2881/// nor a class handle wrapping one (audit A9 — class-wrapped handles like
2882/// `Foo$new(...)` are unwrapped automatically; this fires only when *no*
2883/// `.ptr`/slot/attribute could be recovered at all).
2884fn not_a_handle_error(actual: SEXPTYPE) -> SexpError {
2885    SexpError::InvalidValue(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected an external pointer or a miniextendr class object wrapping one, got {0:?}",
                actual))
    })format!(
2886        "expected an external pointer or a miniextendr class object wrapping one, got {:?}",
2887        actual
2888    ))
2889}
2890
2891/// An `ExternalPtr<T>` from a bare `EXTPTRSXP`, or from a class handle
2892/// carrying one (R6 `private$.ptr`, S4 `ptr` slot, S7 `.ptr` attribute, a
2893/// list or environment with `.ptr`; generated Env/S3 handles are already bare
2894/// `EXTPTRSXP`s). A pointer unwrapped from a class handle is rooted for the
2895/// handle's lifetime: R code can drop the class handle's reference while Rust
2896/// holds the pointer, and the finalizer would then free the value.
2897fn external_ptr_from_sexp<T: TypedExternal>(sexp: SEXP) -> Result<ExternalPtr<T>, SexpError> {
2898    let actual = sexp.type_of();
2899    if actual != SEXPTYPE::EXTPTRSXP {
2900        return match unsafe { crate::externalptr::unwrap_class_handle(sexp) } {
2901            // SAFETY: on R's main thread, like every conversion from R.
2902            Some(inner) => unsafe { ExternalPtr::wrap_sexp_with_error(inner) }
2903                .map(|ptr| unsafe { ptr.rooted() })
2904                .map_err(type_mismatch_to_sexp_error),
2905            None => Err(not_a_handle_error(actual)),
2906        };
2907    }
2908
2909    // Use ExternalPtr's type-checked constructor
2910    unsafe { ExternalPtr::wrap_sexp_with_error(sexp) }.map_err(type_mismatch_to_sexp_error)
2911}
2912
2913/// The handle a generated wrapper borrows for a `&T` / `&mut T` /
2914/// [`ExternalPtrRef`](crate::ExternalPtrRef) /
2915/// [`ExternalPtrMut`](crate::ExternalPtrMut) argument: converted like an
2916/// `ExternalPtr<T>` argument. A free function, so the generated `::<T>` is
2917/// spanned on `T` and a `T` that isn't `TypedExternal` gets one error.
2918#[doc(hidden)]
2919#[inline]
2920pub fn __mx_external_arg<T: TypedExternal>(sexp: SEXP) -> Result<ExternalPtr<T>, SexpError> {
2921    external_ptr_from_sexp(sexp)
2922}
2923
2924/// [`__mx_external_arg`] for an `Option` argument: `NULL` is `None`.
2925#[doc(hidden)]
2926#[inline]
2927pub fn __mx_optional_external_arg<T: TypedExternal>(
2928    sexp: SEXP,
2929) -> Result<Option<ExternalPtr<T>>, SexpError> {
2930    if sexp.type_of() == SEXPTYPE::NILSXP {
2931        return Ok(None);
2932    }
2933    external_ptr_from_sexp(sexp).map(Some)
2934}
2935
2936/// Convert R EXTPTRSXP to `ExternalPtr<T>`.
2937///
2938/// This enables using `ExternalPtr<T>` as parameter types in `#[miniextendr]`
2939/// functions, for a body that keeps or consumes the handle; a body that only
2940/// reads the value takes `&T`.
2941///
2942/// # Example
2943///
2944/// ```ignore
2945/// #[derive(ExternalPtr)]
2946/// struct MyData { value: i32 }
2947///
2948/// #[miniextendr]
2949/// fn process(data: ExternalPtr<MyData>) -> i32 {
2950///     data.borrow().value
2951/// }
2952/// ```
2953impl<T: TypedExternal> TryFromSexp for ExternalPtr<T> {
2954    type Error = SexpError;
2955
2956    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
2957        external_ptr_from_sexp(sexp)
2958    }
2959
2960    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
2961        let actual = sexp.type_of();
2962        if actual != SEXPTYPE::EXTPTRSXP {
2963            return match unsafe { crate::externalptr::unwrap_class_handle(sexp) } {
2964                Some(inner) => unsafe { ExternalPtr::wrap_sexp_unchecked(inner) }
2965                    // SAFETY: on R's main thread (caller contract).
2966                    .map(|ptr| unsafe { ptr.rooted() })
2967                    .ok_or_else(|| {
2968                        SexpError::InvalidValue(
2969                            "failed to convert external pointer: type mismatch or null pointer"
2970                                .to_string(),
2971                        )
2972                    }),
2973                None => Err(not_a_handle_error(actual)),
2974            };
2975        }
2976
2977        // Use ExternalPtr's type-checked constructor (unchecked variant)
2978        unsafe { ExternalPtr::wrap_sexp_unchecked(sexp) }.ok_or_else(|| {
2979            SexpError::InvalidValue(
2980                "failed to convert external pointer: type mismatch or null pointer".to_string(),
2981            )
2982        })
2983    }
2984}
2985
2986impl<T: TypedExternal> TryFromSexp for Option<ExternalPtr<T>> {
2987    type Error = SexpError;
2988
2989    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
2990        if sexp.type_of() == SEXPTYPE::NILSXP {
2991            return Ok(None);
2992        }
2993        let ptr: ExternalPtr<T> = TryFromSexp::try_from_sexp(sexp)?;
2994        Ok(Some(ptr))
2995    }
2996
2997    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
2998        if sexp.type_of() == SEXPTYPE::NILSXP {
2999            return Ok(None);
3000        }
3001        let ptr: ExternalPtr<T> = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
3002        Ok(Some(ptr))
3003    }
3004}
3005
3006/// Convert an R list (VECSXP) of external pointers to `Vec<ExternalPtr<T>>`.
3007///
3008/// Each element must be an `EXTPTRSXP` carrying a `T`; conversion delegates to
3009/// [`ExternalPtr::<T>::try_from_sexp`] per element. This lets `#[miniextendr]`
3010/// functions accept an R `list()` of opaque handles (issue #827). A user crate
3011/// can't write this impl itself — the orphan rule rejects
3012/// `impl TryFromSexp for Vec<ExternalPtr<T>>` there because both `Vec` and
3013/// `TryFromSexp` are foreign — so it lives here, keyed on `ExternalPtr<T>` to
3014/// avoid colliding with the atomic-vector impls.
3015impl<T: TypedExternal> TryFromSexp for Vec<ExternalPtr<T>> {
3016    type Error = SexpError;
3017
3018    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
3019        map_vecsxp_with(sexp, |_i, elem| {
3020            <ExternalPtr<T> as TryFromSexp>::try_from_sexp(elem)
3021        })
3022    }
3023
3024    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
3025        unsafe {
3026            map_vecsxp_with_unchecked(sexp, |_i, elem| {
3027                <ExternalPtr<T> as TryFromSexp>::try_from_sexp_unchecked(elem)
3028            })
3029        }
3030    }
3031}
3032
3033/// Convert an R list (VECSXP) of external pointers / `NULL`s to
3034/// `Vec<Option<ExternalPtr<T>>>`. `NULL` elements map to `None`; every other
3035/// element must be an `EXTPTRSXP` carrying a `T` (issue #827).
3036impl<T: TypedExternal> TryFromSexp for Vec<Option<ExternalPtr<T>>> {
3037    type Error = SexpError;
3038
3039    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
3040        map_vecsxp_with(sexp, |_i, elem| {
3041            <Option<ExternalPtr<T>> as TryFromSexp>::try_from_sexp(elem)
3042        })
3043    }
3044
3045    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
3046        unsafe {
3047            map_vecsxp_with_unchecked(sexp, |_i, elem| {
3048                <Option<ExternalPtr<T>> as TryFromSexp>::try_from_sexp_unchecked(elem)
3049            })
3050        }
3051    }
3052}
3053// endregion
3054
3055// region: R connections — TryFromSexp impls (issue #175, #176)
3056
3057#[cfg(feature = "connections")]
3058mod connections_from_r {
3059    use crate::SEXP;
3060    use crate::connection::access::{self, ConnState};
3061    use crate::connection::{RNullConnection, RStderr, RStdin, RStdout};
3062    use crate::from_r::{SexpError, TryFromSexp};
3063
3064    // Strict validation: confirm description == expected_desc and class == "terminal".
3065    unsafe fn validate_terminal(sexp: SEXP, expected_desc: &str) -> Result<(), SexpError> {
3066        let ConnState {
3067            description: desc,
3068            class: cls,
3069            ..
3070        } = unsafe { access::state(sexp) };
3071        if desc != expected_desc {
3072            return Err(SexpError::InvalidValue(format!(
3073                "expected terminal connection with description {:?}, got {:?}",
3074                expected_desc, desc
3075            )));
3076        }
3077        if cls != "terminal" {
3078            return Err(SexpError::InvalidValue(format!(
3079                "expected class \"terminal\", got {:?}",
3080                cls
3081            )));
3082        }
3083        Ok(())
3084    }
3085
3086    impl TryFromSexp for RStdin {
3087        type Error = SexpError;
3088
3089        fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
3090            unsafe { validate_terminal(sexp, "stdin") }?;
3091            Ok(RStdin)
3092        }
3093
3094        unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
3095            Self::try_from_sexp(sexp)
3096        }
3097    }
3098
3099    impl TryFromSexp for RStdout {
3100        type Error = SexpError;
3101
3102        fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
3103            unsafe { validate_terminal(sexp, "stdout") }?;
3104            Ok(RStdout)
3105        }
3106
3107        unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
3108            Self::try_from_sexp(sexp)
3109        }
3110    }
3111
3112    impl TryFromSexp for RStderr {
3113        type Error = SexpError;
3114
3115        fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
3116            unsafe { validate_terminal(sexp, "stderr") }?;
3117            Ok(RStderr)
3118        }
3119
3120        unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
3121            Self::try_from_sexp(sexp)
3122        }
3123    }
3124
3125    /// Accepts any open, write-capable connection — not just the null device.
3126    ///
3127    /// This is intentional: validating against `description == "/dev/null"` /
3128    /// `"NUL"` is brittle across platforms, and the type is a write target, not
3129    /// a specific device. Substituting a `file()` connection for
3130    /// `RNullConnection` is supported. The handle borrows the connection: the
3131    /// R caller owns it, and dropping the handle leaves it open.
3132    impl TryFromSexp for RNullConnection {
3133        type Error = SexpError;
3134
3135        fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
3136            let state = unsafe { access::state(sexp) };
3137            if !state.is_open {
3138                return Err(SexpError::InvalidValue(
3139                    "expected an open connection".to_string(),
3140                ));
3141            }
3142            if !state.can_write {
3143                return Err(SexpError::InvalidValue(
3144                    "expected a write-capable connection".to_string(),
3145                ));
3146            }
3147            // Preserve the SEXP so it lives as long as this Rust struct.
3148            unsafe { crate::sys::R_PreserveObject(sexp) };
3149            Ok(unsafe { RNullConnection::from_preserved_sexp(sexp) })
3150        }
3151
3152        unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
3153            Self::try_from_sexp(sexp)
3154        }
3155    }
3156}
3157
3158// endregion
3159
3160// region: txtProgressBar — TryFromSexp (issue #177)
3161
3162#[cfg(feature = "connections")]
3163mod txt_progress_bar_from_r {
3164    use crate::from_r::{SexpError, TryFromSexp};
3165    use crate::sys::R_PreserveObject;
3166    use crate::txt_progress_bar::RTxtProgressBar;
3167    use crate::{SEXP, SexpExt};
3168
3169    /// The handle borrows the bar: the R caller owns it, and dropping the
3170    /// handle leaves it open.
3171    impl TryFromSexp for RTxtProgressBar {
3172        type Error = SexpError;
3173
3174        fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
3175            // Must be a list (VECSXP) with class "txtProgressBar".
3176            if !sexp.inherits_class(c"txtProgressBar") {
3177                return Err(SexpError::InvalidValue(
3178                    "expected a SEXP with class \"txtProgressBar\"".to_string(),
3179                ));
3180            }
3181            // Pin on the precious list so GC cannot collect while Rust holds it.
3182            unsafe { R_PreserveObject(sexp) };
3183            Ok(unsafe { RTxtProgressBar::from_preserved_sexp(sexp) })
3184        }
3185
3186        unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
3187            Self::try_from_sexp(sexp)
3188        }
3189    }
3190}
3191
3192// endregion
3193
3194// region: Helper macros for feature-gated modules
3195
3196/// Implement `TryFromSexp for Option<T>` where T already implements TryFromSexp.
3197///
3198/// NULL → None, otherwise delegates to T::try_from_sexp and wraps in Some.
3199///
3200/// Crate-internal: the orphan rule forbids `impl TryFromSexp for Option<T>`
3201/// outside `miniextendr-api` (#1731), so this only expands here.
3202macro_rules! impl_option_try_from_sexp {
3203    ($t:ty) => {
3204        impl $crate::from_r::TryFromSexp for Option<$t> {
3205            const NATIVE_BORROW: Option<$crate::from_r::NativeBorrow> =
3206                <$t as $crate::from_r::TryFromSexp>::NATIVE_BORROW;
3207            const CHARACTER_ONLY: bool = <$t as $crate::from_r::TryFromSexp>::CHARACTER_ONLY;
3208
3209            type Error = $crate::from_r::SexpError;
3210            // `NULL` (`None`) is "not given" and passes `no_na`.
3211            #[inline]
3212            fn __mx_has_na(&self) -> bool {
3213                self.as_ref()
3214                    .is_some_and(<$t as $crate::from_r::TryFromSexp>::__mx_has_na)
3215            }
3216
3217            fn try_from_sexp(sexp: $crate::SEXP) -> Result<Self, Self::Error> {
3218                use $crate::{SEXPTYPE, SexpExt};
3219                if sexp.type_of() == SEXPTYPE::NILSXP {
3220                    return Ok(None);
3221                }
3222                <$t as $crate::from_r::TryFromSexp>::try_from_sexp(sexp).map(Some)
3223            }
3224
3225            unsafe fn try_from_sexp_unchecked(sexp: $crate::SEXP) -> Result<Self, Self::Error> {
3226                use $crate::{SEXPTYPE, SexpExt};
3227                if sexp.type_of() == SEXPTYPE::NILSXP {
3228                    return Ok(None);
3229                }
3230                unsafe {
3231                    <$t as $crate::from_r::TryFromSexp>::try_from_sexp_unchecked(sexp).map(Some)
3232                }
3233            }
3234        }
3235    };
3236}
3237pub(crate) use impl_option_try_from_sexp;
3238
3239/// Implement `TryFromSexp for Vec<T>` from R list (VECSXP).
3240///
3241/// Each element is converted via T::try_from_sexp. Crate-internal, like
3242/// [`impl_option_try_from_sexp!`]: `Vec<T>` impls are orphans downstream.
3243#[allow(unused_macros)] // every caller is behind a feature
3244macro_rules! impl_vec_try_from_sexp_list {
3245    ($t:ty) => {
3246        impl $crate::from_r::TryFromSexp for Vec<$t> {
3247            const NATIVE_BORROW: Option<$crate::from_r::NativeBorrow> =
3248                $crate::from_r::NativeBorrow::in_list(
3249                    <$t as $crate::from_r::TryFromSexp>::NATIVE_BORROW,
3250                );
3251
3252            type Error = $crate::from_r::SexpError;
3253
3254            fn try_from_sexp(sexp: $crate::SEXP) -> Result<Self, Self::Error> {
3255                use $crate::from_r::SexpTypeError;
3256                use $crate::{SEXPTYPE, SexpExt};
3257
3258                let actual = sexp.type_of();
3259                if actual != SEXPTYPE::VECSXP {
3260                    return Err(SexpTypeError {
3261                        expected: SEXPTYPE::VECSXP,
3262                        actual,
3263                    }
3264                    .into());
3265                }
3266
3267                let len = sexp.len();
3268                let mut result = Vec::with_capacity(len);
3269                for i in 0..len {
3270                    let elem = sexp.vector_elt(i as $crate::R_xlen_t);
3271                    result.push(<$t as $crate::from_r::TryFromSexp>::try_from_sexp(elem)?);
3272                }
3273                Ok(result)
3274            }
3275
3276            unsafe fn try_from_sexp_unchecked(sexp: $crate::SEXP) -> Result<Self, Self::Error> {
3277                use $crate::from_r::SexpTypeError;
3278                use $crate::{SEXPTYPE, SexpExt};
3279
3280                let actual = sexp.type_of();
3281                if actual != SEXPTYPE::VECSXP {
3282                    return Err(SexpTypeError {
3283                        expected: SEXPTYPE::VECSXP,
3284                        actual,
3285                    }
3286                    .into());
3287                }
3288
3289                let len = unsafe { sexp.len_unchecked() };
3290                let mut result = Vec::with_capacity(len);
3291                for i in 0..len {
3292                    let elem = unsafe { sexp.vector_elt_unchecked(i as $crate::R_xlen_t) };
3293                    result.push(unsafe {
3294                        <$t as $crate::from_r::TryFromSexp>::try_from_sexp_unchecked(elem)?
3295                    });
3296                }
3297                Ok(result)
3298            }
3299        }
3300    };
3301}
3302// Every caller is a feature-gated integration (serde, aho-corasick, globset).
3303#[allow(unused_imports)]
3304pub(crate) use impl_vec_try_from_sexp_list;
3305
3306/// Implement `TryFromSexp for Vec<Option<T>>` from R list (VECSXP).
3307///
3308/// NULL elements become None, others are converted via T::try_from_sexp.
3309/// Crate-internal, like [`impl_option_try_from_sexp!`].
3310#[allow(unused_macros)] // every caller is behind a feature
3311macro_rules! impl_vec_option_try_from_sexp_list {
3312    ($t:ty) => {
3313        impl $crate::from_r::TryFromSexp for Vec<Option<$t>> {
3314            const NATIVE_BORROW: Option<$crate::from_r::NativeBorrow> =
3315                $crate::from_r::NativeBorrow::in_list(
3316                    <$t as $crate::from_r::TryFromSexp>::NATIVE_BORROW,
3317                );
3318
3319            type Error = $crate::from_r::SexpError;
3320
3321            fn try_from_sexp(sexp: $crate::SEXP) -> Result<Self, Self::Error> {
3322                use $crate::from_r::SexpTypeError;
3323                use $crate::{SEXPTYPE, SexpExt};
3324
3325                let actual = sexp.type_of();
3326                if actual != SEXPTYPE::VECSXP {
3327                    return Err(SexpTypeError {
3328                        expected: SEXPTYPE::VECSXP,
3329                        actual,
3330                    }
3331                    .into());
3332                }
3333
3334                let len = sexp.len();
3335                let mut result = Vec::with_capacity(len);
3336                for i in 0..len {
3337                    let elem = sexp.vector_elt(i as $crate::R_xlen_t);
3338                    if elem == $crate::SEXP::nil() {
3339                        result.push(None);
3340                    } else {
3341                        result.push(Some(<$t as $crate::from_r::TryFromSexp>::try_from_sexp(
3342                            elem,
3343                        )?));
3344                    }
3345                }
3346                Ok(result)
3347            }
3348
3349            unsafe fn try_from_sexp_unchecked(sexp: $crate::SEXP) -> Result<Self, Self::Error> {
3350                use $crate::from_r::SexpTypeError;
3351                use $crate::{SEXPTYPE, SexpExt};
3352
3353                let actual = sexp.type_of();
3354                if actual != SEXPTYPE::VECSXP {
3355                    return Err(SexpTypeError {
3356                        expected: SEXPTYPE::VECSXP,
3357                        actual,
3358                    }
3359                    .into());
3360                }
3361
3362                let len = unsafe { sexp.len_unchecked() };
3363                let mut result = Vec::with_capacity(len);
3364                for i in 0..len {
3365                    let elem = unsafe { sexp.vector_elt_unchecked(i as $crate::R_xlen_t) };
3366                    if elem == $crate::SEXP::nil() {
3367                        result.push(None);
3368                    } else {
3369                        result.push(Some(unsafe {
3370                            <$t as $crate::from_r::TryFromSexp>::try_from_sexp_unchecked(elem)?
3371                        }));
3372                    }
3373                }
3374                Ok(result)
3375            }
3376        }
3377    };
3378}
3379// Every caller is a feature-gated integration (serde, aho-corasick, globset).
3380#[allow(unused_imports)]
3381pub(crate) use impl_vec_option_try_from_sexp_list;
3382
3383/// Cap on the number of per-element failures listed in a batched vector
3384/// conversion error; the remainder is summarized as `"and N more"`.
3385///
3386/// `pub(crate)` (rather than file-private) so [`crate::into_r_as`]'s
3387/// `StorageCoerceError::Batched` (#1097) shares the exact same cap instead of
3388/// drifting from the inbound [`BatchedErrors`] path.
3389pub(crate) const BATCHED_ERROR_CAP: usize = 10;
3390
3391/// Bounded accumulator that folds per-element conversion failures into one
3392/// batched [`SexpError::InvalidValue`], with the elements numbered as R
3393/// counts them (1-based).
3394///
3395/// Backs every vector conversion that walks its input: `Vec<T>` /
3396/// `Vec<Option<T>>` for a string-parsed type ([`ParsedRStr`], #1143), the
3397/// numeric-coercion vector shells [`from_numeric_vec_with`] /
3398/// [`collect_coerced`] / [`coerce_slice_to_vec`] (#1192), tuples, factors,
3399/// the `As*Vec` markers and the optional integrations. Instead of bailing on
3400/// the first NA or failing element, they walk the whole vector and record
3401/// each failure here with its 0-based index; the message says where each one
3402/// is, `(element 2)`.
3403///
3404/// Only the first [`BATCHED_ERROR_CAP`] failures are retained; every later
3405/// failure is counted but its closure is never invoked. This keeps an
3406/// all-failing N-element vector from materialising N `String`s just to
3407/// discard all but 10: the memory held is bounded regardless of input size.
3408/// The remainder is summarized as `"; and N more"`.
3409///
3410/// Two foldings:
3411/// - [`into_element_error`](Self::into_element_error): each entry is the
3412///   failure's reason (`NA is not allowed`, `value out of range`); entries
3413///   with the same reason share one position list:
3414///   `NA is not allowed (elements 2, 4); value out of range (element 3)`.
3415/// - [`into_value_error`](Self::into_value_error): each entry is the
3416///   offending value, listed with the positions after them, as
3417///   [`AsNumericVec`](crate::convert::AsNumericVec) does:
3418///   `non-numeric value(s): "n/a", "<0.1" (elements 2, 5)`.
3419///
3420/// Neither names the Rust type: an argument's conversion condition carries it
3421/// as `e$rust_type` (#1591).
3422#[derive(#[automatically_derived]impl ::core::default::Default for BatchedErrors {
    #[inline]
    fn default() -> Self {
        BatchedErrors {
            listed: ::core::default::Default::default(),
            total: ::core::default::Default::default(),
        }
    }
}Default)]
3423pub(crate) struct BatchedErrors {
3424    /// `(0-based index, reason or value)` of the first [`BATCHED_ERROR_CAP`]
3425    /// failures.
3426    listed: Vec<(usize, String)>,
3427    total: usize,
3428}
3429
3430impl BatchedErrors {
3431    /// Record the failure of the element at 0-based `index`. `item` (its
3432    /// reason or value) is evaluated, with whatever it allocates, only for the
3433    /// first [`BATCHED_ERROR_CAP`] failures; later ones are counted for the
3434    /// `"and N more"` tail but never built.
3435    #[inline]
3436    pub fn push(&mut self, index: usize, item: impl FnOnce() -> String) {
3437        if self.listed.len() < BATCHED_ERROR_CAP {
3438            self.listed.push((index, item()));
3439        }
3440        self.total += 1;
3441    }
3442
3443    /// Whether any failure has been recorded.
3444    #[inline]
3445    pub fn is_empty(&self) -> bool {
3446        self.total == 0
3447    }
3448
3449    /// Append the `"; and N more"` tail when failures past the cap were counted.
3450    fn write_more_tail(&self, msg: &mut String) {
3451        if self.total > self.listed.len() {
3452            use std::fmt::Write;
3453            let _ = msg.write_fmt(format_args!("; and {0} more", self.total - self.listed.len()))write!(msg, "; and {} more", self.total - self.listed.len());
3454        }
3455    }
3456
3457    /// Fold the recorded `(index, reason)` failures into one
3458    /// [`SexpError::InvalidValue`]; see [`element_message`](Self::element_message).
3459    pub fn into_element_error(self) -> SexpError {
3460        SexpError::InvalidValue(self.element_message())
3461    }
3462
3463    /// The message behind [`into_element_error`](Self::into_element_error):
3464    /// each distinct reason once, in the order it first occurred, followed by
3465    /// the 1-based positions of the elements that failed with it:
3466    ///
3467    /// `NA is not allowed (elements 2, 4); value out of range (element 3)`
3468    pub fn element_message(&self) -> String {
3469        if true {
    if !(self.total > 0) {
        {
            ::core::panicking::panic_fmt(format_args!("batching zero conversion errors"));
        }
    };
};debug_assert!(self.total > 0, "batching zero conversion errors");
3470        let mut groups: Vec<(&str, Vec<usize>)> = Vec::new();
3471        for (index, reason) in &self.listed {
3472            match groups.iter_mut().find(|(r, _)| *r == reason.as_str()) {
3473                Some((_, indices)) => indices.push(*index),
3474                None => groups.push((reason.as_str(), ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [*index]))vec![*index])),
3475            }
3476        }
3477        let mut msg = String::new();
3478        for (k, (reason, indices)) in groups.iter().enumerate() {
3479            if k > 0 {
3480                msg.push_str("; ");
3481            }
3482            msg.push_str(reason);
3483            push_element_positions(&mut msg, indices.iter().copied());
3484        }
3485        self.write_more_tail(&mut msg);
3486        msg
3487    }
3488
3489    /// Fold recorded `(0-based index, offending value)` pairs into one
3490    /// [`SexpError::InvalidValue`] that shows the values and where they are:
3491    ///
3492    /// `<what> value(s): "n/a", "<0.1" (elements 2, 5)`
3493    ///
3494    /// Values are quoted (Rust `Debug` escaping, so invisible characters show),
3495    /// and element numbers are 1-based, as R counts them. Past the cap, the
3496    /// `"; and N more"` tail matches [`into_element_error`](Self::into_element_error).
3497    pub fn into_value_error(self, what: &str) -> SexpError {
3498        SexpError::InvalidValue(self.value_message(what))
3499    }
3500
3501    /// The message behind [`into_value_error`](Self::into_value_error).
3502    fn value_message(&self, what: &str) -> String {
3503        use std::fmt::Write;
3504        if true {
    if !(self.total > 0) {
        {
            ::core::panicking::panic_fmt(format_args!("batching zero rejected values"));
        }
    };
};debug_assert!(self.total > 0, "batching zero rejected values");
3505        let mut msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} value(s): ", what))
    })format!("{what} value(s): ");
3506        for (k, (_, value)) in self.listed.iter().enumerate() {
3507            if k > 0 {
3508                msg.push_str(", ");
3509            }
3510            let _ = msg.write_fmt(format_args!("{0:?}", value))write!(msg, "{value:?}");
3511        }
3512        push_element_positions(&mut msg, self.listed.iter().map(|(index, _)| *index));
3513        self.write_more_tail(&mut msg);
3514        msg
3515    }
3516}
3517
3518/// Append ` (element 2)` / ` (elements 2, 5)` for the given 0-based indices,
3519/// numbered as R counts them. The one spelling of an element position in a
3520/// conversion message.
3521pub(crate) fn push_element_positions(
3522    msg: &mut String,
3523    indices: impl ExactSizeIterator<Item = usize>,
3524) {
3525    use std::fmt::Write;
3526    msg.push_str(if indices.len() == 1 {
3527        " (element "
3528    } else {
3529        " (elements "
3530    });
3531    for (k, index) in indices.enumerate() {
3532        if k > 0 {
3533            msg.push_str(", ");
3534        }
3535        let _ = msg.write_fmt(format_args!("{0}", index + 1))write!(msg, "{}", index + 1);
3536    }
3537    msg.push(')');
3538}
3539
3540/// The failures of a list read element by element ([`map_vecsxp_batched`]),
3541/// folded into one error that keeps the classes and fields of the check
3542/// refusals among them.
3543///
3544/// Each failure's reason goes into a [`BatchedErrors`], so the message has the
3545/// grammar of every batched conversion: `got a data frame (element 2); expected
3546/// list, got numeric (elements 3, 5)`. A check's refusal
3547/// ([`SexpError::Condition`]) is worded by its
3548/// [`argument_message`](crate::condition::RError::argument_message) when it has
3549/// one (the type's own words for a value refused as an argument), else by its
3550/// message; any other error by [`SexpError::r_reason`].
3551///
3552/// With no refusal among the failures the error is the batch's
3553/// [`SexpError::InvalidValue`]. With one, it is a [`SexpError::Condition`]
3554/// with the batch's message, the classes of every refusal (in the order they
3555/// first occur) and their fields (the first of each name), so a handler for a
3556/// check's class catches a list of the type as it catches one value of it.
3557#[derive(#[automatically_derived]impl ::core::default::Default for ElementErrors {
    #[inline]
    fn default() -> Self {
        ElementErrors {
            batch: ::core::default::Default::default(),
            refused: ::core::default::Default::default(),
            class: ::core::default::Default::default(),
            data: ::core::default::Default::default(),
        }
    }
}Default)]
3558pub(crate) struct ElementErrors {
3559    batch: BatchedErrors,
3560    refused: bool,
3561    class: Vec<String>,
3562    data: crate::condition::ConditionData,
3563}
3564
3565impl ElementErrors {
3566    /// Record the failure of the element at 0-based `index`.
3567    pub(crate) fn push(&mut self, index: usize, error: SexpError) {
3568        for refusal in error.reported_conditions() {
3569            self.refused = true;
3570            for class in refusal.classes() {
3571                if !self.class.contains(class) {
3572                    self.class.push(class.clone());
3573                }
3574            }
3575            for (name, value) in refusal.fields() {
3576                if !self.data.iter().any(|(seen, _)| seen == name) {
3577                    self.data.push((name.clone(), value.clone()));
3578                }
3579            }
3580        }
3581        self.batch.push(index, || match &error {
3582            SexpError::Condition(refusal) => refusal
3583                .argument_message_str()
3584                .unwrap_or(refusal.message_str())
3585                .to_string(),
3586            other => other.r_reason(false),
3587        });
3588    }
3589
3590    /// The values read, or the one error for every failure recorded.
3591    pub(crate) fn into_result<T>(self, values: T) -> Result<T, SexpError> {
3592        if self.batch.is_empty() {
3593            return Ok(values);
3594        }
3595        if !self.refused {
3596            return Err(self.batch.into_element_error());
3597        }
3598        let mut error =
3599            crate::condition::RError::new(self.batch.element_message()).class(self.class);
3600        for (name, value) in self.data {
3601            error = error.data(name, value);
3602        }
3603        Err(SexpError::Condition(error))
3604    }
3605}
3606
3607/// Read a list (`VECSXP`) element by element with `read`, which gets each
3608/// element's `SEXP`, and report every element that fails in one error
3609/// ([`ElementErrors`]), its position numbered as R counts it. Anything but a
3610/// `VECSXP` is a type error, and no element is read.
3611pub(crate) fn map_vecsxp_batched<U>(
3612    sexp: SEXP,
3613    mut read: impl FnMut(SEXP) -> Result<U, SexpError>,
3614) -> Result<Vec<U>, SexpError> {
3615    let actual = sexp.type_of();
3616    if actual != SEXPTYPE::VECSXP {
3617        return Err(SexpTypeError {
3618            expected: SEXPTYPE::VECSXP,
3619            actual,
3620        }
3621        .into());
3622    }
3623    let len = sexp.len();
3624    let mut values = Vec::with_capacity(len);
3625    let mut errors = ElementErrors::default();
3626    for i in 0..len {
3627        let index = crate::R_xlen_t::try_from(i).expect("a list index fits R_xlen_t");
3628        match read(sexp.vector_elt(index)) {
3629            Ok(value) => values.push(value),
3630            Err(e) => errors.push(i, e),
3631        }
3632    }
3633    errors.into_result(values)
3634}
3635
3636/// ` (element <k>)` for one 0-based `index`: the position suffix of a single
3637/// per-element failure, as [`BatchedErrors`] writes it.
3638pub(crate) fn element_position(index: usize) -> String {
3639    let mut s = String::new();
3640    push_element_positions(&mut s, std::iter::once(index));
3641    s
3642}
3643
3644// endregion
3645
3646#[cfg(test)]
3647mod tests;