1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use super::{ShellError, shell_error::io::IoError};
use crate::{FromValue, IntoValue, Span, Type, Value, record};
use miette::{Diagnostic, LabeledSpan, NamedSource, SourceSpan};
use serde::{Deserialize, Serialize};
use std::{fmt, fs};
// # use nu_protocol::{FromValue, Value, ShellError, record, Span};
/// A very generic type of error used for interfacing with external code, such as scripts and
/// plugins.
///
/// This generally covers most of the interface of [`miette::Diagnostic`], but with types that are
/// well-defined for our protocol.
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
pub struct LabeledError {
/// The main message for the error.
pub msg: String,
/// Labeled spans attached to the error, demonstrating to the user where the problem is.
#[serde(default)]
pub labels: Box<Vec<ErrorLabel>>,
/// A unique machine- and search-friendly error code to associate to the error. (e.g.
/// `nu::shell::missing_config_value`)
#[serde(default)]
pub code: Option<String>,
/// A link to documentation about the error, used in conjunction with `code`
#[serde(default)]
pub url: Option<String>,
/// Additional help for the error, usually a hint about what the user might try
#[serde(default)]
pub help: Option<String>,
/// Errors that are related to or caused this error
#[serde(default)]
pub inner: Box<Vec<ShellError>>,
}
impl LabeledError {
/// Create a new plain [`LabeledError`] with the given message.
///
/// This is usually used builder-style with methods like [`.with_label()`](Self::with_label) to
/// build an error.
///
/// # Example
///
/// ```rust
/// # use nu_protocol::LabeledError;
/// let error = LabeledError::new("Something bad happened");
/// assert_eq!("Something bad happened", error.to_string());
/// ```
pub fn new(msg: impl Into<String>) -> Self {
Self {
msg: msg.into(),
..Default::default()
}
}
/// Add a labeled span to the error to demonstrate to the user where the problem is.
///
/// # Example
///
/// ```rust
/// # use nu_protocol::{LabeledError, Span};
/// # let span = Span::test_data();
/// let error = LabeledError::new("An error")
/// .with_label("happened here", span);
/// assert_eq!("happened here", &error.labels[0].text);
/// assert_eq!(span, error.labels[0].span);
/// ```
pub fn with_label(mut self, text: impl Into<String>, span: Span) -> Self {
self.labels.push(ErrorLabel {
text: text.into(),
span,
});
self
}
/// Add a unique machine- and search-friendly error code to associate to the error. (e.g.
/// `nu::shell::missing_config_value`)
///
/// # Example
///
/// ```rust
/// # use nu_protocol::LabeledError;
/// let error = LabeledError::new("An error")
/// .with_code("my_product::error");
/// assert_eq!(Some("my_product::error"), error.code.as_deref());
/// ```
pub fn with_code(mut self, code: impl Into<String>) -> Self {
self.code = Some(code.into());
self
}
/// Add a link to documentation about the error, used in conjunction with `code`.
///
/// # Example
///
/// ```rust
/// # use nu_protocol::LabeledError;
/// let error = LabeledError::new("An error")
/// .with_url("https://example.org/");
/// assert_eq!(Some("https://example.org/"), error.url.as_deref());
/// ```
pub fn with_url(mut self, url: impl Into<String>) -> Self {
self.url = Some(url.into());
self
}
/// Add additional help for the error, usually a hint about what the user might try.
///
/// # Example
///
/// ```rust
/// # use nu_protocol::LabeledError;
/// let error = LabeledError::new("An error")
/// .with_help("did you try turning it off and back on again?");
/// assert_eq!(Some("did you try turning it off and back on again?"), error.help.as_deref());
/// ```
pub fn with_help(mut self, help: impl Into<String>) -> Self {
self.help = Some(help.into());
self
}
/// Add an error that is related to or caused this error.
///
/// # Example
///
/// ```rust
/// # use nu_protocol::{LabeledError, ShellError};
/// let error = LabeledError::new("An error")
/// .with_inner(LabeledError::new("out of coolant"));
/// let check: ShellError = LabeledError::new("out of coolant").into();
/// assert_eq!(check, error.inner[0]);
/// ```
pub fn with_inner(mut self, inner: impl Into<ShellError>) -> Self {
let inner_error: ShellError = inner.into();
self.inner.push(inner_error);
self
}
/// Create a [`LabeledError`] from a type that implements [`miette::Diagnostic`].
///
/// # Example
///
/// [`ShellError`] implements `miette::Diagnostic`:
///
/// ```rust
/// # use nu_protocol::{ShellError, LabeledError, shell_error::{self, io::IoError}, Span};
/// #
/// let error = LabeledError::from_diagnostic(
/// &ShellError::Io(IoError::new_with_additional_context(
/// shell_error::io::ErrorKind::from_std(std::io::ErrorKind::Other),
/// Span::test_data(),
/// None,
/// "some error"
/// ))
/// );
/// assert!(error.to_string().contains("I/O error"));
/// ```
pub fn from_diagnostic(diag: &(impl miette::Diagnostic + ?Sized)) -> Self {
Self {
msg: diag.to_string(),
labels: diag
.labels()
.into_iter()
.flatten()
.map(|label| ErrorLabel {
text: label.label().unwrap_or("").into(),
span: Span::new(label.offset(), label.offset() + label.len()),
})
.collect::<Vec<_>>()
.into(),
code: diag.code().map(|s| s.to_string()),
url: diag.url().map(|s| s.to_string()),
help: diag.help().map(|s| s.to_string()),
inner: diag
.related()
.into_iter()
.flatten()
.map(|i| Self::from_diagnostic(i).into())
.collect::<Vec<_>>()
.into(),
}
}
}
/// A labeled span within a [`LabeledError`].
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ErrorLabel {
/// Text to show together with the span
pub text: String,
/// Span pointing at where the text references in the source
pub span: Span,
}
impl From<ErrorLabel> for LabeledSpan {
fn from(val: ErrorLabel) -> Self {
LabeledSpan::new(
(!val.text.is_empty()).then_some(val.text),
val.span.start,
val.span.end - val.span.start,
)
}
}
impl From<ErrorLabel> for SourceSpan {
fn from(val: ErrorLabel) -> Self {
SourceSpan::new(val.span.start.into(), val.span.end - val.span.start)
}
}
impl FromValue for ErrorLabel {
fn from_value(v: Value) -> Result<Self, ShellError> {
let record = v.clone().into_record()?;
let text = String::from_value(match record.get("text") {
Some(val) => val.clone(),
None => Value::string("", v.span()),
})
.unwrap_or("originates from here".into());
let span = Span::from_value(match record.get("span") {
Some(val) => val.clone(),
// Maybe there's a better way...
None => Value::record(
record! {
"start" => Value::int(v.span().start as i64, v.span()),
"end" => Value::int(v.span().end as i64, v.span()),
},
v.span(),
),
});
match span {
Ok(s) => Ok(Self { text, span: s }),
Err(e) => Err(e),
}
}
fn expected_type() -> crate::Type {
Type::Record(
vec![
("text".into(), Type::String),
("span".into(), Type::record()),
]
.into(),
)
}
}
impl IntoValue for ErrorLabel {
fn into_value(self, span: Span) -> Value {
record! {
"text" => Value::string(self.text, span),
"span" => span.into_value(span),
}
.into_value(span)
}
}
/// Optionally named error source
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ErrorSource {
name: Option<String>,
text: Option<String>,
path: Option<String>,
}
impl ErrorSource {
pub fn new(name: Option<String>, text: String) -> Self {
Self {
name,
text: Some(text),
path: None,
}
}
}
impl From<ErrorSource> for NamedSource<String> {
fn from(value: ErrorSource) -> Self {
let name = value.name.unwrap_or_default();
match value {
ErrorSource {
text: Some(text),
path: None,
..
} => NamedSource::new(name, text),
ErrorSource {
text: None,
path: Some(path),
..
} => {
let text = fs::read_to_string(&path).unwrap_or_default();
NamedSource::new(path, text)
}
_ => NamedSource::new(name, "".into()),
}
}
}
impl FromValue for ErrorSource {
fn from_value(v: Value) -> Result<Self, ShellError> {
let record = v.clone().into_record()?;
let name = record
.get("name")
.and_then(|s| String::from_value(s.clone()).ok());
// let name = String::from_value(record.get("name").unwrap().clone()).ok();
let text = if let Some(text) = record.get("text") {
String::from_value(text.clone()).ok()
} else {
None
};
let path = if let Some(path) = record.get("path") {
String::from_value(path.clone()).ok()
} else {
None
};
match (text, path) {
// Prioritize not reading from a file and using the text raw
(text @ Some(_), _) => Ok(ErrorSource {
name,
text,
path: None,
}),
(_, path @ Some(_)) => Ok(ErrorSource {
name: path.clone(),
text: None,
path,
}),
_ => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
fn expected_type() -> crate::Type {
Type::Record(
vec![
("name".into(), Type::String),
("text".into(), Type::String),
("path".into(), Type::String),
]
.into(),
)
}
}
impl IntoValue for ErrorSource {
fn into_value(self, span: Span) -> Value {
match self {
Self {
name: Some(name),
text: Some(text),
..
} => record! {
"name" => Value::string(name, span),
"text" => Value::string(text, span),
},
Self {
text: Some(text), ..
} => record! {
"text" => Value::string(text, span)
},
Self {
name: Some(name),
path: Some(path),
..
} => record! {
"name" => Value::string(name, span),
"path" => Value::string(path, span),
},
Self {
path: Some(path), ..
} => record! {
"path" => Value::string(path, span),
},
_ => record! {},
}
.into_value(span)
}
}
impl fmt::Display for LabeledError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.msg)
}
}
impl std::error::Error for LabeledError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.inner.first().map(|r| r as _)
}
}
impl Diagnostic for LabeledError {
fn code<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
self.code.as_ref().map(Box::new).map(|b| b as _)
}
fn help<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
self.help.as_ref().map(Box::new).map(|b| b as _)
}
fn url<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
self.url.as_ref().map(Box::new).map(|b| b as _)
}
fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {
Some(Box::new(
self.labels.iter().map(|label| label.clone().into()),
))
}
fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn Diagnostic> + 'a>> {
Some(Box::new(self.inner.iter().map(|r| r as _)))
}
}
impl From<ShellError> for LabeledError {
fn from(err: ShellError) -> Self {
Self::from_diagnostic(&err)
}
}
impl From<IoError> for LabeledError {
fn from(err: IoError) -> Self {
Self::from_diagnostic(&err)
}
}