Skip to main content

nu_protocol/errors/shell_error/
eval_block_with_input.rs

1use crate::{ShellError, Span};
2use miette::{Diagnostic, LabeledSpan, Severity, SourceSpan};
3use std::{
4    error::Error as StdError,
5    fmt::{self, Display},
6};
7
8/// An error raised while a closure ran on one pipeline input value.
9///
10/// Commands that run a closure per input value (`each`, `par-each`, `items`) wrap the closure's
11/// error in this type so the report also points at the value being processed. With
12/// `NU_BACKTRACE` set, an error from a stream is also wrapped once for each call the stream
13/// passed through, labeled with [`CALLER`](Self::CALLER).
14///
15/// It reports as the wrapped error: the message, code, help, and related errors are the
16/// wrapped error's, and its labels gain [`label`](Self::label) at [`span`](Self::span).
17/// `try`/`catch` therefore sees the wrapped error's message in `$e.msg`.
18///
19/// A wrapped error that resolves its labels against its own source code can't share a snippet
20/// with [`span`](Self::span). The report then shows the message with only this label, and
21/// lists the wrapped error as related.
22#[derive(Debug, Clone, PartialEq)]
23pub struct EvalBlockWithInputError {
24    /// Span of the input value the closure was running on, or of the call a failing stream
25    /// passed through.
26    pub span: Span,
27
28    /// Text of the label at [`span`](Self::span), [`SOURCE_VALUE`](Self::SOURCE_VALUE) or
29    /// [`CALLER`](Self::CALLER).
30    pub label: &'static str,
31
32    /// The error the closure raised.
33    pub error: Box<ShellError>,
34}
35
36impl EvalBlockWithInputError {
37    /// Label for the input value a closure was running on.
38    pub const SOURCE_VALUE: &'static str = "source value";
39
40    /// Label for a call that a failing stream passed through, the same text
41    /// [`ChainedError`](crate::ChainedError) uses for a backtrace frame.
42    pub const CALLER: &'static str = "error happened when running this";
43
44    /// Wraps `error` with a `label` at `span`.
45    ///
46    /// `exit` and interrupts are returned unwrapped: they aren't about the input value, and the
47    /// code that handles them (`catch`, `finally`, the REPL, `nu -c`) matches the bare variant.
48    pub fn wrap(error: ShellError, span: Span, label: &'static str) -> ShellError {
49        if error.is_interrupt() || matches!(error, ShellError::Exit { .. }) {
50            return error;
51        }
52        ShellError::EvalBlockWithInput(Self {
53            span,
54            label,
55            error: Box::new(error),
56        })
57    }
58
59    /// The wrapped error when its labels can share a snippet with this one. An error with its
60    /// own source code resolves its labels against that source, where [`span`](Self::span)
61    /// would point at unrelated text.
62    fn inline_error(&self) -> Option<&ShellError> {
63        self.error.source_code().is_none().then_some(&*self.error)
64    }
65}
66
67impl Display for EvalBlockWithInputError {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        Display::fmt(&self.error, f)
70    }
71}
72
73// `source()` stays `None`: miette prints the source chain as extra lines, which would repeat
74// the wrapped error that this type already reports as itself.
75impl StdError for EvalBlockWithInputError {}
76
77// `source_code()` stays `None`: an inline error has none, and otherwise this type's only label
78// is resolved by the caller against the working set.
79impl Diagnostic for EvalBlockWithInputError {
80    fn code<'a>(&'a self) -> Option<Box<dyn Display + 'a>> {
81        self.error.code()
82    }
83
84    fn severity(&self) -> Option<Severity> {
85        self.error.severity()
86    }
87
88    fn help<'a>(&'a self) -> Option<Box<dyn Display + 'a>> {
89        self.inline_error().and_then(|error| error.help())
90    }
91
92    fn url<'a>(&'a self) -> Option<Box<dyn Display + 'a>> {
93        self.inline_error().and_then(|error| error.url())
94    }
95
96    fn labels(&self) -> Option<Box<dyn Iterator<Item = LabeledSpan> + '_>> {
97        let mut labels: Vec<_> = self
98            .inline_error()
99            .and_then(|error| error.labels())
100            .into_iter()
101            .flatten()
102            .collect();
103        // A span the wrapped error already labels keeps that label: a stream's first caller
104        // is usually the failing call itself. Of nested closures, only the innermost input
105        // value is labeled, since that is the value the failing closure ran on.
106        let span = SourceSpan::from(self.span);
107        let already_labeled = labels.iter().any(|label| {
108            *label.inner() == span
109                || (self.label == Self::SOURCE_VALUE && label.label() == Some(Self::SOURCE_VALUE))
110        });
111        if !already_labeled {
112            labels.push(LabeledSpan::new_with_span(Some(self.label.into()), span));
113        }
114        Some(Box::new(labels.into_iter()))
115    }
116
117    fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn Diagnostic> + 'a>> {
118        match self.inline_error() {
119            Some(error) => error.related(),
120            None => Some(Box::new(std::iter::once(&*self.error as &dyn Diagnostic))),
121        }
122    }
123
124    fn diagnostic_source(&self) -> Option<&dyn Diagnostic> {
125        self.inline_error()
126            .and_then(|error| error.diagnostic_source())
127    }
128}
129
130#[cfg(test)]
131mod test {
132    use super::*;
133    use crate::shell_error::generic::GenericError;
134
135    fn input_error(error: ShellError, span: Span) -> ShellError {
136        EvalBlockWithInputError::wrap(error, span, EvalBlockWithInputError::SOURCE_VALUE)
137    }
138
139    fn label_texts(error: &dyn Diagnostic) -> Vec<Option<String>> {
140        error
141            .labels()
142            .into_iter()
143            .flatten()
144            .map(|label| label.label().map(str::to_string))
145            .collect()
146    }
147
148    #[test]
149    fn reports_as_the_wrapped_error() {
150        let inner = GenericError::new("boom", "here", Span::new(10, 12)).with_code("my::code");
151        let error = input_error(inner.into(), Span::new(1, 2));
152
153        assert_eq!(error.to_string(), "boom");
154        assert_eq!(
155            error.code().map(|code| code.to_string()),
156            Some("my::code".into())
157        );
158        assert_eq!(
159            label_texts(&error),
160            [Some("here".into()), Some("source value".into())]
161        );
162    }
163
164    #[test]
165    fn reports_wrapped_error_with_own_source_as_related() {
166        let inner = ShellError::from(GenericError::new_internal("boom", "here"));
167        let error = input_error(inner.clone(), Span::new(1, 2));
168
169        assert_eq!(error.to_string(), "boom");
170        assert_eq!(label_texts(&error), [Some("source value".into())]);
171        assert!(error.source_code().is_none());
172        let related: Vec<_> = error.related().into_iter().flatten().collect();
173        assert_eq!(related.len(), 1);
174        assert_eq!(related[0].to_string(), "boom");
175        assert_eq!(label_texts(related[0]), [Some("here".into())]);
176    }
177
178    #[test]
179    fn labels_only_the_innermost_input_value() {
180        let inner = GenericError::new("boom", "here", Span::new(10, 12));
181        let error = input_error(input_error(inner.into(), Span::new(5, 6)), Span::new(1, 2));
182
183        let spans: Vec<_> = error
184            .labels()
185            .into_iter()
186            .flatten()
187            .map(|label| *label.inner())
188            .collect();
189        assert_eq!(spans, [Span::new(10, 12).into(), Span::new(5, 6).into()]);
190    }
191
192    #[test]
193    fn labels_each_caller_once() {
194        let inner = GenericError::new("boom", "here", Span::new(10, 12));
195        let caller = |error, span| {
196            EvalBlockWithInputError::wrap(error, span, EvalBlockWithInputError::CALLER)
197        };
198        let error = caller(caller(inner.into(), Span::new(10, 12)), Span::new(1, 2));
199
200        assert_eq!(
201            label_texts(&error),
202            [
203                Some("here".into()),
204                Some("error happened when running this".into())
205            ]
206        );
207    }
208
209    #[test]
210    fn passes_control_flow_through() {
211        let exit = ShellError::Exit {
212            code: 4,
213            abort: false,
214        };
215        assert_eq!(input_error(exit.clone(), Span::new(1, 2)), exit);
216
217        let interrupted = ShellError::Interrupted {
218            span: Span::new(3, 4),
219        };
220        assert_eq!(
221            input_error(interrupted.clone(), Span::new(1, 2)),
222            interrupted
223        );
224    }
225}