1//! Error types for fallible [`IntoR`](crate::into_r::IntoR) conversions.
2//!
3//! [`IntoRError`] is returned by `try_into_sexp` when conversion fails
4//! (e.g., string exceeds R's `i32` length limit, or fields of a tuple fail).
56use crate::RValue;
7use crate::condition::{ConditionCall, ConditionData, ErrParts, RConditionData};
8use crate::from_r::BatchedErrors;
910/// Error returned by [`IntoR::try_into_sexp`](crate::into_r::IntoR::try_into_sexp)
11/// for types whose conversion to R can fail.
12///
13/// # Variants
14///
15/// - `StringTooLong`: a Rust string exceeds R's `i32` length limit (~2 GB)
16/// - `LengthOverflow`: a collection length exceeds R's `R_xlen_t` capacity
17/// - `Elements`: elements of a container failed to convert (a tuple's
18/// fields, the rows of a `Vec` of tuples), each with its own condition
19///
20/// It implements [`RConditionData`]. Returned from a `#[miniextendr]`
21/// function, an `Elements` error raises the batched message, the class every
22/// failing element shares (else none beyond `rust_error`) and `e$errors`,
23/// one entry per failing element: see [`FailedElements`].
24#[derive(#[automatically_derived]impl ::core::fmt::Debug for IntoRError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::StringTooLong { len: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"StringTooLong len", &__self_0),
Self::LengthOverflow { len: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"LengthOverflow len", &__self_0),
Self::Elements(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Elements", &__self_0),
}
}
}Debug, #[automatically_derived]impl ::core::clone::Clone for IntoRError {
#[inline]
fn clone(&self) -> Self {
match self {
Self::StringTooLong { len: __self_0 } =>
IntoRError::StringTooLong {
len: ::core::clone::Clone::clone(__self_0),
},
Self::LengthOverflow { len: __self_0 } =>
IntoRError::LengthOverflow {
len: ::core::clone::Clone::clone(__self_0),
},
Self::Elements(__self_0) =>
IntoRError::Elements(::core::clone::Clone::clone(__self_0)),
}
}
}Clone)]
25pub enum IntoRError {
26/// A string's byte length exceeds `i32::MAX`.
27StringTooLong {
28/// Actual byte length of the string.
29len: usize,
30 },
31/// A collection's element count exceeds the target R vector capacity.
32LengthOverflow {
33/// Actual element count.
34len: usize,
35 },
36/// Elements of a container failed to convert.
37Elements(FailedElements),
38}
3940impl std::fmt::Displayfor IntoRError {
41fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42match self {
43 IntoRError::StringTooLong { len } => {
44f.write_fmt(format_args!("string byte length {0} exceeds R\'s i32 limit ({1})",
len, i32::MAX))write!(
45f,
46"string byte length {} exceeds R's i32 limit ({})",
47 len,
48 i32::MAX
49 )50 }
51 IntoRError::LengthOverflow { len } => {
52f.write_fmt(format_args!("collection length {0} overflows R vector capacity",
len))write!(f, "collection length {} overflows R vector capacity", len)53 }
54 IntoRError::Elements(failed) => f.write_str(&failed.message),
55 }
56 }
57}
5859impl std::error::Errorfor IntoRError {}
6061/// The condition an `IntoRError` raises in R: its message; for `Elements`
62/// the shared class of the failing elements and their conditions as
63/// `e$errors`.
64impl RConditionDatafor IntoRError {
65fn message(&self) -> String {
66self.to_string()
67 }
6869fn class(&self) -> Vec<String> {
70match self {
71 IntoRError::Elements(failed) => failed.class.clone(),
72 IntoRError::StringTooLong { .. } | IntoRError::LengthOverflow { .. } => Vec::new(),
73 }
74 }
7576fn data(&self) -> Option<ConditionData> {
77match self {
78 IntoRError::Elements(failed) => Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(crate::condition::ERRORS_FIELD.to_owned(),
failed.errors_rvalue())]))vec![(
79crate::condition::ERRORS_FIELD.to_owned(),
80 failed.errors_rvalue(),
81 )]),
82 IntoRError::StringTooLong { .. } | IntoRError::LengthOverflow { .. } => None,
83 }
84 }
8586/// The `.mx_errors` field of `Elements` is the framework's own.
87fn __mx_keeps_internal_fields(&self) -> bool {
88true
89}
90}
9192/// The elements of a container whose conversion to R failed (a tuple's
93/// fields, the rows of a `Vec` of tuples, the elements of an `AsJsonVec`):
94/// the batched message, the class
95/// they share and each failing element's own condition with its position.
96///
97/// Raised in R (`kind = "result_err"`):
98///
99/// - the message names every failing position, in the grammar of every
100/// batched conversion: `map keys must be strings for R named lists
101/// (element 2)`;
102/// - the class vector is the one every failing element has, when they all
103/// have the same, so a handler for the element's class catches the
104/// container as it catches the element alone; when they differ (or have
105/// none) the error has only the `rust_error` classes;
106/// - `e$errors` is a list with one entry per failing element,
107/// `list(index = , condition = )`: `index` is its position, numbered as R
108/// counts (`2L` for a tuple's second field, `c(3L, 2L)` for the second
109/// field of a `Vec` of tuples' third row), and `condition` the condition
110/// the element raises as a return value of its own, with its classes,
111/// message and fields.
112///
113/// `e$errors` lists every failure. Only the message stops at the first ten,
114/// ending `; and N more`. The shared class is decided over every failure.
115#[derive(#[automatically_derived]impl ::core::fmt::Debug for FailedElements {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"FailedElements message class elements", &self.message,
&self.class, &&self.elements)
}
}Debug, #[automatically_derived]impl ::core::clone::Clone for FailedElements {
#[inline]
fn clone(&self) -> Self {
FailedElements {
message: ::core::clone::Clone::clone(&self.message),
class: ::core::clone::Clone::clone(&self.class),
elements: ::core::clone::Clone::clone(&self.elements),
}
}
}Clone)]
116pub struct FailedElements {
117 message: String,
118 class: Vec<String>,
119 elements: Vec<FailedElement>,
120}
121122impl FailedElements {
123/// The batched message, naming every failing position.
124pub fn message(&self) -> &str {
125&self.message
126 }
127128/// The classes every failing element shares; empty when they differ.
129pub fn class(&self) -> &[String] {
130&self.class
131 }
132133/// The listed failing elements, in the order they failed.
134pub fn elements(&self) -> &[FailedElement] {
135&self.elements
136 }
137138/// `e$errors` as the tagged values the R raise helper builds into
139 /// `list(index = , condition = )` entries.
140fn errors_rvalue(&self) -> RValue {
141 RValue::List(
142self.elements
143 .iter()
144 .map(|element| (None, element.entry_rvalue()))
145 .collect(),
146 )
147 }
148}
149150/// One failing element of a [`FailedElements`]: its position and the parts
151/// of its condition.
152#[derive(#[automatically_derived]impl ::core::fmt::Debug for FailedElement {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field5_finish(f,
"FailedElement index message class data call", &self.index,
&self.message, &self.class, &self.data, &&self.call)
}
}Debug, #[automatically_derived]impl ::core::clone::Clone for FailedElement {
#[inline]
fn clone(&self) -> Self {
FailedElement {
index: ::core::clone::Clone::clone(&self.index),
message: ::core::clone::Clone::clone(&self.message),
class: ::core::clone::Clone::clone(&self.class),
data: ::core::clone::Clone::clone(&self.data),
call: ::core::clone::Clone::clone(&self.call),
}
}
}Clone)]
153pub struct FailedElement {
154/// Position path, numbered as R counts (1-based).
155index: Vec<usize>,
156 message: String,
157 class: Vec<String>,
158 data: Option<ConditionData>,
159 call: ConditionCall,
160}
161162impl FailedElement {
163fn new(index: usize, parts: ErrParts) -> Self {
164FailedElement {
165 index: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[index + 1]))vec![index + 1],
166 message: parts.message,
167 class: parts.class,
168 data: parts.data,
169 call: parts.call,
170 }
171 }
172173/// The element's position, numbered as R counts: one number for a field
174 /// or an element, the row then the field for a `Vec` of tuples.
175pub fn index(&self) -> &[usize] {
176&self.index
177 }
178179/// The element's own message.
180pub fn message(&self) -> &str {
181&self.message
182 }
183184/// The element's own classes.
185pub fn class(&self) -> &[String] {
186&self.class
187 }
188189/// The element's own fields.
190pub fn data(&self) -> Option<&ConditionData> {
191self.data.as_ref()
192 }
193194/// `list(index = , condition = <tagged value>)`.
195fn entry_rvalue(&self) -> RValue {
196let parts = ErrParts {
197 message: self.message.clone(),
198 class: self.class.clone(),
199 data: self.data.clone(),
200 call: self.call,
201 };
202 RValue::List(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(Some("index".to_owned()), index_rvalue(&self.index)),
(Some("condition".to_owned()),
crate::condition::tagged_rvalue(crate::error_value::kind::RESULT_ERR,
parts))]))vec![
203 (Some("index".to_owned()), index_rvalue(&self.index)),
204 (
205Some("condition".to_owned()),
206crate::condition::tagged_rvalue(crate::error_value::kind::RESULT_ERR, parts),
207 ),
208 ])
209 }
210}
211212/// A position path as R numbers it: an integer vector, or a double vector
213/// for a position past R's integer range (a row of a long list).
214fn index_rvalue(index: &[usize]) -> RValue {
215match index216 .iter()
217 .map(|&position| i32::try_from(position).map(Some))
218 .collect::<Result<Vec<_>, _>>()
219 {
220Ok(positions) => RValue::Integer(positions),
221// Positions of an R long vector stay below 2^52, so a double holds
222 // them exactly.
223Err(_) => RValue::Double(index.iter().map(|&position| positionas f64).collect()),
224 }
225}
226227/// The failures of a container's elements, folded into one
228/// [`IntoRError::Elements`].
229///
230/// Each failure's message goes into a [`BatchedErrors`], so the message is
231/// the one every batched conversion writes (it lists the first
232/// [`BATCHED_ERROR_CAP`](crate::from_r::BATCHED_ERROR_CAP)). Every failure
233/// keeps its condition parts for `e$errors` and takes part in the shared
234/// class.
235#[derive(#[automatically_derived]impl ::core::default::Default for ElementFailures {
#[inline]
fn default() -> Self {
ElementFailures {
batch: ::core::default::Default::default(),
elements: ::core::default::Default::default(),
class: ::core::default::Default::default(),
}
}
}Default)]
236pub(crate) struct ElementFailures {
237 batch: BatchedErrors,
238 elements: Vec<FailedElement>,
239/// The class every failure so far has; `None` before the first, empty
240 /// once two differ.
241class: Option<Vec<String>>,
242}
243244impl ElementFailures {
245/// Record the failure of the element at 0-based `index`.
246#[track_caller]
247pub(crate) fn push<E: RConditionData + ?Sized>(&mut self, index: usize, error: &E) {
248self.share(error.class());
249let parts = crate::condition::into_r_err_parts(error);
250let reason = parts.message.clone();
251self.elements.push(FailedElement::new(index, parts));
252self.batch.push(index, || reason);
253 }
254255/// Record the failure of the row at 0-based `row`, itself a container
256 /// (a tuple): its failed elements are listed with the row in front of
257 /// their positions, its message is the row's reason.
258#[track_caller]
259pub(crate) fn push_row(&mut self, row: usize, error: IntoRError) {
260let IntoRError::Elements(failed) = errorelse {
261return self.push(row, &error);
262 };
263self.share(failed.class);
264self.elements
265 .extend(failed.elements.into_iter().map(|mut element| {
266element.index.insert(0, row + 1);
267element268 }));
269let message = failed.message;
270self.batch.push(row, || message);
271 }
272273/// Fold one failure's classes into the shared class.
274fn share(&mut self, class: Vec<String>) {
275match &mut self.class {
276None => self.class = Some(class),
277Some(shared) if *shared != class => shared.clear(),
278Some(_) => {}
279 }
280 }
281282/// Whether any failure has been recorded.
283pub(crate) fn is_empty(&self) -> bool {
284self.batch.is_empty()
285 }
286287/// The one error for every failure recorded.
288pub(crate) fn into_error(self) -> IntoRError {
289 IntoRError::Elements(FailedElements {
290 message: self.batch.element_message(),
291 class: self.class.unwrap_or_default(),
292 elements: self.elements,
293 })
294 }
295}
296297#[cfg(test)]
298mod tests;