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
5152use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
5354use crate::altrep_traits::NA_REAL;
55use crate::coerce::TryCoerce;
56use crate::{IsNA, RLogical, SEXP, SEXPTYPE, SexpExt};
5758/// [`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 {
64any_na(sexp)
65}
6667/// 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 {
84if !sexp.is_vector() {
85return false;
86 }
87let n = sexp.xlength();
88if sexp.is_data_frame() {
89return (0..n).any(|i| any_na(sexp.vector_elt(i)));
90 }
91let 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.
94match sexp.type_of() {
95 SEXPTYPE::LGLSXPif altrep => {
96 (0..n).any(|i| RLogical::from_i32(sexp.logical_elt(i)).is_na())
97 }
98 SEXPTYPE::INTSXPif altrep => (0..n).any(|i| sexp.integer_elt(i).is_na()),
99 SEXPTYPE::REALSXPif altrep => (0..n).any(|i| sexp.real_elt(i).is_nan()),
100 SEXPTYPE::CPLXSXPif altrep => (0..n).any(|i| {
101let v = sexp.complex_elt(i);
102v.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| {
114let elt = sexp.vector_elt(i);
115elt.is_vector_atomic() && elt.len() == 1 && any_na(elt)
116 }),
117_ => false,
118 }
119}
120121// region: CHARSXP to string conversion
122123/// 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";
129130/// 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";
134135/// 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> {
159unsafe {
160let encoding = crate::sys::Rf_getCharCE(charsxp);
161let text = utf8_text(encoding, charsxp.r_char(), charsxp.len(), || {
162crate::sys::Rf_translateCharUTF8(charsxp)
163 })?;
164text.warn_if_native();
165Ok(text.as_str())
166 }
167}
168169/// 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> {
175unsafe {
176let encoding = crate::sys::Rf_getCharCE_unchecked(charsxp);
177let text = utf8_text(
178 encoding,
179 charsxp.r_char_unchecked(),
180 charsxp.len_unchecked(),
181 || crate::sys::Rf_translateCharUTF8_unchecked(charsxp),
182 )?;
183text.warn_if_native();
184Ok(text.as_str())
185 }
186}
187188/// 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.
192Own(&'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.
196Translated { text: &'static str, native: bool },
197}
198199impl Utf8Text {
200#[inline]
201fn as_str(&self) -> &'static str {
202match *self {
203 Utf8Text::Own(text) | Utf8Text::Translated { text, .. } => text,
204 }
205 }
206207#[inline]
208fn warn_if_native(&self) {
209if let Utf8Text::Translated { native: true, .. } = self {
210crate::encoding::warn_native_translation();
211 }
212 }
213}
214215/// 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> {
236unsafe {
237match encoding {
238crate::cetype_t::CE_UTF8 => return charsxp_utf8_bytes(own, len).map(Utf8Text::Own),
239crate::cetype_t::CE_BYTES => return Err(bytes_refusal()),
240_ => {}
241 }
242let utf8 = translate();
243if std::ptr::eq(utf8, own) {
244return charsxp_utf8_bytes(own, len).map(Utf8Text::Own);
245 }
246Ok(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}
252253/// [`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> {
263unsafe {
264let encoding = crate::sys::Rf_getCharCE(charsxp);
265let text = utf8_text(encoding, charsxp.r_char(), charsxp.len(), || {
266crate::sys::Rf_translateCharUTF8(charsxp)
267 })?;
268text.warn_if_native();
269Ok(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}
275276/// [`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 {
286unsafe { try_charsxp_to_str(charsxp) }.unwrap_or_else(|e| refuse_text(&e))
287}
288289/// [`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> {
297unsafe { try_charsxp_to_cow(charsxp) }.unwrap_or_else(|e| refuse_text(&e))
298}
299300/// 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 {
310unsafe {
311let encoding = crate::sys::Rf_getCharCE(charsxp);
312match utf8_text(encoding, charsxp.r_char(), charsxp.len(), || {
313crate::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}
325326/// 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> {
336unsafe {
337match try_charsxp_to_str(charsxp) {
338Ok(text) => std::borrow::Cow::Borrowed(text),
339Err(_) => {
340String::from_utf8_lossy(r_slice(charsxp.r_char().cast::<u8>(), charsxp.len()))
341 }
342 }
343 }
344}
345346/// The error for a string marked as bytes ([`BYTES_REASON`]).
347fn bytes_refusal() -> SexpError {
348 SexpError::InvalidValue(BYTES_REASON.to_string())
349}
350351/// 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}
360361/// 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}
369370#[inline]
371unsafe fn charsxp_utf8_bytes(
372 ptr: *const std::os::raw::c_char,
373 len: usize,
374) -> Result<&'static str, SexpError> {
375let bytes = unsafe { r_slice(ptr.cast::<u8>(), len) };
376 std::str::from_utf8(bytes).map_err(|_| SexpError::InvalidValue(INVALID_UTF8_REASON.to_string()))
377}
378379#[inline]
380unsafe fn translated_charsxp_to_str(ptr: *const std::os::raw::c_char) -> &'static str {
381if !!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");
382unsafe { std::ffi::CStr::from_ptr(ptr) }
383 .to_str()
384 .expect("R string translation produced invalid UTF-8")
385}
386387/// 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> {
405if charsxp.is_null_or_nil() || charsxp.is_na_string() {
406return None;
407 }
408Some(unsafe { charsxp_to_cow_lossy(charsxp) }.into_owned())
409}
410411/// 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] {
425if len == 0 {
426&[]
427 } else {
428unsafe { std::slice::from_raw_parts(ptr, len) }
429 }
430}
431432/// 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] {
439if len == 0 {
440&mut []
441 } else {
442unsafe { std::slice::from_raw_parts_mut(ptr, len) }
443 }
444}
445446#[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.
450pub expected: SEXPTYPE,
451/// Actual R type encountered.
452pub actual: SEXPTYPE,
453}
454455impl std::fmt::Displayfor SexpTypeError {
456fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
457f.write_fmt(format_args!("type mismatch: expected {0:?}, got {1:?}",
self.expected, self.actual))write!(
458f,
459"type mismatch: expected {:?}, got {:?}",
460self.expected, self.actual
461 )462 }
463}
464465impl std::error::Errorfor SexpTypeError {}
466467#[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"`.
474pub expected: &'static str,
475/// Actual R type encountered.
476pub actual: SEXPTYPE,
477}
478479impl std::fmt::Displayfor SexpClassError {
480fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
481f.write_fmt(format_args!("class mismatch: expected {0}, got {1:?}",
self.expected, self.actual))write!(
482f,
483"class mismatch: expected {}, got {:?}",
484self.expected, self.actual
485 )486 }
487}
488489impl std::error::Errorfor SexpClassError {}
490491#[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.
495pub expected: usize,
496/// Actual length encountered.
497pub actual: usize,
498}
499500impl std::fmt::Displayfor SexpLengthError {
501fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
502f.write_fmt(format_args!("length mismatch: expected {0}, got {1}",
self.expected, self.actual))write!(
503f,
504"length mismatch: expected {}, got {}",
505self.expected, self.actual
506 )507 }
508}
509510impl std::error::Errorfor SexpLengthError {}
511512#[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.
516pub sexp_type: SEXPTYPE,
517}
518519impl std::fmt::Displayfor SexpNaError {
520fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
521f.write_fmt(format_args!("unexpected NA value in {0:?}", self.sexp_type))write!(f, "unexpected NA value in {:?}", self.sexp_type)522 }
523}
524525impl std::error::Errorfor SexpNaError {}
526527#[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.
531Type(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`.
535Class(SexpClassError),
536/// Length did not match the expected one.
537Length(SexpLengthError),
538/// Missing value encountered where disallowed.
539Na(SexpNaError),
540/// Value is syntactically valid but semantically invalid (e.g. parse error).
541InvalidValue(String),
542/// A required field was missing from a named list.
543MissingField(String),
544/// A named list has duplicate non-empty names.
545DuplicateName(String),
546/// A `match_arg` choice did not match (from `#[derive(MatchArg)]`'s
547 /// `TryFromSexp`), kept whole so the argument error names the choices.
548MatchArg(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.
564Condition(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")]
570EitherConversion {
571/// Error from attempting to convert to the Left type
572left_error: Box<SexpError>,
573/// Error from attempting to convert to the Right type
574right_error: Box<SexpError>,
575 },
576}
577578impl 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).
588pub(crate) fn r_reason(&self, expected_known: bool) -> String {
589let got = crate::typed_list::sexptype_name(self.actual);
590let hint = if self.expected == SEXPTYPE::VECSXP && self.actual == SEXPTYPE::LISTSXP {
591", convert it with as.list()"
592} else {
593""
594};
595if 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}",
600crate::typed_list::sexptype_name(self.expected)
601 )602 }
603 }
604}
605606impl 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`.
609pub(crate) fn r_reason(&self, expected_known: bool) -> String {
610let got = crate::typed_list::sexptype_name(self.actual);
611if 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}
618619impl 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`.
622pub(crate) fn r_reason(&self, expected_known: bool) -> String {
623if 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 {}",
628self.expected, self.actual
629 )630 }
631 }
632}
633634/// 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`.
640Noun(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.
644Choices(
645&'static [&'static str],
646&'static [crate::match_arg::MatchArgAlias],
647 ),
648}
649650#[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).
656fn join(&self, right: &KindExpected) -> String {
657use crate::match_arg::choice_expectation;
658match (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)) => {
664format!("{l} or {}", choice_expectation(r, aliases, false, ""))
665 }
666 (KindExpected::Choices(l, l_aliases), KindExpected::Choices(r, r_aliases)) => {
667let mut both: Vec<&str> = l.to_vec();
668 both.extend(r.iter().filter(|c| !l.contains(c)));
669let 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 }
679680/// This expectation on its own: the noun, or `one of "a", "b"`.
681fn text(&self) -> String {
682match self {
683 KindExpected::Noun(noun) => noun.clone(),
684 KindExpected::Choices(choices, aliases) => {
685crate::match_arg::choice_expectation(choices, aliases, false, "")
686 }
687 }
688 }
689}
690691/// 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`).
697Known(&'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).
702Opaque {
703/// `<T as TryFromSexp>::__MX_EXPECTATION`.
704declared: Option<&'a str>,
705/// The fallback name of the arm.
706noun: &'a str,
707 },
708/// An `Option<T>` or `Result<T, ()>` arm: `NULL or <T>`.
709Nullable(&'a ExpectedArm<'a>),
710/// A nested `Either`, matched with the two sides of its error.
711Either(&'a ExpectedArm<'a>, &'a ExpectedArm<'a>),
712}
713714#[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.
718fn resolve(&self, error: &SexpError) -> Option<(KindExpected, bool)> {
719match 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() {
729Some(expected) => (expected, true),
730None => (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) => {
739let SexpError::EitherConversion {
740 left_error,
741 right_error,
742 } = error
743else {
744return None;
745 };
746let (l, l_known) = left.resolve(left_error)?;
747let (r, r_known) = right.resolve(right_error)?;
748Some((KindExpected::Noun(l.join(&r)), l_known || r_known))
749 }
750 }
751 }
752}
753754/// 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> {
769match arms.resolve(error)? {
770 (expected, true) => Some(expected.text()),
771 (_, false) => None,
772 }
773}
774775impl 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.
785pub(crate) fn r_expectation(&self) -> Option<String> {
786match self {
787 SexpError::MatchArg(e) => Some(e.expectation()),
788 SexpError::Class(e) => Some(e.expected.to_string()),
789#[cfg(feature = "either")]
790SexpError::EitherConversion {
791 left_error,
792 right_error,
793 } => both_kind_mismatches(left_error, right_error).map(|(expected, _)| expected),
794_ => None,
795 }
796 }
797798/// 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")]
805fn kind_mismatch(&self) -> Option<(KindExpected, SEXPTYPE)> {
806match 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 }
825826/// 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")]
832fn arm_expectation(&self) -> Option<KindExpected> {
833match self {
834 SexpError::MatchArg(e) => Some(KindExpected::Choices(e.choices(), e.aliases())),
835_ => self.kind_mismatch().map(|(expected, _)| expected),
836 }
837 }
838839/// 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 `; `.
874pub(crate) fn r_reason(&self, expected_known: bool) -> String {
875match 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")]
886SexpError::EitherConversion {
887 left_error,
888 right_error,
889 } => {
890let (l, r) = (left_error.as_ref(), right_error.as_ref());
891if let Some((expected, actual)) = both_kind_mismatches(l, r) {
892let got = crate::typed_list::sexptype_name(actual);
893if expected_known {
894format!("got {got}")
895 } else {
896format!("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 {
903let (l, r) = (l.r_reason(expected_known), r.r_reason(expected_known));
904if l == r { l } else { format!("{l}; {r}") }
905 }
906 }
907 }
908 }
909910/// 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.
915pub(crate) fn reported_conditions(&self) -> Vec<&crate::condition::RError> {
916match 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")]
919SexpError::EitherConversion {
920 left_error,
921 right_error,
922 } => {
923let (l, r) = (left_error.as_ref(), right_error.as_ref());
924if 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 {
931let mut both = l.reported_conditions();
932 both.extend(r.reported_conditions());
933 both
934 }
935 }
936_ => Vec::new(),
937 }
938 }
939}
940941/// 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)> {
946let (l, actual) = left.kind_mismatch()?;
947let (r, _) = right.kind_mismatch()?;
948Some((l.join(&r), actual))
949}
950951impl std::fmt::Displayfor SexpError {
952fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
953match 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")]
964SexpError::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}
975976impl std::error::Errorfor SexpError {
977fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
978match 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).
988SexpError::Condition(_) => None,
989#[cfg(feature = "either")]
990SexpError::EitherConversion { .. } => None,
991 }
992 }
993}
994995impl From<SexpTypeError> for SexpError {
996fn from(e: SexpTypeError) -> Self {
997 SexpError::Type(e)
998 }
999}
10001001impl From<SexpClassError> for SexpError {
1002fn from(e: SexpClassError) -> Self {
1003 SexpError::Class(e)
1004 }
1005}
10061007impl From<SexpLengthError> for SexpError {
1008fn from(e: SexpLengthError) -> Self {
1009 SexpError::Length(e)
1010 }
1011}
10121013impl From<SexpNaError> for SexpError {
1014fn from(e: SexpNaError) -> Self {
1015 SexpError::Na(e)
1016 }
1017}
10181019pub mod borrow;
1020pub use borrow::NativeBorrow;
10211022#[doc(hidden)]
1023pub mod prepared;
10241025/// 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.
1049const NATIVE_BORROW: Option<NativeBorrow> = None;
10501051/// 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 /// ```
1093const CHARACTER_ONLY: bool = false;
10941095/// 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)]
1106const __MX_EXPECTATION: Option<&'static str> = None;
11071108/// The error type returned when conversion fails.
1109type Error;
11101111/// 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.
1114fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error>;
11151116/// 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.
1123unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1124// Default: just call the checked version
1125Self::try_from_sexp(sexp)
1126 }
11271128/// 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)]
1135unsafe fn __mx_try_from_rooted(root: crate::Root<'_>) -> Result<Self, Self::Error> {
1136Self::try_from_sexp(root.get())
1137 }
11381139/// 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)]
1155fn __mx_prepare(sexp: SEXP) -> prepared::Prepared<Self> {
1156if 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 }
11621163/// 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]
1170fn __mx_materialize(sexp: SEXP, arms: prepared::Arms) -> Result<Self, Self::Error> {
1171let _ = arms;
1172Self::try_from_sexp(sexp)
1173 }
11741175/// 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]
1189fn __mx_has_na(&self) -> bool {
1190false
1191}
11921193/// 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]
1219fn __mx_input_has_na(&self, input: SEXP) -> bool {
1220any_na(input) || self.__mx_has_na()
1221 }
12221223/// 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]
1245fn __mx_try_from_sexp_with_check(
1246 sexp: SEXP,
1247 check: &ElementCheck<'_>,
1248 ) -> Result<Self, SexpError>
1249where
1250Self::Error: Into<SexpError>,
1251 {
1252 check(sexp)?;
1253Self::try_from_sexp(sexp).map_err(Into::into)
1254 }
12551256/// [`__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]
1265unsafe fn __mx_try_from_sexp_unchecked_with_check(
1266 sexp: SEXP,
1267 check: &ElementCheck<'_>,
1268 ) -> Result<Self, SexpError>
1269where
1270Self::Error: Into<SexpError>,
1271 {
1272 check(sexp)?;
1273unsafe { Self::try_from_sexp_unchecked(sexp) }.map_err(Into::into)
1274 }
1275}
12761277/// 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;
12821283/// 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> {
1288Ok(())
1289}
12901291// 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.
12981299impl<T> TryFromSexpfor Box<[T]>
1300where
1301Vec<T>: TryFromSexp,
1302{
1303const NATIVE_BORROW: Option<NativeBorrow> = <Vec<T> as TryFromSexp>::NATIVE_BORROW;
1304const CHARACTER_ONLY: bool = <Vec<T> as TryFromSexp>::CHARACTER_ONLY;
13051306type Error = <Vec<T> as TryFromSexp>::Error;
13071308#[inline]
1309fn 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 }
13121313#[inline]
1314unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1315unsafe { <Vec<T> as TryFromSexp>::try_from_sexp_unchecked(sexp) }
1316 .map(|v| v.into_boxed_slice())
1317 }
1318}
1319// endregion
13201321macro_rules!impl_try_from_sexp_scalar_native {
1322 ($t:ty, $sexptype:ident) => {
1323impl TryFromSexp for $t {
1324type Error = SexpError;
13251326#[inline]
1327fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1328let actual = sexp.type_of();
1329if actual != SEXPTYPE::$sexptype {
1330return Err(SexpTypeError {
1331 expected: SEXPTYPE::$sexptype,
1332 actual,
1333 }
1334 .into());
1335 }
1336let len = sexp.len();
1337if len != 1 {
1338return Err(SexpLengthError {
1339 expected: 1,
1340 actual: len,
1341 }
1342 .into());
1343 }
1344unsafe { 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 }
13551356#[inline]
1357unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1358let actual = sexp.type_of();
1359if actual != SEXPTYPE::$sexptype {
1360return Err(SexpTypeError {
1361 expected: SEXPTYPE::$sexptype,
1362 actual,
1363 }
1364 .into());
1365 }
1366let len = unsafe { sexp.len_unchecked() };
1367if len != 1 {
1368return Err(SexpLengthError {
1369 expected: 1,
1370 actual: len,
1371 }
1372 .into());
1373 }
1374unsafe { 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}
13881389// 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 TryFromSexpfor i32 {
1392type Error = SexpError;
13931394#[inline]
1395fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1396let actual = sexp.type_of();
1397if actual != SEXPTYPE::INTSXP {
1398return Err(SexpTypeError {
1399 expected: SEXPTYPE::INTSXP,
1400actual,
1401 }
1402 .into());
1403 }
1404let len = sexp.len();
1405if len != 1 {
1406return Err(SexpLengthError {
1407 expected: 1,
1408 actual: len,
1409 }
1410 .into());
1411 }
1412let 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 })?;
1421if v.is_na() {
1422return Err(SexpNaError {
1423 sexp_type: SEXPTYPE::INTSXP,
1424 }
1425 .into());
1426 }
1427Ok(v)
1428 }
14291430#[inline]
1431unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1432let actual = sexp.type_of();
1433if actual != SEXPTYPE::INTSXP {
1434return Err(SexpTypeError {
1435 expected: SEXPTYPE::INTSXP,
1436actual,
1437 }
1438 .into());
1439 }
1440let len = unsafe { sexp.len_unchecked() };
1441if len != 1 {
1442return Err(SexpLengthError {
1443 expected: 1,
1444 actual: len,
1445 }
1446 .into());
1447 }
1448let 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 })?;
1457if v.is_na() {
1458return Err(SexpNaError {
1459 sexp_type: SEXPTYPE::INTSXP,
1460 }
1461 .into());
1462 }
1463Ok(v)
1464 }
1465}
14661467impl 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);
14711472/// 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 TryFromSexpfor SEXP {
1497type Error = SexpError;
14981499/// 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]
1506fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1507Ok(unsafe { crate::altrep_sexp::ensure_materialized(sexp) })
1508 }
15091510#[inline]
1511unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1512Ok(unsafe { crate::altrep_sexp::ensure_materialized(sexp) })
1513 }
1514}
15151516impl TryFromSexpfor Option<SEXP> {
1517type Error = SexpError;
15181519#[inline]
1520fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1521if sexp.type_of() == SEXPTYPE::NILSXP {
1522Ok(None)
1523 } else {
1524Ok(Some(unsafe {
1525crate::altrep_sexp::ensure_materialized(sexp)
1526 }))
1527 }
1528 }
15291530#[inline]
1531unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1532Self::try_from_sexp(sexp)
1533 }
1534}
1535// endregion
15361537mod logical;
15381539mod coerced_scalars;
1540pub(crate) use coerced_scalars::{coerce_real_value, coerce_value};
15411542mod references;
15431544// region: Blanket implementations for slices with arbitrary lifetimes
15451546/// 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> {
1550let actual = sexp.type_of();
1551if actual == T::SEXP_TYPE {
1552Ok(())
1553 } else {
1554Err(SexpTypeError {
1555 expected: T::SEXP_TYPE,
1556actual,
1557 })
1558 }
1559}
15601561/// 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> TryFromSexpfor &[T]
1567where
1568T: crate::RNativeType + Copy,
1569{
1570const NATIVE_BORROW: Option<NativeBorrow> = Some(NativeBorrow::slice(T::SEXP_TYPE, false));
15711572type Error = SexpTypeError;
15731574#[inline]
1575fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1576 native_slice_type::<T>(sexp)?;
1577Ok(unsafe { sexp.as_slice::<T>() })
1578 }
15791580#[inline]
1581unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1582 native_slice_type::<T>(sexp)?;
1583Ok(unsafe { sexp.as_slice_unchecked::<T>() })
1584 }
15851586fn __mx_prepare(sexp: SEXP) -> prepared::Prepared<Self> {
1587 prepared::native_leaf(native_slice_type::<T>(sexp))
1588 }
1589}
15901591/// 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> TryFromSexpfor &mut [T]
1604where
1605T: crate::RNativeType + Copy,
1606{
1607const NATIVE_BORROW: Option<NativeBorrow> = Some(NativeBorrow::slice(T::SEXP_TYPE, true));
16081609type Error = SexpTypeError;
16101611#[inline]
1612fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1613 native_slice_type::<T>(sexp)?;
1614let len = sexp.len();
1615let ptr = unsafe { T::dataptr_mut(sexp) };
1616Ok(unsafe { r_slice_mut(ptr, len) })
1617 }
16181619#[inline]
1620unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1621 native_slice_type::<T>(sexp)?;
1622let len = unsafe { sexp.len_unchecked() };
1623let ptr = unsafe { T::dataptr_mut(sexp) };
1624Ok(unsafe { r_slice_mut(ptr, len) })
1625 }
16261627fn __mx_prepare(sexp: SEXP) -> prepared::Prepared<Self> {
1628 prepared::native_leaf(native_slice_type::<T>(sexp))
1629 }
1630}
16311632/// Blanket impl for `Option<&[T]>` where T: RNativeType
1633impl<T> TryFromSexpfor Option<&[T]>
1634where
1635T: crate::RNativeType + Copy,
1636{
1637const NATIVE_BORROW: Option<NativeBorrow> = <&[T] as TryFromSexp>::NATIVE_BORROW;
16381639type Error = SexpError;
16401641#[inline]
1642fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1643if sexp.type_of() == SEXPTYPE::NILSXP {
1644return Ok(None);
1645 }
1646let slice: &[T] = TryFromSexp::try_from_sexp(sexp).map_err(SexpError::from)?;
1647Ok(Some(slice))
1648 }
16491650#[inline]
1651unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1652if sexp.type_of() == SEXPTYPE::NILSXP {
1653return Ok(None);
1654 }
1655let slice: &[T] =
1656unsafe { TryFromSexp::try_from_sexp_unchecked(sexp).map_err(SexpError::from)? };
1657Ok(Some(slice))
1658 }
16591660fn __mx_prepare(sexp: SEXP) -> prepared::Prepared<Self> {
1661if sexp.type_of() == SEXPTYPE::NILSXP {
1662return prepared::Prepared::Ready(None);
1663 }
1664 prepared::native_leaf(native_slice_type::<T>(sexp).map_err(SexpError::from))
1665 }
1666}
16671668/// Blanket impl for `Option<&mut [T]>` where T: RNativeType
1669impl<T> TryFromSexpfor Option<&mut [T]>
1670where
1671T: crate::RNativeType + Copy,
1672{
1673const NATIVE_BORROW: Option<NativeBorrow> = <&mut [T] as TryFromSexp>::NATIVE_BORROW;
16741675type Error = SexpError;
16761677#[inline]
1678fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1679if sexp.type_of() == SEXPTYPE::NILSXP {
1680return Ok(None);
1681 }
1682let slice: &mut [T] = TryFromSexp::try_from_sexp(sexp).map_err(SexpError::from)?;
1683Ok(Some(slice))
1684 }
16851686#[inline]
1687unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1688if sexp.type_of() == SEXPTYPE::NILSXP {
1689return Ok(None);
1690 }
1691let slice: &mut [T] =
1692unsafe { TryFromSexp::try_from_sexp_unchecked(sexp).map_err(SexpError::from)? };
1693Ok(Some(slice))
1694 }
16951696fn __mx_prepare(sexp: SEXP) -> prepared::Prepared<Self> {
1697if sexp.type_of() == SEXPTYPE::NILSXP {
1698return prepared::Prepared::Ready(None);
1699 }
1700 prepared::native_leaf(native_slice_type::<T>(sexp).map_err(SexpError::from))
1701 }
1702}
1703// endregion
17041705mod strings;
17061707mod str_parse;
1708pub use str_parse::{ParseRStr, ParsedRStr};
17091710// region: Result conversions (NULL -> Err(()))
17111712impl<T> TryFromSexpfor Result<T, ()>
1713where
1714T: TryFromSexp,
1715 T::Error: Into<SexpError>,
1716{
1717const NATIVE_BORROW: Option<crate::from_r::NativeBorrow> = T::NATIVE_BORROW;
17181719type Error = SexpError;
1720// `NULL` (`Err(())`) is "not given" and passes `no_na`.
1721#[inline]
1722fn __mx_has_na(&self) -> bool {
1723self.as_ref().is_ok_and(T::__mx_has_na)
1724 }
17251726// 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]
1729fn __mx_input_has_na(&self, input: SEXP) -> bool {
1730match self {
1731Ok(v) => T::__mx_input_has_na(v, input),
1732Err(()) => false,
1733 }
1734 }
17351736#[inline]
1737fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1738if sexp.type_of() == SEXPTYPE::NILSXP {
1739return Ok(Err(()));
1740 }
1741let value = T::try_from_sexp(sexp).map_err(Into::into)?;
1742Ok(Ok(value))
1743 }
17441745#[inline]
1746unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1747if sexp.type_of() == SEXPTYPE::NILSXP {
1748return Ok(Err(()));
1749 }
1750let value = unsafe { T::try_from_sexp_unchecked(sexp).map_err(Into::into)? };
1751Ok(Ok(value))
1752 }
17531754fn __mx_prepare(sexp: SEXP) -> prepared::Prepared<Self> {
1755if sexp.type_of() == SEXPTYPE::NILSXP {
1756return prepared::Prepared::Ready(Err(()));
1757 }
1758 T::__mx_prepare(sexp).map(Ok, Into::into)
1759 }
17601761fn __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
17661767mod na_vectors;
17681769mod collections;
17701771mod tuples;
17721773// region: Fixed-size array conversions
17741775/// 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> TryFromSexpfor [T; N]
1780where
1781T: crate::RNativeType + Copy,
1782{
1783type Error = SexpError;
17841785fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1786let slice: &[T] = TryFromSexp::try_from_sexp(sexp)?;
1787if slice.len() != N {
1788return Err(SexpLengthError {
1789 expected: N,
1790 actual: slice.len(),
1791 }
1792 .into());
1793 }
17941795// T: Copy, length verified above. Use MaybeUninit + copy_from_slice.
1796let mut arr = std::mem::MaybeUninit::<[T; N]>::uninit();
1797unsafe {
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.
1800let dst: &mut [T] = std::slice::from_raw_parts_mut(arr.as_mut_ptr().cast::<T>(), N);
1801dst.copy_from_slice(&slice[..N]);
1802Ok(arr.assume_init())
1803 }
1804 }
18051806unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1807Self::try_from_sexp(sexp)
1808 }
1809}
1810// endregion
18111812// region: VecDeque conversions
18131814use std::collections::VecDeque;
18151816/// Blanket impl: Convert R vector to `VecDeque<T>` where T: RNativeType.
1817impl<T> TryFromSexpfor VecDeque<T>
1818where
1819T: crate::RNativeType + Copy,
1820{
1821type Error = SexpTypeError;
18221823fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1824let slice: &[T] = TryFromSexp::try_from_sexp(sexp)?;
1825Ok(VecDeque::from(slice.to_vec()))
1826 }
18271828unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1829let slice: &[T] = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
1830Ok(VecDeque::from(slice.to_vec()))
1831 }
1832}
1833// endregion
18341835// region: BinaryHeap conversions
18361837use std::collections::BinaryHeap;
18381839/// 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> TryFromSexpfor BinaryHeap<T>
1843where
1844T: crate::RNativeType + Copy + Ord,
1845{
1846type Error = SexpTypeError;
18471848fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1849let slice: &[T] = TryFromSexp::try_from_sexp(sexp)?;
1850Ok(BinaryHeap::from(slice.to_vec()))
1851 }
18521853unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1854let slice: &[T] = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
1855Ok(BinaryHeap::from(slice.to_vec()))
1856 }
1857}
1858// endregion
18591860mod cow_and_paths;
1861mod rooted;
1862pub use rooted::TryFromRoot;
18631864// 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.
18681869/// Convert R value to `Option<Vec<T>>`: NULL → None, otherwise Some(vec).
1870impl<T> TryFromSexpfor Option<Vec<T>>
1871where
1872Vec<T>: TryFromSexp,
1873 <Vec<T> as TryFromSexp>::Error: Into<SexpError>,
1874{
1875const NATIVE_BORROW: Option<NativeBorrow> = <Vec<T> as TryFromSexp>::NATIVE_BORROW;
1876const CHARACTER_ONLY: bool = <Vec<T> as TryFromSexp>::CHARACTER_ONLY;
18771878type Error = SexpError;
18791880#[inline]
1881fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1882if sexp.type_of() == SEXPTYPE::NILSXP {
1883Ok(None)
1884 } else {
1885Vec::<T>::try_from_sexp(sexp).map(Some).map_err(Into::into)
1886 }
1887 }
18881889#[inline]
1890unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1891if sexp.type_of() == SEXPTYPE::NILSXP {
1892Ok(None)
1893 } else {
1894unsafe {
1895Vec::<T>::try_from_sexp_unchecked(sexp)
1896 .map(Some)
1897 .map_err(Into::into)
1898 }
1899 }
1900 }
1901}
19021903macro_rules!impl_option_map_try_from_sexp {
1904 ($(#[$meta:meta])* $map_ty:ident) => {
1905 $(#[$meta])*
1906impl<V: TryFromSexp> TryFromSexp for Option<$map_ty<String, V>>
1907where
1908V::Error: Into<SexpError>,
1909 {
1910const NATIVE_BORROW: Option<NativeBorrow> =
1911 <$map_ty<String, V> as TryFromSexp>::NATIVE_BORROW;
19121913type Error = SexpError;
1914#[inline]
1915fn __mx_has_na(&self) -> bool {
1916self.as_ref()
1917 .is_some_and(<$map_ty<String, V> as TryFromSexp>::__mx_has_na)
1918 }
19191920#[inline]
1921fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1922if sexp.type_of() == SEXPTYPE::NILSXP {
1923Ok(None)
1924 } else {
1925$map_ty::<String, V>::try_from_sexp(sexp).map(Some)
1926 }
1927 }
1928 }
1929 };
1930}
19311932#[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).
1934HashMap
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).
1938BTreeMap
1939);
19401941macro_rules!impl_option_set_try_from_sexp {
1942 ($(#[$meta:meta])* $set_ty:ident) => {
1943 $(#[$meta])*
1944impl<T> TryFromSexp for Option<$set_ty<T>>
1945where
1946$set_ty<T>: TryFromSexp,
1947 <$set_ty<T> as TryFromSexp>::Error: Into<SexpError>,
1948 {
1949const CHARACTER_ONLY: bool = <$set_ty<T> as TryFromSexp>::CHARACTER_ONLY;
19501951type Error = SexpError;
19521953#[inline]
1954fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1955if sexp.type_of() == SEXPTYPE::NILSXP {
1956Ok(None)
1957 } else {
1958$set_ty::<T>::try_from_sexp(sexp)
1959 .map(Some)
1960 .map_err(Into::into)
1961 }
1962 }
1963 }
1964 };
1965}
19661967#[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).
1969HashSet
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).
1973BTreeSet
1974);
1975// endregion
19761977// region: Nested vector conversions (list of vectors)
19781979/// Convert R list (VECSXP) to `Vec<Vec<T>>`.
1980///
1981/// Each element of the R list must be convertible to `Vec<T>`.
1982impl<T> TryFromSexpfor Vec<Vec<T>>
1983where
1984Vec<T>: TryFromSexp,
1985 <Vec<T> as TryFromSexp>::Error: Into<SexpError>,
1986{
1987const NATIVE_BORROW: Option<NativeBorrow> =
1988NativeBorrow::in_list(<Vec<T> as TryFromSexp>::NATIVE_BORROW);
19891990type Error = SexpError;
19911992fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
1993map_vecsxp_with(sexp, |_i, elem| {
1994Vec::<T>::try_from_sexp(elem).map_err(Into::into)
1995 })
1996 }
19971998unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
1999unsafe {
2000map_vecsxp_with_unchecked(sexp, |_i, elem| {
2001Vec::<T>::try_from_sexp_unchecked(elem).map_err(Into::into)
2002 })
2003 }
2004 }
2005}
2006// endregion
20072008// region: Coerced wrapper - bridge between TryFromSexp and TryCoerce
20092010use crate::coerce::Coerced;
20112012/// 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> TryFromSexpfor Coerced<T, R>
2026where
2027R: TryFromSexp,
2028 R: TryCoerce<T>,
2029 <R as TryFromSexp>::Error: Into<SexpError>,
2030 <R as TryCoerce<T>>::Error: std::fmt::Display,
2031{
2032type Error = SexpError;
20332034#[inline]
2035fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
2036let r_val: R = R::try_from_sexp(sexp).map_err(Into::into)?;
2037let 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}")))?;
2040Ok(Coerced::new(value))
2041 }
20422043#[inline]
2044unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
2045let r_val: R = unsafe { R::try_from_sexp_unchecked(sexp).map_err(Into::into)? };
2046let 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}")))?;
2049Ok(Coerced::new(value))
2050 }
2051}
2052// endregion
20532054/// 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> {
2059if sexp.type_of() == SEXPTYPE::INTSXP {
2060Coerced::<bool, i32>::try_from_sexp(sexp).map(Coerced::into_inner)
2061 } else {
2062bool::try_from_sexp(sexp)
2063 }
2064}
20652066/// 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> {
2069if sexp.type_of() == SEXPTYPE::INTSXP {
2070let slice: &[i32] = TryFromSexp::try_from_sexp(sexp)?;
2071coerce_slice_to_vec(slice)
2072 } else {
2073Vec::<bool>::try_from_sexp(sexp)
2074 }
2075}
20762077/// 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> {
2085if sexp.type_of() == SEXPTYPE::INTSXP {
2086i32::try_from_sexp(sexp)
2087 } else {
2088 coerced_scalars::try_from_sexp_numeric_scalar(sexp)
2089 }
2090}
20912092/// 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> {
2100match sexp.type_of() {
2101 SEXPTYPE::INTSXP => {
2102let v: Option<i32> = TryFromSexp::try_from_sexp(sexp)?;
2103Ok(v.map_or(NA_REAL, f64::from))
2104 }
2105 SEXPTYPE::LGLSXP => {
2106let v: RLogical = TryFromSexp::try_from_sexp(sexp)?;
2107Ok(if v.is_na() {
2108NA_REAL2109 } else {
2110f64::from(v.to_i32())
2111 })
2112 }
2113 SEXPTYPE::RAWSXP => {
2114let v: u8 = TryFromSexp::try_from_sexp(sexp)?;
2115Ok(f64::from(v))
2116 }
2117_ => f64::try_from_sexp(sexp),
2118 }
2119}
21202121/// 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> {
2129if sexp.type_of() == SEXPTYPE::INTSXP {
2130return Vec::<i32>::try_from_sexp(sexp).map_err(SexpError::from);
2131 }
2132from_numeric_vec_with(
2133sexp,
2134Ok,
2135 |v: f64| {
2136if v.is_na() {
2137Ok(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}
21472148/// 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> {
2154if sexp.type_of() == SEXPTYPE::REALSXP {
2155return Vec::<f64>::try_from_sexp(sexp).map_err(SexpError::from);
2156 }
2157from_numeric_vec_with(
2158sexp,
2159 |v: i32| Ok(if v.is_na() { NA_REAL } else { f64::from(v) }),
2160Ok,
2161 |v: u8| Ok(f64::from(v)),
2162 |v: RLogical| {
2163Ok(if v.is_na() {
2164NA_REAL2165 } else {
2166f64::from(v.to_i32())
2167 })
2168 },
2169 )
2170}
21712172// region: Optional scalars: `NULL` or a plain `NA` (#2305)
21732174/// 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 {
2191match 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}
21972198/// [`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 {
2207match sexp.type_of() {
2208 SEXPTYPE::NILSXP => true,
2209 SEXPTYPE::LGLSXP => unsafe {
2210sexp.len_unchecked() == 1
2211&& RLogical::from_i32(crate::sys::LOGICAL_ELT_unchecked(sexp, 0)).is_na()
2212 },
2213_ => false,
2214 }
2215}
22162217// endregion
22182219// region: Coerced optional parameters (`Option<T>` / `Vec<Option<T>>`, #2274)
22202221/// 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> {
2229if sexp.type_of() == SEXPTYPE::NILSXP {
2230return Ok(None);
2231 }
2232match read(sexp) {
2233Ok(value) => Ok(Some(value)),
2234Err(SexpError::Na(_)) => Ok(None),
2235Err(e) => Err(e),
2236 }
2237}
22382239/// 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> {
2245coerced_option(sexp, try_from_sexp_coerced_bool)
2246}
22472248/// 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> {
2256coerced_option(sexp, try_from_sexp_coerced_i32)
2257}
22582259/// 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> {
2267coerced_option(sexp, try_from_sexp_coerced_f64).map(|v| v.filter(|x| !x.is_na()))
2268}
22692270/// 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> {
2277if sexp.type_of() != SEXPTYPE::INTSXP {
2278return Vec::<Option<bool>>::try_from_sexp(sexp);
2279 }
2280let slice: &[i32] = TryFromSexp::try_from_sexp(sexp)?;
2281collect_coerced(
2282slice.len(),
2283slice.iter().map(|&v| {
2284if v.is_na() {
2285Ok(None)
2286 } else {
2287 coerced_scalars::coerce_value(v).map(Some)
2288 }
2289 }),
2290 )
2291}
22922293/// 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> {
2301if sexp.type_of() == SEXPTYPE::INTSXP {
2302return Vec::<Option<i32>>::try_from_sexp(sexp);
2303 }
2304from_numeric_vec_with(
2305sexp,
2306 |v: i32| Ok(if v.is_na() { None } else { Some(v) }),
2307 |v: f64| {
2308if v.is_na() {
2309Ok(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}
23182319/// 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> {
2326if sexp.type_of() == SEXPTYPE::REALSXP {
2327return Vec::<Option<f64>>::try_from_sexp(sexp);
2328 }
2329from_numeric_vec_with(
2330sexp,
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| {
2335Ok(if v.is_na() {
2336None2337 } else {
2338Some(f64::from(v.to_i32()))
2339 })
2340 },
2341 )
2342}
23432344// endregion
23452346// 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.
23512352/// 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
2362R: Copy + TryCoerce<T>,
2363 <R as TryCoerce<T>>::Error: std::fmt::Display,
2364{
2365let mut result = Vec::with_capacity(slice.len());
2366let mut errors = BatchedErrors::default();
2367for (i, v) in slice.iter().copied().enumerate() {
2368match v.try_coerce() {
2369Ok(x) => result.push(x),
2370Err(e) => errors.push(i, || e.to_string()),
2371 }
2372 }
2373if errors.is_empty() {
2374Ok(result)
2375 } else {
2376Err(errors.into_element_error())
2377 }
2378}
23792380/// 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> {
2394let mut result = Vec::with_capacity(len);
2395let mut errors = BatchedErrors::default();
2396for (i, item) in iter.enumerate() {
2397match item {
2398Ok(v) => result.push(v),
2399Err(e) => errors.push(i, || e.r_reason(false)),
2400 }
2401 }
2402if errors.is_empty() {
2403Ok(result)
2404 } else {
2405Err(errors.into_element_error())
2406 }
2407}
24082409/// 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
2431FI: 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{
2436let actual = sexp.type_of();
2437match actual {
2438 SEXPTYPE::INTSXP => {
2439let slice: &[i32] = unsafe { sexp.as_slice() };
2440collect_coerced(slice.len(), slice.iter().copied().map(map_i32))
2441 }
2442 SEXPTYPE::REALSXP => {
2443let slice: &[f64] = unsafe { sexp.as_slice() };
2444collect_coerced(slice.len(), slice.iter().copied().map(map_f64))
2445 }
2446 SEXPTYPE::RAWSXP => {
2447let slice: &[u8] = unsafe { sexp.as_slice() };
2448collect_coerced(slice.len(), slice.iter().copied().map(map_u8))
2449 }
2450 SEXPTYPE::LGLSXP => {
2451let slice: &[RLogical] = unsafe { sexp.as_slice() };
2452collect_coerced(slice.len(), slice.iter().copied().map(map_lgl))
2453 }
2454_ => Err(SexpTypeError {
2455 expected: SEXPTYPE::REALSXP,
2456actual,
2457 }
2458 .into()),
2459 }
2460}
24612462/// 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,
2484mut map: impl FnMut(SEXP/* charsxp */, usize) -> Result<U, SexpError>,
2485) -> Result<Vec<U>, SexpError> {
2486let actual = sexp.type_of();
2487if actual != SEXPTYPE::STRSXP {
2488return Err(SexpTypeError {
2489 expected: SEXPTYPE::STRSXP,
2490actual,
2491 }
2492 .into());
2493 }
24942495let len = sexp.len();
2496let mut result = Vec::with_capacity(len);
2497let mut errors = ElementErrors::default();
2498for i in 0..len {
2499let charsxp = sexp.string_elt(i as crate::R_xlen_t);
2500match map(charsxp, i) {
2501Ok(value) => result.push(value),
2502Err(e) => errors.push(i, e),
2503 }
2504 }
2505errors.into_result(result)
2506}
25072508/// 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 {
2519let ty = value.type_of();
2520if ty == SEXPTYPE::NILSXP {
2521return "got NULL".to_string();
2522 }
2523let 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 );
2532if !atomic {
2533return ::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 }
2535if value.len() == 0 {
2536return "got length 0".to_string();
2537 }
2538if ty == SEXPTYPE::STRSXP {
2539let charsxp = value.string_elt(0);
2540if charsxp != SEXP::na_string() {
2541// SAFETY: a non-NA CHARSXP of a live STRSXP.
2542return ::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}
25472548/// 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> {
2557let actual = sexp.type_of();
2558if actual != SEXPTYPE::STRSXP {
2559return Err(SexpTypeError {
2560 expected: SEXPTYPE::STRSXP,
2561actual,
2562 }
2563 .into());
2564 }
25652566let len = sexp.len();
2567if len != 1 {
2568return Err(SexpLengthError {
2569 expected: 1,
2570 actual: len,
2571 }
2572 .into());
2573 }
25742575Ok(sexp.string_elt(0))
2576}
25772578/// 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> {
2587let actual = sexp.type_of();
2588if actual != SEXPTYPE::STRSXP {
2589return Err(SexpTypeError {
2590 expected: SEXPTYPE::STRSXP,
2591actual,
2592 }
2593 .into());
2594 }
25952596let len = unsafe { sexp.len_unchecked() };
2597if len != 1 {
2598return Err(SexpLengthError {
2599 expected: 1,
2600 actual: len,
2601 }
2602 .into());
2603 }
26042605Ok(unsafe { sexp.string_elt_unchecked(0) })
2606}
26072608/// 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,
2618mut map: impl FnMut(usize, SEXP) -> Result<U, SexpError>,
2619) -> Result<Vec<U>, SexpError> {
2620let actual = sexp.type_of();
2621if actual != SEXPTYPE::VECSXP {
2622return Err(SexpTypeError {
2623 expected: SEXPTYPE::VECSXP,
2624actual,
2625 }
2626 .into());
2627 }
26282629let len = sexp.len();
2630let mut result = Vec::with_capacity(len);
2631for i in 0..len {
2632let elem = sexp.vector_elt(i as crate::R_xlen_t);
2633 result.push(map(i, elem)?);
2634 }
2635Ok(result)
2636}
26372638/// 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,
2648mut map: impl FnMut(usize, SEXP) -> Result<U, SexpError>,
2649) -> Result<Vec<U>, SexpError> {
2650let actual = sexp.type_of();
2651if actual != SEXPTYPE::VECSXP {
2652return Err(SexpTypeError {
2653 expected: SEXPTYPE::VECSXP,
2654actual,
2655 }
2656 .into());
2657 }
26582659let len = unsafe { sexp.len_unchecked() };
2660let mut result = Vec::with_capacity(len);
2661for i in 0..len {
2662let elem = unsafe { sexp.vector_elt_unchecked(i as crate::R_xlen_t) };
2663 result.push(map(i, elem)?);
2664 }
2665Ok(result)
2666}
26672668/// 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
2679i32: TryCoerce<T>,
2680f64: TryCoerce<T>,
2681u8: TryCoerce<T>,
2682 <i32as TryCoerce<T>>::Error: std::fmt::Display,
2683 <f64as TryCoerce<T>>::Error: std::fmt::Display,
2684 <u8as TryCoerce<T>>::Error: std::fmt::Display,
2685{
2686from_numeric_vec_with(
2687sexp,
2688 |v: i32| {
2689if v.is_na() {
2690Err(SexpNaError {
2691 sexp_type: SEXPTYPE::INTSXP,
2692 }
2693 .into())
2694 } else {
2695coerce_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.)
2700coerce_real_value,
2701coerce_value,
2702 |v: RLogical| {
2703if v.is_na() {
2704Err(SexpNaError {
2705 sexp_type: SEXPTYPE::LGLSXP,
2706 }
2707 .into())
2708 } else {
2709coerce_value(v.to_i32())
2710 }
2711 },
2712 )
2713}
27142715/// Implement `TryFromSexp for Vec<$target>` by coercing from integer/real/logical/raw.
2716macro_rules!impl_vec_try_from_sexp_numeric {
2717 ($target:ty) => {
2718impl TryFromSexp for Vec<$target> {
2719type Error = SexpError;
27202721fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
2722 try_from_sexp_numeric_vec(sexp)
2723 }
27242725unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
2726 try_from_sexp_numeric_vec(sexp)
2727 }
2728 }
2729 };
2730}
27312732impl 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);
27412742/// Convert R logical vector (LGLSXP) to `Vec<bool>` (errors on NA).
2743impl TryFromSexpfor Vec<bool> {
2744type Error = SexpError;
27452746fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
2747let actual = sexp.type_of();
2748if actual != SEXPTYPE::LGLSXP {
2749return Err(SexpTypeError {
2750 expected: SEXPTYPE::LGLSXP,
2751actual,
2752 }
2753 .into());
2754 }
2755let slice: &[RLogical] = unsafe { sexp.as_slice() };
2756coerce_slice_to_vec(slice)
2757 }
27582759unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
2760Self::try_from_sexp(sexp)
2761 }
2762}
2763// endregion
27642765// region: Direct HashSet / BTreeSet coercion conversions
27662767/// 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
2773S: std::iter::FromIterator<T>,
2774i32: TryCoerce<T>,
2775f64: TryCoerce<T>,
2776u8: TryCoerce<T>,
2777 <i32as TryCoerce<T>>::Error: std::fmt::Display,
2778 <f64as TryCoerce<T>>::Error: std::fmt::Display,
2779 <u8as TryCoerce<T>>::Error: std::fmt::Display,
2780{
2781let vec = try_from_sexp_numeric_vec(sexp)?;
2782Ok(vec.into_iter().collect())
2783}
27842785macro_rules!impl_set_try_from_sexp_numeric {
2786 ($set_ty:ident, $target:ty) => {
2787impl TryFromSexp for $set_ty<$target> {
2788type Error = SexpError;
27892790fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
2791 try_from_sexp_numeric_set(sexp)
2792 }
27932794unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
2795 try_from_sexp_numeric_set(sexp)
2796 }
2797 }
2798 };
2799}
28002801impl 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);
28092810impl 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);
28182819macro_rules!impl_set_try_from_sexp_bool {
2820 ($set_ty:ident) => {
2821impl TryFromSexp for $set_ty<bool> {
2822type Error = SexpError;
28232824fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
2825let vec: Vec<bool> = TryFromSexp::try_from_sexp(sexp)?;
2826Ok(vec.into_iter().collect())
2827 }
28282829unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
2830Self::try_from_sexp(sexp)
2831 }
2832 }
2833 };
2834}
28352836impl 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
28392840// region: ExternalPtr conversions
28412842use crate::externalptr::{ExternalPtr, TypeMismatchError, TypedExternal};
28432844/// 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 {
2848match 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.
2861TypeMismatchError::Restored { .. } | TypeMismatchError::OtherVersion { .. } => {
2862let message = e.to_string();
2863let classes: Vec<String> = e2864 .restored_classes()
2865 .map(|classes| classes.iter().map(|&class| class.to_owned()).collect())
2866 .unwrap_or_default();
2867let mut error = crate::condition::RError::new(message.clone())
2868 .class(classes)
2869 .argument_message(message);
2870if let TypeMismatchError::OtherVersion { saved, current, .. } = e {
2871error = error2872 .data("saved_version", saved)
2873 .data("current_version", current);
2874 }
2875 SexpError::Condition(error)
2876 }
2877 }
2878}
28792880/// 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}
28902891/// 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> {
2898let actual = sexp.type_of();
2899if actual != SEXPTYPE::EXTPTRSXP {
2900return match unsafe { crate::externalptr::unwrap_class_handle(sexp) } {
2901// SAFETY: on R's main thread, like every conversion from R.
2902Some(inner) => unsafe { ExternalPtr::wrap_sexp_with_error(inner) }
2903 .map(|ptr| unsafe { ptr.rooted() })
2904 .map_err(type_mismatch_to_sexp_error),
2905None => Err(not_a_handle_error(actual)),
2906 };
2907 }
29082909// Use ExternalPtr's type-checked constructor
2910unsafe { ExternalPtr::wrap_sexp_with_error(sexp) }.map_err(type_mismatch_to_sexp_error)
2911}
29122913/// 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> {
2921external_ptr_from_sexp(sexp)
2922}
29232924/// [`__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> {
2930if sexp.type_of() == SEXPTYPE::NILSXP {
2931return Ok(None);
2932 }
2933external_ptr_from_sexp(sexp).map(Some)
2934}
29352936/// 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> TryFromSexpfor ExternalPtr<T> {
2954type Error = SexpError;
29552956fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
2957external_ptr_from_sexp(sexp)
2958 }
29592960unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
2961let actual = sexp.type_of();
2962if actual != SEXPTYPE::EXTPTRSXP {
2963return match unsafe { crate::externalptr::unwrap_class_handle(sexp) } {
2964Some(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 }),
2973None => Err(not_a_handle_error(actual)),
2974 };
2975 }
29762977// Use ExternalPtr's type-checked constructor (unchecked variant)
2978unsafe { 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}
29852986impl<T: TypedExternal> TryFromSexpfor Option<ExternalPtr<T>> {
2987type Error = SexpError;
29882989fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
2990if sexp.type_of() == SEXPTYPE::NILSXP {
2991return Ok(None);
2992 }
2993let ptr: ExternalPtr<T> = TryFromSexp::try_from_sexp(sexp)?;
2994Ok(Some(ptr))
2995 }
29962997unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
2998if sexp.type_of() == SEXPTYPE::NILSXP {
2999return Ok(None);
3000 }
3001let ptr: ExternalPtr<T> = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
3002Ok(Some(ptr))
3003 }
3004}
30053006/// 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> TryFromSexpfor Vec<ExternalPtr<T>> {
3016type Error = SexpError;
30173018fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
3019map_vecsxp_with(sexp, |_i, elem| {
3020 <ExternalPtr<T> as TryFromSexp>::try_from_sexp(elem)
3021 })
3022 }
30233024unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
3025unsafe {
3026map_vecsxp_with_unchecked(sexp, |_i, elem| {
3027 <ExternalPtr<T> as TryFromSexp>::try_from_sexp_unchecked(elem)
3028 })
3029 }
3030 }
3031}
30323033/// 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> TryFromSexpfor Vec<Option<ExternalPtr<T>>> {
3037type Error = SexpError;
30383039fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
3040map_vecsxp_with(sexp, |_i, elem| {
3041 <Option<ExternalPtr<T>> as TryFromSexp>::try_from_sexp(elem)
3042 })
3043 }
30443045unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
3046unsafe {
3047map_vecsxp_with_unchecked(sexp, |_i, elem| {
3048 <Option<ExternalPtr<T>> as TryFromSexp>::try_from_sexp_unchecked(elem)
3049 })
3050 }
3051 }
3052}
3053// endregion
30543055// region: R connections — TryFromSexp impls (issue #175, #176)
30563057#[cfg(feature = "connections")]
3058mod connections_from_r {
3059use crate::SEXP;
3060use crate::connection::access::{self, ConnState};
3061use crate::connection::{RNullConnection, RStderr, RStdin, RStdout};
3062use crate::from_r::{SexpError, TryFromSexp};
30633064// Strict validation: confirm description == expected_desc and class == "terminal".
3065unsafe fn validate_terminal(sexp: SEXP, expected_desc: &str) -> Result<(), SexpError> {
3066let ConnState {
3067 description: desc,
3068 class: cls,
3069 ..
3070 } = unsafe { access::state(sexp) };
3071if desc != expected_desc {
3072return Err(SexpError::InvalidValue(format!(
3073"expected terminal connection with description {:?}, got {:?}",
3074 expected_desc, desc
3075 )));
3076 }
3077if cls != "terminal" {
3078return Err(SexpError::InvalidValue(format!(
3079"expected class \"terminal\", got {:?}",
3080 cls
3081 )));
3082 }
3083Ok(())
3084 }
30853086impl TryFromSexp for RStdin {
3087type Error = SexpError;
30883089fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
3090unsafe { validate_terminal(sexp, "stdin") }?;
3091Ok(RStdin)
3092 }
30933094unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
3095Self::try_from_sexp(sexp)
3096 }
3097 }
30983099impl TryFromSexp for RStdout {
3100type Error = SexpError;
31013102fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
3103unsafe { validate_terminal(sexp, "stdout") }?;
3104Ok(RStdout)
3105 }
31063107unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
3108Self::try_from_sexp(sexp)
3109 }
3110 }
31113112impl TryFromSexp for RStderr {
3113type Error = SexpError;
31143115fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
3116unsafe { validate_terminal(sexp, "stderr") }?;
3117Ok(RStderr)
3118 }
31193120unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
3121Self::try_from_sexp(sexp)
3122 }
3123 }
31243125/// 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.
3132impl TryFromSexp for RNullConnection {
3133type Error = SexpError;
31343135fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
3136let state = unsafe { access::state(sexp) };
3137if !state.is_open {
3138return Err(SexpError::InvalidValue(
3139"expected an open connection".to_string(),
3140 ));
3141 }
3142if !state.can_write {
3143return 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.
3148unsafe { crate::sys::R_PreserveObject(sexp) };
3149Ok(unsafe { RNullConnection::from_preserved_sexp(sexp) })
3150 }
31513152unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
3153Self::try_from_sexp(sexp)
3154 }
3155 }
3156}
31573158// endregion
31593160// region: txtProgressBar — TryFromSexp (issue #177)
31613162#[cfg(feature = "connections")]
3163mod txt_progress_bar_from_r {
3164use crate::from_r::{SexpError, TryFromSexp};
3165use crate::sys::R_PreserveObject;
3166use crate::txt_progress_bar::RTxtProgressBar;
3167use crate::{SEXP, SexpExt};
31683169/// The handle borrows the bar: the R caller owns it, and dropping the
3170 /// handle leaves it open.
3171impl TryFromSexp for RTxtProgressBar {
3172type Error = SexpError;
31733174fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
3175// Must be a list (VECSXP) with class "txtProgressBar".
3176if !sexp.inherits_class(c"txtProgressBar") {
3177return 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.
3182unsafe { R_PreserveObject(sexp) };
3183Ok(unsafe { RTxtProgressBar::from_preserved_sexp(sexp) })
3184 }
31853186unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
3187Self::try_from_sexp(sexp)
3188 }
3189 }
3190}
31913192// endregion
31933194// region: Helper macros for feature-gated modules
31953196/// 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) => {
3204impl $crate::from_r::TryFromSexp for Option<$t> {
3205const NATIVE_BORROW: Option<$crate::from_r::NativeBorrow> =
3206 <$t as $crate::from_r::TryFromSexp>::NATIVE_BORROW;
3207const CHARACTER_ONLY: bool = <$t as $crate::from_r::TryFromSexp>::CHARACTER_ONLY;
32083209type Error = $crate::from_r::SexpError;
3210// `NULL` (`None`) is "not given" and passes `no_na`.
3211#[inline]
3212fn __mx_has_na(&self) -> bool {
3213self.as_ref()
3214 .is_some_and(<$t as $crate::from_r::TryFromSexp>::__mx_has_na)
3215 }
32163217fn try_from_sexp(sexp: $crate::SEXP) -> Result<Self, Self::Error> {
3218use $crate::{SEXPTYPE, SexpExt};
3219if sexp.type_of() == SEXPTYPE::NILSXP {
3220return Ok(None);
3221 }
3222 <$t as $crate::from_r::TryFromSexp>::try_from_sexp(sexp).map(Some)
3223 }
32243225unsafe fn try_from_sexp_unchecked(sexp: $crate::SEXP) -> Result<Self, Self::Error> {
3226use $crate::{SEXPTYPE, SexpExt};
3227if sexp.type_of() == SEXPTYPE::NILSXP {
3228return Ok(None);
3229 }
3230unsafe {
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;
32383239/// 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) => {
3246impl $crate::from_r::TryFromSexp for Vec<$t> {
3247const NATIVE_BORROW: Option<$crate::from_r::NativeBorrow> =
3248$crate::from_r::NativeBorrow::in_list(
3249 <$t as $crate::from_r::TryFromSexp>::NATIVE_BORROW,
3250 );
32513252type Error = $crate::from_r::SexpError;
32533254fn try_from_sexp(sexp: $crate::SEXP) -> Result<Self, Self::Error> {
3255use $crate::from_r::SexpTypeError;
3256use $crate::{SEXPTYPE, SexpExt};
32573258let actual = sexp.type_of();
3259if actual != SEXPTYPE::VECSXP {
3260return Err(SexpTypeError {
3261 expected: SEXPTYPE::VECSXP,
3262 actual,
3263 }
3264 .into());
3265 }
32663267let len = sexp.len();
3268let mut result = Vec::with_capacity(len);
3269for i in 0..len {
3270let elem = sexp.vector_elt(i as $crate::R_xlen_t);
3271 result.push(<$t as $crate::from_r::TryFromSexp>::try_from_sexp(elem)?);
3272 }
3273Ok(result)
3274 }
32753276unsafe fn try_from_sexp_unchecked(sexp: $crate::SEXP) -> Result<Self, Self::Error> {
3277use $crate::from_r::SexpTypeError;
3278use $crate::{SEXPTYPE, SexpExt};
32793280let actual = sexp.type_of();
3281if actual != SEXPTYPE::VECSXP {
3282return Err(SexpTypeError {
3283 expected: SEXPTYPE::VECSXP,
3284 actual,
3285 }
3286 .into());
3287 }
32883289let len = unsafe { sexp.len_unchecked() };
3290let mut result = Vec::with_capacity(len);
3291for i in 0..len {
3292let 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 }
3297Ok(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;
33053306/// 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) => {
3313impl $crate::from_r::TryFromSexp for Vec<Option<$t>> {
3314const NATIVE_BORROW: Option<$crate::from_r::NativeBorrow> =
3315$crate::from_r::NativeBorrow::in_list(
3316 <$t as $crate::from_r::TryFromSexp>::NATIVE_BORROW,
3317 );
33183319type Error = $crate::from_r::SexpError;
33203321fn try_from_sexp(sexp: $crate::SEXP) -> Result<Self, Self::Error> {
3322use $crate::from_r::SexpTypeError;
3323use $crate::{SEXPTYPE, SexpExt};
33243325let actual = sexp.type_of();
3326if actual != SEXPTYPE::VECSXP {
3327return Err(SexpTypeError {
3328 expected: SEXPTYPE::VECSXP,
3329 actual,
3330 }
3331 .into());
3332 }
33333334let len = sexp.len();
3335let mut result = Vec::with_capacity(len);
3336for i in 0..len {
3337let elem = sexp.vector_elt(i as $crate::R_xlen_t);
3338if 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 }
3346Ok(result)
3347 }
33483349unsafe fn try_from_sexp_unchecked(sexp: $crate::SEXP) -> Result<Self, Self::Error> {
3350use $crate::from_r::SexpTypeError;
3351use $crate::{SEXPTYPE, SexpExt};
33523353let actual = sexp.type_of();
3354if actual != SEXPTYPE::VECSXP {
3355return Err(SexpTypeError {
3356 expected: SEXPTYPE::VECSXP,
3357 actual,
3358 }
3359 .into());
3360 }
33613362let len = unsafe { sexp.len_unchecked() };
3363let mut result = Vec::with_capacity(len);
3364for i in 0..len {
3365let elem = unsafe { sexp.vector_elt_unchecked(i as $crate::R_xlen_t) };
3366if 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 }
3374Ok(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;
33823383/// 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;
33903391/// 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.
3426listed: Vec<(usize, String)>,
3427 total: usize,
3428}
34293430impl 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]
3436pub fn push(&mut self, index: usize, item: impl FnOnce() -> String) {
3437if self.listed.len() < BATCHED_ERROR_CAP {
3438self.listed.push((index, item()));
3439 }
3440self.total += 1;
3441 }
34423443/// Whether any failure has been recorded.
3444#[inline]
3445pub fn is_empty(&self) -> bool {
3446self.total == 0
3447}
34483449/// Append the `"; and N more"` tail when failures past the cap were counted.
3450fn write_more_tail(&self, msg: &mut String) {
3451if self.total > self.listed.len() {
3452use std::fmt::Write;
3453let _ = msg.write_fmt(format_args!("; and {0} more", self.total - self.listed.len()))write!(msg, "; and {} more", self.total - self.listed.len());
3454 }
3455 }
34563457/// Fold the recorded `(index, reason)` failures into one
3458 /// [`SexpError::InvalidValue`]; see [`element_message`](Self::element_message).
3459pub fn into_element_error(self) -> SexpError {
3460 SexpError::InvalidValue(self.element_message())
3461 }
34623463/// 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)`
3468pub fn element_message(&self) -> String {
3469if true {
if !(self.total > 0) {
{
::core::panicking::panic_fmt(format_args!("batching zero conversion errors"));
}
};
};debug_assert!(self.total > 0, "batching zero conversion errors");
3470let mut groups: Vec<(&str, Vec<usize>)> = Vec::new();
3471for (index, reason) in &self.listed {
3472match groups.iter_mut().find(|(r, _)| *r == reason.as_str()) {
3473Some((_, indices)) => indices.push(*index),
3474None => 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 }
3477let mut msg = String::new();
3478for (k, (reason, indices)) in groups.iter().enumerate() {
3479if k > 0 {
3480 msg.push_str("; ");
3481 }
3482 msg.push_str(reason);
3483 push_element_positions(&mut msg, indices.iter().copied());
3484 }
3485self.write_more_tail(&mut msg);
3486msg3487 }
34883489/// 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).
3497pub fn into_value_error(self, what: &str) -> SexpError {
3498 SexpError::InvalidValue(self.value_message(what))
3499 }
35003501/// The message behind [`into_value_error`](Self::into_value_error).
3502fn value_message(&self, what: &str) -> String {
3503use std::fmt::Write;
3504if true {
if !(self.total > 0) {
{
::core::panicking::panic_fmt(format_args!("batching zero rejected values"));
}
};
};debug_assert!(self.total > 0, "batching zero rejected values");
3505let mut msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} value(s): ", what))
})format!("{what} value(s): ");
3506for (k, (_, value)) in self.listed.iter().enumerate() {
3507if k > 0 {
3508 msg.push_str(", ");
3509 }
3510let _ = msg.write_fmt(format_args!("{0:?}", value))write!(msg, "{value:?}");
3511 }
3512push_element_positions(&mut msg, self.listed.iter().map(|(index, _)| *index));
3513self.write_more_tail(&mut msg);
3514msg3515 }
3516}
35173518/// 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) {
3525use std::fmt::Write;
3526msg.push_str(if indices.len() == 1 {
3527" (element "
3528} else {
3529" (elements "
3530});
3531for (k, index) in indices.enumerate() {
3532if k > 0 {
3533 msg.push_str(", ");
3534 }
3535let _ = msg.write_fmt(format_args!("{0}", index + 1))write!(msg, "{}", index + 1);
3536 }
3537msg.push(')');
3538}
35393540/// 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}
35643565impl ElementErrors {
3566/// Record the failure of the element at 0-based `index`.
3567pub(crate) fn push(&mut self, index: usize, error: SexpError) {
3568for refusal in error.reported_conditions() {
3569self.refused = true;
3570for class in refusal.classes() {
3571if !self.class.contains(class) {
3572self.class.push(class.clone());
3573 }
3574 }
3575for (name, value) in refusal.fields() {
3576if !self.data.iter().any(|(seen, _)| seen == name) {
3577self.data.push((name.clone(), value.clone()));
3578 }
3579 }
3580 }
3581self.batch.push(index, || match &error {
3582 SexpError::Condition(refusal) => refusal3583 .argument_message_str()
3584 .unwrap_or(refusal.message_str())
3585 .to_string(),
3586 other => other.r_reason(false),
3587 });
3588 }
35893590/// The values read, or the one error for every failure recorded.
3591pub(crate) fn into_result<T>(self, values: T) -> Result<T, SexpError> {
3592if self.batch.is_empty() {
3593return Ok(values);
3594 }
3595if !self.refused {
3596return Err(self.batch.into_element_error());
3597 }
3598let mut error =
3599crate::condition::RError::new(self.batch.element_message()).class(self.class);
3600for (name, value) in self.data {
3601 error = error.data(name, value);
3602 }
3603Err(SexpError::Condition(error))
3604 }
3605}
36063607/// 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,
3613mut read: impl FnMut(SEXP) -> Result<U, SexpError>,
3614) -> Result<Vec<U>, SexpError> {
3615let actual = sexp.type_of();
3616if actual != SEXPTYPE::VECSXP {
3617return Err(SexpTypeError {
3618 expected: SEXPTYPE::VECSXP,
3619actual,
3620 }
3621 .into());
3622 }
3623let len = sexp.len();
3624let mut values = Vec::with_capacity(len);
3625let mut errors = ElementErrors::default();
3626for i in 0..len {
3627let index = crate::R_xlen_t::try_from(i).expect("a list index fits R_xlen_t");
3628match read(sexp.vector_elt(index)) {
3629Ok(value) => values.push(value),
3630Err(e) => errors.push(i, e),
3631 }
3632 }
3633errors.into_result(values)
3634}
36353636/// ` (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 {
3639let mut s = String::new();
3640push_element_positions(&mut s, std::iter::once(index));
3641s3642}
36433644// endregion
36453646#[cfg(test)]
3647mod tests;