Skip to main content

miniextendr_api/
condition.rs

1//! Condition macros and signal enum for the Rust→R condition pipeline.
2//!
3//! This module provides two things:
4//!
5//! 1. **[`enum@RCondition`] enum** — the internal panic payload used by `error!()`,
6//!    `warning!()`, `message!()`, and `condition!()` macros. Caught by
7//!    [`crate::unwind_protect::with_r_unwind_protect`] before the generic
8//!    panic→error path, then forwarded to R as a structured condition with
9//!    `rust_*` class layering via
10//!    [`crate::error_value::make_rust_condition_value`].
11//!
12//! 2. **[`AsRError`] struct** — wraps any `E: std::error::Error` and
13//!    preserves the full error chain (cause/source) when converting to an R
14//!    error message. Use as the `Err` type in `Result` returns.
15//!
16//! # When to reach for what
17//!
18//! There are three Rust→R error-emission paths and they are not
19//! interchangeable. The crate-level rationale (why tagged-SEXP at all, what
20//! `error_in_r` defaults imply, and the `with_r_unwind_protect` leak) lives
21//! on [`crate::error_value`]; the practical picking-one summary:
22//!
23//! - **`panic!`** — escape hatch. Becomes class `c("rust_error",
24//!   "simpleError", "error", "condition")` with `kind = "panic"`. Use for
25//!   genuine bugs or impossible states. Cheapest in source; coarsest in R
26//!   (callers can only match `rust_error` / `error`, not a specific class).
27//! - **`error!` / `warning!` / `message!` / `condition!`** (this module) —
28//!   typed conditions. Same transport, but allow an optional `class =
29//!   "name"` so R-side `tryCatch` can route by class. `warning!` /
30//!   `message!` / `condition!` are the only way to emit non-error
31//!   conditions; `panic!` is always an error.
32//! - **`Result<T, E>` with [`AsRError<E>`]** — value-style propagation
33//!   through Rust code. Converts at the boundary; `kind = "result_err"`.
34//!   Best when the failure path is real-and-recoverable in Rust and the
35//!   error chain (`std::error::Error::source`) is worth preserving.
36//!
37//! `Rf_error` is *not* on this list. Direct `Rf_error` skips Rust
38//! destructors unconditionally and is forbidden by lint MXL300; see
39//! [`crate::error_value`] for the full reasoning.
40//!
41//! # Macro-vs-module name collision
42//!
43//! `#[macro_export]` puts each macro at the *crate root*, where `error!` and
44//! `condition!` collide with the same-named modules `pub mod error` and `pub
45//! mod condition`. The practical implication: `use miniextendr_api::{error,
46//! condition}` imports the *modules*, not the macros, and a subsequent
47//! `error!(...)` call fails to resolve.
48//!
49//! Workarounds, in rough order of ergonomics:
50//!
51//! 1. Invoke via fully-qualified path: `miniextendr_api::error!("...")`.
52//! 2. `use miniextendr_api as mx;` then `mx::error!("...")`.
53//! 3. `warning!` and `message!` have no module conflict — `use
54//!    miniextendr_api::{warning, message};` works directly.
55//!
56//! See the individual macro docs for the per-macro reminder.
57//!
58//! # Condition macros
59//!
60//! The four macros are the user-facing API for raising non-panic conditions from
61//! Rust. They ride the tagged-condition transport that every `#[miniextendr]`
62//! function uses:
63//!
64//! ```ignore
65//! use miniextendr_api::{error, warning, message, condition};
66//!
67//! #[miniextendr]
68//! fn demo_error() {
69//!     error!("something went wrong: {}", 42);
70//! }
71//!
72//! #[miniextendr]
73//! fn demo_warning() {
74//!     warning!("something looks suspicious");
75//! }
76//!
77//! #[miniextendr]
78//! fn demo_message() {
79//!     message!("progress: {} of {}", 1, 10);
80//! }
81//!
82//! #[miniextendr]
83//! fn demo_condition() {
84//!     condition!("a signallable condition");
85//! }
86//! ```
87//!
88//! Optional `class =` extension for programmatic catching:
89//!
90//! ```ignore
91//! #[miniextendr]
92//! fn typed_error(name: &str) {
93//!     error!(class = "my_error", "missing field: {name}");
94//! }
95//! ```
96//!
97//! ```r
98//! tryCatch(typed_error("x"), my_error = function(e) "caught!")
99//! # [1] "caught!"
100//! ```
101//!
102//! Optional `data =` extension attaches structured fields readable as
103//! `e$<name>` in handlers (rlang-`abort()`-style):
104//!
105//! ```ignore
106//! #[miniextendr]
107//! fn validate(value: i32) {
108//!     if !(0..=100).contains(&value) {
109//!         miniextendr_api::error!(
110//!             class = "validation_error",
111//!             data = [("value", value), ("min", 0), ("max", 100)],
112//!             "value {value} out of range"
113//!         );
114//!     }
115//! }
116//! ```
117//!
118//! ```r
119//! tryCatch(validate(150L), validation_error = function(e) c(e$value, e$min, e$max))
120//! # [1] 150   0 100
121//! ```
122//!
123//! Supported `data` value types (anything with `RValue: From<_>`): scalars and
124//! `Vec`s of `i32`, `f64`, `bool`, `String` / `&str`; their NA-aware `Option` /
125//! `Vec<Option<_>>` forms (`None` → R `NA`); the wide-integer ladder (`i64` /
126//! `u32`, narrowed to `integer(1)` when it fits, `double(1)` otherwise); and the
127//! [`RValue::debug`](crate::RValue::debug) escape hatch, which stringifies any
128//! `T: Debug`. For nested lists or complex/raw/NA-bearing values build an
129//! [`RValue`](crate::RValue) directly. The payload is built as a Send-safe owned
130//! value at the call site and materialised as R objects at the unwind
131//! boundary.
132//!
133//! Three `data =` grammars are accepted (see [`crate::error!`]):
134//! - single pair: `data = ("name", value)`
135//! - bracketed list: `data = [("a", v1), ("b", v2)]`
136//! - keyed builder sugar: `data = { value = 42, code = 7 }` (bare-ident keys)
137//!
138//! # `AsRError`
139//!
140//! ```ignore
141//! use miniextendr_api::condition::AsRError;
142//!
143//! #[miniextendr]
144//! fn parse_config(path: &str) -> Result<i32, AsRError<std::io::Error>> {
145//!     let content = std::fs::read_to_string(path).map_err(AsRError)?;
146//!     Ok(content.len() as i32)
147//! }
148//! ```
149
150// region: ConditionData — Send-safe owned condition-data payload
151
152/// Named condition-data payload: an ordered list of `(name, value)` pairs.
153///
154/// Produced by the macros' `data = ...` form and consumed by
155/// [`crate::error_value::make_rust_condition_value`]. Each value is an
156/// [`RValue`](crate::RValue) — an owned, `Send`, R-native value tree. Send-safe
157/// by construction (no live `SEXP`), so the payload can travel through
158/// `panic_any`, whose payload must be `Send`; the R objects are materialised
159/// on the main thread at the unwind boundary.
160///
161/// The macros accept any value with `RValue: From<_>` (scalars and `Vec`s of
162/// `i32` / `f64` / `bool` / `String` / `&str`; their NA-aware `Option` /
163/// `Vec<Option<_>>` forms; the `i64` / `u32` wide-integer ladder); a scalar
164/// `7i32` becomes `integer(1)` and a `Vec<i32>` becomes `integer(n)`. Any
165/// `T: Debug` rides along via [`RValue::debug`](crate::RValue::debug). For
166/// nested lists or complex/raw values build an [`RValue`](crate::RValue)
167/// directly.
168pub type ConditionData = Vec<(String, crate::RValue)>;
169
170// endregion
171
172// region: ConditionCall — whether a condition reports a call
173
174/// Whether a condition reports a call (`conditionCall()`): the per-condition
175/// equivalent of R's `warning(..., call. = FALSE)` / `stop(..., call. = FALSE)`.
176///
177/// Every condition a `#[miniextendr]` function raises carries the call its
178/// transport captured: the wrapper's call as written (or the caller's, under
179/// `call = caller`), `NULL` in ALTREP and connection callbacks. A condition
180/// about the data rather than the call opts out with [`ConditionCall::None`];
181/// its siblings from the same function keep their call.
182///
183/// Spellings: `call = none` first in [`crate::warning!`], [`crate::error!`],
184/// [`crate::condition!`] and the `defer_*!` macros;
185/// [`RError::without_call`]; `#[condition(call = none)]` on a
186/// `#[derive(RCondition)]` type or variant; or an
187/// [`RConditionData::call`] impl.
188///
189/// On the tagged condition value the choice is the `call` slot itself:
190/// `FALSE` for [`ConditionCall::None`], read back by the R helper (and by the
191/// trait-ABI re-panic, [`RCondition::from_tagged_sexp`]) as "no call".
192#[derive(#[automatically_derived]impl ::core::fmt::Debug for ConditionCall {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ConditionCall::Inherit => "Inherit",
                ConditionCall::None => "None",
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ConditionCall {
}
#[automatically_derived]impl ::core::clone::Clone for ConditionCall {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ConditionCall { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    ConditionCall {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ConditionCall {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ConditionCall { }Eq, #[automatically_derived]impl ::core::default::Default for ConditionCall {
    #[inline]
    fn default() -> Self { Self::Inherit }
}Default)]
193pub enum ConditionCall {
194    /// The call the transport captured (the default).
195    #[default]
196    Inherit,
197    /// No call: `conditionCall()` is `NULL` and the printed condition has no
198    /// `In f(...) :` prefix.
199    None,
200}
201
202impl ConditionCall {
203    /// `call` when the condition keeps its call, `None` otherwise: the call to
204    /// hand a transport that takes the R call object directly.
205    #[inline]
206    pub fn apply(self, call: Option<crate::SEXP>) -> Option<crate::SEXP> {
207        match self {
208            ConditionCall::Inherit => call,
209            ConditionCall::None => Option::None,
210        }
211    }
212}
213
214// endregion
215
216// region: RCondition enum — structured condition payload
217
218/// Owned payload for structured R conditions.
219///
220/// `#[derive(RCondition)]` gives a struct or enum a conversion into this
221/// payload. Its `#[condition(kind = warning)]` (or `error` / `message` /
222/// `condition`) chooses the signal; an enum variant can override the kind.
223/// Convert with `RCondition::from(value)`, then call [`defer`](Self::defer)
224/// to accompany a return value, or [`raise`](Self::raise) to leave Rust.
225///
226/// Raised by the `error!()`, `warning!()`, `message!()`, and `condition!()`
227/// macros via `std::panic::panic_any`. Caught by `with_r_unwind_protect`
228/// before the generic panic→string path and forwarded to R as a tagged SEXP
229/// with `rust_*` class layering. The `defer_*` family
230/// ([`crate::deferred_condition`]) queues the same payloads instead of
231/// panicking, so the call still returns its value.
232///
233/// Every variant carries the same four parts: the message, the user classes
234/// (prepended to the `rust_*` layering, empty for none), the optional `data`
235/// fields and the [`ConditionCall`] choice. All four are owned and `Send`, so
236/// the payload can travel through `panic_any`. Each variant is one kind of the
237/// tagged condition value ([`crate::error_value::kind`]).
238#[derive(#[automatically_derived]impl ::core::fmt::Debug for RCondition {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Error {
                message: __self_0,
                class: __self_1,
                data: __self_2,
                call: __self_3 } =>
                ::core::fmt::Formatter::debug_struct_field4_finish(f,
                    "Error message class data call", __self_0, __self_1,
                    __self_2, &__self_3),
            Self::Warning {
                message: __self_0,
                class: __self_1,
                data: __self_2,
                call: __self_3 } =>
                ::core::fmt::Formatter::debug_struct_field4_finish(f,
                    "Warning message class data call", __self_0, __self_1,
                    __self_2, &__self_3),
            Self::Message {
                message: __self_0,
                class: __self_1,
                data: __self_2,
                call: __self_3 } =>
                ::core::fmt::Formatter::debug_struct_field4_finish(f,
                    "Message message class data call", __self_0, __self_1,
                    __self_2, &__self_3),
            Self::Condition {
                message: __self_0,
                class: __self_1,
                data: __self_2,
                call: __self_3 } =>
                ::core::fmt::Formatter::debug_struct_field4_finish(f,
                    "Condition message class data call", __self_0, __self_1,
                    __self_2, &__self_3),
            Self::Conversion {
                message: __self_0,
                class: __self_1,
                data: __self_2,
                call: __self_3 } =>
                ::core::fmt::Formatter::debug_struct_field4_finish(f,
                    "Conversion message class data call", __self_0, __self_1,
                    __self_2, &__self_3),
        }
    }
}Debug, #[automatically_derived]impl ::core::clone::Clone for RCondition {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::Error {
                message: __self_0,
                class: __self_1,
                data: __self_2,
                call: __self_3 } =>
                RCondition::Error {
                    message: ::core::clone::Clone::clone(__self_0),
                    class: ::core::clone::Clone::clone(__self_1),
                    data: ::core::clone::Clone::clone(__self_2),
                    call: ::core::clone::Clone::clone(__self_3),
                },
            Self::Warning {
                message: __self_0,
                class: __self_1,
                data: __self_2,
                call: __self_3 } =>
                RCondition::Warning {
                    message: ::core::clone::Clone::clone(__self_0),
                    class: ::core::clone::Clone::clone(__self_1),
                    data: ::core::clone::Clone::clone(__self_2),
                    call: ::core::clone::Clone::clone(__self_3),
                },
            Self::Message {
                message: __self_0,
                class: __self_1,
                data: __self_2,
                call: __self_3 } =>
                RCondition::Message {
                    message: ::core::clone::Clone::clone(__self_0),
                    class: ::core::clone::Clone::clone(__self_1),
                    data: ::core::clone::Clone::clone(__self_2),
                    call: ::core::clone::Clone::clone(__self_3),
                },
            Self::Condition {
                message: __self_0,
                class: __self_1,
                data: __self_2,
                call: __self_3 } =>
                RCondition::Condition {
                    message: ::core::clone::Clone::clone(__self_0),
                    class: ::core::clone::Clone::clone(__self_1),
                    data: ::core::clone::Clone::clone(__self_2),
                    call: ::core::clone::Clone::clone(__self_3),
                },
            Self::Conversion {
                message: __self_0,
                class: __self_1,
                data: __self_2,
                call: __self_3 } =>
                RCondition::Conversion {
                    message: ::core::clone::Clone::clone(__self_0),
                    class: ::core::clone::Clone::clone(__self_1),
                    data: ::core::clone::Clone::clone(__self_2),
                    call: ::core::clone::Clone::clone(__self_3),
                },
        }
    }
}Clone)]
239pub enum RCondition {
240    /// Raised by `error!(...)` / `error!(class = "...", ...)`, and by the
241    /// `Result<T, E>` Err arm once reconstructed across a package boundary.
242    Error {
243        /// Human-readable condition message.
244        message: String,
245        /// User classes, most specific first, before the framework's classes.
246        class: Vec<String>,
247        /// Named fields attached to the R condition.
248        data: Option<ConditionData>,
249        /// Call attribution policy; messages always omit the call.
250        call: ConditionCall,
251    },
252    /// Raised by `warning!(...)` / `warning!(class = "...", ...)`.
253    Warning {
254        /// Human-readable condition message.
255        message: String,
256        /// User classes, most specific first, before the framework's classes.
257        class: Vec<String>,
258        /// Named fields attached to the R condition.
259        data: Option<ConditionData>,
260        /// Call attribution policy; messages always omit the call.
261        call: ConditionCall,
262    },
263    /// Raised by `message!(...)`, and queued by [`crate::defer_message()`]. Only
264    /// the typed-payload path fills `class` (the macro has no `class =` form);
265    /// the R helper layers it in front of `rust_message` like the other kinds.
266    /// A message never reports a call, whatever `call` says.
267    Message {
268        /// Human-readable condition message.
269        message: String,
270        /// User classes, most specific first, before the framework's classes.
271        class: Vec<String>,
272        /// Named fields attached to the R condition.
273        data: Option<ConditionData>,
274        /// Call attribution policy; messages always omit the call.
275        call: ConditionCall,
276    },
277    /// Raised by `condition!(...)` / `condition!(class = "...", ...)`.
278    Condition {
279        /// Human-readable condition message.
280        message: String,
281        /// User classes, most specific first, before the framework's classes.
282        class: Vec<String>,
283        /// Named fields attached to the R condition.
284        data: Option<ConditionData>,
285        /// Call attribution policy; messages always omit the call.
286        call: ConditionCall,
287    },
288    /// An argument error, `kind = "conversion"`: raised by
289    /// [`crate::arg_error!`] / [`ArgError::raise`] (built by
290    /// [`RCondition::arg_error`]), and a failed argument conversion once
291    /// reconstructed across a package boundary.
292    Conversion {
293        /// Human-readable condition message.
294        message: String,
295        /// User classes, most specific first, before the framework's classes.
296        class: Vec<String>,
297        /// Named fields attached to the R condition.
298        data: Option<ConditionData>,
299        /// Call attribution policy; messages always omit the call.
300        call: ConditionCall,
301    },
302}
303
304impl RCondition {
305    /// Leave the current Rust body with this condition.
306    ///
307    /// The enclosing miniextendr guard forwards it to R with its kind and
308    /// metadata intact. Like `warning!`, raising a warning still exits Rust:
309    /// muffling it in R does not resume this Rust body. Use [`defer`](Self::defer)
310    /// to keep computing and return a value.
311    pub fn raise(self) -> ! {
312        std::panic::panic_any(self)
313    }
314
315    /// Queue this condition until the current guarded call returns.
316    ///
317    /// Preserves its declared kind, classes, fields and call policy, including
318    /// for a mixed-kind enum. Errors queued here stop R at that boundary.
319    ///
320    /// From another thread it goes to R's main thread over a channel; see
321    /// [Threads and boundaries](crate::deferred_condition#threads-and-boundaries).
322    pub fn defer(self) {
323        crate::deferred_condition::defer(self);
324    }
325
326    /// The error condition of a classed error value: its
327    /// [`message`](RConditionData::message), [`class`](RConditionData::class),
328    /// [`data`](RConditionData::data) fields and
329    /// [`call`](RConditionData::call) choice, as a `Result` return raises it.
330    ///
331    /// For raising a typed error by hand where no `Result` reaches the
332    /// generated code, such as a helper deep inside a body:
333    ///
334    /// ```ignore
335    /// let model = load(path).unwrap_or_else(|e| RCondition::from_data(&e).raise());
336    /// ```
337    ///
338    /// Raised, it is `kind = "error"`; returned as `Err` it would be
339    /// `"result_err"`. Both are R errors with the same classes and fields.
340    /// A `data()` field with a reserved name (`message`, `call`, `kind`)
341    /// panics here, as in a generated `Err` arm.
342    #[track_caller]
343    pub fn from_data<E: RConditionData + ?Sized>(e: &E) -> RCondition {
344        RCondition::Error {
345            message: e.message(),
346            class: e.class(),
347            data: check_err_fields(e.data(), e.__mx_keeps_internal_fields()),
348            call: e.call(),
349        }
350    }
351
352    /// Split into the kind (one of [`crate::error_value::kind`]) and the
353    /// [`ErrParts`] (message, class, data, call choice) that
354    /// [`crate::error_value::condition_parts_value`] builds the tagged value
355    /// from.
356    #[doc(hidden)]
357    pub fn into_parts(self) -> (&'static str, ErrParts) {
358        use crate::error_value::kind;
359        let (kind, message, class, data, call) = match self {
360            RCondition::Error {
361                message,
362                class,
363                data,
364                call,
365            } => (kind::ERROR, message, class, data, call),
366            RCondition::Warning {
367                message,
368                class,
369                data,
370                call,
371            } => (kind::WARNING, message, class, data, call),
372            RCondition::Message {
373                message,
374                class,
375                data,
376                call,
377            } => (kind::MESSAGE, message, class, data, call),
378            RCondition::Condition {
379                message,
380                class,
381                data,
382                call,
383            } => (kind::CONDITION, message, class, data, call),
384            RCondition::Conversion {
385                message,
386                class,
387                data,
388                call,
389            } => (kind::CONVERSION, message, class, data, call),
390        };
391        (
392            kind,
393            ErrParts {
394                message,
395                class,
396                data,
397                call,
398            },
399        )
400    }
401
402    /// The condition message, as `conditionMessage()` would read it in R.
403    ///
404    /// Use it on a condition [`catch_condition`] caught or
405    /// [`capture`](crate::deferred_condition::capture) collected, for example
406    /// to put a cause's text into a new message.
407    pub fn message(&self) -> &str {
408        match self {
409            RCondition::Error { message, .. }
410            | RCondition::Warning { message, .. }
411            | RCondition::Message { message, .. }
412            | RCondition::Condition { message, .. }
413            | RCondition::Conversion { message, .. } => message,
414        }
415    }
416
417    /// This condition with `parent` as its cause, as `rlang::abort(parent = )`
418    /// chains conditions.
419    ///
420    /// R gets the cause as the field `e$parent`: a condition object with its
421    /// own classes, message and fields (and its own parent, if it has one),
422    /// built like the condition itself but not signalled. The cause's classes
423    /// stay out of this condition's class vector, so a handler written for
424    /// the cause's class does not catch this condition; code that wants the
425    /// cause branches on it: `inherits(e$parent, "pkg_error_config")`.
426    ///
427    /// The cause reports the same call as this condition, or none when it was
428    /// raised with `call = none`. A second `with_parent` replaces the first,
429    /// and the cause replaces a `data` field this condition names `parent`.
430    ///
431    /// ```ignore
432    /// match catch_condition(|| load_config(path)) {
433    ///     Ok(value) => value,
434    ///     Err(cause) => RCondition::Error {
435    ///         message: format!("could not load the model: {}", cause.message()),
436    ///         class: vec!["pkg_error_load".into()],
437    ///         data: None,
438    ///         call: ConditionCall::Inherit,
439    ///     }
440    ///     .with_parent(cause)
441    ///     .raise(),
442    /// }
443    /// ```
444    pub fn with_parent(mut self, parent: RCondition) -> Self {
445        let encoded = parent.into_tagged_rvalue();
446        let data = match &mut self {
447            RCondition::Error { data, .. }
448            | RCondition::Warning { data, .. }
449            | RCondition::Message { data, .. }
450            | RCondition::Condition { data, .. }
451            | RCondition::Conversion { data, .. } => data,
452        };
453        let fields = data.get_or_insert_with(Vec::new);
454        fields.retain(|(name, _)| name != PARENT_FIELD);
455        fields.push((PARENT_FIELD.to_owned(), encoded));
456        self
457    }
458
459    /// The condition as the tagged value the R raise helper reads (`error`,
460    /// `kind`, `class`, `call`, `data`), in [`RValue`](crate::RValue) form so
461    /// it can travel inside another condition's data ([`Self::with_parent`]).
462    fn into_tagged_rvalue(self) -> crate::RValue {
463        let (kind, parts) = self.into_parts();
464        tagged_rvalue(kind, parts)
465    }
466
467    /// Which call the condition reports when R raises it: see
468    /// [`ConditionCall`].
469    pub fn call(&self) -> ConditionCall {
470        match self {
471            RCondition::Error { call, .. }
472            | RCondition::Warning { call, .. }
473            | RCondition::Message { call, .. }
474            | RCondition::Condition { call, .. }
475            | RCondition::Conversion { call, .. } => *call,
476        }
477    }
478
479    /// The user classes and the fields, whatever the variant.
480    fn class_and_data(&self) -> (&[String], &Option<ConditionData>) {
481        match self {
482            RCondition::Error { class, data, .. }
483            | RCondition::Warning { class, data, .. }
484            | RCondition::Message { class, data, .. }
485            | RCondition::Condition { class, data, .. }
486            | RCondition::Conversion { class, data, .. } => (class, data),
487        }
488    }
489
490    /// The payload of [`crate::arg_error!`] and [`ArgError::raise`]: the
491    /// argument error of parameter `param` (its R name) with `message`.
492    ///
493    /// `kind = "conversion"`, `e$param` as the only data field, and the class
494    /// [`CONVERSION_ERROR_CLASS_MARKER`], which the generated R replaces with
495    /// the crate's `conversion_error_class`: the condition the wrapper's own
496    /// argument checks raise (`.miniextendr_arg_error`).
497    #[doc(hidden)]
498    pub fn arg_error(param: impl Into<String>, message: String, call: ConditionCall) -> Self {
499        RCondition::Conversion {
500            message,
501            class: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [CONVERSION_ERROR_CLASS_MARKER.to_string()]))vec![CONVERSION_ERROR_CLASS_MARKER.to_string()],
502            data: Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(CONVERSION_PARAM_FIELD.to_string(),
                    crate::RValue::from(param.into()))]))vec![(
503                CONVERSION_PARAM_FIELD.to_string(),
504                crate::RValue::from(param.into()),
505            )]),
506            call,
507        }
508    }
509}
510
511/// The class that stands for the crate's `conversion_error_class` in a tagged
512/// condition value (#1740).
513///
514/// A `macro_rules!` macro cannot read `[package.metadata.miniextendr]`, so
515/// [`crate::arg_error!`] cannot name the crate's classes the way the
516/// generated conversion arms do. It writes this class instead, and the
517/// generated R wrapper's `.miniextendr_raise_condition` replaces it with
518/// `.miniextendr_conversion_error_class`, the binding its own argument checks
519/// read. The string is that binding's name. Where no generated wrapper raises
520/// the condition (a raising guard: an ALTREP `RUnwind` callback,
521/// [`crate::unwind_protect::with_r_unwind_protect_or_raise`]) Rust replaces it
522/// with the classes `miniextendr_init!` registered for the package
523/// ([`resolve_conversion_error_class_marker`]). So does a trait-ABI shim
524/// ([`crate::unwind_protect::with_r_unwind_protect_shim`]): the condition is
525/// raised by another package's wrapper, and takes the implementing package's
526/// classes, as from that package's own wrapper.
527#[doc(hidden)]
528pub const CONVERSION_ERROR_CLASS_MARKER: &str = ".miniextendr_conversion_error_class";
529
530/// `class` with [`CONVERSION_ERROR_CLASS_MARKER`] replaced by `crate_classes`,
531/// in place, as the generated `.miniextendr_raise_condition` replaces it in R.
532/// A raising guard has no generated R to do it, so it calls this with
533/// [`crate_conversion_error_class`].
534pub(crate) fn resolve_conversion_error_class_marker(
535    class: Vec<String>,
536    crate_classes: &[&str],
537) -> Vec<String> {
538    let mut resolved = Vec::with_capacity(class.len() + crate_classes.len());
539    for c in class {
540        if c == CONVERSION_ERROR_CLASS_MARKER {
541            resolved.extend(crate_classes.iter().map(|&k| k.to_string()));
542        } else {
543            resolved.push(c);
544        }
545    }
546    resolved
547}
548
549/// The package crate's `conversion_error_class`, from the entry
550/// `miniextendr_init!` registers in
551/// [`MX_CONVERSION_ERROR_CLASS`](crate::registry::MX_CONVERSION_ERROR_CLASS)
552/// (each package links its own copy of this crate, so it is that package's),
553/// or on wasm32 from the `wasm_registry.rs` snapshot (#1768). Empty when the
554/// crate sets none.
555pub(crate) fn crate_conversion_error_class() -> &'static [&'static str] {
556    crate::registry::conversion_error_class()
557}
558
559/// Run `f`, returning a condition raised inside it as `Err` instead of
560/// letting it reach R; any other unwind carries on.
561///
562/// For a body that turns another function's failure into its own result: a
563/// refusal that names the reason, a fallback, a retry.
564///
565/// ```ignore
566/// use miniextendr_api::condition::catch_condition;
567///
568/// match catch_condition(|| load_config(path)) {
569///     Ok(object) => object,
570///     Err(cause) => error!(
571///         class = "pkg_error_load",
572///         data = ("cause", cause.message().to_string()),
573///         "cannot load the model: {}", cause.message()
574///     ),
575/// }
576/// ```
577///
578/// **Caught:** every [`RCondition`](enum@RCondition) payload, with its kind, classes, data
579/// and call choice: [`error!`](crate::error!) / [`rust_error!`](crate::rust_error!),
580/// [`warning!`](crate::warning!), [`message!`](crate::message!),
581/// [`condition!`](crate::condition!), [`RCondition::raise`], the argument and
582/// conversion errors ([`RCondition::arg_error`]) and the `ExternalPtr` type
583/// errors. An `Err` can be raised again with [`RCondition::raise`] or queued
584/// with [`RCondition::defer`].
585///
586/// **Resumed** unchanged, with [`std::panic::resume_unwind`]:
587/// - an R error, interrupt or other R exit crossing the Rust frames (R code
588///   run through [`with_r_unwind_protect`](crate::unwind_protect::with_r_unwind_protect)
589///   or [`eval_with_handlers`](crate::expression::eval_with_handlers)), so
590///   R carries on to the context it was jumping to;
591/// - a plain `panic!()` or any other payload, which still becomes an R error
592///   at the boundary, with its source location.
593///
594/// Use [`try_eval_with_handlers`](crate::expression::try_eval_with_handlers)
595/// to get an R error back as a value.
596///
597/// Deferred conditions queued inside `f` stay queued (see
598/// [`deferred_condition::capture`](crate::deferred_condition::capture)). A
599/// caught raise still runs the panic hook: with `MINIEXTENDR_BACKTRACE=true`
600/// it prints the panic to stderr.
601pub fn catch_condition<T>(f: impl FnOnce() -> T) -> Result<T, RCondition> {
602    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
603        Ok(value) => Ok(value),
604        Err(payload) => match payload.downcast::<RCondition>() {
605            Ok(condition) => Err(*condition),
606            Err(payload) => std::panic::resume_unwind(payload),
607        },
608    }
609}
610
611/// A condition of `kind` as the tagged value the R raise helper reads
612/// (`error`, `kind`, `class`, `call`, `data`), in [`RValue`](crate::RValue)
613/// form, so it can travel inside another condition's data: a cause
614/// ([`RCondition::with_parent`], `e$parent`) or a failed element
615/// ([`IntoRError::Elements`](crate::into_r_error::IntoRError::Elements),
616/// `e$errors`).
617pub(crate) fn tagged_rvalue(kind: &str, parts: ErrParts) -> crate::RValue {
618    use crate::RValue;
619    let text = |value: String| RValue::Character(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Some(value)]))vec![Some(value)]);
620    let class = if parts.class.is_empty() {
621        RValue::Null
622    } else {
623        RValue::Character(parts.class.into_iter().map(Some).collect())
624    };
625    let call = match parts.call {
626        ConditionCall::Inherit => RValue::Null,
627        ConditionCall::None => RValue::Logical(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Some(false)]))vec![Some(false)]),
628    };
629    let data = parts.data.map_or(RValue::Null, |fields| {
630        RValue::List(
631            fields
632                .into_iter()
633                .map(|(name, value)| (Some(name), value))
634                .collect(),
635        )
636    });
637    RValue::List(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(Some("error".to_owned()), text(parts.message)),
                (Some("kind".to_owned()), text(kind.to_owned())),
                (Some("class".to_owned()), class),
                (Some("call".to_owned()), call),
                (Some("data".to_owned()), data)]))vec![
638        (Some("error".to_owned()), text(parts.message)),
639        (Some("kind".to_owned()), text(kind.to_owned())),
640        (Some("class".to_owned()), class),
641        (Some("call".to_owned()), call),
642        (Some("data".to_owned()), data),
643    ])
644}
645
646// endregion
647
648// region: Macros
649
650/// Internal: one condition-data field name, validated against the reserved
651/// slots. Not part of the public API.
652///
653/// - `lit "name"` / `ident name`: the name is a literal, so the reserved-name
654///   check runs at compile time (`const` assertion) and the field costs one
655///   `to_string()` at runtime.
656/// - `expr <e>`: a computed name; checked at runtime by
657///   [`crate::condition::check_condition_field_name`].
658#[doc(hidden)]
659#[macro_export]
660macro_rules! __mx_condition_field_name {
661    (lit $name:literal) => {{
662        const _: () = ::core::assert!(
663            !$crate::condition::is_reserved_condition_field($name),
664            "condition data field name is reserved: `message`, `call` and `kind` are the condition's own slots, and `.mx_parent` and `.mx_errors` carry its parent and its failed elements; rename the field"
665        );
666        ($name).to_string()
667    }};
668    (ident $name:ident) => {{
669        const _: () = ::core::assert!(
670            !$crate::condition::is_reserved_condition_field(::core::stringify!($name)),
671            "condition data field name is reserved: `message`, `call` and `kind` are the condition's own slots, and `.mx_parent` and `.mx_errors` carry its parent and its failed elements; rename the field"
672        );
673        ::core::stringify!($name).to_string()
674    }};
675    (expr $name:expr) => {
676        $crate::condition::check_condition_field_name(($name).to_string())
677    };
678}
679
680/// Internal: one `(name, value)` pair of a bracketed `data = [...]` list; the
681/// name goes through the reserved-slot check (compile time for literals).
682#[doc(hidden)]
683#[macro_export]
684macro_rules! __mx_condition_pair {
685    (($name:literal, $value:expr $(,)?)) => {
686        ($crate::__mx_condition_field_name!(lit $name), $crate::RValue::from($value))
687    };
688    (($name:expr, $value:expr $(,)?)) => {
689        ($crate::__mx_condition_field_name!(expr $name), $crate::RValue::from($value))
690    };
691}
692
693/// Internal: normalise a macro `data = ...` argument into
694/// `Option<ConditionData>`. Not part of the public API.
695///
696/// Three forms are accepted:
697/// - a single pair: `("name", value)`
698/// - a bracketed list of pairs: `[("a", v1), ("b", v2)]`
699/// - keyed builder sugar: `{ name = value, other = value }` — the field name is
700///   a bare identifier (stringified by the macro), so `{ value = 42, code = 7 }`
701///   is shorthand for `[("value", 42), ("code", 7)]`.
702///
703/// Each `value` is converted via `RValue::from`, so any type with an `RValue`
704/// `From` impl (the scalar/vector/`Option`/wide-integer set, and tuples of
705/// those as unnamed lists) works without ceremony.
706///
707/// Field names are checked against the condition's own slots (`message` /
708/// `call` / `kind`): at compile time when the name is a literal or bare
709/// identifier, at runtime otherwise.
710#[doc(hidden)]
711#[macro_export]
712macro_rules! __mx_condition_data {
713    (($name:literal, $value:expr $(,)?)) => {
714        ::std::option::Option::Some(::std::vec![(
715            $crate::__mx_condition_field_name!(lit $name),
716            $crate::RValue::from($value),
717        )])
718    };
719    (($name:expr, $value:expr $(,)?)) => {
720        ::std::option::Option::Some(::std::vec![(
721            $crate::__mx_condition_field_name!(expr $name),
722            $crate::RValue::from($value),
723        )])
724    };
725    ([ $($pair:tt),* $(,)? ]) => {
726        ::std::option::Option::Some(::std::vec![
727            $( $crate::__mx_condition_pair!($pair), )*
728        ])
729    };
730    ({ $($name:ident = $value:expr),* $(,)? }) => {
731        ::std::option::Option::Some(::std::vec![
732            $(
733                (
734                    $crate::__mx_condition_field_name!(ident $name),
735                    $crate::RValue::from($value),
736                ),
737            )*
738        ])
739    };
740}
741
742/// Internal: parse the shared option grid of `error!` / `warning!` /
743/// `condition!` and the `defer_*!` macros into `(call, class, data, message)`.
744/// Not part of the public API.
745///
746/// Accepted orders (every part optional except the message):
747/// `call = none`, then `class = ..`, then `data = ..`, then the `format!`
748/// arguments. `class` takes anything implementing
749/// [`crate::condition::ConditionClass`] (one string or several). A `call`
750/// other than `none`, or one after `class` / `data`, is a compile error: a
751/// `format!` string must start with a literal, so `call` as the first token is
752/// never a message.
753///
754/// ```compile_fail
755/// # use miniextendr_api as mx;
756/// # fn f() {
757/// mx::warning!(call = wrapper, "no such call option");
758/// # }
759/// ```
760///
761/// ```compile_fail
762/// # use miniextendr_api as mx;
763/// # fn f() {
764/// mx::warning!(class = "pkg_warning", call = none, "`call` goes first");
765/// # }
766/// ```
767///
768/// ```
769/// # use miniextendr_api as mx;
770/// # fn f() {
771/// mx::warning!(call = none, class = "pkg_warning", data = { n = 1 }, "plain");
772/// # }
773/// ```
774#[doc(hidden)]
775#[macro_export]
776macro_rules! __mx_condition_parts {
777    // The option grid after the `call` choice: `(class, data, message)`.
778    (@options class = $class:expr, call $($rest:tt)*) => {
779        $crate::__mx_condition_parts!(@misplaced_call)
780    };
781    (@options class = $class:expr, data = $data:tt, call $($rest:tt)*) => {
782        $crate::__mx_condition_parts!(@misplaced_call)
783    };
784    (@options data = $data:tt, call $($rest:tt)*) => {
785        $crate::__mx_condition_parts!(@misplaced_call)
786    };
787    (@options class = $class:expr, data = $data:tt, $($arg:tt)*) => {
788        (
789            $crate::condition::ConditionClass::into_condition_class($class),
790            $crate::__mx_condition_data!($data),
791            ::std::format!($($arg)*),
792        )
793    };
794    (@options data = $data:tt, $($arg:tt)*) => {
795        (
796            ::std::vec::Vec::<::std::string::String>::new(),
797            $crate::__mx_condition_data!($data),
798            ::std::format!($($arg)*),
799        )
800    };
801    (@options class = $class:expr, $($arg:tt)*) => {
802        (
803            $crate::condition::ConditionClass::into_condition_class($class),
804            ::std::option::Option::<$crate::condition::ConditionData>::None,
805            ::std::format!($($arg)*),
806        )
807    };
808    (@options $($arg:tt)*) => {
809        (
810            ::std::vec::Vec::<::std::string::String>::new(),
811            ::std::option::Option::<$crate::condition::ConditionData>::None,
812            ::std::format!($($arg)*),
813        )
814    };
815    (@options call $($rest:tt)*) => {
816        ::core::compile_error!("condition macros: `call = none` is given twice")
817    };
818    (@misplaced_call) => {
819        ::core::compile_error!(
820            "condition macros: `call = none` comes first, before `class = ...` and `data = ...`: \
821             `warning!(call = none, class = \"...\", \"...\")`"
822        )
823    };
824    // Entry: the optional `call = none`, then the option grid.
825    (call = none, $($rest:tt)+) => {{
826        let (__mx_class, __mx_data, __mx_message) =
827            $crate::__mx_condition_parts!(@options $($rest)+);
828        (
829            $crate::condition::ConditionCall::None,
830            __mx_class,
831            __mx_data,
832            __mx_message,
833        )
834    }};
835    (call $($rest:tt)*) => {
836        ::core::compile_error!(
837            "condition macros: the only call option is `call = none` (no call, like R's \
838             `call. = FALSE`), and it comes first, followed by a comma: \
839             `warning!(call = none, \"...\")`"
840        )
841    };
842    ($($rest:tt)*) => {{
843        let (__mx_class, __mx_data, __mx_message) =
844            $crate::__mx_condition_parts!(@options $($rest)*);
845        (
846            $crate::condition::ConditionCall::Inherit,
847            __mx_class,
848            __mx_data,
849            __mx_message,
850        )
851    }};
852}
853
854/// Raise an R error from Rust with `rust_error` class layering.
855///
856/// Rides the tagged-condition transport that every `#[miniextendr]` function uses.
857/// The raised condition has class `c("rust_error", "simpleError", "error", "condition")`.
858///
859/// An optional `class = "name"` form prepends a custom class for programmatic catching:
860/// `c("name", "rust_error", "simpleError", "error", "condition")`. `class` also
861/// takes a vector (`class = ["pkg_error_missing_field", "pkg_error"]`, or any
862/// [`ConditionClass`] value) so handlers can catch the family or the member.
863///
864/// The framework layers (`rust_error`, `simpleError`, `error`, `condition`)
865/// always follow the user classes; no option leaves them out. Handlers and
866/// `inherits()` see the user classes as on an R `errorCondition()`; a test
867/// that compares the whole class vector with an R implementation's compares
868/// the leading classes instead.
869///
870/// # Structured `data = ...` payloads
871///
872/// An optional `data = ...` form (after `class`, before the message) attaches
873/// named fields to the condition object, rlang-`abort()`-style. Handlers read
874/// them as `e$<name>` instead of parsing the message string:
875///
876/// ```ignore
877/// // Single field:
878/// mx::error!(class = "range_error", data = ("value", value), "value {value} out of range");
879///
880/// // Multiple fields (bracketed list of pairs):
881/// mx::error!(
882///     class = "validation_error",
883///     data = [("value", value), ("min", 0), ("max", 100)],
884///     "value {value} out of range"
885/// );
886///
887/// // Keyed builder sugar (bare-ident keys, stringified by the macro):
888/// mx::error!(
889///     class = "validation_error",
890///     data = { value = value, min = 0, max = 100 },
891///     "value {value} out of range"
892/// );
893/// ```
894///
895/// ```r
896/// tryCatch(validate(150L), validation_error = function(e) c(e$value, e$min, e$max))
897/// # [1] 150   0 100
898/// ```
899///
900/// Argument order is fixed: `call = none` (optional), then `class = ...`
901/// (optional), then `data = ...` (optional), then the format message.
902///
903/// Field names `message`, `call` and `kind` are the condition's own slots and
904/// are rejected (at compile time for literal / bare-identifier names, at
905/// runtime otherwise); give the field another name (`rule` instead of `kind`,
906/// say). A downstream error type with such a field renames it where the
907/// payload is built (`#[serde(rename)]`, a different key).
908///
909/// **Supported value types**: scalars and `Vec`s of `i32`, `f64`, `bool`, and
910/// `String` (plus `&str` / `Vec<&str>`, converted to owned); their NA-aware
911/// `Option` / `Vec<Option<_>>` forms (→ R `NA`); the wide-integer ladder (`i64`
912/// / `u32`); and the [`RValue::debug`](crate::RValue::debug) escape hatch for
913/// any `T: Debug`. The payload is owned — it travels through `panic_any`, so
914/// live `SEXP`s cannot ride along; the R objects are materialised on the main
915/// thread at the unwind boundary. For nested lists or complex/raw values build an
916/// [`RValue`](crate::RValue) directly.
917///
918/// # Conditions without a call
919///
920/// A leading `call = none` raises the condition with no call, like R's
921/// `stop(..., call. = FALSE)`: `conditionCall(e)` is `NULL` and the error
922/// prints as `Error: <message>` instead of `Error in f(...) : <message>`. Use
923/// it for a condition about the data rather than about the call. Classes and
924/// `data` are unchanged:
925///
926/// ```ignore
927/// mx::error!(call = none, class = "pkg_bad_row", data = { row = row }, "row {row} is malformed");
928/// ```
929///
930/// The same marker exists as [`RError::without_call`] for `Result` errors and
931/// as `#[condition(call = none)]` on a `#[derive(RCondition)]` type or
932/// variant; see [`ConditionCall`].
933///
934/// # See also
935///
936/// - [`crate::warning!`] / [`crate::message!`] / [`crate::condition!`] — the
937///   non-error sibling kinds (warning continues execution; message is muffled
938///   by `suppressMessages`; condition is silent without a handler).
939/// - [`std::panic!`] — escape hatch with the same `rust_error` class layering
940///   but no custom-class slot. Use for true bugs / impossible states; reach for
941///   `error!` when callers might want to route by class.
942/// - [`AsRError`] — wraps `Result<_, E: std::error::Error>` for value-style
943///   propagation through Rust code; converts at the boundary.
944/// - [`crate::error_value`] — module-level rationale for the tagged-SEXP
945///   transport and the `error_in_r` default.
946///
947/// **Name-collision note.** Because `pub mod error` exists at the crate root,
948/// `use miniextendr_api::error` imports the module rather than this macro, and
949/// glob imports (`use miniextendr_api::*;`) hit the same shadow. Prefer the
950/// collision-free alias [`crate::rust_error!`], which has the identical
951/// expansion; otherwise invoke via `miniextendr_api::error!(...)` (fully
952/// qualified) or `mx::error!(...)` after `use miniextendr_api as mx;`.
953///
954/// # Examples
955///
956/// ```ignore
957/// use miniextendr_api as mx;
958///
959/// #[miniextendr]
960/// fn fail() {
961///     mx::error!("something went wrong: {}", 42);
962/// }
963///
964/// // With a custom class for tryCatch:
965/// #[miniextendr]
966/// fn typed_fail(name: &str) {
967///     mx::error!(class = "my_error", "missing field: {name}");
968/// }
969/// ```
970///
971/// ```r
972/// tryCatch(fail(), rust_error = function(e) conditionMessage(e))
973/// # [1] "something went wrong: 42"
974///
975/// tryCatch(typed_fail("x"), my_error = function(e) "caught!")
976/// # [1] "caught!"
977/// ```
978#[macro_export]
979macro_rules! error {
980    ($($t:tt)*) => {{
981        let (__mx_call, __mx_class, __mx_data, __mx_message) =
982            $crate::__mx_condition_parts!($($t)*);
983        ::std::panic::panic_any($crate::condition::RCondition::Error {
984            message: __mx_message,
985            class: __mx_class,
986            data: __mx_data,
987            call: __mx_call,
988        })
989    }};
990}
991
992/// Collision-free alias for [`crate::error!`].
993///
994/// Identical expansion and grammar (`call = none`, `class = …`, `data = …`,
995/// and the plain `format!` forms) — it exists so that `use miniextendr_api::*;` or
996/// `use miniextendr_api::rust_error;` gives you a usable macro name. The bare
997/// `error!` name is shadowed at the crate root by `pub mod error` (see the
998/// name-collision note on [`crate::error!`]), so a glob or direct import
999/// resolves to the module, not the macro. `rust_error!` has no such clash.
1000///
1001/// # Example
1002///
1003/// ```ignore
1004/// use miniextendr_api::rust_error;
1005///
1006/// #[miniextendr]
1007/// fn typed_fail(name: &str) {
1008///     rust_error!(class = "my_error", "missing field: {name}");
1009/// }
1010/// ```
1011#[macro_export]
1012macro_rules! rust_error {
1013    ($($t:tt)*) => { $crate::error!($($t)*) };
1014}
1015
1016/// Raise an R warning from Rust with `rust_warning` class layering.
1017///
1018/// Rides the tagged-condition transport that every `#[miniextendr]` function uses.
1019/// Unlike `panic!`, execution continues after `warning!` is caught by a handler.
1020/// The raised condition has class `c("rust_warning", "simpleWarning", "warning", "condition")`.
1021///
1022/// An optional `class = "name"` form prepends a custom class. An optional
1023/// `data = ...` form (after `class`, before the message) attaches named fields
1024/// readable as `w$<name>` in handlers — same grammar and supported value types
1025/// as [`crate::error!`] (see there for details):
1026///
1027/// ```ignore
1028/// warning!(class = "truncation", data = ("dropped", n), "dropped {n} rows");
1029/// ```
1030///
1031/// A leading `call = none` raises the warning without a call, like R's
1032/// `warning(..., call. = FALSE)`: `conditionCall(w)` is `NULL` and the
1033/// printed warning has no `In f(...) :` prefix. Use it for a warning about the
1034/// data rather than about the call (see
1035/// [conditions without a call](crate::error!#conditions-without-a-call)):
1036///
1037/// ```ignore
1038/// warning!(call = none, class = "pkg_override", data = { row = row }, "row {row} overrides an earlier row");
1039/// ```
1040///
1041/// # See also
1042///
1043/// - [`crate::error!`] — fatal sibling; aborts the call instead of continuing.
1044/// - [`crate::defer_warning!`] / [`crate::defer_warning()`] — queue the warning
1045///   and still return the value (signalled when the call returns).
1046/// - [`crate::message!`] / [`crate::condition!`] — softer signal kinds (muffled
1047///   by `suppressMessages` / silent without handler, respectively).
1048/// - [`std::panic!`] — escape hatch when "continue after this" is not a sensible
1049///   semantic.
1050/// - [`crate::error_value`] — tagged-SEXP transport rationale.
1051///
1052/// No name-collision caveat: there is no `pub mod warning`, so
1053/// `use miniextendr_api::warning;` then `warning!(...)` works directly.
1054///
1055/// # Example
1056///
1057/// ```ignore
1058/// use miniextendr_api::warning;
1059///
1060/// #[miniextendr]
1061/// fn maybe_warn(x: i32) -> i32 {
1062///     if x > 100 {
1063///         warning!("x is large: {x}");
1064///     }
1065///     x * 2
1066/// }
1067/// ```
1068///
1069/// ```r
1070/// withCallingHandlers(
1071///   maybe_warn(200L),
1072///   warning = function(w) { cat("saw:", conditionMessage(w)); invokeRestart("muffleWarning") }
1073/// )
1074/// # saw: x is large: 200
1075/// # [1] 400
1076/// ```
1077#[macro_export]
1078macro_rules! warning {
1079    ($($t:tt)*) => {{
1080        let (__mx_call, __mx_class, __mx_data, __mx_message) =
1081            $crate::__mx_condition_parts!($($t)*);
1082        ::std::panic::panic_any($crate::condition::RCondition::Warning {
1083            message: __mx_message,
1084            class: __mx_class,
1085            data: __mx_data,
1086            call: __mx_call,
1087        })
1088    }};
1089}
1090
1091/// Emit an R message from Rust with `rust_message` class layering.
1092///
1093/// Rides the tagged-condition transport that every `#[miniextendr]` function uses.
1094/// The raised condition has class `c("rust_message", "simpleMessage", "message", "condition")`.
1095/// Muffled by `suppressMessages()` automatically (standard R restart mechanism).
1096///
1097/// An optional `data = ...` form (before the message) attaches named fields
1098/// readable as `m$<name>` in `withCallingHandlers` — same grammar and
1099/// supported value types as [`crate::error!`] (see there for details). There
1100/// is no `class =` form for `message!`, and no `call =` form: an R message
1101/// carries no call (`conditionCall(m)` is `NULL`), so there is nothing to drop.
1102///
1103/// # See also
1104///
1105/// - [`crate::warning!`] / [`crate::condition!`] — louder/quieter sibling kinds.
1106/// - [`crate::error!`] — for fatal failures.
1107/// - [`std::panic!`] — escape hatch.
1108/// - [`crate::error_value`] — tagged-SEXP transport rationale.
1109///
1110/// No name-collision caveat: there is no `pub mod message`, so
1111/// `use miniextendr_api::message;` then `message!(...)` works directly.
1112///
1113/// # Example
1114///
1115/// ```ignore
1116/// use miniextendr_api::message;
1117///
1118/// #[miniextendr]
1119/// fn log_step(step: i32) {
1120///     message!("step {} complete", step);
1121/// }
1122/// ```
1123///
1124/// ```r
1125/// log_step(3L)
1126/// # step 3 complete
1127///
1128/// suppressMessages(log_step(3L))  # no output
1129/// ```
1130#[macro_export]
1131macro_rules! message {
1132    (call $($rest:tt)*) => {
1133        ::core::compile_error!(
1134            "message!: there is no `call` option, an R message carries no call"
1135        )
1136    };
1137    (data = $data:tt, $($arg:tt)*) => {
1138        ::std::panic::panic_any($crate::condition::RCondition::Message {
1139            message: ::std::format!($($arg)*),
1140            class: ::std::vec::Vec::new(),
1141            data: $crate::__mx_condition_data!($data),
1142            call: $crate::condition::ConditionCall::Inherit,
1143        })
1144    };
1145    ($($arg:tt)*) => {
1146        ::std::panic::panic_any($crate::condition::RCondition::Message {
1147            message: ::std::format!($($arg)*),
1148            class: ::std::vec::Vec::new(),
1149            data: ::std::option::Option::None,
1150            call: $crate::condition::ConditionCall::Inherit,
1151        })
1152    };
1153}
1154
1155/// Signal a generic R condition from Rust with `rust_condition` class layering.
1156///
1157/// Rides the tagged-condition transport that every `#[miniextendr]` function uses.
1158/// Unlike `error!`, a bare condition is a silent no-op if there is no handler.
1159/// The raised condition has class `c("rust_condition", "simpleCondition", "condition")`.
1160///
1161/// An optional `class = "name"` form prepends a custom class. An optional
1162/// `data = ...` form (after `class`, before the message) attaches named fields
1163/// readable as `c$<name>` in handlers — same grammar and supported value types
1164/// as [`crate::error!`] (see there for details). A leading `call = none`
1165/// signals the condition without a call (`conditionCall(c)` is `NULL`), like
1166/// [`crate::error!`]'s.
1167///
1168/// # See also
1169///
1170/// - [`crate::error!`] / [`crate::warning!`] / [`crate::message!`] — louder
1171///   condition kinds. Pick `condition!` when "no handler = silent" is the
1172///   right default (progress events, structured logging hooks).
1173/// - [`std::panic!`] — escape hatch when the failure cannot be ignored.
1174/// - [`crate::error_value`] — tagged-SEXP transport rationale.
1175///
1176/// **Name-collision note.** Because `pub mod condition` exists at the crate
1177/// root, `use miniextendr_api::condition` imports the module rather than this
1178/// macro, and glob imports (`use miniextendr_api::*;`) hit the same shadow.
1179/// Prefer the collision-free alias [`crate::rust_condition!`], which has the
1180/// identical expansion; otherwise invoke via `miniextendr_api::condition!(...)`
1181/// (fully qualified) or `mx::condition!(...)` after `use miniextendr_api as mx;`.
1182///
1183/// # Example
1184///
1185/// ```ignore
1186/// use miniextendr_api::condition;
1187///
1188/// #[miniextendr]
1189/// fn signal_progress(n: i32) {
1190///     condition!(class = "my_progress", "processed {n} items");
1191/// }
1192/// ```
1193///
1194/// ```r
1195/// withCallingHandlers(
1196///   signal_progress(42L),
1197///   my_progress = function(c) cat("progress:", conditionMessage(c), "\n")
1198/// )
1199/// # progress: processed 42 items
1200/// ```
1201#[macro_export]
1202macro_rules! condition {
1203    ($($t:tt)*) => {{
1204        let (__mx_call, __mx_class, __mx_data, __mx_message) =
1205            $crate::__mx_condition_parts!($($t)*);
1206        ::std::panic::panic_any($crate::condition::RCondition::Condition {
1207            message: __mx_message,
1208            class: __mx_class,
1209            data: __mx_data,
1210            call: __mx_call,
1211        })
1212    }};
1213}
1214
1215/// Collision-free alias for [`crate::condition!`].
1216///
1217/// Identical expansion and grammar (`call = none`, `class = …`, `data = …`,
1218/// and the plain `format!` forms) — it exists so that `use miniextendr_api::*;` or
1219/// `use miniextendr_api::rust_condition;` gives you a usable macro name. The
1220/// bare `condition!` name is shadowed at the crate root by `pub mod condition`
1221/// (see the name-collision note on [`crate::condition!`]), so a glob or direct
1222/// import resolves to the module, not the macro. `rust_condition!` has no such
1223/// clash.
1224///
1225/// # Example
1226///
1227/// ```ignore
1228/// use miniextendr_api::rust_condition;
1229///
1230/// #[miniextendr]
1231/// fn signal_progress(n: i32) {
1232///     rust_condition!(class = "my_progress", "processed {n} items");
1233/// }
1234/// ```
1235#[macro_export]
1236macro_rules! rust_condition {
1237    ($($t:tt)*) => { $crate::condition!($($t)*) };
1238}
1239
1240/// Raise the argument error the generated R wrapper raises for a bad
1241/// argument, from a `#[miniextendr]` function body.
1242///
1243/// `arg_error!(param = "mode", "'mode' should be one of {}", choices)` raises
1244/// the condition of the wrapper's own argument checks (`match_arg`,
1245/// `inherits`, `no_na`, type preconditions) and of a failed argument
1246/// conversion: `kind = "conversion"`, `e$param` set to `param` (the
1247/// argument's R name), the message as formatted, and the crate's
1248/// `conversion_error_class` (`[package.metadata.miniextendr]`) before the
1249/// `rust_error` layering:
1250///
1251/// ```r
1252/// class(e)
1253/// # [1] "pkg_error_argument" "pkg_error" "rust_error" "simpleError" "error" "condition"
1254/// ```
1255///
1256/// Use it for a check that applies on some paths only, where a
1257/// `#[miniextendr]` attribute on the parameter would check every call: an
1258/// argument passed on to another function's body, say, which skips that
1259/// function's R wrapper and its checks. [`crate::match_arg_param`] matches a
1260/// raw choice argument with the wrapper's semantics and message and raises
1261/// through this macro.
1262///
1263/// It diverges like [`crate::error!`] (the same `panic_any` transport), and
1264/// conditions queued with [`crate::defer_warning!`] & co. are signalled first.
1265/// The call is the one the wrapper's checks report: the wrapper's call as
1266/// written, or under `#[miniextendr(call = caller)]` its caller's. A leading
1267/// `call = none` raises it without a call, as for the other condition macros.
1268/// There is no `class =` or `data =`: the classes are the crate's and the only
1269/// field is `param`, so the condition is the wrapper's.
1270///
1271/// ```ignore
1272/// use miniextendr_api::{arg_error, miniextendr};
1273///
1274/// #[miniextendr]
1275/// pub fn in_metres(x: f64, unit: &str) -> f64 {
1276///     match unit {
1277///         "m" => x,
1278///         "cm" => x / 100.0,
1279///         _ => arg_error!(param = "unit", "'unit' should be one of \"m\", \"cm\""),
1280///     }
1281/// }
1282/// ```
1283///
1284/// # How the crate's classes get there
1285///
1286/// A `macro_rules!` macro cannot read `[package.metadata.miniextendr]`, so the
1287/// tagged condition value carries the marker class
1288/// [`CONVERSION_ERROR_CLASS_MARKER`]
1289/// and the generated wrapper's `.miniextendr_raise_condition` replaces it with
1290/// `.miniextendr_conversion_error_class`, the binding its own checks use. Across
1291/// a trait-ABI call the consumer package's wrapper raises the condition, so
1292/// its crate's classes apply. A raising guard (an ALTREP `RUnwind` callback,
1293/// `with_r_unwind_protect_or_raise`) has no generated R: it resolves the
1294/// marker in Rust against the classes `miniextendr_init!` registered (on
1295/// wasm32, the copy in the `wasm_registry.rs` snapshot), then raises the same
1296/// condition, `kind = "conversion"` included (#1768). A connection callback
1297/// returns its fallback, as for any panic.
1298///
1299/// The generated `no_na` check after a conversion builds the same condition
1300/// with [`crate::error_value::arg_check_condition_value`], which takes the
1301/// classes the macro read at expansion time.
1302///
1303/// # Grammar
1304///
1305/// `arg_error!([call = none,] param = <expr>, <format string>, <args>...)`.
1306/// `param` is anything `Into<String>`. A `call` anywhere but first, a repeated
1307/// one, a missing `param`, and `class =` / `data =` are compile errors:
1308///
1309/// ```compile_fail
1310/// # use miniextendr_api as mx;
1311/// # fn f() {
1312/// mx::arg_error!(param = "mode", call = none, "bad");
1313/// # }
1314/// ```
1315///
1316/// ```compile_fail
1317/// # use miniextendr_api as mx;
1318/// # fn f() {
1319/// mx::arg_error!("'mode' is bad");
1320/// # }
1321/// ```
1322///
1323/// ```compile_fail
1324/// # use miniextendr_api as mx;
1325/// # fn f() {
1326/// mx::arg_error!(param = "mode", class = "pkg_error", "bad");
1327/// # }
1328/// ```
1329///
1330/// ```
1331/// # use miniextendr_api as mx;
1332/// # fn f(mode: &str) -> ! {
1333/// mx::arg_error!(call = none, param = "mode", "'mode' is {mode:?}")
1334/// # }
1335/// ```
1336#[macro_export]
1337macro_rules! arg_error {
1338    // Internal: after the optional `call = none`.
1339    (@param $call:expr; call $($rest:tt)*) => {
1340        ::core::compile_error!("arg_error!: `call = none` is given twice")
1341    };
1342    (@param $call:expr; param = $param:expr, call $($rest:tt)*) => {
1343        ::core::compile_error!(
1344            "arg_error!: `call = none` comes first, before `param`: \
1345             `arg_error!(call = none, param = \"mode\", \"...\")`"
1346        )
1347    };
1348    (@param $call:expr; param = $param:expr, class $($rest:tt)*) => {
1349        $crate::arg_error!(@no_class_or_data)
1350    };
1351    (@param $call:expr; param = $param:expr, data $($rest:tt)*) => {
1352        $crate::arg_error!(@no_class_or_data)
1353    };
1354    (@param $call:expr; param = $param:expr, $($arg:tt)+) => {
1355        ::std::panic::panic_any($crate::condition::RCondition::arg_error(
1356            $param,
1357            ::std::format!($($arg)+),
1358            $call,
1359        ))
1360    };
1361    (@param $call:expr; $($rest:tt)*) => {
1362        ::core::compile_error!(
1363            "arg_error!: name the argument, then give the message: \
1364             `arg_error!(param = \"mode\", \"'mode' should be one of ...\")`"
1365        )
1366    };
1367    (@no_class_or_data) => {
1368        ::core::compile_error!(
1369            "arg_error!: takes no `class` or `data`: its classes are the crate's \
1370             `conversion_error_class` and its only field is `param`, as for the wrapper's \
1371             own argument errors; use `error!` for a classed error"
1372        )
1373    };
1374    // Entry: the optional `call = none`, then `param = ...` and the message.
1375    (call = none, $($rest:tt)*) => {
1376        $crate::arg_error!(@param $crate::condition::ConditionCall::None; $($rest)*)
1377    };
1378    (call $($rest:tt)*) => {
1379        ::core::compile_error!(
1380            "arg_error!: the only call option is `call = none` (no call, like R's \
1381             `call. = FALSE`), and it comes first, followed by a comma: \
1382             `arg_error!(call = none, param = \"mode\", \"...\")`"
1383        )
1384    };
1385    ($($rest:tt)*) => {
1386        $crate::arg_error!(@param $crate::condition::ConditionCall::Inherit; $($rest)*)
1387    };
1388}
1389
1390// endregion
1391
1392// region: Class vectors and reserved field names
1393
1394/// What the condition macros' `class = …` (and [`RError::class`]) accept: one
1395/// class or several, as `&str` / `String` / arrays / `Vec` / slices.
1396///
1397/// The classes are prepended in order to the `rust_*` layering, so put the most
1398/// specific first: `class = ["pkg_error_missing_field", "pkg_error"]` renders
1399/// as `c("pkg_error_missing_field", "pkg_error", "rust_error", …)` and both
1400/// `tryCatch(pkg_error_missing_field = …)` and `tryCatch(pkg_error = …)` match.
1401pub trait ConditionClass {
1402    /// The class vector, most specific first.
1403    fn into_condition_class(self) -> Vec<String>;
1404}
1405
1406impl ConditionClass for &str {
1407    fn into_condition_class(self) -> Vec<String> {
1408        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [self.to_string()]))vec![self.to_string()]
1409    }
1410}
1411impl ConditionClass for String {
1412    fn into_condition_class(self) -> Vec<String> {
1413        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [self]))vec![self]
1414    }
1415}
1416impl ConditionClass for &String {
1417    fn into_condition_class(self) -> Vec<String> {
1418        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [self.clone()]))vec![self.clone()]
1419    }
1420}
1421impl<const N: usize> ConditionClass for [&str; N] {
1422    fn into_condition_class(self) -> Vec<String> {
1423        self.iter().map(|s| s.to_string()).collect()
1424    }
1425}
1426impl<const N: usize> ConditionClass for [String; N] {
1427    fn into_condition_class(self) -> Vec<String> {
1428        self.into_iter().collect()
1429    }
1430}
1431impl ConditionClass for Vec<&str> {
1432    fn into_condition_class(self) -> Vec<String> {
1433        self.into_iter().map(str::to_string).collect()
1434    }
1435}
1436impl ConditionClass for Vec<String> {
1437    fn into_condition_class(self) -> Vec<String> {
1438        self
1439    }
1440}
1441impl ConditionClass for &[&str] {
1442    fn into_condition_class(self) -> Vec<String> {
1443        self.iter().map(|s| s.to_string()).collect()
1444    }
1445}
1446impl ConditionClass for &[String] {
1447    fn into_condition_class(self) -> Vec<String> {
1448        self.to_vec()
1449    }
1450}
1451
1452/// Condition-data field names that would overwrite the condition object's own
1453/// slots when the R helper splices `data` in (`utils::modifyList` over
1454/// `list(message, call, kind)`).
1455pub const RESERVED_CONDITION_FIELDS: &[&str] = &["message", "call", "kind"];
1456
1457/// `true` for [`RESERVED_CONDITION_FIELDS`]. `const` so the macros can reject a
1458/// literal field name at compile time:
1459///
1460/// ```compile_fail
1461/// # use miniextendr_api as mx;
1462/// # fn f() {
1463/// mx::rust_error!(data = ("kind", 1), "boom");
1464/// # }
1465/// ```
1466///
1467/// Any other name is fine, so the fix for a clash is a rename at the source:
1468///
1469/// ```
1470/// # use miniextendr_api as mx;
1471/// # fn f() {
1472/// mx::rust_error!(data = ("rule", 1), "boom");
1473/// # }
1474/// ```
1475pub const fn is_reserved_condition_field(name: &str) -> bool {
1476    str_eq(name, "message")
1477        || str_eq(name, "call")
1478        || str_eq(name, "kind")
1479        || str_eq(name, PARENT_FIELD)
1480        || str_eq(name, ERRORS_FIELD)
1481}
1482
1483/// `a == b`, usable in `const fn`.
1484const fn str_eq(a: &str, b: &str) -> bool {
1485    let (a, b) = (a.as_bytes(), b.as_bytes());
1486    if a.len() != b.len() {
1487        return false;
1488    }
1489    let mut i = 0;
1490    while i < a.len() {
1491        if a[i] != b[i] {
1492            return false;
1493        }
1494        i += 1;
1495    }
1496    true
1497}
1498
1499/// The `data` field under which [`RCondition::with_parent`] sends a cause to
1500/// R; the raise helper turns it into the condition object `e$parent`.
1501const PARENT_FIELD: &str = ".mx_parent";
1502
1503/// The `data` field under which a container's failed conversion
1504/// ([`IntoRError::Elements`](crate::into_r_error::IntoRError::Elements)) sends
1505/// its failed elements to R: a list of `list(index, condition)` entries whose
1506/// `condition` is a tagged value. The raise helper turns it into `e$errors`,
1507/// each entry's condition built like `e$parent`.
1508pub(crate) const ERRORS_FIELD: &str = ".mx_errors";
1509
1510/// Whether `name` is a field the framework itself puts among a condition's
1511/// data ([`PARENT_FIELD`], [`ERRORS_FIELD`]).
1512fn is_internal_field(name: &str) -> bool {
1513    name == PARENT_FIELD || name == ERRORS_FIELD
1514}
1515
1516/// Runtime half of the reserved-name check, for computed field names (the
1517/// macros' `expr` path and [`RConditionData::data`] on user types). Panics
1518/// when `name` is reserved; the panic becomes a plain `rust_error` in R,
1519/// replacing the former silent overwrite.
1520#[track_caller]
1521pub fn check_condition_field_name(name: String) -> String {
1522    if is_reserved_condition_field(&name) {
1523        {
    ::core::panicking::panic_fmt(format_args!("condition data field `{0}` is reserved: `message`, `call` and `kind` are the condition\'s own slots, and `.mx_parent` and `.mx_errors` carry its parent and its failed elements; rename the field.",
            name));
};panic!(
1524            "condition data field `{name}` is reserved: `message`, `call` and `kind` are the \
1525             condition's own slots, and `.mx_parent` and `.mx_errors` carry its parent and its \
1526             failed elements; rename the field."
1527        );
1528    }
1529    name
1530}
1531
1532/// Apply [`check_condition_field_name`] to every field of a payload.
1533#[track_caller]
1534pub fn check_condition_data(data: Option<ConditionData>) -> Option<ConditionData> {
1535    data.map(|fields| {
1536        fields
1537            .into_iter()
1538            .map(|(name, value)| (check_condition_field_name(name), value))
1539            .collect()
1540    })
1541}
1542
1543// endregion
1544
1545// region: Classed `Result` errors — RConditionData + RError
1546
1547/// Give a `Result<T, E>` error type an R class vector and structured fields.
1548///
1549/// Every `#[miniextendr]` function or method returning `Result<T, E>` raises
1550/// `Err(e)` as an R error. Implement this trait for `E` (or return
1551/// [`RError`], which implements it) and the `Err` arm raises
1552/// `c(<class()…>, "rust_error", "simpleError", "error", "condition")` with
1553/// every `data()` field readable as `e$<name>`, so a thiserror-style error enum
1554/// can keep `?` composition *and* give R handlers something to dispatch on.
1555///
1556/// Without an impl, the `Err` arm falls back in two steps. Under the `serde`
1557/// feature an `E: serde::Serialize + Display` is classed from its serde shape
1558/// (see `serde_err_parts`: variant → member class, fields → data, `Display`
1559/// → message). Anything else is a bare `rust_error` whose message is
1560/// `format!("{e:?}")`.
1561///
1562/// ```ignore
1563/// use miniextendr_api::condition::{ConditionData, RConditionData};
1564///
1565/// #[derive(Debug, thiserror::Error)]
1566/// pub enum PkgError {
1567///     #[error("column `{column}` is missing")]
1568///     MissingColumn { column: String },
1569///     #[error("{value} exceeds {max}")]
1570///     TooLarge { value: f64, max: f64 },
1571/// }
1572///
1573/// impl RConditionData for PkgError {
1574///     fn message(&self) -> String { self.to_string() }
1575///     fn class(&self) -> Vec<String> {
1576///         let member = match self {
1577///             PkgError::MissingColumn { .. } => "pkg_error_missing_column",
1578///             PkgError::TooLarge { .. } => "pkg_error_too_large",
1579///         };
1580///         vec![member.into(), "pkg_error".into()]
1581///     }
1582///     fn data(&self) -> Option<ConditionData> {
1583///         Some(match self {
1584///             PkgError::MissingColumn { column } => vec![("column".into(), column.clone().into())],
1585///             PkgError::TooLarge { value, max } => vec![("value".into(), (*value).into()), ("max".into(), (*max).into())],
1586///         })
1587///     }
1588/// }
1589///
1590/// #[miniextendr]
1591/// pub fn check(value: f64) -> Result<f64, PkgError> { /* uses `?` freely */ }
1592/// ```
1593///
1594/// ```r
1595/// tryCatch(check(1e9), pkg_error_too_large = function(e) e$max)   # member
1596/// tryCatch(check(1e9), pkg_error = function(e) conditionMessage(e)) # family
1597/// ```
1598///
1599/// Detection is by trait, not by attribute: the generated `Err` arm probes
1600/// `E: RConditionData` first and falls back to the `Debug` rendering
1601/// otherwise, so existing `Result<T, String>` / `Result<T, MyDebugError>`
1602/// functions are unchanged. The condition's `kind` stays `"result_err"`.
1603///
1604/// The same impl classes argument-conversion failures: when a parameter
1605/// type's `TryFromSexp::Error` implements this trait, a failed conversion
1606/// raises its classes and fields with `kind = "conversion"`, the message
1607/// `'<p>' must be <expected>: <message()>` (or `invalid '<p>' argument:
1608/// <message()>` when the argument's type has no R-facing expectation), the
1609/// parameter's R name as `e$param` and the Rust type as `e$rust_type`
1610/// (unless `data()` has a field of the same name, which then wins). An error
1611/// type without the impl renders with `Display` and keeps the plain
1612/// `rust_error` class vector.
1613///
1614/// `data()` field names must not be `message`, `call` or `kind` (see
1615/// [`RESERVED_CONDITION_FIELDS`]); a reserved name raises a plain
1616/// `rust_error` explaining the clash, so rename such a field at the source.
1617///
1618/// [`call()`](RConditionData::call) returning [`ConditionCall::None`] drops
1619/// the call (`conditionCall(e)` is `NULL`), for errors and warnings about the
1620/// data rather than the call.
1621pub trait RConditionData {
1622    /// The condition message (`conditionMessage(e)`).
1623    fn message(&self) -> String;
1624    /// User classes, most specific first; empty for none.
1625    fn class(&self) -> Vec<String> {
1626        Vec::new()
1627    }
1628    /// Structured fields spliced into the condition object (`e$<name>`).
1629    fn data(&self) -> Option<ConditionData> {
1630        None
1631    }
1632    /// Whether the condition reports a call. [`ConditionCall::None`] makes
1633    /// `conditionCall()` `NULL`, like R's `call. = FALSE`, for a condition
1634    /// about the data rather than the call; the default keeps the call the
1635    /// transport captured. Honoured by `defer_*` and by `Result` returns;
1636    /// an argument-conversion error always keeps the call (see
1637    /// [`conversion_err_parts`]). `#[condition(call = none)]` on a derived
1638    /// type or variant overrides this.
1639    fn call(&self) -> ConditionCall {
1640        ConditionCall::Inherit
1641    }
1642    /// The whole message when this error refuses an argument, or `None`.
1643    ///
1644    /// When the error comes out of a parameter's conversion (the type's
1645    /// `TryFromSexp`, or its [`check_sexp`](crate::TryFromSexpElement::check_sexp)
1646    /// under `Option<T>` / `Vec<T>` / `Vec<Option<T>>`), a `Some` is the
1647    /// condition's message as given, in place of
1648    /// `'<p>' must be <expected>: <message()>`. The classes, `kind`,
1649    /// `e$param`, `e$rust_type` and the call are unchanged. This is how a type
1650    /// words a refusal once for every parameter of that type, as
1651    /// `#[miniextendr(inherits(..., message = ...))]` does for one parameter:
1652    /// both use the author's message as given and name the argument in
1653    /// `e$param`. Ignored everywhere else (`Result` returns, `defer_*`), and
1654    /// inside an `Either`, whose message names both arms. For a refused
1655    /// element of a list of objects (`Vec<T>` of a newtype over `List`), it
1656    /// is that element's reason, before the element's position, in the
1657    /// prefixed batched message: an element is not the whole argument.
1658    fn argument_message(&self) -> Option<String> {
1659        None
1660    }
1661    /// Internal: whether the framework's own fields among
1662    /// [`data()`](RConditionData::data) are what they say, which the
1663    /// generated `Err` arms pass on: a `.mx_parent` field is a cause
1664    /// [`RCondition::with_parent`] attached (`e$parent`), a `.mx_errors`
1665    /// field the failed elements of a container's conversion (`e$errors`,
1666    /// [`IntoRError::Elements`](crate::into_r_error::IntoRError::Elements)).
1667    /// Every other reserved name is refused ([`check_condition_data`]). True
1668    /// for an [`RCondition`](enum@RCondition), an
1669    /// [`IntoRError`](crate::into_r_error::IntoRError) and an [`RError`]
1670    /// converted from either.
1671    #[doc(hidden)]
1672    fn __mx_keeps_internal_fields(&self) -> bool {
1673        false
1674    }
1675}
1676
1677/// [`check_condition_data`] for an `Err` arm's fields, passing the
1678/// framework's own fields when `keeps_internal_fields`
1679/// ([`RConditionData::__mx_keeps_internal_fields`]).
1680#[track_caller]
1681fn check_err_fields(
1682    data: Option<ConditionData>,
1683    keeps_internal_fields: bool,
1684) -> Option<ConditionData> {
1685    data.map(|fields| {
1686        fields
1687            .into_iter()
1688            .map(|(name, value)| (check_err_field(name, keeps_internal_fields), value))
1689            .collect()
1690    })
1691}
1692
1693/// [`check_condition_field_name`], passing the framework's own fields
1694/// (`.mx_parent`, `.mx_errors`) when `keeps_internal_fields`.
1695#[track_caller]
1696fn check_err_field(name: String, keeps_internal_fields: bool) -> String {
1697    if keeps_internal_fields && is_internal_field(&name) {
1698        name
1699    } else {
1700        check_condition_field_name(name)
1701    }
1702}
1703
1704/// `#[derive(RCondition)]`: [`RConditionData`] generated from a type's shape
1705/// (`#[condition(class = "…")]`, `#[condition(message = "…")]`, the
1706/// `rename` / `skip` / `debug` field options) and `From<T>` for
1707/// [`RCondition`](enum@RCondition) with the declared kind
1708/// (`#[condition(kind = …)]`, default `error`).
1709#[doc(inline)]
1710pub use miniextendr_macros::RCondition;
1711
1712/// A ready-made classed error value for `Result<T, RError>` returns.
1713///
1714/// Carries a message, an optional class vector, structured fields and the
1715/// call choice, and implements [`RConditionData`]. Any
1716/// `std::error::Error` converts into it with `?` / [`From`] (the message keeps
1717/// the `caused by:` chain, like [`AsRError`]), after which the builder methods
1718/// add the R-facing parts ([`RError::class`], [`RError::data`],
1719/// [`RError::without_call`]):
1720///
1721/// ```ignore
1722/// use miniextendr_api::condition::RError;
1723///
1724/// #[miniextendr]
1725/// pub fn parse_port(s: &str) -> Result<i32, RError> {
1726///     let port: i32 = s
1727///         .parse()
1728///         .map_err(|e| RError::from(e).class(["pkg_bad_port", "pkg_error"]).data("input", s))?;
1729///     Ok(port)
1730/// }
1731/// ```
1732///
1733/// ```r
1734/// e <- tryCatch(parse_port("x"), pkg_bad_port = function(e) e)
1735/// e$input          # "x"
1736/// class(e)[1:2]    # "pkg_bad_port" "pkg_error"
1737/// ```
1738///
1739/// `RError` deliberately does **not** implement `std::error::Error`: that
1740/// keeps the blanket `From<E: Error>` coherent. It does implement `Display`
1741/// (the message), so it also works with `#[miniextendr(unwrap_in_r)]`.
1742#[derive(#[automatically_derived]impl ::core::fmt::Debug for RError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            "RError message class data call argument_message keeps_internal_fields";
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.message, &self.class, &self.data, &self.call,
                        &self.argument_message, &&self.keeps_internal_fields];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, names, values)
    }
}Debug, #[automatically_derived]impl ::core::clone::Clone for RError {
    #[inline]
    fn clone(&self) -> Self {
        RError {
            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),
            argument_message: ::core::clone::Clone::clone(&self.argument_message),
            keeps_internal_fields: ::core::clone::Clone::clone(&self.keeps_internal_fields),
        }
    }
}Clone)]
1743pub struct RError {
1744    message: String,
1745    class: Vec<String>,
1746    data: ConditionData,
1747    call: ConditionCall,
1748    argument_message: Option<String>,
1749    /// Converted from an [`RCondition`](enum@RCondition) or an
1750    /// [`IntoRError`](crate::into_r_error::IntoRError): a `.mx_parent` field
1751    /// is the cause it carried, a `.mx_errors` field its failed elements
1752    /// ([`RConditionData::__mx_keeps_internal_fields`]).
1753    keeps_internal_fields: bool,
1754}
1755
1756impl RError {
1757    /// A classless error with `message`.
1758    pub fn new(message: impl Into<String>) -> Self {
1759        RError {
1760            message: message.into(),
1761            class: Vec::new(),
1762            data: Vec::new(),
1763            call: ConditionCall::Inherit,
1764            argument_message: None,
1765            keeps_internal_fields: false,
1766        }
1767    }
1768
1769    /// Raise the condition without a call: `conditionCall(e)` is `NULL` and
1770    /// the printed condition has no `In f(...) :` prefix, like R's
1771    /// `stop(..., call. = FALSE)`. For an error or warning about the data, not
1772    /// the call. Applies to `Result` returns and the `defer_*` functions; see
1773    /// [`ConditionCall`].
1774    pub fn without_call(mut self) -> Self {
1775        self.call = ConditionCall::None;
1776        self
1777    }
1778
1779    /// Append user classes (most specific first). Accepts one string or a
1780    /// vector, see [`ConditionClass`].
1781    pub fn class(mut self, class: impl ConditionClass) -> Self {
1782        self.class.extend(class.into_condition_class());
1783        self
1784    }
1785
1786    /// Attach a structured field readable as `e$<name>`. Any value with an
1787    /// [`RValue`](crate::RValue) `From` impl works. The name must not be
1788    /// `message`, `call` or `kind`; see [`RESERVED_CONDITION_FIELDS`].
1789    pub fn data(mut self, name: impl Into<String>, value: impl Into<crate::RValue>) -> Self {
1790        self.data.push((name.into(), value.into()));
1791        self
1792    }
1793
1794    /// The whole message of the argument error when this error refuses an
1795    /// argument, used as given instead of `'<p>' must be <expected>:
1796    /// <message>`; see [`RConditionData::argument_message`]. `message` stays
1797    /// the message everywhere else.
1798    ///
1799    /// ```ignore
1800    /// fn model_object(x: SEXP) -> Result<(), RError> {
1801    ///     if x.inherits_class(c"data.frame") {
1802    ///         return Err(RError::new("got a data frame")
1803    ///             .argument_message("use model_from_df() for a data frame"));
1804    ///     }
1805    ///     Ok(())
1806    /// }
1807    /// ```
1808    pub fn argument_message(mut self, message: impl Into<String>) -> Self {
1809        self.argument_message = Some(message.into());
1810        self
1811    }
1812
1813    /// The message.
1814    pub fn message_str(&self) -> &str {
1815        &self.message
1816    }
1817
1818    /// The whole argument-error message, if one was given
1819    /// ([`RError::argument_message`]).
1820    pub fn argument_message_str(&self) -> Option<&str> {
1821        self.argument_message.as_deref()
1822    }
1823
1824    /// The user classes, most specific first.
1825    pub fn classes(&self) -> &[String] {
1826        &self.class
1827    }
1828
1829    /// The structured fields as attached (unprefixed).
1830    pub fn fields(&self) -> &ConditionData {
1831        &self.data
1832    }
1833}
1834
1835impl<E: std::error::Error> From<E> for RError {
1836    /// Message = the error's `Display` plus its `source()` chain, one
1837    /// `caused by:` line per link (same rendering as [`AsRError`]).
1838    fn from(err: E) -> Self {
1839        let mut message = err.to_string();
1840        let mut current: &dyn std::error::Error = &err;
1841        while let Some(source) = current.source() {
1842            message.push_str("\n  caused by: ");
1843            message.push_str(&source.to_string());
1844            current = source;
1845        }
1846        RError::new(message)
1847    }
1848}
1849
1850impl std::fmt::Display for RError {
1851    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1852        f.write_str(&self.message)
1853    }
1854}
1855
1856impl RConditionData for RError {
1857    fn message(&self) -> String {
1858        self.message.clone()
1859    }
1860    fn class(&self) -> Vec<String> {
1861        self.class.clone()
1862    }
1863    fn data(&self) -> Option<ConditionData> {
1864        (!self.data.is_empty()).then(|| self.data.clone())
1865    }
1866    fn call(&self) -> ConditionCall {
1867        self.call
1868    }
1869    fn argument_message(&self) -> Option<String> {
1870        self.argument_message.clone()
1871    }
1872    fn __mx_keeps_internal_fields(&self) -> bool {
1873        self.keeps_internal_fields
1874    }
1875}
1876
1877/// An [`RCondition`](enum@RCondition) returned as an `Err` (#2217): from a
1878/// `#[miniextendr]` function or method returning `Result<T, RCondition>`.
1879/// Its message, classes, fields and call choice reach R as given. Like any `Err`, it is an
1880/// R error whatever its variant: the kind is read only where the condition is
1881/// raised or deferred ([`RCondition::raise`], [`RCondition::defer`]). A cause
1882/// attached with [`RCondition::with_parent`], as a caught refusal of a
1883/// restored object carries one, stays its `e$parent`, also through the
1884/// [`SexpError`](crate::from_r::SexpError) it converts into.
1885///
1886/// It is how a body hands on a condition [`catch_condition`] caught, or one
1887/// built by [`serde_condition!`](crate::serde_condition):
1888///
1889/// ```ignore
1890/// #[miniextendr]
1891/// pub fn load(path: &str) -> Result<Model, RCondition> {
1892///     let config = catch_condition(|| read_config(path))?;
1893///     Ok(Model::new(config))
1894/// }
1895/// ```
1896impl RConditionData for RCondition {
1897    fn message(&self) -> String {
1898        RCondition::message(self).to_owned()
1899    }
1900    fn class(&self) -> Vec<String> {
1901        self.class_and_data().0.to_vec()
1902    }
1903    fn data(&self) -> Option<ConditionData> {
1904        self.class_and_data().1.clone()
1905    }
1906    fn call(&self) -> ConditionCall {
1907        RCondition::call(self)
1908    }
1909    /// A `.mx_parent` field is the cause [`RCondition::with_parent`]
1910    /// attached (a refusal [`catch_condition`] caught carries one), a
1911    /// `.mx_errors` field the failed elements of an
1912    /// [`IntoRError`](crate::into_r_error::IntoRError) it was built from.
1913    fn __mx_keeps_internal_fields(&self) -> bool {
1914        true
1915    }
1916}
1917
1918/// The error of a conversion that cannot fail (an
1919/// [`IntoR`](crate::into_r::IntoR) with `Error = Infallible`): no value
1920/// exists, so nothing is ever read.
1921impl RConditionData for std::convert::Infallible {
1922    fn message(&self) -> String {
1923        match *self {}
1924    }
1925}
1926
1927/// Any classed error (an [`RError`], a `#[derive(RCondition)]` type)
1928/// converts into a [`SexpError::Condition`](crate::from_r::SexpError::Condition)
1929/// with its message, classes, fields and call choice, so a newtype's
1930/// [`check_sexp`](crate::TryFromSexpElement::check_sexp) can refuse with it
1931/// and a conversion whose error converts into `SexpError` keeps its classes.
1932impl<E: RConditionData> From<E> for crate::from_r::SexpError {
1933    fn from(e: E) -> Self {
1934        crate::from_r::SexpError::Condition(RError {
1935            message: e.message(),
1936            class: e.class(),
1937            data: e.data().unwrap_or_default(),
1938            call: e.call(),
1939            argument_message: e.argument_message(),
1940            keeps_internal_fields: e.__mx_keeps_internal_fields(),
1941        })
1942    }
1943}
1944
1945/// An argument error as a value: the parameter's R name and the message.
1946/// [`ArgError::raise`] raises it as the generated wrapper's own argument
1947/// error, through [`crate::arg_error!`].
1948///
1949/// [`crate::match_arg_param`] returns it for a choice argument the body
1950/// matches itself. Raise it where the argument is bad, or handle it:
1951///
1952/// ```ignore
1953/// use miniextendr_api::{SEXP, match_arg_param, miniextendr};
1954///
1955/// #[miniextendr]
1956/// pub fn prepare(data: SEXP, mode: SEXP) -> String {
1957///     if is_data_frame(data) {
1958///         let mode: Mode = match_arg_param(mode, "mode").unwrap_or_else(|e| e.raise());
1959///         // ...
1960///     }
1961///     // ...
1962/// }
1963/// ```
1964///
1965/// It does not implement [`RConditionData`]: returned as a body's `Err` it
1966/// would take the `Result` path (`kind = "result_err"`), not the argument
1967/// error's.
1968#[derive(#[automatically_derived]impl ::core::fmt::Debug for ArgError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "ArgError param message", &self.param, &&self.message)
    }
}Debug, #[automatically_derived]impl ::core::clone::Clone for ArgError {
    #[inline]
    fn clone(&self) -> Self {
        ArgError {
            param: ::core::clone::Clone::clone(&self.param),
            message: ::core::clone::Clone::clone(&self.message),
        }
    }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for ArgError
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ArgError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.param == other.param && self.message == other.message
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ArgError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<String>;
    }
}Eq)]
1969pub struct ArgError {
1970    param: String,
1971    message: String,
1972}
1973
1974impl ArgError {
1975    /// The argument error of parameter `param` (its R name) with `message`,
1976    /// used as given.
1977    pub fn new(param: impl Into<String>, message: impl Into<String>) -> Self {
1978        ArgError {
1979            param: param.into(),
1980            message: message.into(),
1981        }
1982    }
1983
1984    /// The parameter's R name (`e$param`).
1985    pub fn param(&self) -> &str {
1986        &self.param
1987    }
1988
1989    /// The message (`conditionMessage(e)`).
1990    pub fn message(&self) -> &str {
1991        &self.message
1992    }
1993
1994    /// Raise it: `arg_error!(param = <param>, "{}", <message>)`. The
1995    /// condition is the one the generated wrapper raises for that parameter;
1996    /// see [`crate::arg_error!`].
1997    pub fn raise(self) -> ! {
1998        std::panic::panic_any(RCondition::arg_error(
1999            self.param,
2000            self.message,
2001            ConditionCall::Inherit,
2002        ))
2003    }
2004}
2005
2006impl std::fmt::Display for ArgError {
2007    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2008        f.write_str(&self.message)
2009    }
2010}
2011
2012impl std::error::Error for ArgError {}
2013
2014/// The parts of a condition the generated `Err` arms hand to
2015/// [`crate::error_value::result_err_condition_value`] /
2016/// [`crate::error_value::conversion_condition_value`], and that
2017/// [`RCondition::into_parts`] splits a payload into: message, user classes,
2018/// `data` fields and the [`ConditionCall`] choice.
2019#[doc(hidden)]
2020#[derive(#[automatically_derived]impl ::core::fmt::Debug for ErrParts {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "ErrParts message class data call", &self.message, &self.class,
            &self.data, &&self.call)
    }
}Debug)]
2021pub struct ErrParts {
2022    pub message: String,
2023    pub class: Vec<String>,
2024    pub data: Option<ConditionData>,
2025    pub call: ConditionCall,
2026}
2027
2028/// Autoref-specialisation probe, first stage, preferred arm: `E: RConditionData`.
2029///
2030/// Under the `serde` feature a declared-shape stage runs before this one: a
2031/// shape that `serde_error_shape!` declared for `E` wins over the impl (see
2032/// `ErrShapeDeclared`).
2033///
2034/// The generated code calls `(&e).__mx_classed_parts()` with both first-stage
2035/// traits in scope. Method resolution tries the receiver type `&E` by value
2036/// first, which only this impl (on `E`, taking `&self`) satisfies; the
2037/// [`ErrPartsUnclassed`] arm on `&E` needs one more auto-ref and is only
2038/// reached when `E` does not implement [`RConditionData`]. It yields `None`,
2039/// and the second stage ([`ErrPartsSerde`] / [`ErrPartsDebug`]) decides.
2040///
2041/// Two two-way probes rather than one three-way probe: the `Serialize` and
2042/// `Debug` bounds both hold for `&E` whenever they hold for `E`, so a single
2043/// method name with three impls at increasing reference depth is ambiguous at
2044/// the first step. Each stage has exactly one impl on `E` and one on `&E`.
2045#[doc(hidden)]
2046pub trait ErrPartsClassed {
2047    fn __mx_classed_parts(&self) -> Option<ErrParts>;
2048}
2049
2050impl<E: RConditionData> ErrPartsClassed for E {
2051    #[track_caller]
2052    fn __mx_classed_parts(&self) -> Option<ErrParts> {
2053        Some(into_r_err_parts(self))
2054    }
2055}
2056
2057/// First stage, fallback arm: no [`RConditionData`] impl.
2058#[doc(hidden)]
2059pub trait ErrPartsUnclassed {
2060    fn __mx_classed_parts(&self) -> Option<ErrParts>;
2061}
2062
2063impl<E> ErrPartsUnclassed for &E {
2064    fn __mx_classed_parts(&self) -> Option<ErrParts> {
2065        None
2066    }
2067}
2068
2069/// Second stage, preferred arm: `E: Serialize + Display` under the `serde`
2070/// feature, classed via [`serde_err_parts`] with the defaults (`kind` tag,
2071/// the `<crate>_error` prefix the macro passes in, no shapes).
2072/// `#[miniextendr(serde_error(..))]` bypasses the probe with explicit options.
2073///
2074/// The trait exists without the feature so the generated `use` resolves; it
2075/// then has no impl and every type takes the [`ErrPartsDebug`] arm.
2076#[doc(hidden)]
2077pub trait ErrPartsSerde {
2078    fn __mx_fallback_parts(&self, prefix: &str) -> ErrParts;
2079}
2080
2081#[cfg(feature = "serde")]
2082impl<E: ::serde::Serialize + std::fmt::Display> ErrPartsSerde for E {
2083    #[track_caller]
2084    fn __mx_fallback_parts(&self, prefix: &str) -> ErrParts {
2085        serde_err_parts(self, prefix, &[])
2086    }
2087}
2088
2089/// Second stage, fallback arm: any `E: Debug` (the historical
2090/// `format!("{e:?}")` rendering, no class, no data).
2091#[doc(hidden)]
2092pub trait ErrPartsDebug {
2093    fn __mx_fallback_parts(&self, prefix: &str) -> ErrParts;
2094}
2095
2096impl<E: std::fmt::Debug> ErrPartsDebug for &E {
2097    fn __mx_fallback_parts(&self, _prefix: &str) -> ErrParts {
2098        ErrParts {
2099            message: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", self))
    })format!("{self:?}"),
2100            class: Vec::new(),
2101            data: None,
2102            call: ConditionCall::Inherit,
2103        }
2104    }
2105}
2106
2107/// Internal: the `Err(e)` probe used by generated wrappers. Not public API.
2108///
2109/// `$prefix` is the family class for the serde arms (`<crate>_error`, computed
2110/// by the macro from `CARGO_CRATE_NAME` at expansion time). `$marker` is the
2111/// calling crate's marker type (`crate::__MiniextendrInitMarker`), under which
2112/// [`serde_error_shape!`](crate::serde_error_shape) declarations are looked up
2113/// first, under the `serde` feature: a declared shape wins over the stages
2114/// below (the `ErrShapeDeclared` probe).
2115#[doc(hidden)]
2116#[macro_export]
2117macro_rules! __mx_result_err_parts {
2118    ($e:expr, $prefix:expr, $marker:ty) => {{
2119        #[allow(unused_imports)]
2120        use $crate::condition::{
2121            ErrPartsClassed as _, ErrPartsDebug as _, ErrPartsSerde as _, ErrPartsUnclassed as _,
2122        };
2123        match &$e {
2124            __mx_e => match $crate::__mx_declared_err_parts!(__mx_e, $prefix, $marker) {
2125                ::core::option::Option::Some(parts) => parts,
2126                ::core::option::Option::None => match __mx_e.__mx_classed_parts() {
2127                    ::core::option::Option::Some(parts) => parts,
2128                    ::core::option::Option::None => __mx_e.__mx_fallback_parts($prefix),
2129                },
2130            },
2131        }
2132    }};
2133}
2134
2135/// Internal: the condition parts of a failed return conversion
2136/// (`IntoR::try_into_sexp` returned `Err(e)`) in generated code, and of each
2137/// failed element of a container's conversion. Not public API.
2138///
2139/// Every `IntoR::Error` implements [`RConditionData`], so the error gives its
2140/// message, classes, fields and call choice wherever it fails, in a generic
2141/// trait shim and inside a tuple too. No declared serde shape, so the call
2142/// site needs no `__MiniextendrInitMarker`.
2143#[doc(hidden)]
2144#[track_caller]
2145pub fn into_r_err_parts<E: RConditionData + ?Sized>(e: &E) -> ErrParts {
2146    ErrParts {
2147        message: e.message(),
2148        class: e.class(),
2149        data: check_err_fields(e.data(), e.__mx_keeps_internal_fields()),
2150        call: e.call(),
2151    }
2152}
2153
2154// endregion
2155
2156// region: Classed argument-conversion errors
2157
2158/// Conversion probe, preferred arm: `E: RConditionData`.
2159///
2160/// When an argument fails its `TryFromSexp` conversion, the generated wrapper
2161/// calls `(&e).__mx_conversion_parts(expected_known)` with the three
2162/// conversion-probe traits in scope (see [`crate::__mx_conversion_err_parts!`]).
2163/// This impl, on `E` taking `&self`, matches the receiver `&E` by value, so a
2164/// `TryFromSexp::Error` that implements [`RConditionData`] contributes its
2165/// class vector, message and data. [`ConversionErrBuiltin`] matches at the
2166/// same step for the built-in conversion errors, which never implement
2167/// [`RConditionData`], so the two never compete. [`ConversionErrDisplay`]
2168/// needs one more auto-ref and is only reached otherwise.
2169///
2170/// Unlike the `Result` probe ([`crate::__mx_result_err_parts!`]) there is no
2171/// serde stage and the fallback is `Display`, not `Debug`: the generated code
2172/// has always rendered conversion errors with `Display`, which every built-in
2173/// error type (`SexpError`, `MatchArgError`, ...) implements.
2174#[doc(hidden)]
2175pub trait ConversionErrClassed {
2176    fn __mx_conversion_parts(&self, expected_known: bool) -> ErrParts;
2177}
2178
2179impl<E: RConditionData> ConversionErrClassed for E {
2180    #[track_caller]
2181    fn __mx_conversion_parts(&self, _expected_known: bool) -> ErrParts {
2182        ErrParts {
2183            message: self.message(),
2184            class: self.class(),
2185            data: check_err_fields(self.data(), self.__mx_keeps_internal_fields()),
2186            call: self.call(),
2187        }
2188    }
2189}
2190
2191/// Conversion probe, built-in arm: the framework's own conversion errors
2192/// ([`SexpError`](crate::from_r::SexpError) and the
2193/// [`SexpTypeError`](crate::from_r::SexpTypeError) /
2194/// [`SexpClassError`](crate::from_r::SexpClassError) /
2195/// [`SexpLengthError`](crate::from_r::SexpLengthError) /
2196/// [`SexpNaError`](crate::from_r::SexpNaError) it wraps, and
2197/// [`MatchArgError`](crate::match_arg::MatchArgError)), reworded for R
2198/// users (#1591).
2199///
2200/// Their `Display` text is written for the package author: SEXPTYPE names
2201/// (`expected INTSXP, got STRSXP`) and a variant prefix (`invalid value: ...`).
2202/// The condition message says instead what the argument should have been,
2203/// with the reason from `SexpError::r_reason` (`got character`,
2204/// `got length 2`, `NA is not allowed`, the invalid value's own text, ...)
2205/// or `MatchArgError::r_reason` (`got "zzz"`).
2206///
2207/// `expected_known` is set by the macro when it knows the argument's R-facing
2208/// expectation and puts it in the message prefix (`'x' must be a single
2209/// integer`); the reason then does not repeat it. The type names are those of
2210/// [`sexptype_name`](crate::typed_list::sexptype_name) (`numeric` for a
2211/// double, `list`, `NULL`, ...).
2212#[doc(hidden)]
2213pub trait ConversionErrBuiltin {
2214    fn __mx_conversion_parts(&self, expected_known: bool) -> ErrParts;
2215}
2216
2217/// The R-facing reason for a built-in conversion error, see
2218/// [`ConversionErrBuiltin`].
2219fn builtin_reason_parts(message: String) -> ErrParts {
2220    ErrParts {
2221        message,
2222        class: Vec::new(),
2223        data: None,
2224        call: ConditionCall::Inherit,
2225    }
2226}
2227
2228impl ConversionErrBuiltin for crate::from_r::SexpTypeError {
2229    fn __mx_conversion_parts(&self, expected_known: bool) -> ErrParts {
2230        builtin_reason_parts(self.r_reason(expected_known))
2231    }
2232}
2233
2234impl ConversionErrBuiltin for crate::from_r::SexpClassError {
2235    fn __mx_conversion_parts(&self, expected_known: bool) -> ErrParts {
2236        builtin_reason_parts(self.r_reason(expected_known))
2237    }
2238}
2239
2240impl ConversionErrBuiltin for crate::from_r::SexpLengthError {
2241    fn __mx_conversion_parts(&self, expected_known: bool) -> ErrParts {
2242        builtin_reason_parts(self.r_reason(expected_known))
2243    }
2244}
2245
2246impl ConversionErrBuiltin for crate::from_r::SexpNaError {
2247    fn __mx_conversion_parts(&self, _expected_known: bool) -> ErrParts {
2248        builtin_reason_parts("NA is not allowed".to_string())
2249    }
2250}
2251
2252/// A `SexpError` also carries the classes and fields of the check refusals
2253/// ([`SexpError::Condition`](crate::from_r::SexpError::Condition)) whose
2254/// reasons its message reports, directly or from an `Either` arm.
2255impl ConversionErrBuiltin for crate::from_r::SexpError {
2256    fn __mx_conversion_parts(&self, expected_known: bool) -> ErrParts {
2257        let mut parts = builtin_reason_parts(self.r_reason(expected_known));
2258        let mut data = ConditionData::new();
2259        for refusal in self.reported_conditions() {
2260            for class in refusal.classes() {
2261                if !parts.class.contains(class) {
2262                    parts.class.push(class.clone());
2263                }
2264            }
2265            for (name, value) in refusal.fields() {
2266                if !data.iter().any(|(seen, _)| seen == name) {
2267                    data.push((
2268                        check_err_field(name.clone(), refusal.keeps_internal_fields),
2269                        value.clone(),
2270                    ));
2271                }
2272            }
2273        }
2274        parts.data = (!data.is_empty()).then_some(data);
2275        parts
2276    }
2277}
2278
2279impl ConversionErrBuiltin for crate::match_arg::MatchArgError {
2280    fn __mx_conversion_parts(&self, expected_known: bool) -> ErrParts {
2281        builtin_reason_parts(self.r_reason(expected_known))
2282    }
2283}
2284
2285/// Conversion probe, fallback arm: any `E: Display`. The message is the
2286/// error's `Display` text, with no class and no data, so the condition keeps
2287/// the plain `rust_error` class vector.
2288#[doc(hidden)]
2289pub trait ConversionErrDisplay {
2290    fn __mx_conversion_parts(&self, expected_known: bool) -> ErrParts;
2291}
2292
2293impl<E: std::fmt::Display> ConversionErrDisplay for &E {
2294    fn __mx_conversion_parts(&self, _expected_known: bool) -> ErrParts {
2295        ErrParts {
2296            message: self.to_string(),
2297            class: Vec::new(),
2298            data: None,
2299            call: ConditionCall::Inherit,
2300        }
2301    }
2302}
2303
2304/// Internal: the argument-conversion `Err(e)` probe used by generated
2305/// wrappers. Not public API. Yields the error's own [`ErrParts`];
2306/// [`crate::error_value::conversion_condition_value`] adds the parameter
2307/// context.
2308///
2309/// The second argument is `expected_known` (see [`ConversionErrBuiltin`]):
2310/// `true` when the message prefix already states what the argument should
2311/// be. It defaults to `false`.
2312#[doc(hidden)]
2313#[macro_export]
2314macro_rules! __mx_conversion_err_parts {
2315    ($e:expr) => {
2316        $crate::__mx_conversion_err_parts!($e, false)
2317    };
2318    ($e:expr, $expected_known:expr) => {{
2319        #[allow(unused_imports)]
2320        use $crate::condition::{
2321            ConversionErrBuiltin as _, ConversionErrClassed as _, ConversionErrDisplay as _,
2322        };
2323        match &$e {
2324            __mx_e => __mx_e.__mx_conversion_parts($expected_known),
2325        }
2326    }};
2327}
2328
2329/// Expectation probe, built-in arm: an error that knows what the value should
2330/// have been. A `match_arg` choice error (`MatchArgError`, or a `SexpError`
2331/// carrying one, as `#[derive(MatchArg)]`'s `TryFromSexp` returns) names its
2332/// choices: `one of "fast", "slow"`; a class error names the class
2333/// (`a data frame`); an `Either` whose arms both refused the kind of value
2334/// names both (`one of "fast", "slow", or numeric`).
2335#[doc(hidden)]
2336pub trait ConversionExpectBuiltin {
2337    fn __mx_conversion_expectation(&self) -> Option<String>;
2338}
2339
2340impl ConversionExpectBuiltin for crate::from_r::SexpError {
2341    fn __mx_conversion_expectation(&self) -> Option<String> {
2342        self.r_expectation()
2343    }
2344}
2345
2346impl ConversionExpectBuiltin for crate::match_arg::MatchArgError {
2347    fn __mx_conversion_expectation(&self) -> Option<String> {
2348        Some(self.expectation())
2349    }
2350}
2351
2352/// Expectation probe, fallback arm: any other error type says nothing about
2353/// what the value should have been.
2354#[doc(hidden)]
2355pub trait ConversionExpectNone {
2356    fn __mx_conversion_expectation(&self) -> Option<String>;
2357}
2358
2359impl<E> ConversionExpectNone for &E {
2360    fn __mx_conversion_expectation(&self) -> Option<String> {
2361        None
2362    }
2363}
2364
2365/// Internal: what a failed argument conversion's error says the value should
2366/// have been, for a parameter whose Rust type gives the macro no R-facing
2367/// expectation (#1594). `Some("one of \"fast\", \"slow\"")` for a `match_arg`
2368/// choice error, `Some("a data frame")` for a class error, the joined
2369/// expectation of an `Either` whose arms both refused the kind of value,
2370/// `None` otherwise. Not public API.
2371#[doc(hidden)]
2372#[macro_export]
2373macro_rules! __mx_conversion_expectation {
2374    ($e:expr) => {{
2375        #[allow(unused_imports)]
2376        use $crate::condition::{ConversionExpectBuiltin as _, ConversionExpectNone as _};
2377        match &$e {
2378            __mx_e => __mx_e.__mx_conversion_expectation(),
2379        }
2380    }};
2381}
2382
2383/// Whole-message probe, built-in arm: a `match_arg` choice error, as a
2384/// [`MatchArgError`](crate::match_arg::MatchArgError) or at the top of a
2385/// `SexpError` (`#[derive(MatchArg)]`'s `TryFromSexp` returns one), words the
2386/// whole argument error the way the wrapper's R-side `match_arg` check
2387/// (`.miniextendr_match_arg`) does, from the same
2388/// [`MatchArgError::arg_error`](crate::match_arg::MatchArgError::arg_error)
2389/// (#1767): `'mode' should be one of "fast", "slow"`, `'mode' must be of
2390/// length 1`, `'mode' must be NULL or a character vector`. So a `match_arg`
2391/// type converted without `#[miniextendr(match_arg)]` and one checked by the
2392/// wrapper raise the same message.
2393///
2394/// A choice error inside an `Either` is not one: the `Either` names both of
2395/// its arms (`'x' must be one of "oral", "bolus", or a single double: got
2396/// logical`).
2397#[doc(hidden)]
2398pub trait ConversionArgMessageBuiltin {
2399    fn __mx_conversion_arg_message(&self, name: &str) -> Option<String>;
2400}
2401
2402impl ConversionArgMessageBuiltin for crate::match_arg::MatchArgError {
2403    fn __mx_conversion_arg_message(&self, name: &str) -> Option<String> {
2404        Some(self.arg_error(name).message().to_string())
2405    }
2406}
2407
2408impl ConversionArgMessageBuiltin for crate::from_r::SexpError {
2409    fn __mx_conversion_arg_message(&self, name: &str) -> Option<String> {
2410        match self {
2411            crate::from_r::SexpError::MatchArg(e) => Some(e.arg_error(name).message().to_string()),
2412            // A type's check refusal (`check_sexp` under `Option<T>` /
2413            // `Vec<T>`, or a conversion whose error converted into
2414            // `SexpError`) with its own whole message (#1833).
2415            crate::from_r::SexpError::Condition(e) => e.argument_message_str().map(str::to_string),
2416            _ => None,
2417        }
2418    }
2419}
2420
2421/// Whole-message probe, classed arm: any [`RConditionData`] answers with its
2422/// [`argument_message`](RConditionData::argument_message), so a type's own
2423/// conversion error can word the whole argument error (#1833). Same autoref
2424/// level as [`ConversionArgMessageBuiltin`], like [`ConversionErrClassed`]:
2425/// no built-in error type implements [`RConditionData`].
2426#[doc(hidden)]
2427pub trait ConversionArgMessageClassed {
2428    fn __mx_conversion_arg_message(&self, name: &str) -> Option<String>;
2429}
2430
2431impl<E: RConditionData> ConversionArgMessageClassed for E {
2432    fn __mx_conversion_arg_message(&self, _name: &str) -> Option<String> {
2433        self.argument_message()
2434    }
2435}
2436
2437/// Whole-message probe, fallback arm: any other error leaves the message to
2438/// the prefix and the error's reason.
2439#[doc(hidden)]
2440pub trait ConversionArgMessageNone {
2441    fn __mx_conversion_arg_message(&self, name: &str) -> Option<String>;
2442}
2443
2444impl<E> ConversionArgMessageNone for &E {
2445    fn __mx_conversion_arg_message(&self, _name: &str) -> Option<String> {
2446        None
2447    }
2448}
2449
2450/// Internal: the whole message of a failed argument conversion whose error
2451/// words it itself (a `match_arg` choice error, see
2452/// [`ConversionArgMessageBuiltin`], or an error with an
2453/// [`argument_message`](RConditionData::argument_message), see
2454/// [`ConversionArgMessageClassed`]), for the argument `$name`; `None`
2455/// otherwise. [`crate::error_value::conversion_condition_value`] then uses it
2456/// in place of `<prefix>: <reason>`. Not public API.
2457#[doc(hidden)]
2458#[macro_export]
2459macro_rules! __mx_conversion_arg_message {
2460    ($e:expr, $name:expr) => {{
2461        #[allow(unused_imports)]
2462        use $crate::condition::{
2463            ConversionArgMessageBuiltin as _, ConversionArgMessageClassed as _,
2464            ConversionArgMessageNone as _,
2465        };
2466        match &$e {
2467            __mx_e => __mx_e.__mx_conversion_arg_message($name),
2468        }
2469    }};
2470}
2471
2472/// The message prefix of a conversion failure whose expectation comes from
2473/// the error at run time (see [`crate::__mx_conversion_expectation!`]):
2474/// `'<p>' must be <expected>` (`'<p>' must be NULL or <expected>` for an
2475/// `Option<_>` parameter, `nullable`), else `invalid '<p>' argument`.
2476#[doc(hidden)]
2477pub fn conversion_prefix(param: &str, nullable: bool, expected: Option<&str>) -> String {
2478    match expected {
2479        Some(expected) if nullable => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}\' must be NULL or {1}",
                param, expected))
    })format!("'{param}' must be NULL or {expected}"),
