Skip to main content

miniextendr_api/
into_r_error.rs

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).
5
6use crate::RValue;
7use crate::condition::{ConditionCall, ConditionData, ErrParts, RConditionData};
8use crate::from_r::BatchedErrors;
9
10/// 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`.
27    StringTooLong {
28        /// Actual byte length of the string.
29        len: usize,
30    },
31    /// A collection's element count exceeds the target R vector capacity.
32    LengthOverflow {
33        /// Actual element count.
34        len: usize,
35    },
36    /// Elements of a container failed to convert.
37    Elements(FailedElements),
38}
39
40impl std::fmt::Display for IntoRError {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            IntoRError::StringTooLong { len } => {
44                f.write_fmt(format_args!("string byte length {0} exceeds R\'s i32 limit ({1})",
        len, i32::MAX))write!(
45                    f,
46                    "string byte length {} exceeds R's i32 limit ({})",
47                    len,
48                    i32::MAX
49                )
50            }
51            IntoRError::LengthOverflow { len } => {
52                f.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}
58
59impl std::error::Error for IntoRError {}
60
61/// 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 RConditionData for IntoRError {
65    fn message(&self) -> String {
66        self.to_string()
67    }
68
69    fn class(&self) -> Vec<String> {
70        match self {
71            IntoRError::Elements(failed) => failed.class.clone(),
72            IntoRError::StringTooLong { .. } | IntoRError::LengthOverflow { .. } => Vec::new(),
73        }
74    }
75
76    fn data(&self) -> Option<ConditionData> {
77        match 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![(
79                crate::condition::ERRORS_FIELD.to_owned(),
80                failed.errors_rvalue(),
81            )]),
82            IntoRError::StringTooLong { .. } | IntoRError::LengthOverflow { .. } => None,
83        }
84    }
85
86    /// The `.mx_errors` field of `Elements` is the framework's own.
87    fn __mx_keeps_internal_fields(&self) -> bool {
88        true
89    }
90}
91
92/// 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}
121
122impl FailedElements {
123    /// The batched message, naming every failing position.
124    pub fn message(&self) -> &str {
125        &self.message
126    }
127
128    /// The classes every failing element shares; empty when they differ.
129    pub fn class(&self) -> &[String] {
130        &self.class
131    }
132
133    /// The listed failing elements, in the order they failed.
134    pub fn elements(&self) -> &[FailedElement] {
135        &self.elements
136    }
137
138    /// `e$errors` as the tagged values the R raise helper builds into
139    /// `list(index = , condition = )` entries.
140    fn errors_rvalue(&self) -> RValue {
141        RValue::List(
142            self.elements
143                .iter()
144                .map(|element| (None, element.entry_rvalue()))
145                .collect(),
146        )
147    }
148}
149
150/// 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).
155    index: Vec<usize>,
156    message: String,
157    class: Vec<String>,
158    data: Option<ConditionData>,
159    call: ConditionCall,
160}
161
162impl FailedElement {
163    fn new(index: usize, parts: ErrParts) -> Self {
164        FailedElement {
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    }
172
173    /// 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.
175    pub fn index(&self) -> &[usize] {
176        &self.index
177    }
178
179    /// The element's own message.
180    pub fn message(&self) -> &str {
181        &self.message
182    }
183
184    /// The element's own classes.
185    pub fn class(&self) -> &[String] {
186        &self.class
187    }
188
189    /// The element's own fields.
190    pub fn data(&self) -> Option<&ConditionData> {
191        self.data.as_ref()
192    }
193
194    /// `list(index = , condition = <tagged value>)`.
195    fn entry_rvalue(&self) -> RValue {
196        let 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            (
205                Some("condition".to_owned()),
206                crate::condition::tagged_rvalue(crate::error_value::kind::RESULT_ERR, parts),
207            ),
208        ])
209    }
210}
211
212/// 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 {
215    match index
216        .iter()
217        .map(|&position| i32::try_from(position).map(Some))
218        .collect::<Result<Vec<_>, _>>()
219    {
220        Ok(positions) => RValue::Integer(positions),
221        // Positions of an R long vector stay below 2^52, so a double holds
222        // them exactly.
223        Err(_) => RValue::Double(index.iter().map(|&position| position as f64).collect()),
224    }
225}
226
227/// 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.
241    class: Option<Vec<String>>,
242}
243
244impl ElementFailures {
245    /// Record the failure of the element at 0-based `index`.
246    #[track_caller]
247    pub(crate) fn push<E: RConditionData + ?Sized>(&mut self, index: usize, error: &E) {
248        self.share(error.class());
249        let parts = crate::condition::into_r_err_parts(error);
250        let reason = parts.message.clone();
251        self.elements.push(FailedElement::new(index, parts));
252        self.batch.push(index, || reason);
253    }
254
255    /// 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]
259    pub(crate) fn push_row(&mut self, row: usize, error: IntoRError) {
260        let IntoRError::Elements(failed) = error else {
261            return self.push(row, &error);
262        };
263        self.share(failed.class);
264        self.elements
265            .extend(failed.elements.into_iter().map(|mut element| {
266                element.index.insert(0, row + 1);
267                element
268            }));
269        let message = failed.message;
270        self.batch.push(row, || message);
271    }
272
273    /// Fold one failure's classes into the shared class.
274    fn share(&mut self, class: Vec<String>) {
275        match &mut self.class {
276            None => self.class = Some(class),
277            Some(shared) if *shared != class => shared.clear(),
278            Some(_) => {}
279        }
280    }
281
282    /// Whether any failure has been recorded.
283    pub(crate) fn is_empty(&self) -> bool {
284        self.batch.is_empty()
285    }
286
287    /// The one error for every failure recorded.
288    pub(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}
296
297#[cfg(test)]
298mod tests;