Skip to main content

extendr_api/conditions/
mod.rs

1//! # Condition objects
2//!
3//! In R, a condition is an S3 list with:
4//! - `message`: a character vector describing the condition
5//! - `call`: the call that triggered the condition, or `NULL`
6//! - a class attribute including `"condition"` and optionally `"error"`,
7//!   `"warning"`, or `"message"`
8//!
9//! rlang conditions may include `trace` and `parent` fields, which are
10//! represented as `Option<List>` and `Option<RCondition>` respectively.
11//!
12//! ## Types
13//!
14//! This module provides four types:
15//!
16//! - [`ConditionKind`]: an enum discriminating the base R condition type
17//!   (`condition`, `message`, `warning`, `error`).
18//!
19//! - [`Condition`]: a Rust-native representation. Construct one with [`ConditionBuilder::default()`]. This is the primary type we encourage you to work with for its ergonomics due to its use of std types.
20//!
21//! - [`RCondition`]: a thin wrapper around a [`List`] that already exists in R
22//!   memory as a proper condition object. Use this when receiving or returning
23//!   condition objects at the R boundary.
24//!
25//! - [`ConditionBuilder`]: a builder for [`Condition`]. Create a builder with [`ConditionBuilder::default()`] to start, chain setters, and call `.build()` to produce a [`Condition`].
26//!
27//! ## Conversions
28//!
29//! | From \ To   | `List`  | `RCondition` | `Robj`  | `Condition` |
30//! |-------------|---------|--------------|---------|-------------|
31//! | `Condition` | `From`  | `From`       | `From`  | —           |
32//! | `List`      | —       | `TryFrom`    | blanket | `TryFrom`   |
33//! | `&List`     | —       | `TryFrom`    | —       | `TryFrom`   |
34//! | `RCondition`| `From`  | —            | `From`  | `TryFrom`   |
35//! | `Robj`      | —       | `TryFrom`    | —       | `TryFrom`   |
36//! | `&Robj`     | —       | `TryFrom`    | —       | `TryFrom`   |
37use crate::{
38    robj::Rinternals, Attributes, Error, IntoRobj, Language, List, Operators, Robj, Strings,
39};
40
41/// Discriminates the kind of R condition being constructed.
42#[derive(Copy, Debug, Clone, PartialEq)]
43pub enum ConditionKind {
44    /// A generic condition. Base class: `"condition"`.
45    Condition,
46    /// A message condition. Base classes: `"message"`, `"condition"`.
47    Message,
48    /// A warning condition. Base classes: `"warning"`, `"condition"`.
49    Warning,
50    /// An error condition. Base classes: `"error"`, `"condition"`.
51    Error,
52}
53
54/// Rust-native representation of an R condition.
55///
56/// This is the primary type to work with. Construct one via
57/// [`ConditionBuilder::default()`] and convert it to R types via the
58/// `From`/`Into` impls. To read a condition from R, use `TryFrom<Robj>` or
59/// `TryFrom<List>`.
60#[derive(Debug, Clone, PartialEq)]
61pub struct Condition {
62    /// The condition message. Corresponds to the `message` character vector in R.
63    pub message: Vec<String>,
64    /// The base kind of condition, used to set the R class hierarchy.
65    pub kind: ConditionKind,
66    /// User-defined subclasses prepended to the base classes. `None` means no
67    /// custom classes beyond those implied by `kind`.
68    pub class: Option<Vec<String>>,
69    /// The call that triggered the condition, or `None` for `NULL`.
70    pub call: Option<Language>,
71    /// An optional parent condition, used to chain conditions with rlang.
72    pub parent: Option<RCondition>,
73    /// An optional traceback. The structure is not validated.
74    pub trace: Option<List>,
75}
76
77impl From<Condition> for List {
78    fn from(value: Condition) -> Self {
79        let msg = Strings::from_values(value.message).into_robj();
80
81        let call_robj = value.call.map(|v| v.into()).unwrap_or_default();
82        let parent_robj = value.parent.map(|v| Robj::from(v.0)).unwrap_or_default();
83        let trace_robj = value.trace.map(Robj::from).unwrap_or_default();
84
85        let mut cnd = List::from_pairs([
86            ("message", msg),
87            ("trace", trace_robj),
88            ("parent", parent_robj),
89            ("call", call_robj),
90        ]);
91
92        let base_classes: &[&str] = match value.kind {
93            ConditionKind::Condition => &["condition"],
94            ConditionKind::Message => &["message", "condition"],
95            ConditionKind::Warning => &["warning", "condition"],
96            ConditionKind::Error => &["error", "condition"],
97        };
98
99        let mut class = value.class.unwrap_or_default();
100        class.extend(base_classes.iter().map(|s| s.to_string()));
101        cnd.set_class(&class)
102            .expect("set_class on a list should never fail");
103        cnd
104    }
105}
106
107impl From<Condition> for RCondition {
108    fn from(value: Condition) -> Self {
109        Self(List::from(value))
110    }
111}
112
113impl From<Condition> for Robj {
114    fn from(value: Condition) -> Self {
115        Robj::from(List::from(value))
116    }
117}
118
119impl TryFrom<&List> for Condition {
120    type Error = Error;
121
122    fn try_from(list: &List) -> std::result::Result<Self, Self::Error> {
123        let message: Vec<String> = Strings::try_from(list.dollar("message")?)?.into();
124
125        let cls = list
126            .class()
127            .map(|inner| inner.map(|s| s.to_string()).collect::<Vec<_>>())
128            .unwrap_or_default();
129
130        if !cls.iter().any(|c| c == "condition") {
131            return Err(Error::Other(
132                "object does not inherit from `condition`".into(),
133            ));
134        }
135
136        let base_kinds = ["error", "warning", "message"];
137        let matched: Vec<&str> = base_kinds
138            .iter()
139            .copied()
140            .filter(|k| cls.iter().any(|c| c == k))
141            .collect();
142
143        if matched.len() > 1 {
144            return Err(Error::Other(format!(
145                "ambiguous condition: inherits from multiple base kinds: {}",
146                matched.join(", ")
147            )));
148        }
149
150        let kind = match matched.first().copied() {
151            Some("error") => ConditionKind::Error,
152            Some("warning") => ConditionKind::Warning,
153            Some("message") => ConditionKind::Message,
154            _ => ConditionKind::Condition,
155        };
156
157        let base_classes: &[&str] = match kind {
158            ConditionKind::Condition => &["condition"],
159            ConditionKind::Message => &["message", "condition"],
160            ConditionKind::Warning => &["warning", "condition"],
161            ConditionKind::Error => &["error", "condition"],
162        };
163        let user_class: Vec<String> = cls
164            .iter()
165            .filter(|c| !base_classes.contains(&c.as_str()))
166            .cloned()
167            .collect();
168        let class = if user_class.is_empty() {
169            None
170        } else {
171            Some(user_class)
172        };
173
174        let call = list.dollar("call").ok().and_then(|v| {
175            if v.is_null() {
176                None
177            } else {
178                Language::try_from(&v).ok()
179            }
180        });
181
182        let parent = list.dollar("parent").ok().and_then(|v| {
183            if v.is_null() {
184                None
185            } else {
186                List::try_from(&v).ok().map(RCondition)
187            }
188        });
189
190        let trace = list.dollar("trace").ok().and_then(|v| {
191            if v.is_null() {
192                None
193            } else {
194                List::try_from(&v).ok()
195            }
196        });
197
198        Ok(Condition {
199            message,
200            kind,
201            class,
202            call,
203            parent,
204            trace,
205        })
206    }
207}
208
209impl TryFrom<List> for Condition {
210    type Error = Error;
211
212    fn try_from(value: List) -> std::result::Result<Self, Self::Error> {
213        Condition::try_from(&value)
214    }
215}
216
217impl TryFrom<&Robj> for Condition {
218    type Error = Error;
219
220    fn try_from(value: &Robj) -> std::result::Result<Self, Self::Error> {
221        Condition::try_from(List::try_from(value)?)
222    }
223}
224
225impl TryFrom<Robj> for Condition {
226    type Error = Error;
227
228    fn try_from(value: Robj) -> std::result::Result<Self, Self::Error> {
229        Condition::try_from(&value)
230    }
231}
232
233/// A validated R condition object held as a [`List`].
234///
235/// Use this as a function argument or return type when exchanging condition
236/// objects with R. To inspect or modify fields, convert to [`Condition`] via
237/// `TryFrom`.
238#[derive(Clone, PartialEq, Debug)]
239pub struct RCondition(pub List);
240
241impl TryFrom<List> for RCondition {
242    type Error = Error;
243
244    fn try_from(value: List) -> std::result::Result<Self, Self::Error> {
245        Condition::try_from(&value)?;
246        Ok(RCondition(value))
247    }
248}
249
250impl TryFrom<&List> for RCondition {
251    type Error = Error;
252
253    fn try_from(value: &List) -> std::result::Result<Self, Self::Error> {
254        Condition::try_from(value)?;
255        Ok(RCondition(value.clone()))
256    }
257}
258
259impl From<RCondition> for List {
260    fn from(value: RCondition) -> Self {
261        value.0
262    }
263}
264
265impl From<RCondition> for Robj {
266    fn from(value: RCondition) -> Self {
267        Robj::from(value.0)
268    }
269}
270
271impl TryFrom<RCondition> for Condition {
272    type Error = Error;
273
274    fn try_from(value: RCondition) -> std::result::Result<Self, Self::Error> {
275        Condition::try_from(value.0)
276    }
277}
278
279impl TryFrom<&Robj> for RCondition {
280    type Error = Error;
281
282    fn try_from(value: &Robj) -> std::result::Result<Self, Self::Error> {
283        RCondition::try_from(List::try_from(value)?)
284    }
285}
286
287impl TryFrom<Robj> for RCondition {
288    type Error = Error;
289
290    fn try_from(value: Robj) -> std::result::Result<Self, Self::Error> {
291        RCondition::try_from(&value)
292    }
293}
294
295/// Builder for constructing a [`Condition`].
296pub struct ConditionBuilder {
297    message: Vec<String>,
298    kind: ConditionKind,
299    class: Option<Vec<String>>,
300    call: Option<Language>,
301    parent: Option<RCondition>,
302    trace: Option<List>,
303}
304
305impl ConditionBuilder {
306    /// Set the condition message. Accepts any iterable of strings.
307    pub fn set_message(mut self, message: impl IntoIterator<Item = impl Into<String>>) -> Self {
308        self.message = message.into_iter().map(|s| s.into()).collect();
309        self
310    }
311
312    /// Set the condition kind, which determines the base R class hierarchy.
313    pub fn set_kind(mut self, kind: ConditionKind) -> Self {
314        self.kind = kind;
315        self
316    }
317
318    /// Set user-defined subclasses. These are prepended to the base classes
319    /// derived from [`ConditionKind`].
320    pub fn set_class(mut self, class: impl IntoIterator<Item = impl Into<String>>) -> Self {
321        self.class = Some(class.into_iter().map(|s| s.into()).collect());
322        self
323    }
324
325    /// Set the call associated with the condition.
326    pub fn set_call(mut self, call: Language) -> Self {
327        self.call = Some(call);
328        self
329    }
330
331    /// Set a parent condition. Accepts anything that converts into [`RCondition`],
332    /// including a [`Condition`].
333    pub fn set_parent(mut self, parent: impl Into<RCondition>) -> Self {
334        self.parent = Some(parent.into());
335        self
336    }
337
338    /// Set the traceback. The structure of the list is not validated.
339    pub fn set_trace(mut self, trace: List) -> Self {
340        self.trace = Some(trace);
341        self
342    }
343
344    /// Consume the builder and produce a [`Condition`].
345    pub fn build(self) -> Condition {
346        Condition {
347            message: self.message,
348            kind: self.kind,
349            class: self.class,
350            call: self.call,
351            parent: self.parent,
352            trace: self.trace,
353        }
354    }
355}
356
357impl Default for ConditionBuilder {
358    fn default() -> Self {
359        Self {
360            message: Vec::new(),
361            kind: ConditionKind::Condition,
362            class: None,
363            call: None,
364            parent: None,
365            trace: None,
366        }
367    }
368}
369
370/// Format an error message with rlang-style bullets.
371pub fn format_cnd_message(header: &str, body: &[&str]) -> String {
372    use std::io::IsTerminal;
373    let use_color = std::io::stderr().is_terminal();
374    let bang = if use_color { "\x1b[33m!\x1b[0m" } else { "!" };
375    let bullet = if use_color {
376        "\x1b[36m\u{2022}\x1b[0m"
377    } else {
378        "\u{2022}"
379    };
380
381    let mut msg = format!("\n{bang} {header}");
382    for line in body {
383        msg.push('\n');
384        msg.push_str(&format!("{bullet} {line}"));
385    }
386    msg
387}
388
389/// Format a warning message with rlang-style bullets.
390pub fn format_warn_message(header: &str, body: &[&str]) -> String {
391    use std::io::IsTerminal;
392    let use_color = std::io::stderr().is_terminal();
393    let bullet = if use_color {
394        "\x1b[36m\u{2022}\x1b[0m"
395    } else {
396        "\u{2022}"
397    };
398
399    let mut msg = header.to_string();
400    for line in body {
401        msg.push('\n');
402        msg.push_str(&format!("{bullet} {line}"));
403    }
404    msg
405}
406
407#[doc(hidden)]
408pub fn to_c_message(msg: impl Into<String>) -> std::ffi::CString {
409    let msg = msg.into();
410    std::ffi::CString::new(msg.replace('\0', "\\0")).unwrap_or_default()
411}
412
413/// Signal a warning with an rlang-style formatted message.
414#[macro_export]
415macro_rules! warn {
416    ($msg:expr) => {{
417        let formatted = $crate::conditions::format_warn_message($msg, &[]);
418        let c_msg = $crate::conditions::to_c_message(formatted);
419        unsafe {
420            $crate::Rf_warningcall($crate::R_NilValue, c"%s".as_ptr(), c_msg.as_ptr());
421        }
422    }};
423    ($msg:expr, $body:expr) => {{
424        let formatted = $crate::conditions::format_warn_message($msg, $body);
425        let c_msg = $crate::conditions::to_c_message(formatted);
426        unsafe {
427            $crate::Rf_warningcall($crate::R_NilValue, c"%s".as_ptr(), c_msg.as_ptr());
428        }
429    }};
430    ($msg:expr, $body:expr, $call:expr) => {{
431        let formatted = $crate::conditions::format_warn_message($msg, $body);
432        let c_msg = $crate::conditions::to_c_message(formatted);
433        let call_robj = $call.call();
434        unsafe {
435            let call_sexp = call_robj
436                .as_ref()
437                .map(|c| c.get())
438                .unwrap_or($crate::R_NilValue);
439            $crate::Rf_warningcall(call_sexp, c"%s".as_ptr(), c_msg.as_ptr());
440        }
441    }};
442}
443
444/// Signal an error with an rlang-style formatted message.
445#[macro_export]
446macro_rules! abort {
447    ($msg:expr) => {{
448        let formatted = $crate::conditions::format_cnd_message($msg, &[]);
449        let c_msg = $crate::conditions::to_c_message(formatted);
450        unsafe {
451            $crate::Rf_errorcall($crate::R_NilValue, c"%s".as_ptr(), c_msg.as_ptr());
452        }
453    }};
454
455    ($msg:expr, call = $call:expr) => {{
456        let formatted = $crate::conditions::format_cnd_message($msg, &[]);
457        let c_msg = $crate::conditions::to_c_message(formatted);
458        let call_robj = $call.call();
459        unsafe {
460            let call_sexp = call_robj
461                .as_ref()
462                .map(|c| c.get())
463                .unwrap_or($crate::R_NilValue);
464            $crate::Rf_errorcall(call_sexp, c"%s".as_ptr(), c_msg.as_ptr());
465        }
466    }};
467
468    ($msg:expr, $body:expr) => {{
469        let formatted = $crate::conditions::format_cnd_message($msg, $body);
470        let c_msg = $crate::conditions::to_c_message(formatted);
471        unsafe {
472            $crate::Rf_errorcall($crate::R_NilValue, c"%s".as_ptr(), c_msg.as_ptr());
473        }
474    }};
475
476    ($msg:expr, $body:expr, $call:expr) => {{
477        let formatted = $crate::conditions::format_cnd_message($msg, $body);
478        let c_msg = $crate::conditions::to_c_message(formatted);
479        let call_robj = $call.call();
480        unsafe {
481            let call_sexp = call_robj
482                .as_ref()
483                .map(|c| c.get())
484                .unwrap_or($crate::R_NilValue);
485            $crate::Rf_errorcall(call_sexp, c"%s".as_ptr(), c_msg.as_ptr());
486        }
487    }};
488}
489
490#[cfg(test)]
491mod tests {
492    use extendr_engine::with_r;
493
494    use crate::{
495        conditions::{Condition, ConditionBuilder, ConditionKind, RCondition},
496        Attributes, List, Result, Robj,
497    };
498
499    #[test]
500    fn test_format_cnd_message_no_body() {
501        let msg = super::format_cnd_message("something went wrong", &[]);
502        assert!(msg.contains("something went wrong"));
503    }
504
505    #[test]
506    fn test_format_cnd_message_with_body() {
507        let msg = super::format_cnd_message("something went wrong", &["detail 1", "detail 2"]);
508        assert!(msg.contains("something went wrong"));
509        assert!(msg.contains("detail 1"));
510        assert!(msg.contains("detail 2"));
511    }
512
513    #[test]
514    fn roundtrip_with_class() -> Result<()> {
515        with_r(|| {
516            let cnd = ConditionBuilder::default()
517                .set_kind(ConditionKind::Message)
518                .set_message(["this is a custom message"])
519                .set_class(["class1", "class2"])
520                .build();
521            let c2 = Condition::try_from(RCondition::from(cnd.clone()))?;
522            assert_eq!(cnd, c2);
523            Ok(())
524        })
525    }
526
527    #[test]
528    fn roundtrip_no_class() -> Result<()> {
529        with_r(|| {
530            let cnd = ConditionBuilder::default()
531                .set_kind(ConditionKind::Warning)
532                .set_message(["watch out"])
533                .build();
534            let c2 = Condition::try_from(RCondition::from(cnd.clone()))?;
535            assert_eq!(cnd, c2);
536            Ok(())
537        })
538    }
539
540    #[test]
541    fn roundtrip_via_robj() -> Result<()> {
542        with_r(|| {
543            let cnd = ConditionBuilder::default()
544                .set_kind(ConditionKind::Error)
545                .set_message(["something failed"])
546                .set_class(["my_error"])
547                .build();
548            let robj = Robj::from(cnd.clone());
549            let c2 = Condition::try_from(robj)?;
550            assert_eq!(cnd, c2);
551            Ok(())
552        })
553    }
554
555    #[test]
556    fn roundtrip_all_kinds() -> Result<()> {
557        with_r(|| {
558            for (kind, expected_base) in [
559                (ConditionKind::Condition, "condition"),
560                (ConditionKind::Message, "message"),
561                (ConditionKind::Warning, "warning"),
562                (ConditionKind::Error, "error"),
563            ] {
564                let cnd = ConditionBuilder::default()
565                    .set_kind(kind)
566                    .set_message(["msg"])
567                    .build();
568                let list = List::from(cnd);
569                let cls: Vec<_> = list.class().unwrap().collect();
570                assert!(cls.contains(&expected_base), "missing {expected_base}");
571                assert!(cls.contains(&"condition"), "missing condition");
572            }
573            Ok(())
574        })
575    }
576
577    #[test]
578    fn err_not_a_condition() -> Result<()> {
579        with_r(|| {
580            let list = List::from_pairs([("message", Robj::from("oops"))]);
581            let result = Condition::try_from(&list);
582            assert!(result.is_err());
583            Ok(())
584        })
585    }
586
587    #[test]
588    fn err_not_a_list() -> Result<()> {
589        with_r(|| {
590            let robj = Robj::from("just a string");
591            let result = Condition::try_from(&robj);
592            assert!(result.is_err());
593            Ok(())
594        })
595    }
596
597    #[test]
598    fn err_ambiguous_kind() -> Result<()> {
599        with_r(|| {
600            let mut list =
601                List::from_pairs([("message", Robj::from("oops")), ("call", Robj::null())]);
602            list.set_class(&["error", "warning", "condition"]).unwrap();
603            let result = Condition::try_from(&list);
604            assert!(result.is_err());
605            Ok(())
606        })
607    }
608
609    #[test]
610    fn roundtrip_rcondition_to_condition() -> Result<()> {
611        with_r(|| {
612            let cnd = ConditionBuilder::default()
613                .set_kind(ConditionKind::Error)
614                .set_message(["bad thing"])
615                .set_class(["my_err"])
616                .build();
617            let rcnd = RCondition::from(cnd.clone());
618            let c2 = Condition::try_from(rcnd)?;
619            assert_eq!(cnd, c2);
620            Ok(())
621        })
622    }
623}