2480        Some(expected) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}\' must be {1}", param,
                expected))
    })format!("'{param}' must be {expected}"),
2481        None => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("invalid \'{0}\' argument", param))
    })format!("invalid '{param}' argument"),
2482    }
2483}
2484
2485/// The name of the structured field that carries the failing parameter's R
2486/// name on every argument-conversion condition (`e$param`).
2487const CONVERSION_PARAM_FIELD: &str = "param";
2488
2489/// The name of the structured field that carries the Rust type an argument
2490/// failed to convert to (`e$rust_type`, #1591).
2491const CONVERSION_RUST_TYPE_FIELD: &str = "rust_type";
2492
2493/// Combine an argument-conversion error's own parts with the wrapper's
2494/// parameter context.
2495///
2496/// - The message becomes `<prefix>: <error message>`. For an argument the
2497///   macro writes the prefix in R terms (#1591): `'<p>' must be <expected>`
2498///   when it knows what the argument should be (`'x' must be a single
2499///   integer`, `'dv' must be numeric`), `invalid '<p>' argument` otherwise.
2500///   A sidecar setter passes its own prefix. An error that words the whole
2501///   argument error itself, a `match_arg` choice error (#1767) or one with an
2502///   [`argument_message`](RConditionData::argument_message) (#1833), gives
2503///   `arg_message` ([`crate::__mx_conversion_arg_message!`]), which is the
2504///   message instead.
2505/// - The class vector is the error's own (empty for the built-in and
2506///   `Display` arms), followed by `crate_class`, the crate's
2507///   `conversion_error_class` from `[package.metadata.miniextendr]`, minus
2508///   any class the error already names. The R helper appends the
2509///   `rust_error` layering after both.
2510/// - `param` (the parameter's R name) is added as the first data field,
2511///   `e$param`, and `rust_type` (the Rust type as written in the signature,
2512///   when given) after it, `e$rust_type`. Neither is added when the error's
2513///   own data already has a field of that name: the type author's value is
2514///   kept, since the framework never overwrites a field the type author
2515///   chose, and R's `e$name` reads only the first of two same-named fields.
2516/// - The call is always the wrapper's ([`ConditionCall::Inherit`]), whatever
2517///   the error type's [`RConditionData::call`] says: the R-side checks
2518///   (`.miniextendr_arg_error`) raise the same condition with the call
2519///   (#1591), and an argument error must not differ by which side caught it.
2520#[doc(hidden)]
2521pub fn conversion_err_parts(
2522    prefix: &str,
2523    param: &str,
2524    rust_type: Option<&str>,
2525    crate_class: &[&str],
2526    parts: ErrParts,
2527    arg_message: Option<String>,
2528) -> ErrParts {
2529    let ErrParts {
2530        message,
2531        mut class,
2532        data,
2533        call: _,
2534    } = parts;
2535    let message = arg_message.unwrap_or_else(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", prefix, message))
    })format!("{prefix}: {message}"));
