Skip to main content

miniextendr_api/
deferred_condition.rs

1//! Deferred conditions: signal an R warning, message or condition **and**
2//! still return a value.
3//!
4//! [`crate::warning!`], [`crate::message!`] and [`crate::condition!`] unwind
5//! the Rust function: R sees the signal, the call returns `invisible(NULL)`.
6//! That is the right shape for "stop here, but softly", not for "here is the
7//! result, and by the way …". The `defer_*` family queues the condition
8//! instead; the generated C wrapper signals everything queued during the call
9//! once the Rust body has returned, in queue order, and then hands the value
10//! to R.
11//!
12//! ```ignore
13//! use miniextendr_api::{defer_warning, miniextendr};
14//! use miniextendr_api::RCondition;
15//!
16//! #[derive(Debug, RCondition)]
17//! #[condition(class = "pkg_warning")]
18//! enum PkgWarning {
19//!     #[condition(message = "dropped {dropped} of {total} rows")]
20//!     Truncated { dropped: i32, total: i32 },
21//! }
22//!
23//! #[miniextendr]
24//! fn trim(n: i32) -> i32 {
25//!     defer_warning(PkgWarning::Truncated { dropped: 2, total: n });
26//!     n - 2
27//! }
28//! ```
29//!
30//! ```r
31//! trim(5L)
32//! # [1] 3
33//! # Warning message:
34//! # In trim(5L) : dropped 2 of 5 rows
35//! w <- tryCatch(trim(5L), pkg_warning_truncated = function(w) w)
36//! w$dropped               # 2
37//! suppressWarnings(trim(5L))   # 3
38//! ```
39//!
40//! # What R sees
41//!
42//! Exactly what `warning()` / `message()` / `signalCondition()` called from
43//! an R function would produce, because that is what runs: the same R helper
44//! the generated wrappers use for the panicking macros re-raises each queued
45//! condition. Class layering (`c(<classes…>, "rust_warning", "simpleWarning",
46//! "warning", "condition")`), `data` fields as `w$<name>` and
47//! `conditionCall()` (the wrapper's call, or `NULL` for a condition queued
48//! with `call = none`) are identical to the immediate forms. `tryCatch(warning = )` exits the call before the value is returned;
49//! `withCallingHandlers` + `invokeRestart("muffleWarning")` keeps it;
50//! `suppressWarnings()` / `suppressMessages()` work as usual.
51//!
52//! # Ordering
53//!
54//! Queued conditions are signalled after the Rust body finished and before R
55//! sees its outcome, so a deferred warning followed by `rust_error!` (or an
56//! `Err` return) is signalled first and the error second, and two deferred
57//! conditions keep their queue order. Nested calls (R code evaluated from
58//! Rust that calls back into another `#[miniextendr]` function) flush only
59//! what they queued themselves.
60//!
61//! # Capturing a block's conditions
62//!
63//! [`capture`] runs a closure and returns what it queued instead of
64//! signalling it, for code whose diagnostics the caller already has (a
65//! replay of the steps that built a saved object). Conditions queued outside
66//! the closure are untouched.
67//!
68//! # Warning placement
69//!
70//! Conditions queued before a failure still signal. If a body must not warn on
71//! failure, collect warning payloads locally and queue them only after its last
72//! fallible step (including any `?`). Moving a warning before a later `?` changes
73//! that behavior: returning `Err` does not cancel the queued warning.
74//!
75//! ```no_run
76//! use miniextendr_api::{defer_warning, miniextendr};
77//! # miniextendr_api::miniextendr_init!(pkg);
78//!
79//! #[miniextendr]
80//! pub fn parse_trimmed(text: String) -> Result<i32, std::num::ParseIntError> {
81//!     let trimmed = text.trim();
82//!     let value = trimmed.parse::<i32>()?;
83//!     if trimmed != text {
84//!         defer_warning!(class = "pkg_trimmed", "removed surrounding whitespace");
85//!     }
86//!     Ok(value)
87//! }
88//! # fn main() {}
89//! ```
90//!
91//! Here, parsing `" bad "` returns an error without a warning; parsing `" 42 "`
92//! queues the whitespace warning and returns `42`.
93//!
94//! # Payloads
95//!
96//! [`defer_warning()`], [`defer_message()`] and [`defer_condition()`] take any
97//! [`RConditionData`] value: a `#[derive(RCondition)]` enum or struct
98//! (class from the type and variant names, message from a `format!` string or
99//! `Display`, fields as `data`), or a hand-built [`crate::condition::RError`].
100//! The [`defer_warning!`](crate::defer_warning!) /
101//! [`defer_message!`](crate::defer_message!) /
102//! [`defer_condition!`](crate::defer_condition!) macros take the
103//! [`crate::warning!`] grammar (`class = …`, `data = …`, format message) for
104//! one-off conditions.
105//!
106//! # Threads and boundaries
107//!
108//! The queue lives on R's main thread, where every generated `.Call` entry
109//! point and every trait-ABI vtable shim flushes what was queued inside it.
110//! A condition queued on another thread (a Rayon task, a `std::thread`) goes
111//! to the main thread over a bounded channel and joins the queue the next
112//! time the main thread reads it: when a call signals its conditions, or
113//! discards them on an R error. Rayon's `par_iter`, `join` and `scope` block
114//! the calling thread until every task has finished, so every condition a
115//! task queued is waiting when the call that ran the parallel section
116//! returns, and that call signals it (or discards it, if it fails with an R
117//! error). Only a thread nobody joins (a `std::thread::spawn` left running, a
118//! `rayon::spawn`) can deliver its conditions to a later, unrelated call.
119//!
120//! The channel holds 1024 conditions. One queued while it is full is
121//! dropped, and the main thread queues a warning that says how many were,
122//! after the ones it received. [`capture`] needs the queue itself, so it
123//! panics off the main thread; capture around the parallel section instead.
124//!
125//! ALTREP `RUnwind` / `RustUnwind` callbacks and connection I/O callbacks also
126//! signal locally, with `conditionCall() = NULL`; raising guards use their
127//! explicit `call` argument. An R-origin error discards the abandoned queue.
128//!
129//! External-pointer finalizers and connection close/destroy/Drop callbacks
130//! suppress deferred conditions: R finalization removes the caller's handlers.
131//! No R signalling or delayed delivery is attempted from destructors guarded
132//! by `drop_catching_panic`. Unguarded raw FFI / `AltrepGuard::Unsafe` callbacks
133//! must not queue conditions; choose a guarded callback instead.
134
135use std::cell::{Cell, OnceCell, RefCell};
136use std::sync::OnceLock;
137use std::sync::atomic::{AtomicUsize, Ordering};
138use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
139
140use crate::SEXP;
141use crate::condition::{RCondition, RConditionData};
142
143// region: Queue
144
145#[doc =
r" Receiving end of the channel from other threads: set on the thread"]
#[doc = r" that opened it (R's main thread), empty on every other thread."]
const RECEIVER: ::std::thread::LocalKey<OnceCell<Receiver<RCondition>>> =
    {
        const __RUST_STD_INTERNAL_INIT: OnceCell<Receiver<RCondition>> =
            { OnceCell::new() };
        unsafe {
            ::std::thread::LocalKey::new(const {
                        if ::std::mem::needs_drop::<OnceCell<Receiver<RCondition>>>()
                            {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL:
                                        ::std::thread::local_impl::EagerStorage<OnceCell<Receiver<RCondition>>>
                                        =
                                        ::std::thread::local_impl::EagerStorage::new(__RUST_STD_INTERNAL_INIT);
                                    __RUST_STD_INTERNAL_VAL.get()
                                }
                        } else {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL:
                                        OnceCell<Receiver<RCondition>> =
                                        __RUST_STD_INTERNAL_INIT;
                                    &__RUST_STD_INTERNAL_VAL
                                }
                        }
                    })
        }
    };std::thread_local! {
146    /// Conditions queued during the current guarded callback (and enclosing
147    /// calls), on R's main thread; other threads send theirs over the channel
148    /// ([`defer`]). Every borrow ends before any R signalling, so handlers can
149    /// re-enter Rust and queue again.
150    static PENDING: RefCell<Vec<RCondition>> = const { RefCell::new(Vec::new()) };
151    /// Open finalizer suppressions ([`Suppress`]).
152    static SUPPRESSED: Cell<usize> = const { Cell::new(0) };
153    /// Receiving end of the channel from other threads: set on the thread
154    /// that opened it (R's main thread), empty on every other thread.
155    static RECEIVER: OnceCell<Receiver<RCondition>> = const { OnceCell::new() };
156}
157
158/// Capacity of the channel carrying conditions from other threads.
159const CHANNEL_CAPACITY: usize = 1024;
160
161/// Sending end of the channel from other threads. Any thread sends on it.
162static SENDER: OnceLock<SyncSender<RCondition>> = OnceLock::new();
163
164/// Conditions dropped because the channel was full (or not open yet), since
165/// the main thread last received.
166static DROPPED: AtomicUsize = AtomicUsize::new(0);
167
168/// Why [`capture`] refuses to run off R's main thread.
169const CAPTURE_OFF_MAIN_THREAD: &str = "deferred_condition::capture() was called off R's main \
170     thread.\n\
171     \n\
172     Conditions deferred on another thread go to R's main thread, so there is \
173     nothing here to capture. Call capture() on the main thread, around the \
174     parallel section (Rayon, std::thread) that queues them.";
175
176/// Open the channel from other threads and keep its receiving end on the
177/// current thread. [`crate::miniextendr_runtime_init`] calls it on R's main
178/// thread; only the first call opens it.
179pub(crate) fn open_channel() {
180    SENDER.get_or_init(|| {
181        let (tx, rx) = sync_channel(CHANNEL_CAPACITY);
182        RECEIVER.with(|cell| {
183            cell.get_or_init(|| rx);
184        });
185        tx
186    });
187}
188
189/// Queue a warning to be signalled when the current guarded call or callback
190/// returns; the call still returns its value.
191///
192/// `payload` supplies the message, the user classes (prepended to
193/// `rust_warning`) and the `data` fields (`w$<name>`). See the
194/// [module docs](self) for the R-side behaviour and [`defer_warning!`](crate::defer_warning!)
195/// for the macro form.
196///
197/// A later `Err` does not cancel this warning. To avoid warnings on failure,
198/// queue after the last fallible step; see [warning placement](self#warning-placement).
199///
200/// From another thread it goes to R's main thread over a channel; see
201/// [Threads and boundaries](self#threads-and-boundaries).
202pub fn defer_warning(payload: impl RConditionData) {
203    defer(RCondition::Warning {
204        message: payload.message(),
205        class: payload.class(),
206        data: payload.data(),
207        call: payload.call(),
208    });
209}
210
211/// Queue a message (`message()`, muffled by `suppressMessages()`) to be
212/// emitted when the current guarded call or callback returns.
213///
214/// Unlike [`crate::message!`], the payload's classes are honoured: they are
215/// layered in front of `rust_message` so handlers can dispatch on them.
216///
217/// From another thread it goes to R's main thread over a channel; see
218/// [Threads and boundaries](self#threads-and-boundaries).
219pub fn defer_message(payload: impl RConditionData) {
220    defer(RCondition::Message {
221        message: payload.message(),
222        class: payload.class(),
223        data: payload.data(),
224        call: payload.call(),
225    });
226}
227
228/// Queue a plain condition (`signalCondition()`: silent without a handler)
229/// to be signalled when the current guarded call or callback returns.
230///
231/// From another thread it goes to R's main thread over a channel; see
232/// [Threads and boundaries](self#threads-and-boundaries).
233pub fn defer_condition(payload: impl RConditionData) {
234    defer(RCondition::Condition {
235        message: payload.message(),
236        class: payload.class(),
237        data: payload.data(),
238        call: payload.call(),
239    });
240}
241
242/// Run `f` and return the conditions it queued, oldest first, instead of
243/// signalling them when the guarded call returns.
244///
245/// For code that queues diagnostics a caller already has: replaying the
246/// steps that built a saved object repeats warnings the object recorded.
247/// `capture(f).0` discards them; each [`RCondition`](enum@RCondition) can also be inspected,
248/// queued again with [`RCondition::defer`] or raised with
249/// [`RCondition::raise`].
250///
251/// ```ignore
252/// use miniextendr_api::deferred_condition::capture;
253///
254/// let (rebuilt, warnings) = capture(|| rebuild(&snapshot));
255/// debug_assert_eq!(warnings.len(), snapshot.warnings.len());
256/// ```
257///
258/// - Conditions queued before the block, or by enclosing calls, stay queued.
259/// - Conditions a nested `#[miniextendr]` call queued were signalled when
260///   that call returned, as always.
261/// - If `f` unwinds (`error!`, `Err` through a nested raise, an R error), the
262///   block's conditions stay queued and follow the usual rules: a Rust
263///   failure signals them, an R-origin error discards them. To keep them on
264///   failure too, catch the failure inside the block:
265///   `capture(|| catch_condition(|| rebuild(&snapshot)))` (see
266///   [`catch_condition`](crate::condition::catch_condition)).
267/// - Where deferred conditions are suppressed (finalizers, see the
268///   [module docs](self#threads-and-boundaries)), nothing is queued and the
269///   vector is empty.
270/// - Conditions that tasks of a parallel section inside the block queued are
271///   captured too: they have arrived when the section returns.
272///
273/// # Panics
274///
275/// Off R's main thread, where the queue isn't: capture around the parallel
276/// section instead (see [Threads and boundaries](self#threads-and-boundaries)).
277pub fn capture<T>(f: impl FnOnce() -> T) -> (T, Vec<RCondition>) {
278    if !crate::is_r_main_thread() {
279        {
    ::core::panicking::panic_fmt(format_args!("{0}",
            CAPTURE_OFF_MAIN_THREAD));
};panic!("{CAPTURE_OFF_MAIN_THREAD}");
280    }
281    let start = mark();
282    let value = f();
283    (value, take_pending(start))
284}
285
286/// Queue an already-built condition payload. Used by the `defer_*!` macros.
287///
288/// Off R's main thread the condition goes over the channel, with `try_send`:
289/// the main thread may be joining this one, so a send must never wait. A full
290/// channel (or one not open yet) drops it and counts it in `DROPPED`.
291#[doc(hidden)]
292pub fn defer(condition: RCondition) {
293    if crate::is_r_main_thread() {
294        push(condition);
295    } else {
296        let sent = SENDER
297            .get()
298            .is_some_and(|tx| tx.try_send(condition).is_ok());
299        if !sent {
300            DROPPED.fetch_add(1, Ordering::Relaxed);
301        }
302    }
303}
304
305/// Queue on this thread; [`defer`] checks the thread first.
306fn push(condition: RCondition) {
307    if SUPPRESSED.get() == 0 {
308        PENDING.with_borrow_mut(|queue| queue.push(condition));
309    }
310}
311
312/// Append what other threads sent to the queue, then the warning for any
313/// that were dropped. A no-op off the thread that opened the channel.
314///
315/// Called before the queue is read or cut back ([`take_pending`],
316/// [`discard`]), not by [`mark`]: what arrived belongs to the call that reads
317/// next, not to the queue below a new mark, which no call would take.
318fn receive() {
319    RECEIVER.with(|cell| {
320        let Some(rx) = cell.get() else { return };
321        PENDING.with_borrow_mut(|queue| {
322            // Bounded: other threads keep sending while this runs.
323            queue.extend(rx.try_iter().take(CHANNEL_CAPACITY));
324            // After the conditions kept: a full channel drops the newest.
325            let dropped = DROPPED.swap(0, Ordering::Relaxed);
326            if dropped > 0 {
327                queue.push(RCondition::Warning {
328                    message: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} deferred conditions from other threads dropped due to queue overflow",
                dropped))
    })format!(
329                        "{dropped} deferred conditions from other threads dropped due to \
330                         queue overflow"
331                    ),
332                    class: Vec::new(),
333                    data: None,
334                    call: crate::condition::ConditionCall::Inherit,
335                });
336            }
337        });
338    });
339}
340
341/// The queue position at the start of a call. Pair with [`finish`].
342#[doc(hidden)]
343#[inline]
344pub fn mark() -> usize {
345    PENDING.with_borrow(Vec::len)
346}
347
348/// Remove and return everything queued since `mark`, oldest first. Entries
349/// below `mark` belong to enclosing calls and stay.
350#[doc(hidden)]
351pub fn take_pending(mark: usize) -> Vec<RCondition> {
352    // A nested guard inside a finalizer must not drain the enclosing call's
353    // entries: they belong to its signal-capable boundary.
354    if SUPPRESSED.get() != 0 {
355        return Vec::new();
356    }
357    receive();
358    PENDING.with_borrow_mut(|queue| {
359        if queue.len() <= mark {
360            Vec::new()
361        } else {
362            queue.split_off(mark)
363        }
364    })
365}
366
367/// Discard conditions whose Rust/R call was abandoned by an R longjmp.
368pub(crate) fn discard(mark: usize) {
369    if SUPPRESSED.get() == 0 {
370        receive();
371        PENDING.with_borrow_mut(|queue| queue.truncate(mark));
372    }
373}
374
375/// Finalization has no caller condition handlers. Suppress queues throughout
376/// the destructor, including any nested framework boundaries, without R calls.
377pub(crate) struct Suppress(std::marker::PhantomData<std::rc::Rc<()>>);
378
379impl Suppress {
380    pub(crate) fn new() -> Self {
381        SUPPRESSED.set(SUPPRESSED.get() + 1);
382        Self(std::marker::PhantomData)
383    }
384}
385
386impl Drop for Suppress {
387    fn drop(&mut self) {
388        SUPPRESSED.set(SUPPRESSED.get() - 1);
389    }
390}
391
392// endregion
393
394// region: Flush
395
396/// Signal everything queued since `mark`, then return `value`.
397///
398/// Called by the generated C wrappers with the wrapper's outcome (the value
399/// SEXP, or a tagged condition value when the body failed) and by
400/// [`crate::unwind_protect::with_r_unwind_protect_shim`]. The queued
401/// conditions are materialised as tagged condition values and handed to the
402/// R helper (`stop()` / `warning()` / `message()` / `signalCondition()`), so
403/// their R-side shape is identical to the panicking macros'. The signalling
404/// runs under its own `R_UnwindProtect`: an exiting handler unwinds through
405/// it like any R error, and a Rust panic inside (a framework bug) comes back
406/// as a tagged error value, which replaces `value`.
407///
408/// `call` is the wrapper's call object (`conditionCall()` of every signalled
409/// condition); `None` gives `NULL`.
410///
411/// # Safety
412///
413/// Must run on R's main thread. `value` need not be protected: it is rooted
414/// for the duration of the signalling.
415#[doc(hidden)]
416pub unsafe fn finish(mark: usize, value: SEXP, call: Option<SEXP>) -> SEXP {
417    let queued = take_pending(mark);
418    if queued.is_empty() {
419        return value;
420    }
421    let outcome = crate::unwind_protect::with_r_unwind_protect(
422        || {
423            // SAFETY: main thread (caller contract), inside R_UnwindProtect.
424            unsafe {
425                let _value_root = crate::OwnedProtect::new(value);
426                signal_now(queued, call);
427            }
428            SEXP::nil()
429        },
430        call,
431    );
432    if outcome.is_nil() { value } else { outcome }
433}
434
435/// Flush a non-raising callback's conditions after its Rust guard has finished.
436/// R objects in `value` must already be rooted (the same contract as `or_raise`).
437pub(crate) fn finish_guarded<R>(mark: usize, value: R) -> R {
438    let queued = take_pending(mark);
439    if queued.is_empty() {
440        return value;
441    }
442    crate::unwind_protect::with_r_unwind_protect_or_raise(
443        move || {
444            // SAFETY: callback boundary is on R's main thread; this closure is
445            // inside R_UnwindProtect, including the owned result's destructor.
446            unsafe { signal_now(queued, None) };
447            value
448        },
449        None,
450    )
451}
452
453/// Materialise each queued condition and hand it to the R helper.
454///
455/// # Safety
456///
457/// Main thread, inside `R_UnwindProtect` (handlers may longjmp).
458pub(crate) unsafe fn signal_now(queued: Vec<RCondition>, call: Option<SEXP>) {
459    let helper = raise_condition_helper();
460    let call_sexp = call.unwrap_or(SEXP::nil());
461    for condition in queued {
462        // SAFETY: main thread inside R_UnwindProtect (caller contract). The
463        // tagged value and the call object are rooted across `Rf_eval`. A
464        // call-less condition carries the "no call" marker, which the helper
465        // maps to `call = NULL` instead of falling back to `call_sexp`.
466        unsafe {
467            let tagged =
468                crate::OwnedProtect::new(crate::error_value::rust_condition_value(condition, call));
469            let expr =
470                crate::OwnedProtect::new(crate::sys::Rf_lang3(helper, tagged.get(), call_sexp));
471            crate::sys::Rf_eval(expr.get(), crate::sys::R_BaseEnv);
472        }
473    }
474}
475
476/// The `.miniextendr_raise_condition` closure, evaluated once from the shared
477/// source ([`crate::registry::RAISE_CONDITION_HELPER_FN`]) in the base
478/// namespace and preserved for the life of the process.
479///
480/// Evaluating the source here, rather than looking the helper up in a package
481/// namespace, keeps this path independent of which package (or embedded
482/// engine) is running: the helper only needs base and `utils::modifyList`.
483/// The raising guards raise their conditions with it too
484/// (`unwind_protect::raise_rust_condition_via_stop`).
485pub(crate) fn raise_condition_helper() -> SEXP {
486    static HELPER: OnceLock<SEXP> = OnceLock::new();
487    *HELPER.get_or_init(|| {
488        // SAFETY: only reached from `signal_now` and
489        // `raise_rust_condition_via_stop`, on the main thread.
490        unsafe {
491            let closure = crate::expression::r_eval_str(
492                crate::registry::RAISE_CONDITION_HELPER_FN,
493                crate::sys::R_BaseNamespace,
494            )
495            .unwrap_or_else(|err| {
496                {
    ::core::panicking::panic_fmt(format_args!("miniextendr: could not define the deferred-condition helper: {0}",
            err));
}panic!("miniextendr: could not define the deferred-condition helper: {err}")
497            });
498            crate::sys::R_PreserveObject(closure);
499            closure
500        }
501    })
502}
503
504// endregion
505
506// region: Macros
507
508/// Queue an R warning with `rust_warning` class layering and return normally;
509/// the surrounding guarded call or callback signals it after its value is
510/// computed.
511///
512/// Same grammar as [`crate::warning!`]: optional `call = none` (no call, like
513/// R's `warning(..., call. = FALSE)`), optional `class = …` (one class or a
514/// vector, most specific first), optional `data = …` (a pair, a bracketed
515/// list of pairs, or `{ name = value }` sugar), then the `format!` message.
516/// For a typed payload use [`crate::defer_warning()`] with a
517/// `#[derive(RCondition)]` type (`#[condition(call = none)]` on the type
518/// or a variant drops the call there).
519///
520/// A later `Err` does not cancel this warning. To avoid warnings on failure,
521/// queue after the last fallible step; see [warning placement](crate::deferred_condition#warning-placement).
522///
523/// From another thread it goes to R's main thread over a channel; see
524/// [Threads and boundaries](crate::deferred_condition#threads-and-boundaries).
525///
526/// ```ignore
527/// use miniextendr_api::defer_warning;
528///
529/// #[miniextendr]
530/// fn parse_all(xs: Vec<String>) -> Vec<i32> {
531///     let (ok, bad): (Vec<_>, Vec<_>) = xs.iter().map(|s| s.parse::<i32>()).partition(Result::is_ok);
532///     if !bad.is_empty() {
533///         defer_warning!(class = "pkg_unparsed", data = ("n", bad.len() as i32), "{} values could not be parsed", bad.len());
534///     }
535///     ok.into_iter().map(Result::unwrap).collect()
536/// }
537/// ```
538#[macro_export]
539macro_rules! defer_warning {
540    ($($t:tt)*) => {{
541        let (__mx_call, __mx_class, __mx_data, __mx_message) =
542            $crate::__mx_condition_parts!($($t)*);
543        $crate::deferred_condition::defer($crate::condition::RCondition::Warning {
544            message: __mx_message,
545            class: __mx_class,
546            data: __mx_data,
547            call: __mx_call,
548        });
549    }};
550}
551
552/// Queue an R message (`rust_message` layering, muffled by
553/// `suppressMessages()`) and return normally; emitted when the surrounding
554/// guarded call or callback returns.
555///
556/// Same grammar as [`crate::defer_warning!`]. Unlike [`crate::message!`] a
557/// `class = …` part is accepted and layered in front of `rust_message`.
558/// `call = none` is accepted for the shared grammar and changes nothing: an R
559/// message carries no call, so `conditionCall(m)` is `NULL` either way.
560///
561/// From another thread it goes to R's main thread over a channel; see
562/// [Threads and boundaries](crate::deferred_condition#threads-and-boundaries).
563#[macro_export]
564macro_rules! defer_message {
565    ($($t:tt)*) => {{
566        let (__mx_call, __mx_class, __mx_data, __mx_message) =
567            $crate::__mx_condition_parts!($($t)*);
568        $crate::deferred_condition::defer($crate::condition::RCondition::Message {
569            message: __mx_message,
570            class: __mx_class,
571            data: __mx_data,
572            call: __mx_call,
573        });
574    }};
575}
576
577/// Queue a plain R condition (`rust_condition` layering, silent without a
578/// handler) and return normally; signalled when the surrounding
579/// guarded call or callback returns.
580///
581/// Same grammar as [`crate::defer_warning!`]. Useful for progress or audit
582/// events a caller may opt into with `withCallingHandlers()`.
583///
584/// From another thread it goes to R's main thread over a channel; see
585/// [Threads and boundaries](crate::deferred_condition#threads-and-boundaries).
586#[macro_export]
587macro_rules! defer_condition {
588    ($($t:tt)*) => {{
589        let (__mx_call, __mx_class, __mx_data, __mx_message) =
590            $crate::__mx_condition_parts!($($t)*);
591        $crate::deferred_condition::defer($crate::condition::RCondition::Condition {
592            message: __mx_message,
593            class: __mx_class,
594            data: __mx_data,
595            call: __mx_call,
596        });
597    }};
598}
599
600// endregion
601
602// region: Tests — queue semantics (no R runtime needed)
603
604#[cfg(test)]
605mod tests;
606
607// endregion