Skip to main content

miniextendr_api/into_r/
result.rs

1//! `Result<T, E>` conversions to R.
2//!
3//! Used by `#[miniextendr(unwrap_in_r)]` to pass Results to R as values
4//! (`Err` becomes `list(error = ...)`), instead of unwrapping in Rust.
5//! Also provides `NullOnErr` for `Result<T, ()>` → NULL-on-error semantics.
6//!
7//! # Tradeoff
8//!
9//! The two impls in this module have different gating conditions:
10//!
11//! - `IntoR for Result<T, E: Display>` (the `list(error = ...)` shape) fires
12//!   **only** under `#[miniextendr(unwrap_in_r)]` (Result-as-value). Without
13//!   that attribute, a `Result<T, E>` return acts as an **error boundary**:
14//!   `Err(e)` panics with `Debug`-formatted `e`, the framework's
15//!   tagged-condition transport carries it to R, and the wrapper raises a
16//!   classed `rust_*` condition. Failure mode of opting into `unwrap_in_r`
17//!   without telling R callers: they suddenly need to check `$error` on every
18//!   return value instead of using `tryCatch`.
19//! - `IntoR for Result<T, NullOnErr>` fires whenever the error type is `()`,
20//!   **independent of `unwrap_in_r`**: the macro rewrites `Result<T, ()>` to
21//!   `Result<T, NullOnErr>` before the `unwrap_in_r` check, so `Err(())`
22//!   returns `NULL` to R in both modes. A unit error is a deliberate
23//!   "no value" sentinel, not a Rust failure — it never raises an R error.
24
25use std::collections::HashMap;
26
27use crate::into_r::IntoR;
28
29/// Convert `Result<T, E>` to R (value-style, for `#[miniextendr(unwrap_in_r)]`).
30///
31/// # Behavior
32///
33/// - `Ok(value)` → returns the converted value directly
34/// - `Err(msg)` → returns `list(error = "<msg>")` (value-style error)
35///
36/// # When This Is Used
37///
38/// This impl is **only used** when `#[miniextendr(unwrap_in_r)]` is specified.
39/// Without that attribute, `#[miniextendr]` functions returning `Result<T, E>`
40/// will unwrap in Rust and raise an R error on `Err` (error boundary semantics).
41///
42/// # Error Handling Summary
43///
44/// | Mode | On `Err(e)` | Bound Required |
45/// |------|-------------|----------------|
46/// | Default | R error via panic | `E: Debug` |
47/// | `unwrap_in_r` | `list(error = ...)` | `E: Display` |
48///
49/// **Default** (without `unwrap_in_r`): `Result<T, E>` acts as an error boundary:
50/// - `Ok(v)` → `v` converted to R
51/// - `Err(e)` → R error with Debug-formatted message (requires `E: Debug`)
52///
53/// **With `unwrap_in_r`**: `Result<T, E>` is passed through to R:
54/// - `Ok(v)` → `v` converted to R
55/// - `Err(e)` → `list(error = e.to_string())` (requires `E: Display`)
56///
57/// **Exception**: `Result<T, ()>` never reaches this impl in either mode —
58/// the macro rewrites it to `Result<T, NullOnErr>` before the `unwrap_in_r`
59/// check, and `Err(())` returns `NULL`. See [`NullOnErr`].
60///
61/// # Example
62///
63/// ```ignore
64/// // Default: error boundary - Err becomes R stop()
65/// #[miniextendr]
66/// fn divide(x: f64, y: f64) -> Result<f64, String> {
67///     if y == 0.0 { Err("division by zero".into()) }
68///     else { Ok(x / y) }
69/// }
70/// // In R: tryCatch(divide(1, 0), error = ...) catches the error
71///
72/// // Value-style: Err becomes list(error = ...)
73/// #[miniextendr(unwrap_in_r)]
74/// fn divide_safe(x: f64, y: f64) -> Result<f64, String> {
75///     if y == 0.0 { Err("division by zero".into()) }
76///     else { Ok(x / y) }
77/// }
78/// // In R: result <- divide_safe(1, 0)
79/// //       if (!is.null(result$error)) { handle error }
80/// ```
81impl<T, E> IntoR for Result<T, E>
82where
83    T: IntoR,
84    E: std::fmt::Display,
85{
86    /// `T`'s error: an `Ok` value that fails to convert raises its own condition.
87    type Error = T::Error;
88    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
89        match self {
90            Ok(value) => value.try_into_sexp(),
91            Err(msg) => {
92                // Create list(error = msg) for R-side error handling
93                let mut map = HashMap::with_capacity(1);
94                map.insert("error".to_string(), msg.to_string());
95                Ok(map.into_sexp())
96            }
97        }
98    }
99}
100
101/// Marker type for `Result<T, ()>` that converts `Err(())` to NULL.
102///
103/// This type is used internally by the `#[miniextendr]` macro when handling
104/// `Result<T, ()>` return types. When the error type is `()`, there's no
105/// error message to report, so we return NULL instead of raising an error.
106///
107/// # Usage
108///
109/// You typically don't use this directly. When you write:
110///
111/// ```ignore
112/// #[miniextendr]
113/// fn maybe_value(x: i32) -> Result<i32, ()> {
114///     if x > 0 { Ok(x) } else { Err(()) }
115/// }
116/// ```
117///
118/// The macro generates code that converts `Err(())` to `Err(NullOnErr)` and
119/// returns `NULL` in R. This rewrite fires whenever the error type is `()`,
120/// **whether or not** `#[miniextendr(unwrap_in_r)]` is set — the unit-error
121/// check runs before the `unwrap_in_r` check.
122///
123/// # Note
124///
125/// `NullOnErr` intentionally does NOT implement `Display` to avoid conflicting
126/// with the generic `IntoR for Result<T, E: Display>` impl. It has its own
127/// specialized `IntoR` impl that returns NULL on error.
128#[derive(#[automatically_derived]impl ::core::fmt::Debug for NullOnErr {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "NullOnErr")
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for NullOnErr {
}
#[automatically_derived]impl ::core::clone::Clone for NullOnErr {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for NullOnErr { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for NullOnErr
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for NullOnErr {
    #[inline]
    fn eq(&self, other: &Self) -> bool { true }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for NullOnErr { }Eq)]
129pub struct NullOnErr;
130
131/// Convert `Result<T, NullOnErr>` to R, returning NULL on error.
132///
133/// This is a special case for `Result<T, ()>` types where the error
134/// carries no information. Instead of raising an R error, we return NULL.
135/// Fires whenever the error type is `()`, independent of
136/// `#[miniextendr(unwrap_in_r)]`.
137impl<T: IntoR> IntoR for Result<T, NullOnErr> {
138    /// `T`'s error: an `Ok` value that fails to convert raises its own condition.
139    type Error = T::Error;
140    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
141        match self {
142            Ok(value) => value.try_into_sexp(),
143            Err(NullOnErr) => Ok(crate::SEXP::nil()),
144        }
145    }
146}