miniextendr_api/error.rs
1//! Error handling helpers for R API calls.
2//!
3//! ## User-facing path: tagged condition SEXP
4//!
5//! Every `#[miniextendr]` function runs inside
6//! [`with_r_unwind_protect`](crate::unwind_protect::with_r_unwind_protect).
7//! Rust panics and user-raised conditions (`error!()`, `warning!()`, `message!()`,
8//! `condition!()`) are caught, packaged as a tagged SEXP, and returned normally.
9//! The generated R wrapper inspects the SEXP and raises the appropriate R
10//! condition with `rust_*` class layering. **No `Rf_error` longjmp happens on
11//! this path.**
12//!
13//! User code should use:
14//! - `panic!()` — for unrecoverable Rust errors (becomes `rust_error` in R)
15//! - `error!()` / `warning!()` / `message!()` / `condition!()` — for structured
16//! R conditions (see [`mod@crate::condition`])
17//!
18//! See [`crate::error_value`] for the tagged-SEXP layout, the
19//! `error_in_r` default + `no_error_in_r` / `unwrap_in_r` opt-outs, and the
20//! PROTECT-discipline gotcha that R-devel surfaces.
21//!
22//! ## When `Rf_error` still fires (framework-internal)
23//!
24//! `Rf_error` (longjmp via `r_stop`) survives only at the FFI guard site where
25//! there is no SEXP slot to return through:
26//! **`ffi_guard::guarded_ffi_call(GuardMode::CatchUnwind, …)`**, the guard of
27//! ALTREP `RustUnwind` callbacks.
28//!
29//! Trait-ABI vtable shims panic on arity, borrow and conversion failures inside
30//! `with_r_unwind_protect_shim`, which returns a tagged condition SEXP.
31//!
32//! ALTREP `RUnwind` callbacks now route through
33//! `with_r_unwind_protect_sourced` → `raise_rust_condition_via_stop`, which
34//! raises the condition a generated wrapper would (`rust_*` class layering,
35//! `kind`, `data` fields) without going through `r_stop`.
36//!
37//! `r_stop` is `pub(crate)` — no user code should depend on it.
38//!
39//! # Example
40//!
41//! ```ignore
42//! use miniextendr_api::miniextendr;
43//!
44//! #[miniextendr]
45//! fn validate_input(x: i32) -> i32 {
46//! assert!(x >= 0, "x must be non-negative, got {x}");
47//! x * 2
48//! }
49//! ```
50
51/// Raise an R error via `Rf_error` (longjmp). **Crate-internal only.**
52///
53/// Survives at the one guard site where there is no SEXP slot to return
54/// through: [`crate::ffi_guard::guarded_ffi_call`] with `GuardMode::CatchUnwind`
55/// (ALTREP `RustUnwind` callbacks).
56///
57/// User code should use `panic!()` (caught by the framework and converted to a
58/// `rust_error` R condition) or the structured condition macros `error!()` /
59/// `warning!()` / `message!()` / `condition!()`.
60#[inline]
61pub(crate) fn r_stop(msg: &str) -> ! {
62 // Replace interior NUL bytes (user-derived messages can contain them); `CString::new`
63 // would otherwise reject them, and a panic here would abort the process.
64 let c_msg = std::ffi::CString::new(msg.replace('\0', "\u{fffd}")).unwrap_or_default();
65
66 crate::with_r_thread(|| unsafe {
67 crate::sys::Rf_error_unchecked(c"%s".as_ptr(), c_msg.as_ptr());
68 })
69}
70
71/// Raise an R warning with the given message.
72///
73/// Unlike `r_stop`, this returns normally after issuing the warning.
74/// Panics off R's main thread.
75#[inline]
76pub fn r_warning(msg: &str) {
77 // NUL-safe (see r_stop)
78 let c_msg = std::ffi::CString::new(msg.replace('\0', "\u{fffd}")).unwrap_or_default();
79
80 crate::with_r_thread(|| unsafe {
81 crate::sys::Rf_warning_unchecked(c"%s".as_ptr(), c_msg.as_ptr());
82 });
83}
84
85/// Print a message to R's console (internal implementation).
86/// Panics off R's main thread.
87#[doc(hidden)]
88#[inline]
89pub fn _r_print_str(msg: &str) {
90 // NUL-safe (see r_stop)
91 let c_msg = std::ffi::CString::new(msg.replace('\0', "\u{fffd}")).unwrap_or_default();
92
93 crate::with_r_thread(|| unsafe {
94 crate::sys::Rprintf_unchecked(c"%s".as_ptr(), c_msg.as_ptr());
95 });
96}
97
98/// Print a newline to R's console (internal implementation).
99/// Panics off R's main thread.
100#[doc(hidden)]
101#[inline]
102pub fn _r_print_newline() {
103 crate::with_r_thread(|| unsafe {
104 crate::sys::Rprintf_unchecked(c"\n".as_ptr());
105 });
106}
107
108/// Print to R's console (like `print!`).
109///
110/// # Example
111///
112/// ```ignore
113/// use miniextendr_api::r_print;
114///
115/// r_print!("Hello ");
116/// r_print!("value: {}", 42);
117/// ```
118#[macro_export]
119macro_rules! r_print {
120 () => {};
121 ($($arg:tt)*) => {
122 $crate::error::_r_print_str(&::std::format!($($arg)*))
123 };
124}
125
126/// Print to R's console with a newline (like `println!`).
127///
128/// # Example
129///
130/// ```ignore
131/// use miniextendr_api::r_println;
132///
133/// r_println!(); // just a newline
134/// r_println!("Hello, world!");
135/// r_println!("value: {}", 42);
136/// ```
137#[macro_export]
138macro_rules! r_println {
139 () => {
140 $crate::error::_r_print_newline()
141 };
142 ($($arg:tt)*) => {{
143 $crate::error::_r_print_str(&::std::format!($($arg)*));
144 $crate::error::_r_print_newline();
145 }};
146}