2536    for extra in crate_class {
2537        if !class.iter().any(|c| c == extra) {
2538            class.push((*extra).to_string());
2539        }
2540    }
2541    let mut fields = data.unwrap_or_default();
2542    let has_field =
2543        |fields: &ConditionData, field: &str| fields.iter().any(|(name, _)| name == field);
2544    let mut at = 0;
2545    if !has_field(&fields, CONVERSION_PARAM_FIELD) {
2546        fields.insert(0, (CONVERSION_PARAM_FIELD.to_string(), param.into()));
2547        at = 1;
2548    }
2549    if let Some(rust_type) = rust_type
2550        && !has_field(&fields, CONVERSION_RUST_TYPE_FIELD)
2551    {
2552        fields.insert(
2553            at,
2554            (CONVERSION_RUST_TYPE_FIELD.to_string(), rust_type.into()),
2555        );
2556    }
2557    ErrParts {
2558        message,
2559        class,
2560        data: Some(fields),
2561        call: ConditionCall::Inherit,
2562    }
2563}
2564
2565/// The parts of an argument check that failed in Rust after the conversion:
2566/// `#[miniextendr(no_na)]` on a reading marker (`AsNumeric*`,
2567/// `AsCharacter*`) whose converted value holds an `NA` that R's `anyNA()`
2568/// did not see (the hidden `TryFromSexp::__mx_has_na` says so), or on an
2569/// `Either`, which has no R guard, an `NA` the arm taken refuses
2570/// (`TryFromSexp::__mx_input_has_na`).
2571///
2572/// The shape is the R guard's (`.miniextendr_arg_error`): `message` as given
2573/// (the macro writes `'<p>' must not be NA` or the author's own message),
2574/// the classes `crate_class` (the crate's `conversion_error_class`), and
2575/// `param` as the only data field, `e$param`. No `rust_type`: the R guard
2576/// has none, and the two paths raise one condition.
2577#[doc(hidden)]
2578pub fn arg_check_parts(message: &str, param: &str, crate_class: &[&str]) -> ErrParts {
2579    ErrParts {
2580        message: message.to_string(),
2581        class: crate_class.iter().map(|c| (*c).to_string()).collect(),
2582        data: Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(CONVERSION_PARAM_FIELD.to_string(), param.into())]))vec![(CONVERSION_PARAM_FIELD.to_string(), param.into())]),
2583        call: ConditionCall::Inherit,
2584    }
2585}
2586
2587// endregion
2588
2589// region: SerdeErrorShape — `serde_error` options as a shared const (#2207)
2590
2591/// The options of `#[miniextendr(serde_error(..))]` as a value: declared once,
2592/// shared by every function that returns one error type.
2593///
2594/// ```
2595/// use miniextendr_api::condition::SerdeErrorShape;
2596///
2597/// pub const ENGINE: SerdeErrorShape = SerdeErrorShape::new()
2598///     .prefix("engine")
2599///     .skip(&["message"])
2600///     .as_character(&["rule", "column"])
2601///     .as_integer(&["n"]);
2602/// ```
2603///
2604/// Declare it for the error type with
2605/// [`serde_error_shape!`](crate::serde_error_shape), and every
2606/// `#[miniextendr]` function or method of the crate that returns that type
2607/// uses it, without naming it:
2608///
2609/// ```ignore
2610/// miniextendr_api::serde_error_shape!(EngineError = ENGINE);
2611///
2612/// #[miniextendr]
2613/// pub fn check(x: f64) -> Result<f64, EngineError> { /* ... */ }
2614/// ```
2615///
2616/// A function can override it for itself: with options of its own, or with
2617/// another shape named by path, which applies after the declared one:
2618///
2619/// ```ignore
2620/// #[miniextendr(serde_error(as_double("n")))]
2621/// pub fn rate(x: f64) -> Result<f64, EngineError> { /* ... */ }
2622///
2623/// #[miniextendr(serde_error(shape = STRICT, as_double("n")))]
2624/// pub fn strict_rate(x: f64) -> Result<f64, EngineError> { /* ... */ }
2625/// ```
2626///
2627/// The path resolves where the function is defined (`STRICT`,
2628/// `crate::errors::STRICT`, or `Self::SHAPE` on a method for an associated
2629/// const of its type), so a misspelt one is a compile error. The options act
2630/// on the serde-classed `Err` arm, which needs the `serde` feature.
2631///
2632/// # Options
2633///
2634/// One method per `serde_error` option. Fields are named as the error
2635/// serializes them, before any `rename`:
2636///
2637/// - [`tag`](Self::tag): the internally tagged discriminator field consumed
2638///   as the variant; `"kind"` when unset.
2639/// - [`prefix`](Self::prefix): the family class; `<crate>_error`, from the
2640///   function's crate, when unset.
2641/// - [`skip`](Self::skip): fields to drop.
2642/// - [`rename`](Self::rename): `(from, to)` pairs; field `from` reaches R as
2643///   `e$to`.
2644/// - [`as_character`](Self::as_character), [`as_integer`](Self::as_integer),
2645///   [`as_double`](Self::as_double), [`as_logical`](Self::as_logical): the
2646///   field's usual serialization as one vector of that R type, as the
2647///   `miniextendr_api::serde::as_character` & co. field helpers give it from
2648///   the error type's own `#[serde(serialize_with = ..)]`: `character(0)` for
2649///   an empty sequence, `NA` for a `None` element. A value that doesn't fit
2650///   (a string under `as_integer`) raises an R error naming the field and the
2651///   option.
2652///
2653/// A field that a variant doesn't carry is a no-op for that variant, so one
2654/// shape covers an enum whose variants differ.
2655///
2656/// # Precedence
2657///
2658/// Shapes apply in order: the one declared for the error type, then
2659/// `serde_error(shape = ..)`, then the function's own options; for a field
2660/// set by more than one, the later wins. A later `skip` drops a field an
2661/// earlier shape types or renames, and a later `as_*` or `rename` keeps a
2662/// field an earlier shape skips. A type and a new name compose: the
2663/// function's `rename(n = "count")` keeps the shape's `as_integer(&["n"])`.
2664/// A later `tag` or `prefix` replaces an earlier one.
2665///
2666/// # Contradictions don't compile
2667///
2668/// Each method checks its fields against the options already set and panics
2669/// during const evaluation, so a `const` holding a contradictory shape is a
2670/// compile error (E0080) naming the field:
2671///
2672/// - a field in two `as_*` lists;
2673/// - a field skipped and also typed or renamed;
2674/// - a field listed twice, renamed twice, or two renames onto one name;
2675/// - a `rename` target that is one of the condition's own slots (`message`,
2676///   `call`, `kind`);
2677/// - an empty list or name, and an option set twice.
2678///
2679/// ```compile_fail,E0080
2680/// use miniextendr_api::condition::SerdeErrorShape;
2681///
2682/// const ENGINE: SerdeErrorShape = SerdeErrorShape::new()
2683///     .as_integer(&["n"])
2684///     .as_double(&["n"]);
2685/// ```
2686#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for SerdeErrorShape {
}
#[automatically_derived]impl ::core::clone::Clone for SerdeErrorShape {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Option<&'static str>>;
        let _: ::core::clone::AssertParamIsClone<Option<&'static str>>;
        let _: ::core::clone::AssertParamIsClone<&'static [&'static str]>;
        let _:
                ::core::clone::AssertParamIsClone<&'static [(&'static str,
                &'static str)]>;
        let _:
                ::core::clone::AssertParamIsClone<[&'static [&'static str]; 4]>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for SerdeErrorShape { }Copy, #[automatically_derived]impl ::core::fmt::Debug for SerdeErrorShape {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f,
            "SerdeErrorShape tag prefix skip rename types", &self.tag,
            &self.prefix, &self.skip, &self.rename, &&self.types)
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    SerdeErrorShape {
}
#[automatically_derived]impl ::core::cmp::PartialEq for SerdeErrorShape {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.tag == other.tag && self.prefix == other.prefix &&
                    self.skip == other.skip && self.rename == other.rename &&
            self.types == other.types
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for SerdeErrorShape {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Option<&'static str>>;
        let _: ::core::cmp::AssertParamIsEq<Option<&'static str>>;
        let _: ::core::cmp::AssertParamIsEq<&'static [&'static str]>;
        let _:
                ::core::cmp::AssertParamIsEq<&'static [(&'static str,
                &'static str)]>;
        let _: ::core::cmp::AssertParamIsEq<[&'static [&'static str]; 4]>;
    }
}Eq)]
2687pub struct SerdeErrorShape {
2688    tag: Option<&'static str>,
2689    prefix: Option<&'static str>,
2690    skip: &'static [&'static str],
2691    rename: &'static [(&'static str, &'static str)],
2692    /// The `as_*` lists, in [`SHAPE_TYPE_OPTIONS`] order.
2693    types: [&'static [&'static str]; 4],
2694}
2695
2696/// The `as_*` options, in the order of [`SerdeErrorShape`]'s type lists.
2697const SHAPE_TYPE_OPTIONS: [&str; 4] = ["as_logical", "as_integer", "as_double", "as_character"];
2698
2699impl SerdeErrorShape {
2700    /// The discriminator field when no shape names one.
2701    #[cfg(feature = "serde")]
2702    const DEFAULT_TAG: &'static str = "kind";
2703
2704    /// A shape that sets nothing.
2705    pub const fn new() -> Self {
2706        SerdeErrorShape {
2707            tag: None,
2708            prefix: None,
2709            skip: &[],
2710            rename: &[],
2711            types: [&[]; 4],
2712        }
2713    }
2714
2715    /// The internally tagged discriminator field (`#[serde(tag = "...")]`),
2716    /// consumed as the variant.
2717    #[track_caller]
2718    pub const fn tag(mut self, tag: &'static str) -> Self {
2719        self.tag = Some(scalar_option("tag", self.tag, tag));
2720        self
2721    }
2722
2723    /// The family class: conditions get `c("<prefix>_<variant>", "<prefix>")`.
2724    #[track_caller]
2725    pub const fn prefix(mut self, prefix: &'static str) -> Self {
2726        self.prefix = Some(scalar_option("prefix", self.prefix, prefix));
2727        self
2728    }
2729
2730    /// Drop these payload fields.
2731    #[track_caller]
2732    pub const fn skip(mut self, fields: &'static [&'static str]) -> Self {
2733        check_field_list("skip", self.skip.is_empty(), fields);
2734        let mut i = 0;
2735        while i < fields.len() {
2736            let name = fields[i];
2737            if let Some(option) = self.type_option(name) {
2738                conflict(name, option, "skip", "a skipped field has no R type");
2739            }
2740            if self.renames(name) {
2741                conflict(name, "rename", "skip", "a skipped field has no name");
2742            }
2743            i += 1;
2744        }
2745        self.skip = fields;
2746        self
2747    }
2748
2749    /// Splice field `from` as `to`, for each `(from, to)` pair.
2750    #[track_caller]
2751    pub const fn rename(mut self, pairs: &'static [(&'static str, &'static str)]) -> Self {
2752        if !self.rename.is_empty() {
2753            set_twice("rename");
2754        }
2755        if pairs.is_empty() {
2756            fail(ShapeMessage::new().push("`rename` needs at least one pair"));
2757        }
2758        let mut i = 0;
2759        while i < pairs.len() {
2760            let (from, to) = pairs[i];
2761            if from.is_empty() || to.is_empty() {
2762                fail(ShapeMessage::new().push("`rename` has an empty name"));
2763            }
2764            if is_reserved_condition_field(to) {
2765                fail(ShapeMessage::new().push("`rename` target `").push(to).push(
2766                    "` is reserved: `message`, `call` and `kind` are the condition's own slots",
2767                ));
2768            }
2769            let mut j = 0;
2770            while j < i {
2771                if str_eq(pairs[j].0, from) {
2772                    fail(
2773                        ShapeMessage::new()
2774                            .push("field `")
2775                            .push(from)
2776                            .push("` is renamed twice"),
2777                    );
2778                }
2779                if str_eq(pairs[j].1, to) {
2780                    fail(
2781                        ShapeMessage::new()
2782                            .push("two `rename` pairs target `")
2783                            .push(to)
2784                            .push("`; R would read only the first"),
2785                    );
2786                }
2787                j += 1;
2788            }
2789            if const_contains(self.skip, from) {
2790                conflict(from, "skip", "rename", "a skipped field has no name");
2791            }
2792            i += 1;
2793        }
2794        self.rename = pairs;
2795        self
2796    }
2797
2798    /// Give these fields an R `logical` vector.
2799    #[track_caller]
2800    pub const fn as_logical(self, fields: &'static [&'static str]) -> Self {
2801        self.with_type(0, fields)
2802    }
2803
2804    /// Give these fields an R `integer` vector; a value outside R's integer
2805    /// range is an error, not a double.
2806    #[track_caller]
2807    pub const fn as_integer(self, fields: &'static [&'static str]) -> Self {
2808        self.with_type(1, fields)
2809    }
2810
2811    /// Give these fields an R `double` vector; integers widen.
2812    #[track_caller]
2813    pub const fn as_double(self, fields: &'static [&'static str]) -> Self {
2814        self.with_type(2, fields)
2815    }
2816
2817    /// Give these fields an R `character` vector.
2818    #[track_caller]
2819    pub const fn as_character(self, fields: &'static [&'static str]) -> Self {
2820        self.with_type(3, fields)
2821    }
2822
2823    #[track_caller]
2824    const fn with_type(mut self, index: usize, fields: &'static [&'static str]) -> Self {
2825        let option = SHAPE_TYPE_OPTIONS[index];
2826        check_field_list(option, self.types[index].is_empty(), fields);
2827        let mut i = 0;
2828        while i < fields.len() {
2829            let name = fields[i];
2830            if const_contains(self.skip, name) {
2831                conflict(name, "skip", option, "a skipped field has no R type");
2832            }
2833            if let Some(other) = self.type_option(name) {
2834                conflict(name, other, option, "a field has one R type");
2835            }
2836            i += 1;
2837        }
2838        self.types[index] = fields;
2839        self
2840    }
2841
2842    /// The `as_*` option that lists `name`.
2843    const fn type_option(&self, name: &str) -> Option<&'static str> {
2844        let mut i = 0;
2845        while i < self.types.len() {
2846            if const_contains(self.types[i], name) {
2847                return Some(SHAPE_TYPE_OPTIONS[i]);
2848            }
2849            i += 1;
2850        }
2851        None
2852    }
2853
2854    /// Whether a `rename` pair renames `name`.
2855    const fn renames(&self, name: &str) -> bool {
2856        let mut i = 0;
2857        while i < self.rename.len() {
2858            if str_eq(self.rename[i].0, name) {
2859                return true;
2860            }
2861            i += 1;
2862        }
2863        false
2864    }
2865}
2866
2867impl Default for SerdeErrorShape {
2868    fn default() -> Self {
2869        Self::new()
2870    }
2871}
2872
2873/// `tag` / `prefix`: set once, never empty.
2874#[track_caller]
2875const fn scalar_option(
2876    option: &str,
2877    current: Option<&'static str>,
2878    value: &'static str,
2879) -> &'static str {
2880    if current.is_some() {
2881        set_twice(option);
2882    }
2883    if value.is_empty() {
2884        fail(
2885            ShapeMessage::new()
2886                .push("`")
2887                .push(option)
2888                .push("` must not be empty"),
2889        );
2890    }
2891    value
2892}
2893
2894/// A field list: set once, not empty, each name non-empty and listed once.
2895#[track_caller]
2896const fn check_field_list(option: &str, unset: bool, fields: &[&str]) {
2897    if !unset {
2898        set_twice(option);
2899    }
2900    if fields.is_empty() {
2901        fail(
2902            ShapeMessage::new()
2903                .push("`")
2904                .push(option)
2905                .push("` needs at least one field"),
2906        );
2907    }
2908    let mut i = 0;
2909    while i < fields.len() {
2910        if fields[i].is_empty() {
2911            fail(
2912                ShapeMessage::new()
2913                    .push("`")
2914                    .push(option)
2915                    .push("` has an empty field name"),
2916            );
2917        }
2918        let mut j = 0;
2919        while j < i {
2920            if str_eq(fields[j], fields[i]) {
2921                fail(
2922                    ShapeMessage::new()
2923                        .push("field `")
2924                        .push(fields[i])
2925                        .push("` is listed twice in `")
2926                        .push(option)
2927                        .push("`"),
2928                );
2929            }
2930            j += 1;
2931        }
2932        i += 1;
2933    }
2934}
2935
2936#[track_caller]
2937const fn set_twice(option: &str) -> ! {
2938    fail(
2939        ShapeMessage::new()
2940            .push("`")
2941            .push(option)
2942            .push("` is set twice; set each option once"),
2943    )
2944}
2945
2946#[track_caller]
2947const fn conflict(name: &str, first: &str, second: &str, why: &str) -> ! {
2948    fail(
2949        ShapeMessage::new()
2950            .push("field `")
2951            .push(name)
2952            .push("` is in both `")
2953            .push(first)
2954            .push("` and `")
2955            .push(second)
2956            .push("`; ")
2957            .push(why),
2958    )
2959}
2960
2961const fn const_contains(list: &[&str], name: &str) -> bool {
2962    let mut i = 0;
2963    while i < list.len() {
2964        if str_eq(list[i], name) {
2965            return true;
2966        }
2967        i += 1;
2968    }
2969    false
2970}
2971
2972/// A const-evaluation panic message. `const fn` can't `format!`, so the parts
2973/// are copied into a fixed buffer.
2974struct ShapeMessage {
2975    buf: [u8; 256],
2976    len: usize,
2977}
2978
2979impl ShapeMessage {
2980    const fn new() -> Self {
2981        ShapeMessage {
2982            buf: [0; 256],
2983            len: 0,
2984        }
2985        .push("SerdeErrorShape: ")
2986    }
2987
2988    const fn push(mut self, text: &str) -> Self {
2989        let bytes = text.as_bytes();
2990        let mut i = 0;
2991        while i < bytes.len() && self.len < self.buf.len() {
2992            self.buf[self.len] = bytes[i];
2993            self.len += 1;
2994            i += 1;
2995        }
2996        self
2997    }
2998}
2999
3000/// Panic with `message`. `#[track_caller]` here and on every caller puts the
3001/// compile error at the user's `const`, not in this crate.
3002#[track_caller]
3003const fn fail(message: ShapeMessage) -> ! {
3004    let (text, _) = message.buf.split_at(message.len);
3005    match core::str::from_utf8(text) {
3006        Ok(text) => { ::core::panicking::panic_display(&text); }panic!("{}", text),
3007        // The buffer ended inside a long field name's character.
3008        Err(_) => {
3009            {
    ::core::panicking::panic_fmt(format_args!("SerdeErrorShape: contradictory options; a field name is too long to quote"));
}panic!("SerdeErrorShape: contradictory options; a field name is too long to quote")
3010        }
3011    }
3012}
3013
3014// endregion
3015
3016// region: Serde-tagged Result errors (#[miniextendr(serde_error)])
3017
3018/// Build the `Err`-arm parts from the error's serde shape.
3019///
3020/// Reached three ways: for a `Result<T, E>` whose `E` has a shape declared
3021/// by [`serde_error_shape!`](crate::serde_error_shape) (the
3022/// [`ErrShapeDeclared`] probe arm, that one shape); automatically, for every
3023/// other `E` that is `Serialize + Display` without an [`RConditionData`] impl
3024/// (the [`ErrPartsSerde`] probe arm, no shapes); or explicitly through
3025/// `#[miniextendr(serde_error(..))]`, whose options arrive as `shapes`: the
3026/// declared shape first (one that sets nothing when there is none), then the
3027/// named `shape = ..`, then the function's own options as an inline const,
3028/// each applied in order (see [`SerdeErrorShape`], "Precedence").
3029/// `prefix` is the macro's `<crate>_error`, used when no shape sets one.
3030///
3031/// Message from `Display`; classes `[<prefix>_<variant>, <prefix>]` when the
3032/// serialized value carries a variant, `[<prefix>]` otherwise; data from the
3033/// serialized fields (checked against the reserved names). `tag` names the
3034/// internally-tagged discriminator field (`#[serde(tag = "kind")]`), which is
3035/// consumed as the member class rather than spliced as data; externally tagged
3036/// enums (serde's default) yield the variant name directly. See
3037/// `docs/CONDITIONS.md`, "Classed `Result` errors".
3038///
3039/// Field control, applied to the payload fields before the reserved-name
3040/// check (`serde_error(skip(..), rename(..), as_*(..))`, #1457, #2207):
3041///
3042/// - `skip`: fields with these names are dropped.
3043/// - `as_character` / `as_integer` / `as_double` / `as_logical`: the field's
3044///   value becomes one vector of that type, through the same conversion as
3045///   the `serde::as_*` field helpers; a value that doesn't fit panics, naming
3046///   the field and the option.
3047/// - `rename`: `(from, to)` pairs; a field named `from` is spliced as `to`.
3048/// - A remaining field named `message` whose value is the single string equal
3049///   to the `Display` output is dropped: it duplicates the condition's own
3050///   `message` slot, so a wrapped parser error of the shape
3051///   `Variant { message: String }` reaches R without any option.
3052///
3053/// Names that a given variant does not carry are a no-op for that variant.
3054/// Any other collision with `message`, `call` or `kind` still panics via
3055/// [`check_condition_data`].
3056///
3057/// After `skip` / `rename` the field names must be distinct: a `rename` whose
3058/// target is a name the variant already carries (or two payload fields that
3059/// serialize under one name) would give the condition two entries with the
3060/// same name, of which R's `e$name` reads only the first. That panics too,
3061/// naming the field and the rename that produced it (#1459).
3062///
3063/// Serialization failing (a map with non-string keys, a custom `Serialize`
3064/// erroring) panics with both failures in the message: the original error
3065/// text must not be lost behind the reporting problem.
3066#[cfg(feature = "serde")]
3067#[doc(hidden)]
3068#[track_caller]
3069pub fn serde_err_parts<E: ?Sized + ::serde::Serialize + std::fmt::Display>(
3070    e: &E,
3071    prefix: &str,
3072    shapes: &[&SerdeErrorShape],
3073) -> ErrParts {
3074    let message = e.to_string();
3075    let tag = shapes
3076        .iter()
3077        .rev()
3078        .find_map(|s| s.tag)
3079        .unwrap_or(SerdeErrorShape::DEFAULT_TAG);
3080    let prefix = shapes.iter().rev().find_map(|s| s.prefix).unwrap_or(prefix);
3081    let (member, fields) = match crate::serde::rvalue_ser::tagged_parts(e, tag) {
3082        Ok(parts) => parts,
3083        Err(err) => panic!(
3084            "#[miniextendr(serde_error)]: serializing `{}` for its condition data failed ({err}); \
3085             the original error was: {message}",
3086            std::any::type_name::<E>()
3087        ),
3088    };
3089    let mut class = Vec::with_capacity(2);
3090    if let Some(member) = member {
3091        class.push(format!("{prefix}_{member}"));
3092    }
3093    class.push(prefix.to_string());
3094    let mut renames = Vec::new();
3095    let mut data: ConditionData = Vec::with_capacity(fields.len());
3096    for (name, value) in fields {
3097        let Some(field) = FieldShape::resolve(shapes, &name) else {
3098            continue;
3099        };
3100        let value = match field.atomic {
3101            None => value,
3102            Some(atomic) => match atomic.try_coerce(value) {
3103                Ok(value) => value,
3104                Err(element) => panic!(
3105                    "#[miniextendr(serde_error)]: `{}` on condition data field `{name}` failed: \
3106                     {}; the original error was: {message}",
3107                    atomic.helper(),
3108                    atomic.mismatch(element)
3109                ),
3110            },
3111        };
3112        if let Some((from, to)) = field.rename {
3113            renames.push((from, to));
3114            data.push((to.to_string(), value));
3115            continue;
3116        }
3117        let echoes_display = name == "message"
3118            && matches!(&value, crate::RValue::Character(v)
3119                if v.len() == 1 && v[0].as_deref() == Some(message.as_str()));
3120        if !echoes_display {
3121            data.push((name, value));
3122        }
3123    }
3124    check_distinct_field_names(&data, &renames);
3125    ErrParts {
3126        message,
3127        class,
3128        data: check_condition_data((!data.is_empty()).then_some(data)),
3129        call: ConditionCall::Inherit,
3130    }
3131}
3132
3133/// What the shapes, applied in order, give one payload field.
3134#[cfg(feature = "serde")]
3135#[derive(Default)]
3136struct FieldShape {
3137    atomic: Option<crate::serde::rvalue_ser::Atomic>,
3138    rename: Option<(&'static str, &'static str)>,
3139}
3140
3141#[cfg(feature = "serde")]
3142impl FieldShape {
3143    /// `None` when the last shape that names the field skips it. A later
3144    /// `skip` drops what earlier shapes set; a later type or rename replaces
3145    /// that setting and keeps the field.
3146    fn resolve(shapes: &[&SerdeErrorShape], name: &str) -> Option<Self> {
3147        let mut skipped = false;
3148        let mut field = FieldShape::default();
3149        for shape in shapes {
3150            if shape.skip.contains(&name) {
3151                skipped = true;
3152                field = FieldShape::default();
3153            }
3154            if let Some(i) = shape.types.iter().position(|list| list.contains(&name)) {
3155                skipped = false;
3156                field.atomic = Some(crate::serde::rvalue_ser::Atomic::ALL[i]);
3157            }
3158            if let Some(&pair) = shape.rename.iter().find(|(from, _)| *from == name) {
3159                skipped = false;
3160                field.rename = Some(pair);
3161            }
3162        }
3163        (!skipped).then_some(field)
3164    }
3165}
3166
3167/// Panic when two payload fields share a name after `skip` / `rename`.
3168///
3169/// R's `e$<name>` returns the first entry with that name and the second is
3170/// unreachable, which is the silent-overwrite failure the reserved-name rule
3171/// exists to remove (#1440). Neither first-wins nor last-wins would report it.
3172#[cfg(feature = "serde")]
3173#[track_caller]
3174fn check_distinct_field_names(fields: &[(String, crate::RValue)], rename: &[(&str, &str)]) {
3175    let mut seen = std::collections::HashSet::with_capacity(fields.len());
3176    for (name, _) in fields {
3177        if seen.insert(name.as_str()) {
3178            continue;
3179        }
3180        let renames: Vec<String> = rename
3181            .iter()
3182            .filter(|(_, to)| *to == name)
3183            .map(|(from, to)| format!("`rename({from} = \"{to}\")`"))
3184            .collect();
3185        if renames.is_empty() {
3186            panic!(
3187                "#[miniextendr(serde_error)]: condition data field `{name}` appears twice in the \
3188                 serialized payload; R's `e${name}` would read only the first. Give the fields \
3189                 distinct names or `skip` one of them."
3190            );
3191        }
3192        panic!(
3193            "#[miniextendr(serde_error)]: condition data field `{name}` appears twice: {} targets \
3194             a name this variant already carries; R's `e${name}` would read only the first. Pick \
3195             another target or `skip` the existing field.",
3196            renames.join(" and ")
3197        );
3198    }
3199}
3200
3201// endregion
3202
3203// region: Declared shapes — one SerdeErrorShape per error type (#2207)
3204
3205/// The [`SerdeErrorShape`] declared for the error type `Self` by the crate
3206/// whose marker type is `M`. Implemented by
3207/// [`serde_error_shape!`](crate::serde_error_shape), not by hand.
3208///
3209/// `M` is a type local to the declaring crate (`miniextendr_init!` defines it
3210/// at the crate root). That is what lets an R-facing crate declare a shape
3211/// for an error type from a crate that doesn't depend on miniextendr: the
3212/// orphan rule accepts `impl ForeignTrait<LocalType> for ForeignType`. It also
3213/// scopes the declaration to the crate: another crate returning the same type
3214/// looks up its own declaration.
3215///
3216/// The supertraits make a declaration for a type that can't be serialized, or
3217/// has no `Display` for the condition message, an error at the declaration.
3218#[cfg(feature = "serde")]
3219pub trait SerdeErrorShapeFor<M>: ::serde::Serialize + std::fmt::Display {
3220    /// The declared shape.
3221    const SHAPE: &'static SerdeErrorShape;
3222}
3223
3224/// Declare the [`SerdeErrorShape`] of an error type once, for every
3225/// `#[miniextendr]` function and method of this crate that returns it.
3226///
3227/// ```ignore
3228/// use miniextendr_api::condition::SerdeErrorShape;
3229///
3230/// pub const ENGINE: SerdeErrorShape = SerdeErrorShape::new()
3231///     .prefix("engine")
3232///     .as_character(&["rule"])
3233///     .as_integer(&["n"]);
3234///
3235/// miniextendr_api::serde_error_shape!(engine::Error = ENGINE);
3236///
3237/// // Both raise with ENGINE's field types; neither names it.
3238/// #[miniextendr]
3239/// pub fn check(x: f64) -> Result<f64, engine::Error> { /* ... */ }
3240///
3241/// #[miniextendr]
3242/// pub fn rate(x: f64) -> Result<f64, engine::Error> { /* ... */ }
3243/// ```
3244///
3245/// The right-hand side is any constant expression of type
3246/// `SerdeErrorShape`: a path, as above, or the builder chain itself. The type
3247/// must be `Serialize + Display` and may come from any crate, including one
3248/// that can't depend on miniextendr. The declaration goes anywhere in the
3249/// crate that calls `miniextendr_init!`, which defines the marker type it is
3250/// keyed by (see [`SerdeErrorShapeFor`]); it applies to that crate's
3251/// functions only.
3252///
3253/// # Precedence
3254///
3255/// Every `Err` of the type, from a function with or without
3256/// `#[miniextendr(serde_error(..))]`, is classed through serde with the
3257/// declared shape applied first. A function's `serde_error(shape = X)` applies
3258/// next and its own options last; for a field set more than once, the later
3259/// setting wins, by the rules under [`SerdeErrorShape`], "Precedence".
3260///
3261/// The declaration also wins over an [`RConditionData`] impl of the type: it is
3262/// the R-facing crate's choice for its own functions, where the impl is the
3263/// error crate's general one.
3264///
3265/// # One declaration per type
3266///
3267/// A second declaration for a type in the same crate is the compiler's
3268/// conflicting-implementations error:
3269///
3270/// ```compile_fail,E0119
3271/// use miniextendr_api::condition::SerdeErrorShape;
3272///
3273/// miniextendr_api::miniextendr_init!(pkg);
3274///
3275/// const A: SerdeErrorShape = SerdeErrorShape::new().prefix("a");
3276/// const B: SerdeErrorShape = SerdeErrorShape::new().prefix("b");
3277///
3278/// miniextendr_api::serde_error_shape!(String = A);
3279/// miniextendr_api::serde_error_shape!(String = B);
3280///
3281/// fn main() {}
3282/// ```
3283#[cfg(feature = "serde")]
3284#[macro_export]
3285// `crate::` is meant: the marker is the calling crate's.
3286#[allow(clippy::crate_in_macro_def)]
3287macro_rules! serde_error_shape {
3288    ($error:ty = $shape:expr $(,)?) => {
3289        impl $crate::condition::SerdeErrorShapeFor<crate::__MiniextendrInitMarker> for $error {
3290            const SHAPE: &'static $crate::condition::SerdeErrorShape = &$shape;
3291        }
3292    };
3293}
3294
3295/// Declare the `SerdeErrorShape` of an error type once, for every
3296/// `#[miniextendr]` function and method of this crate that returns it. Needs
3297/// the `serde` feature, without which a declaration is a compile error.
3298#[cfg(not(feature = "serde"))]
3299#[macro_export]
3300macro_rules! serde_error_shape {
3301    ($($input:tt)*) => {
3302        ::core::compile_error!(
3303            "`serde_error_shape!` needs the `serde` feature of miniextendr-api; \
3304             enable it to class errors through serde"
3305        );
3306    };
3307}
3308
3309/// The [`RCondition`](enum@RCondition) an error type that is
3310/// `Serialize + Display` gives as a `#[miniextendr]` function's `Err`, for
3311/// code that is not an entry point (#2217): a helper returning
3312/// `Result<T, RCondition>`, a body mixing it with conditions
3313/// [`catch_condition`] caught.
3314///
3315/// `serde_condition!(&err)` takes a reference to the error and runs the probe
3316/// a `Result` return's `Err` arm runs, with the calling crate's marker and
3317/// family class: the shape [`serde_error_shape!`]
3318/// declared for the type in this crate, else the type's [`RConditionData`]
3319/// impl, else its serde shape with the `<crate>_error` family class. The
3320/// condition is an error ([`RCondition::Error`]) with the classes, message,
3321/// fields and call choice an entry point returning `Err(err)` would raise.
3322///
3323/// ```ignore
3324/// use miniextendr_api::condition::{RCondition, catch_condition};
3325///
3326/// miniextendr_api::serde_error_shape!(engine::Error = ENGINE);
3327///
3328/// impl Model {
3329///     fn load(path: &str) -> Result<Self, RCondition> {
3330///         let spec = catch_condition(|| Self::spec(path))?;
3331///         let engine = engine::Engine::load(&spec)
3332///             .map_err(|e| miniextendr_api::serde_condition!(&e))?;
3333///         Ok(Model::new(spec, engine))
3334///     }
3335/// }
3336/// ```
3337///
3338/// The type must be `Serialize + Display`, which the macro checks. The marker
3339/// is the one `miniextendr_init!` defines at the crate root, so the crate must
3340/// call it, as every R package does. Without the `serde` feature the macro
3341/// is a compile error.
3342///
3343/// Pass one reference. An error already held as `&E` (`if let Err(e) =
3344/// &result`) goes in as it is, `serde_condition!(e)`: `&e` is a `&&E`, which
3345/// compiles, since `&E` is `Serialize + Display` too, but skips the declared
3346/// shape and the `RConditionData` impl, as an entry point returning `&E`
3347/// would.
3348#[cfg(feature = "serde")]
3349#[macro_export]
3350// `crate::` is meant: the marker is the calling crate's.
3351#[allow(clippy::crate_in_macro_def)]
3352macro_rules! serde_condition {
3353    // A `match`, not a `let`: a temporary in `$err` (`&Error::new(..)`) lives
3354    // to the end of the scrutinee's match.
3355    ($err:expr $(,)?) => {
3356        match $crate::condition::__mx_serde_condition_arg($err) {
3357            __mx_err => {
3358                let __mx_parts = $crate::__mx_result_err_parts!(
3359                    *__mx_err,
3360                    ::core::concat!(::core::env!("CARGO_CRATE_NAME"), "_error"),
3361                    crate::__MiniextendrInitMarker
3362                );
3363                $crate::condition::RCondition::Error {
3364                    message: __mx_parts.message,
3365                    class: __mx_parts.class,
3366                    data: __mx_parts.data,
3367                    call: __mx_parts.call,
3368                }
3369            }
3370        }
3371    };
3372}
3373
3374/// The `RCondition` a `Serialize + Display` error gives as an entry point's
3375/// `Err`. Needs the `serde` feature, without which it is a compile error.
3376#[cfg(not(feature = "serde"))]
3377#[macro_export]
3378macro_rules! serde_condition {
3379    ($($input:tt)*) => {
3380        ::core::compile_error!(
3381            "`serde_condition!` needs the `serde` feature of miniextendr-api; \
3382             enable it to class errors through serde"
3383        )
3384    };
3385}
3386
3387/// Internal: [`serde_condition!`]'s argument, a
3388/// reference to a `Serialize + Display` error, unchanged. Taking `&E` fixes
3389/// the reference depth the probe's stages see: one reference more would
3390/// skip the declared shape and the [`RConditionData`] stage.
3391#[cfg(feature = "serde")]
3392#[doc(hidden)]
3393#[inline]
3394pub fn __mx_serde_condition_arg<E: ::serde::Serialize + std::fmt::Display>(err: &E) -> &E {
3395    err
3396}
3397
3398/// The receiver of the declared-shape probe: the error, and the marker `M` of
3399/// the crate whose declaration to look up.
3400#[cfg(feature = "serde")]
3401#[doc(hidden)]
3402pub struct DeclaredShapeProbe<'a, M, E>(pub &'a E, pub std::marker::PhantomData<fn() -> M>);
3403
3404/// Declared-shape probe, preferred arm: `E` has a shape declared under `M`.
3405///
3406/// The generated code calls `(&probe).__mx_declared_parts(..)` with both
3407/// traits in scope. This impl, on the probe taking `&self`, matches the
3408/// receiver `&DeclaredShapeProbe` by value; [`ErrShapeUndeclared`] on
3409/// `&DeclaredShapeProbe` needs one more auto-ref and is only reached when
3410/// nothing is declared.
3411#[cfg(feature = "serde")]
3412#[doc(hidden)]
3413pub trait ErrShapeDeclared {
3414    /// The parts under the declared shape, for an `Err` arm without
3415    /// `serde_error(..)`. The call to [`serde_err_parts`] lives here, where
3416    /// `E: Serialize + Display` holds, so an undeclared `E` needn't be.
3417    fn __mx_declared_parts(&self, prefix: &str) -> Option<ErrParts>;
3418    /// The declared shape, first in `serde_error(..)`'s shape list.
3419    fn __mx_declared_shape(&self) -> &'static SerdeErrorShape;
3420}
3421
3422#[cfg(feature = "serde")]
3423impl<M, E: SerdeErrorShapeFor<M>> ErrShapeDeclared for DeclaredShapeProbe<'_, M, E> {
3424    #[track_caller]
3425    fn __mx_declared_parts(&self, prefix: &str) -> Option<ErrParts> {
3426        Some(serde_err_parts(self.0, prefix, &[E::SHAPE]))
3427    }
3428
3429    fn __mx_declared_shape(&self) -> &'static SerdeErrorShape {
3430        E::SHAPE
3431    }
3432}
3433
3434/// Declared-shape probe, fallback arm: no declaration. No parts, and a shape
3435/// that sets nothing.
3436#[cfg(feature = "serde")]
3437#[doc(hidden)]
3438pub trait ErrShapeUndeclared {
3439    fn __mx_declared_parts(&self, prefix: &str) -> Option<ErrParts>;
3440    fn __mx_declared_shape(&self) -> &'static SerdeErrorShape;
3441}
3442
3443#[cfg(feature = "serde")]
3444impl<M, E> ErrShapeUndeclared for &DeclaredShapeProbe<'_, M, E> {
3445    fn __mx_declared_parts(&self, _prefix: &str) -> Option<ErrParts> {
3446        None
3447    }
3448
3449    fn __mx_declared_shape(&self) -> &'static SerdeErrorShape {
3450        const NONE: &SerdeErrorShape = &SerdeErrorShape::new();
3451        NONE
3452    }
3453}
3454
3455/// Internal: the declared-shape stage of [`crate::__mx_result_err_parts!`].
3456/// Without the `serde` feature it is `None` and `$marker` is never resolved,
3457/// so a crate without `miniextendr_init!` (a test crate) still compiles.
3458#[cfg(feature = "serde")]
3459#[doc(hidden)]
3460#[macro_export]
3461macro_rules! __mx_declared_err_parts {
3462    ($e:ident, $prefix:expr, $marker:ty) => {{
3463        #[allow(unused_imports)]
3464        use $crate::condition::{ErrShapeDeclared as _, ErrShapeUndeclared as _};
3465        (&$crate::condition::DeclaredShapeProbe::<$marker, _>($e, ::core::marker::PhantomData))
3466            .__mx_declared_parts($prefix)
3467    }};
3468}
3469
3470/// Internal: the declared-shape stage of [`crate::__mx_result_err_parts!`];
3471/// nothing can be declared without the `serde` feature.
3472#[cfg(not(feature = "serde"))]
3473#[doc(hidden)]
3474#[macro_export]
3475macro_rules! __mx_declared_err_parts {
3476    ($e:ident, $prefix:expr, $marker:ty) => {
3477        ::core::option::Option::None::<$crate::condition::ErrParts>
3478    };
3479}
3480
3481/// Internal: the shape `serde_error_shape!` declared for the type of `$e`
3482/// under `$marker`, or one that sets nothing. It leads the shape list of a
3483/// `#[miniextendr(serde_error(..))]` `Err` arm.
3484#[cfg(feature = "serde")]
3485#[doc(hidden)]
3486#[macro_export]
3487macro_rules! __mx_declared_serde_shape {
3488    ($e:expr, $marker:ty) => {{
3489        #[allow(unused_imports)]
3490        use $crate::condition::{ErrShapeDeclared as _, ErrShapeUndeclared as _};
3491        (&$crate::condition::DeclaredShapeProbe::<$marker, _>(&$e, ::core::marker::PhantomData))
3492            .__mx_declared_shape()
3493    }};
3494}
3495
3496/// Internal: without the `serde` feature, a shape that sets nothing.
3497/// `serde_error(..)` needs the feature anyway: its `serde_err_parts` call
3498/// reports that, and `$marker` is never resolved.
3499#[cfg(not(feature = "serde"))]
3500#[doc(hidden)]
3501#[macro_export]
3502macro_rules! __mx_declared_serde_shape {
3503    ($e:expr, $marker:ty) => {{
3504        const NONE: &$crate::condition::SerdeErrorShape =
3505            &$crate::condition::SerdeErrorShape::new();
3506        NONE
3507    }};
3508}
3509
3510// endregion
3511
3512// region: from_tagged_sexp + repanic_if_rust_error — shim re-panic helpers
3513
3514impl RCondition {
3515    /// Reconstruct an [`RCondition::Error`] from a tagged SEXP produced by
3516    /// [`crate::error_value::make_rust_condition_value`].
3517    ///
3518    /// Returns `Some(RCondition)` when `sexp` has class `"rust_condition_value"` AND
3519    /// the `"__rust_condition__"` attribute is `TRUE`. Returns `None` for all other
3520    /// SEXPs (normal return values, `R_NilValue`, etc.).
3521    ///
3522    /// Reconstructs the matching variant for each kind: `"error"`/`"panic"`/
3523    /// `"result_err"`/`"none_err"`/`"other_rust_error"` →
3524    /// [`RCondition::Error`] (class, message, data and a [`ConditionCall::None`]
3525    /// choice kept; the kind itself is not carried by the variant);
3526    /// `"conversion"` → [`RCondition::Conversion`], so an argument error keeps
3527    /// `kind = "conversion"` across a package boundary (and an
3528    /// [`crate::arg_error!`] its class marker, which the consumer's wrapper
3529    /// resolves); `"warning"` → [`RCondition::Warning`]; `"message"` →
3530    /// [`RCondition::Message`]; `"condition"` → [`RCondition::Condition`].
3531    /// Unknown kinds degrade to [`RCondition::Error`] with the kind string
3532    /// prefixed to the message.
3533    ///
3534    /// # Safety
3535    ///
3536    /// Must be called from R's main thread.
3537    pub unsafe fn from_tagged_sexp(sexp: crate::SEXP) -> Option<Self> {
3538        use crate::SexpExt;
3539        use crate::from_r::TryFromSexp;
3540
3541        // Use SexpExt::inherits_class — wraps Rf_inherits, already main-thread.
3542        if !sexp.inherits_class(c"rust_condition_value") {
3543            return None;
3544        }
3545
3546        // PROTECT across the full inspection window. The string reads below
3547        // allocate when they translate a Latin-1 string (`string_elt_str`
3548        // translates into R's memory stack), and R-devel's GC is aggressive
3549        // enough (see MEMORY.md "Common gotchas") that every SEXP read here
3550        // must stay reachable from the guarded `sexp`.
3551        let _guard = unsafe { crate::gc_protect::OwnedProtect::new(sexp) };
3552
3553        // Verify the __rust_condition__ marker attribute is TRUE (a length-1 LGLSXP
3554        // with value 1). This guards against coincidental class attribute collisions.
3555        let attr_sym = crate::cached_class::rust_condition_attr_symbol();
3556        let marker = sexp.get_attr(attr_sym);
3557        // marker should be a scalar logical TRUE: is_logical() and logical_elt(0) == 1
3558        if !marker.is_logical() || marker.logical_elt(0) != 1 {
3559            return None;
3560        }
3561
3562        // It's a tagged SEXP. Read the elements.
3563        // Both 3-element (legacy) and 4-element (condition) forms have:
3564        //   [0] = error message (STRSXP)
3565        //   [1] = kind string (STRSXP)
3566        //   [2] = class name or NULL (only in 4-element form; absent in legacy)
3567
3568        let len = sexp.len();
3569
3570        // Defense-in-depth: a tagged SEXP must have at least the message and kind
3571        // slots. inherits_class + __rust_condition__ marker should already imply this,
3572        // but a corrupted/spoofed SEXP that satisfies both checks shouldn't OOB
3573        // the vector_elt reads below.
3574        if len < 2 {
3575            return None;
3576        }
3577
3578        let msg_sexp = sexp.vector_elt(0);
3579        let msg: String = msg_sexp
3580            .string_elt_str(0)
3581            .unwrap_or("<invalid error message>")
3582            .to_string();
3583
3584        let kind_sexp = sexp.vector_elt(1);
3585        let kind: &str = kind_sexp
3586            .string_elt_str(0)
3587            .unwrap_or(crate::error_value::kind::PANIC);
3588
3589        // Class slot is element [2] in the 4-element form (NULL in legacy form):
3590        // a STRSXP of any length (the user class vector, family last).
3591        let class: Vec<String> = if len >= 4 {
3592            let class_sexp = sexp.vector_elt(2);
3593            if class_sexp.is_nil() || !class_sexp.is_character() {
3594                Vec::new()
3595            } else {
3596                (0..class_sexp.len() as isize)
3597                    .filter_map(|i| class_sexp.string_elt_str(i).map(str::to_string))
3598                    .collect()
3599            }
3600        } else {
3601            Vec::new()
3602        };
3603
3604        use crate::error_value::kind as kind_const;
3605
3606        // Slot [4] is the optional named-list condition data, present when `len >= 5`.
3607        //
3608        // Each field value is decoded through the single SEXP→owned-tree walker,
3609        // [`RValue::try_from_sexp`], so structured fields survive the cross-package
3610        // trait-ABI re-panic path (`repanic_if_rust_error`): the consumer's outer
3611        // `with_r_unwind_protect` guard rebuilds the tagged SEXP from the
3612        // reconstructed `RCondition`, which now carries the data — so `e$field_name`
3613        // is accessible in R handlers even when the error crossed a package boundary.
3614        //
3615        // `RValue` is NA-aware (logical/integer/character carry `None`; double
3616        // carries the `NA_REAL` bit), so NA-bearing fields now round-trip faithfully
3617        // rather than being dropped. Fields whose name is missing/empty, or whose
3618        // value is not R data (closures, environments, …, which `try_from_sexp`
3619        // rejects) are dropped — safe degradation that preserves message/class/kind.
3620        //
3621        // All reads here are copies into owned Rust values: they create no SEXP
3622        // to root (a Latin-1 name's translation lives on R's memory stack), and
3623        // every element read is reachable from `sexp`, so the existing `_guard`
3624        // OwnedProtect suffices.
3625        let data: Option<ConditionData> = if len >= 5 {
3626            let data_sexp = sexp.vector_elt(4);
3627            if data_sexp.is_nil() || !data_sexp.is_list() {
3628                None
3629            } else {
3630                let data_len = data_sexp.len();
3631                let names_sexp = data_sexp.get_names();
3632                let mut fields: ConditionData = Vec::with_capacity(data_len);
3633                for i in 0..data_len as isize {
3634                    // Read the field name from the names attribute. If missing/empty, skip.
3635                    let name: String = if names_sexp.is_nil() || !names_sexp.is_character() {
3636                        continue;
3637                    } else {
3638                        match names_sexp.string_elt_str(i) {
3639                            Some(s) if !s.is_empty() => s.to_string(),
3640                            _ => continue,
3641                        }
3642                    };
3643                    if let Ok(value) = crate::RValue::try_from_sexp(data_sexp.vector_elt(i)) {
3644                        fields.push((name, value));
3645                    }
3646                }
3647                if fields.is_empty() {
3648                    None
3649                } else {
3650                    Some(fields)
3651                }
3652            }
3653        } else {
3654            None
3655        };
3656
3657        // Slot [3] is the call. Only the "no call" marker (`FALSE`, see
3658        // `make_rust_condition_value_with_data`) survives the re-panic: a call
3659        // object captured by the producer names the vtable shim's frame, and the
3660        // consumer's outer guard attributes the condition to its own call.
3661        let call = if len >= 4 && is_no_call_marker(sexp.vector_elt(3)) {
3662            ConditionCall::None
3663        } else {
3664            ConditionCall::Inherit
3665        };
3666
3667        let cond = match kind {
3668            kind_const::ERROR
3669            | kind_const::PANIC
3670            | kind_const::RESULT_ERR
3671            | kind_const::NONE_ERR
3672            | kind_const::OTHER_RUST_ERROR => RCondition::Error {
3673                message: msg,
3674                class,
3675                data,
3676                call,
3677            },
3678            kind_const::CONVERSION => RCondition::Conversion {
3679                message: msg,
3680                class,
3681                data,
3682                call,
3683            },
3684            kind_const::WARNING => RCondition::Warning {
3685                message: msg,
3686                class,
3687                data,
3688                call,
3689            },
3690            kind_const::MESSAGE => RCondition::Message {
3691                message: msg,
3692                class,
3693                data,
3694                call,
3695            },
3696            kind_const::CONDITION => RCondition::Condition {
3697                message: msg,
3698                class,
3699                data,
3700                call,
3701            },
3702            other => {
3703                // Unknown kind — degrade to error
3704                RCondition::Error {
3705                    message: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("[{0}] {1}", other, msg))
    })format!("[{other}] {msg}"),
3706                    class,
3707                    data,
3708                    call,
3709                }
3710            }
3711        };
3712        Some(cond)
3713    }
3714}
3715
3716/// `true` for the tagged value's "no call" marker in the `call` slot: a
3717/// length-1 logical `FALSE` ([`ConditionCall::None`]). A call object or `NULL`
3718/// is not the marker.
3719fn is_no_call_marker(call: crate::SEXP) -> bool {
3720    use crate::SexpExt;
3721    call.is_logical() && call.len() == 1 && call.logical_elt(0) == 0
3722}
3723
3724/// Inspect a SEXP returned by a trait-ABI vtable shim and, if it is a tagged
3725/// error value, re-panic with the reconstructed [`enum@RCondition`].
3726///
3727/// This is the "re-panic at the View boundary" step of Approach 1 from the
3728/// issue-345 plan. The caller (a generated View method wrapper) does:
3729///
3730/// ```ignore
3731/// let result = { vtable_call };
3732/// ::miniextendr_api::trait_abi::repanic_if_rust_error(result);
3733/// // ... convert result normally if we reach here
3734/// ```
3735///
3736/// When `sexp` is a tagged error value:
3737/// - `RCondition::Error` / `RCondition::Warning` / etc. → `panic_any!(cond)`.
3738///   The outer `with_r_unwind_protect` in the consumer's C entry point will
3739///   catch this and produce a tagged SEXP for the consumer's R wrapper.
3740///
3741/// When `sexp` is a normal value: this is a no-op.
3742///
3743/// # Safety
3744///
3745/// Must be called from R's main thread. `sexp` must be a valid (possibly
3746/// tagged) SEXP.
3747pub unsafe fn repanic_if_rust_error(sexp: crate::SEXP) {
3748    if let Some(cond) = unsafe { RCondition::from_tagged_sexp(sexp) } {
3749        std::panic::panic_any(cond);
3750    }
3751}
3752
3753// endregion
3754
3755// region: AsRError struct — wraps std::error::Error for Result returns
3756
3757/// Structured error wrapper that preserves the `std::error::Error` cause chain.
3758///
3759/// When displayed, formats the error message with its full source chain:
3760/// ```text
3761/// top-level message
3762///   caused by: middle error
3763///   caused by: root cause
3764/// ```
3765///
3766/// Implements `From<E>` so it works with `?` and `.map_err(AsRError)`.
3767///
3768/// # Example
3769///
3770/// ```ignore
3771/// use miniextendr_api::condition::AsRError;
3772/// use std::num::ParseIntError;
3773///
3774/// #[miniextendr]
3775/// fn parse_number(s: &str) -> Result<i32, AsRError<ParseIntError>> {
3776///     s.parse::<i32>().map_err(AsRError)
3777/// }
3778/// ```
3779pub struct AsRError<E: std::error::Error>(pub E);
3780
3781impl<E: std::error::Error> From<E> for AsRError<E> {
3782    #[inline]
3783    fn from(err: E) -> Self {
3784        AsRError(err)
3785    }
3786}
3787
3788impl<E: std::error::Error> std::fmt::Display for AsRError<E> {
3789    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3790        // Write the top-level message
3791        f.write_fmt(format_args!("{0}", self.0))write!(f, "{}", self.0)?;
3792
3793        // Walk the cause chain
3794        let mut current: &dyn std::error::Error = &self.0;
3795        while let Some(source) = current.source() {
3796            f.write_fmt(format_args!("\n  caused by: {0}", source))write!(f, "\n  caused by: {source}")?;
3797            current = source;
3798        }
3799
3800        Ok(())
3801    }
3802}
3803
3804impl<E: std::error::Error> std::fmt::Debug for AsRError<E> {
3805    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3806        f.write_fmt(format_args!("AsRError<{0}>({1})", std::any::type_name::<E>(),
        self))write!(f, "AsRError<{}>({})", std::any::type_name::<E>(), self)
3807    }
3808}
3809
3810impl<E: std::error::Error> AsRError<E> {
3811    /// Get the inner error.
3812    #[inline]
3813    pub fn into_inner(self) -> E {
3814        self.0
3815    }
3816
3817    /// Get the Rust type name of the wrapped error (for programmatic matching).
3818    #[inline]
3819    pub fn rust_type_name(&self) -> &'static str {
3820        std::any::type_name::<E>()
3821    }
3822
3823    /// Collect the full cause chain as a `Vec<String>`.
3824    pub fn cause_chain(&self) -> Vec<String> {
3825        let mut chain = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [self.0.to_string()]))vec![self.0.to_string()];
3826        let mut current: &dyn std::error::Error = &self.0;
3827        while let Some(source) = current.source() {
3828            chain.push(source.to_string());
3829            current = source;
3830        }
3831        chain
3832    }
3833}
3834
3835// endregion
3836
3837// region: Tests — macro grammar + payload contents (no R runtime needed)
3838
3839#[cfg(test)]
3840mod tests;
3841
3842// endregion