1use crate::{
38 robj::Rinternals, Attributes, Error, IntoRobj, Language, List, Operators, Robj, Strings,
39};
40
41#[derive(Copy, Debug, Clone, PartialEq)]
43pub enum ConditionKind {
44 Condition,
46 Message,
48 Warning,
50 Error,
52}
53
54#[derive(Debug, Clone, PartialEq)]
61pub struct Condition {
62 pub message: Vec<String>,
64 pub kind: ConditionKind,
66 pub class: Option<Vec<String>>,
69 pub call: Option<Language>,
71 pub parent: Option<RCondition>,
73 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#[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
295pub 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 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 pub fn set_kind(mut self, kind: ConditionKind) -> Self {
314 self.kind = kind;
315 self
316 }
317
318 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 pub fn set_call(mut self, call: Language) -> Self {
327 self.call = Some(call);
328 self
329 }
330
331 pub fn set_parent(mut self, parent: impl Into<RCondition>) -> Self {
334 self.parent = Some(parent.into());
335 self
336 }
337
338 pub fn set_trace(mut self, trace: List) -> Self {
340 self.trace = Some(trace);
341 self
342 }
343
344 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
370pub 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
389pub 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#[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#[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}