nu_cmd_lang/core_commands/
error_make.rs

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
use nu_engine::command_prelude::*;
use nu_protocol::LabeledError;

#[derive(Clone)]
pub struct ErrorMake;

impl Command for ErrorMake {
    fn name(&self) -> &str {
        "error make"
    }

    fn signature(&self) -> Signature {
        Signature::build("error make")
            .input_output_types(vec![(Type::Nothing, Type::Error)])
            .required(
                "error_struct",
                SyntaxShape::Record(vec![]),
                "The error to create.",
            )
            .switch(
                "unspanned",
                "remove the origin label from the error",
                Some('u'),
            )
            .category(Category::Core)
    }

    fn description(&self) -> &str {
        "Create an error."
    }

    fn search_terms(&self) -> Vec<&str> {
        vec!["panic", "crash", "throw"]
    }

    fn run(
        &self,
        engine_state: &EngineState,
        stack: &mut Stack,
        call: &Call,
        _input: PipelineData,
    ) -> Result<PipelineData, ShellError> {
        let arg: Value = call.req(engine_state, stack, 0)?;

        let throw_span = if call.has_flag(engine_state, stack, "unspanned")? {
            None
        } else {
            Some(call.head)
        };

        Err(make_other_error(&arg, throw_span))
    }

    fn examples(&self) -> Vec<Example> {
        vec![
            Example {
                description: "Create a simple custom error",
                example: r#"error make {msg: "my custom error message"}"#,
                result: None,
            },
            Example {
                description: "Create a more complex custom error",
                example: r#"error make {
        msg: "my custom error message"
        label: {
            text: "my custom label text"  # not mandatory unless $.label exists
            # optional
            span: {
                # if $.label.span exists, both start and end must be present
                start: 123
                end: 456
            }
        }
        help: "A help string, suggesting a fix to the user"  # optional
    }"#,
                result: None,
            },
            Example {
                description:
                    "Create a custom error for a custom command that shows the span of the argument",
                example: r#"def foo [x] {
        error make {
            msg: "this is fishy"
            label: {
                text: "fish right here"
                span: (metadata $x).span
            }
        }
    }"#,
                result: None,
            },
        ]
    }
}

const UNABLE_TO_PARSE: &str = "Unable to parse error format.";

fn make_other_error(value: &Value, throw_span: Option<Span>) -> ShellError {
    let span = value.span();
    let value = match value {
        Value::Record { val, .. } => val,
        _ => {
            return ShellError::GenericError {
                error: "Creating error value not supported.".into(),
                msg: "unsupported error format, must be a record".into(),
                span: throw_span,
                help: None,
                inner: vec![],
            }
        }
    };

    let msg = match value.get("msg") {
        Some(Value::String { val, .. }) => val.clone(),
        Some(_) => {
            return ShellError::GenericError {
                error: UNABLE_TO_PARSE.into(),
                msg: "`$.msg` has wrong type, must be string".into(),
                span: Some(span),
                help: None,
                inner: vec![],
            }
        }
        None => {
            return ShellError::GenericError {
                error: UNABLE_TO_PARSE.into(),
                msg: "missing required member `$.msg`".into(),
                span: Some(span),
                help: None,
                inner: vec![],
            }
        }
    };

    let help = match value.get("help") {
        Some(Value::String { val, .. }) => Some(val.clone()),
        _ => None,
    };

    let (label, label_span) = match value.get("label") {
        Some(value @ Value::Record { val, .. }) => (val, value.span()),
        Some(_) => {
            return ShellError::GenericError {
                error: UNABLE_TO_PARSE.into(),
                msg: "`$.label` has wrong type, must be a record".into(),
                span: Some(span),
                help: None,
                inner: vec![],
            }
        }
        // correct return: no label
        None => {
            return ShellError::GenericError {
                error: msg,
                msg: "originates from here".into(),
                span: throw_span,
                help,
                inner: vec![],
            }
        }
    };

    // remove after a few versions
    if label.get("start").is_some() || label.get("end").is_some() {
        return ShellError::GenericError {
            error: UNABLE_TO_PARSE.into(),
            msg: "`start` and `end` are deprecated".into(),
            span: Some(span),
            help: Some("Use `$.label.span` instead".into()),
            inner: vec![],
        };
    }

    let text = match label.get("text") {
        Some(Value::String { val, .. }) => val.clone(),
        Some(_) => {
            return ShellError::GenericError {
                error: UNABLE_TO_PARSE.into(),
                msg: "`$.label.text` has wrong type, must be string".into(),
                span: Some(label_span),
                help: None,
                inner: vec![],
            }
        }
        None => {
            return ShellError::GenericError {
                error: UNABLE_TO_PARSE.into(),
                msg: "missing required member `$.label.text`".into(),
                span: Some(label_span),
                help: None,
                inner: vec![],
            }
        }
    };

    let (span, span_span) = match label.get("span") {
        Some(value @ Value::Record { val, .. }) => (val, value.span()),
        Some(value) => {
            return ShellError::GenericError {
                error: UNABLE_TO_PARSE.into(),
                msg: "`$.label.span` has wrong type, must be record".into(),
                span: Some(value.span()),
                help: None,
                inner: vec![],
            }
        }
        // correct return: label, no span
        None => {
            return ShellError::GenericError {
                error: msg,
                msg: text,
                span: throw_span,
                help,
                inner: vec![],
            }
        }
    };

    let span_start = match get_span_sides(span, span_span, "start") {
        Ok(val) => val,
        Err(err) => return err,
    };
    let span_end = match get_span_sides(span, span_span, "end") {
        Ok(val) => val,
        Err(err) => return err,
    };

    if span_start > span_end {
        return ShellError::GenericError {
            error: "invalid error format.".into(),
            msg: "`$.label.start` should be smaller than `$.label.end`".into(),
            span: Some(label_span),
            help: Some(format!("{} > {}", span_start, span_end)),
            inner: vec![],
        };
    }

    // correct return: everything present
    let mut error =
        LabeledError::new(msg).with_label(text, Span::new(span_start as usize, span_end as usize));
    error.help = help;
    error.into()
}

fn get_span_sides(span: &Record, span_span: Span, side: &str) -> Result<i64, ShellError> {
    match span.get(side) {
        Some(Value::Int { val, .. }) => Ok(*val),
        Some(_) => Err(ShellError::GenericError {
            error: UNABLE_TO_PARSE.into(),
            msg: format!("`$.span.{side}` must be int"),
            span: Some(span_span),
            help: None,
            inner: vec![],
        }),
        None => Err(ShellError::GenericError {
            error: UNABLE_TO_PARSE.into(),
            msg: format!("`$.span.{side}` must be present, if span is specified."),
            span: Some(span_span),
            help: None,
            inner: vec![],
        }),
    }
}