1#![allow(unused_assignments)]
2use crate::{Span, Type, ast::RedirectionSource, did_you_mean};
3use miette::Diagnostic;
4use serde::{Deserialize, Serialize};
5use std::{
6 borrow::Cow,
7 fmt::Display,
8 str::{Utf8Error, from_utf8},
9};
10use thiserror::Error;
11
12#[derive(Clone, Debug, Error, Diagnostic, Serialize, Deserialize, PartialEq)]
13pub enum ParseError {
14 #[error("Extra tokens in code.")]
18 #[diagnostic(
19 code(nu::parser::extra_tokens),
20 help(
21 "Remove the unexpected tokens, or check for a missing operator, delimiter, or newline above."
22 )
23 )]
24 ExtraTokens(#[label = "extra tokens"] Span),
25
26 #[error("Invalid characters after closing delimiter")]
27 #[diagnostic(
28 code(nu::parser::extra_token_after_closing_delimiter),
29 help("Remove these characters, or check that a delimiter closed too early above.")
30 )]
31 ExtraTokensAfterClosingDelimiter(#[label = "invalid characters"] Span),
32
33 #[error("Extra positional argument.")]
34 #[diagnostic(code(nu::parser::extra_positional), help("Usage: {0}"))]
35 ExtraPositional(String, #[label = "extra positional argument"] Span),
36
37 #[error("Required positional parameter after optional parameter")]
38 #[diagnostic(code(nu::parser::required_after_optional))]
39 RequiredAfterOptional(
40 String,
41 #[label = "required parameter {0} after optional parameter"] Span,
42 ),
43
44 #[error("Positional parameter after the rest parameter.")]
47 #[diagnostic(
48 code(nu::parser::positional_after_rest),
49 help(
50 "The rest parameter takes all remaining positional arguments, so it must be the last positional parameter. Flags can still follow it."
51 )
52 )]
53 PositionalAfterRest(
54 String,
55 #[label = "parameter {0} after the rest parameter"] Span,
56 ),
57
58 #[error("Duplicate parameter or flag.")]
64 #[diagnostic(
65 code(nu::parser::duplicate_parameter),
66 help(
67 "Each parameter and flag needs its own name, and each short flag its own letter. A long flag's variable replaces `-` with `_`, so `--foo-bar` and `foo_bar` clash."
68 )
69 )]
70 DuplicateParameter(
71 String,
72 #[label(primary, "`{0}` uses a name that is already taken")] Span,
73 #[label("first used here")] Span,
74 ),
75
76 #[error("Unexpected end of code.")]
77 #[diagnostic(code(nu::parser::unexpected_eof))]
78 UnexpectedEof(String, #[label("expected closing {0}")] Span),
79
80 #[error("Unclosed delimiter.")]
90 #[diagnostic(code(nu::parser::unclosed_delimiter), help("{3}"))]
91 Unclosed(
92 Cow<'static, str>,
93 #[label("unclosed — opens here (need `{0}`)")] Span,
94 #[label(primary, "expected `{0}` here")] Span,
95 String,
96 ),
97
98 #[error("Unbalanced delimiter.")]
104 #[diagnostic(code(nu::parser::unbalanced_delimiter), help("{3}"))]
105 Unbalanced(
106 &'static str,
107 &'static str,
108 #[label("unexpected `{1}` (unbalanced with `{0}`)")] Span,
109 String,
110 ),
111
112 #[error("Parse mismatch: expected {0}.")]
113 #[diagnostic(
114 code(nu::parser::parse_mismatch),
115 help(
116 "Check the syntax around this position — a typo, missing delimiter, or wrong separator is common."
117 )
118 )]
119 Expected(&'static str, #[label("expected {0}")] Span),
120
121 #[error("Parse mismatch: expected {0}.")]
122 #[diagnostic(
123 code(nu::parser::parse_mismatch_with_full_string_msg),
124 help(
125 "Check the syntax around this position — a typo, missing delimiter, or wrong separator is common."
126 )
127 )]
128 ExpectedWithStringMsg(String, #[label("expected {0}")] Span),
129
130 #[error("Parse mismatch: expected {0}.")]
131 #[diagnostic(
132 code(nu::parser::parse_mismatch_with_did_you_mean),
133 help(
134 "Check the syntax around this position — a typo, missing delimiter, or wrong separator is common."
135 )
136 )]
137 ExpectedWithDidYouMean(&'static str, DidYouMean, #[label("expected {0}. {1}")] Span),
138
139 #[error("Command does not support {0} input.")]
140 #[diagnostic(code(nu::parser::input_type_mismatch))]
141 InputMismatch(String, #[label("command doesn't support {0} input")] Span),
142
143 #[error("Command output doesn't match {0}.")]
144 #[diagnostic(code(nu::parser::output_type_mismatch))]
145 OutputMismatch(
146 Type,
147 String,
148 #[label("expected {0}, but command outputs {1}")] Span,
149 ),
150
151 #[error("Type mismatch during operation.")]
152 #[diagnostic(code(nu::parser::type_mismatch))]
153 Mismatch(String, String, #[label("expected {0}, found {1}")] Span), #[error("The '&&' operator is not supported in Nushell")]
156 #[diagnostic(
157 code(nu::parser::shell_andand),
158 help("use ';' instead of the shell '&&', or 'and' instead of the boolean '&&'")
159 )]
160 ShellAndAnd(#[label("instead of '&&', use ';' or 'and'")] Span),
161
162 #[error("The '||' operator is not supported in Nushell")]
163 #[diagnostic(
164 code(nu::parser::shell_oror),
165 help("use 'try' instead of the shell '||', or 'or' instead of the boolean '||'")
166 )]
167 ShellOrOr(#[label("instead of '||', use 'try' or 'or'")] Span),
168
169 #[error("The '2>' shell operation is 'err>' in Nushell.")]
170 #[diagnostic(code(nu::parser::shell_err))]
171 ShellErrRedirect(#[label("use 'err>' instead of '2>' in Nushell")] Span),
172
173 #[error("The '2>&1' shell operation is 'out+err>' in Nushell.")]
174 #[diagnostic(
175 code(nu::parser::shell_outerr),
176 help("Nushell redirection will write all of stdout before stderr.")
177 )]
178 ShellOutErrRedirect(#[label("use 'out+err>' instead of '2>&1' in Nushell")] Span),
179
180 #[error("Multiple redirections provided for {0}.")]
181 #[diagnostic(code(nu::parser::multiple_redirections))]
182 MultipleRedirections(
183 RedirectionSource,
184 #[label = "first redirection"] Span,
185 #[label = "second redirection"] Span,
186 ),
187
188 #[error("Unexpected redirection.")]
189 #[diagnostic(code(nu::parser::unexpected_redirection))]
190 UnexpectedRedirection {
191 #[label = "redirecting nothing"]
192 span: Span,
193 },
194
195 #[error("The '{op}' operator does not work on values of type '{unsupported}'.")]
197 #[diagnostic(code(nu::parser::operator_unsupported_type))]
198 OperatorUnsupportedType {
199 op: &'static str,
200 unsupported: Type,
201 #[label = "does not support '{unsupported}'"]
202 op_span: Span,
203 #[label("{unsupported}")]
204 unsupported_span: Span,
205 #[help]
206 help: Option<&'static str>,
207 },
208
209 #[error("Types '{lhs}' and '{rhs}' are not compatible for the '{op}' operator.")]
211 #[diagnostic(code(nu::parser::operator_incompatible_types))]
212 OperatorIncompatibleTypes {
213 op: &'static str,
214 lhs: Type,
215 rhs: Type,
216 #[label = "does not operate between '{lhs}' and '{rhs}'"]
217 op_span: Span,
218 #[label("{lhs}")]
219 lhs_span: Span,
220 #[label("{rhs}")]
221 rhs_span: Span,
222 #[help]
223 help: Option<&'static str>,
224 },
225
226 #[error("Capture of mutable variable.")]
227 #[diagnostic(code(nu::parser::expected_keyword))]
228 CaptureOfMutableVar(#[label("capture of mutable variable")] Span),
229
230 #[error("Record field or table column used twice: {0}")]
233 #[diagnostic(code(nu::parser::column_defined_twice))]
234 ColumnDefinedTwice(
235 String,
236 #[label(primary, "field redefined here")] Span,
237 #[label("field first defined here")] Span,
238 ),
239
240 #[error("Expected keyword.")]
241 #[diagnostic(code(nu::parser::expected_keyword))]
242 ExpectedKeyword(String, #[label("expected {0}")] Span),
243
244 #[error("Unexpected keyword.")]
245 #[diagnostic(
246 code(nu::parser::unexpected_keyword),
247 help("'{0}' keyword is allowed only in a module.")
248 )]
249 UnexpectedKeyword(String, #[label("unexpected {0}")] Span),
250
251 #[error("Module `{0}` has a `main` command but `{0}` is a built-in parser keyword.")]
252 #[diagnostic(
253 code(nu::parser::keyword_shadow_module_main),
254 help(
255 "The `main` command cannot be invoked because `{0}` is intercepted by the parser. Either rename the module file, or remove `export def main` and use `use {0}.nu *` to import other commands."
256 )
257 )]
258 KeywordShadowModuleMain(String, #[label("`{0}` is a parser keyword")] Span),
259
260 #[error("Can't create alias to parser keyword.")]
261 #[diagnostic(
262 code(nu::parser::cant_alias_keyword),
263 help("Only the following keywords can be aliased: {0}.")
264 )]
265 CantAliasKeyword(String, #[label("not supported in alias")] Span),
266
267 #[error("Can't create alias to expression.")]
268 #[diagnostic(
269 code(nu::parser::cant_alias_expression),
270 help("Only command calls can be aliased.")
271 )]
272 CantAliasExpression(String, #[label("aliasing {0} is not supported")] Span),
273
274 #[error("Unknown operator")]
275 #[diagnostic(code(nu::parser::unknown_operator), help("{1}"))]
276 UnknownOperator(
277 &'static str,
278 &'static str,
279 #[label("Operator '{0}' not supported")] Span,
280 ),
281
282 #[error("Statement used in pipeline.")]
283 #[diagnostic(
284 code(nu::parser::unexpected_keyword),
285 help(
286 "'{0}' keyword is not allowed in pipeline. Use '{0}' by itself, outside of a pipeline."
287 )
288 )]
289 BuiltinCommandInPipeline(String, #[label("not allowed in pipeline")] Span),
290
291 #[error("{0} statement used in pipeline.")]
292 #[diagnostic(
293 code(nu::parser::unexpected_keyword),
294 help(
295 "Assigning '{1}' to '{2}' does not produce a value to be piped. If the pipeline result is meant to be assigned to '{2}', use '{0} {2} = ({1} | ...)'."
296 )
297 )]
298 AssignInPipeline(String, String, String, #[label("'{0}' in pipeline")] Span),
299
300 #[error("`{0}` used as variable name.")]
301 #[diagnostic(
302 code(nu::parser::name_is_builtin_var),
303 help(
304 "'{0}' is the name of a builtin Nushell variable and cannot be used as a variable name"
305 )
306 )]
307 NameIsBuiltinVar(String, #[label("already a builtin variable")] Span),
308
309 #[error("Can't use parser keyword `{0}` as {1} name.")]
310 #[diagnostic(
311 code(nu::parser::name_is_keyword),
312 help(
313 "Parser keywords cannot be shadowed (including via module exports and `use *`). Choose a different {1} name so language constructs keep working."
314 )
315 )]
316 NameIsKeyword(String, String, #[label("'{0}' is a parser keyword")] Span),
317
318 #[error("Incorrect value")]
319 #[diagnostic(code(nu::parser::incorrect_value), help("{2}"))]
320 IncorrectValue(String, #[label("unexpected {0}")] Span, String),
321
322 #[error("Invalid binary string.")]
323 #[diagnostic(code(nu::parser::invalid_binary_string), help("{1}"))]
324 InvalidBinaryString(#[label("invalid binary string")] Span, String),
325
326 #[error("Multiple rest params.")]
327 #[diagnostic(code(nu::parser::multiple_rest_params))]
328 MultipleRestParams(#[label = "multiple rest params"] Span),
329
330 #[error("Variable not found.")]
331 #[diagnostic(code(nu::parser::variable_not_found))]
332 VariableNotFound(DidYouMean, #[label = "variable not found. {0}"] Span),
333
334 #[error("Use $env.{0} instead of ${0}.")]
335 #[diagnostic(code(nu::parser::env_var_not_var))]
336 EnvVarNotVar(String, #[label = "use $env.{0} instead of ${0}"] Span),
337
338 #[error("Variable name not supported.")]
339 #[diagnostic(code(nu::parser::variable_not_valid))]
340 VariableNotValid(#[label = "variable name can't contain spaces or quotes"] Span),
341
342 #[error("Alias name not supported.")]
343 #[diagnostic(code(nu::parser::variable_not_valid))]
344 AliasNotValid(
345 #[label = "alias name must not be a number, a filesize, a duration, a datetime, a binary literal or a range, contain #, ^, or %, or use whitespace other than single spaces between words"]
346 Span,
347 ),
348
349 #[error("Command name not supported.")]
350 #[diagnostic(code(nu::parser::variable_not_valid))]
351 CommandDefNotValid(
352 #[label = "command name can't be a number, a filesize, a duration, a datetime, a binary literal or a range, contain #, ^, or %, or have whitespace other than single spaces between words"]
353 Span,
354 ),
355
356 #[error("Module not found.")]
357 #[diagnostic(
358 code(nu::parser::module_not_found),
359 help(
360 "module files and their paths must be available before your script is run as parsing occurs before anything is evaluated"
361 )
362 )]
363 ModuleNotFound(#[label = "module {1} not found"] Span, String),
364
365 #[error("Missing mod.nu file.")]
366 #[diagnostic(
367 code(nu::parser::module_missing_mod_nu_file),
368 help(
369 "Directory {0} is missing a mod.nu file.\n\nWhen importing a directory as a Nushell module, it needs to contain a mod.nu file (can be empty). Alternatively, you can use .nu files in the directory as modules individually."
370 )
371 )]
372 ModuleMissingModNuFile(
373 String,
374 #[label = "module directory is missing a mod.nu file"] Span,
375 ),
376
377 #[error("Circular import.")]
378 #[diagnostic(code(nu::parser::circular_import), help("{0}"))]
379 CircularImport(String, #[label = "detected circular import"] Span),
380
381 #[error("Can't export {0} named same as the module.")]
382 #[diagnostic(
383 code(nu::parser::named_as_module),
384 help(
385 "Module {1} can't export {0} named the same as the module. Either change the module name, or export `{2}` {0}."
386 )
387 )]
388 NamedAsModule(
389 String,
390 String,
391 String,
392 #[label = "can't export from module {1}"] Span,
393 ),
394
395 #[error("Module already contains 'main' command.")]
396 #[diagnostic(
397 code(nu::parser::module_double_main),
398 help("Tried to add 'main' command to module '{0}' but it has already been added.")
399 )]
400 ModuleDoubleMain(
401 String,
402 #[label = "module '{0}' already contains 'main'"] Span,
403 ),
404
405 #[error("Can't export alias defined as 'main'.")]
406 #[diagnostic(
407 code(nu::parser::export_main_alias_not_allowed),
408 help(
409 "Exporting aliases as 'main' is not allowed. Either rename the alias or convert it to a custom command."
410 )
411 )]
412 ExportMainAliasNotAllowed(#[label = "can't export from module"] Span),
413
414 #[error("Active overlay not found.")]
415 #[diagnostic(code(nu::parser::active_overlay_not_found))]
416 ActiveOverlayNotFound(#[label = "not an active overlay"] Span),
417
418 #[error("Overlay prefix mismatch.")]
419 #[diagnostic(
420 code(nu::parser::overlay_prefix_mismatch),
421 help(
422 "Overlay {0} already exists {1} a prefix. To add it again, do it {1} the --prefix flag."
423 )
424 )]
425 OverlayPrefixMismatch(
426 String,
427 String,
428 #[label = "already exists {1} a prefix"] Span,
429 ),
430
431 #[error("Module or overlay not found.")]
432 #[diagnostic(
433 code(nu::parser::module_or_overlay_not_found),
434 help(
435 "Requires either an existing overlay, a module, or an import pattern defining a module."
436 )
437 )]
438 ModuleOrOverlayNotFound(#[label = "not a module or an overlay"] Span),
439
440 #[error("Cannot remove the last overlay.")]
441 #[diagnostic(
442 code(nu::parser::cant_remove_last_overlay),
443 help("At least one overlay must always be active.")
444 )]
445 CantRemoveLastOverlay(#[label = "this is the last overlay, can't remove it"] Span),
446
447 #[error("Cannot hide default overlay.")]
448 #[diagnostic(
449 code(nu::parser::cant_hide_default_overlay),
450 help("'{0}' is a default overlay. Default overlays cannot be hidden.")
451 )]
452 CantHideDefaultOverlay(String, #[label = "can't hide overlay"] Span),
453
454 #[error("Cannot add overlay.")]
455 #[diagnostic(code(nu::parser::cant_add_overlay_help), help("{0}"))]
456 CantAddOverlayHelp(String, #[label = "cannot add this overlay"] Span),
457
458 #[error("Duplicate command definition within a block.")]
459 #[diagnostic(code(nu::parser::duplicate_command_def))]
460 DuplicateCommandDef(#[label = "defined more than once"] Span),
461
462 #[error("Unknown command.")]
463 #[diagnostic(
464 code(nu::parser::unknown_command),
465 )]
467 UnknownCommand(#[label = "unknown command"] Span),
468
469 #[error("Non-UTF8 string.")]
470 #[diagnostic(code(nu::parser::non_utf8))]
471 NonUtf8(#[label = "non-UTF8 string"] Span),
472
473 #[error("The `{0}` command doesn't have flag `{1}`.")]
474 #[diagnostic(code(nu::parser::unknown_flag), help("{3}"))]
475 UnknownFlag(String, String, #[label = "unknown flag"] Span, String),
476
477 #[error("Unknown type.")]
478 #[diagnostic(
479 code(nu::parser::unknown_type),
480 help(
481 "check the spelling; a type alias must be defined with `type Name = <type>` above this line, or imported with `use <module> Name`"
482 )
483 )]
484 UnknownType(#[label = "unknown type"] Span),
485
486 #[error("Type alias `{0}` is used before its definition.")]
493 #[diagnostic(
494 code(nu::parser::type_alias_used_before_definition),
495 help("move the `type` statement above its first use")
496 )]
497 TypeAliasUsedBeforeDefinition(
498 String,
499 #[label(primary, "used here")] Span,
500 #[label("defined here")] Span,
501 ),
502
503 #[error("Type alias `{0}` refers to itself.")]
505 #[diagnostic(
506 code(nu::parser::type_alias_self_reference),
507 help("type aliases can't be recursive")
508 )]
509 TypeAliasSelfReference(String, #[label("refers to itself")] Span),
510
511 #[error("`{0}` is a built-in type.")]
514 #[diagnostic(
515 code(nu::parser::type_alias_shadows_builtin),
516 help("choose a name that isn't a built-in type")
517 )]
518 TypeAliasShadowsBuiltin(String, #[label("built-in type")] Span),
519
520 #[error("Type alias name not valid.")]
521 #[diagnostic(code(nu::parser::type_alias_name_not_valid))]
522 TypeAliasNameNotValid(
523 #[label = "a type alias name starts with a letter or `_` and continues with letters, digits, `_` and `-`"]
524 Span,
525 ),
526
527 #[error("Type alias `{0}` takes no type parameters.")]
528 #[diagnostic(code(nu::parser::type_alias_with_params))]
529 TypeAliasWithParams(String, #[label("unexpected type parameters")] Span),
530
531 #[error("Missing `=` in type alias.")]
538 #[diagnostic(code(nu::parser::type_alias_missing_equals), help("{help}"))]
539 TypeAliasMissingEquals {
540 help: String,
541 #[label("expected `=` and a type after this name")]
542 span: Span,
543 },
544
545 #[error("Missing flag argument.")]
546 #[diagnostic(code(nu::parser::missing_flag_param))]
547 MissingFlagParam(String, #[label = "flag missing {0} argument"] Span),
548
549 #[error("Only the last flag in a short flag batch can take an argument.")]
550 #[diagnostic(code(nu::parser::only_last_flag_in_batch_can_take_arg))]
551 OnlyLastFlagInBatchCanTakeArg(#[label = "only the last flag can take args"] Span),
552
553 #[error("Missing required positional argument.")]
554 #[diagnostic(
555 code(nu::parser::missing_positional),
556 help("Usage: {2}. Use `--help` for more information.")
557 )]
558 MissingPositional(String, #[label("missing {0}")] Span, String),
559
560 #[error("Missing argument to `{1}`.")]
561 #[diagnostic(code(nu::parser::keyword_missing_arg))]
562 KeywordMissingArgument(
563 String,
564 String,
565 #[label("missing {0} value that follows {1}")] Span,
566 ),
567
568 #[error("Missing type.")]
569 #[diagnostic(code(nu::parser::missing_type))]
570 MissingType(#[label = "expected type"] Span),
571
572 #[error("Type mismatch.")]
573 #[diagnostic(code(nu::parser::type_mismatch))]
574 TypeMismatch(Type, Type, #[label("expected {0}, found {1}")] Span), #[error("Type mismatch.")]
577 #[diagnostic(code(nu::parser::type_mismatch_help), help("{3}"))]
578 TypeMismatchHelp(Type, Type, #[label("expected {0}, found {1}")] Span, String), #[error("Missing required flag.")]
581 #[diagnostic(code(nu::parser::missing_required_flag))]
582 MissingRequiredFlag(String, #[label("missing required flag {0}")] Span),
583
584 #[error("Incomplete math expression.")]
585 #[diagnostic(code(nu::parser::incomplete_math_expression))]
586 IncompleteMathExpression(#[label = "incomplete math expression"] Span),
587
588 #[error("Unknown state.")]
589 #[diagnostic(code(nu::parser::unknown_state))]
590 UnknownState(String, #[label("{0}")] Span),
591
592 #[error("Internal error.")]
593 #[diagnostic(code(nu::parser::unknown_state))]
594 InternalError(String, #[label("{0}")] Span),
595
596 #[error("Parser incomplete.")]
597 #[diagnostic(code(nu::parser::parser_incomplete))]
598 IncompleteParser(#[label = "parser support missing for this expression"] Span),
599
600 #[error("Rest parameter needs a name.")]
601 #[diagnostic(code(nu::parser::rest_needs_name))]
602 RestNeedsName(#[label = "needs a parameter name"] Span),
603
604 #[error("Parameter not correct type.")]
605 #[diagnostic(code(nu::parser::parameter_mismatch_type))]
606 ParameterMismatchType(
607 String,
608 String,
609 String,
610 #[label = "parameter {0} needs to be '{1}' instead of '{2}'"] Span,
611 ),
612
613 #[error("Default values should be constant expressions.")]
614 #[diagnostic(code(nu::parser::non_constant_default_value))]
615 NonConstantDefaultValue(#[label = "expected a constant value"] Span),
616
617 #[error("Extra columns.")]
618 #[diagnostic(code(nu::parser::extra_columns))]
619 ExtraColumns(
620 usize,
621 #[label("expected {0} column{}", if *.0 == 1 { "" } else { "s" })] Span,
622 ),
623
624 #[error("Missing columns.")]
625 #[diagnostic(code(nu::parser::missing_columns))]
626 MissingColumns(
627 usize,
628 #[label("expected {0} column{}", if *.0 == 1 { "" } else { "s" })] Span,
629 ),
630
631 #[error("{0}")]
632 #[diagnostic(code(nu::parser::assignment_mismatch))]
633 AssignmentMismatch(String, String, #[label("{1}")] Span),
634
635 #[error("Wrong import pattern structure.")]
636 #[diagnostic(code(nu::parser::wrong_import_pattern))]
637 WrongImportPattern(String, #[label = "{0}"] Span),
638
639 #[error("Export not found.")]
640 #[diagnostic(code(nu::parser::export_not_found))]
641 ExportNotFound(#[label = "could not find imports"] Span),
642
643 #[error("File not found")]
644 #[diagnostic(
645 code(nu::parser::sourced_file_not_found),
646 help("sourced files need to be available before your script is run")
647 )]
648 SourcedFileNotFound(String, #[label("File not found: {0}")] Span),
649
650 #[error("Script file is too large to load with `run`")]
651 #[diagnostic(
652 code(nu::parser::script_file_too_large),
653 help(
654 "The `run` command refuses files larger than {max_size} bytes at parse time (file is {size} bytes). Use a smaller script, or invoke large scripts with `nu path/to/script.nu`."
655 )
656 )]
657 ScriptFileTooLarge {
658 path: String,
659 size: u64,
660 max_size: u64,
661 #[label("file too large for `run`: {path}")]
662 span: Span,
663 },
664
665 #[error("Script file does not appear to be text")]
666 #[diagnostic(
667 code(nu::parser::script_file_not_text),
668 help(
669 "The `run` command only loads UTF-8 text scripts. Binary data (NUL bytes, invalid UTF-8, or dense control characters) is rejected."
670 )
671 )]
672 ScriptFileNotText {
673 path: String,
674 #[label("not a text script for `run`: {path}")]
675 span: Span,
676 },
677
678 #[error("File not found")]
679 #[diagnostic(
680 code(nu::parser::registered_file_not_found),
681 help("registered files need to be available before your script is run")
682 )]
683 RegisteredFileNotFound(String, #[label("File not found: {0}")] Span),
684
685 #[error("File not found")]
686 #[diagnostic(code(nu::parser::file_not_found))]
687 FileNotFound(String, #[label("File not found: {0}")] Span),
688
689 #[error("Plugin not found")]
690 #[diagnostic(
691 code(nu::parser::plugin_not_found),
692 help(
693 "plugins need to be added to the plugin registry file before your script is run (see `plugin add`)"
694 )
695 )]
696 PluginNotFound {
697 name: String,
698 #[label("Plugin not found: {name}")]
699 name_span: Span,
700 #[label("in this registry file")]
701 plugin_config_span: Option<Span>,
702 },
703
704 #[error("Invalid literal")] #[diagnostic()]
706 InvalidLiteral(String, String, #[label("{0} in {1}")] Span),
707
708 #[error("Invalid literal")]
712 #[diagnostic(code(nu::parser::literal_too_large))]
713 LiteralTooLarge(String, #[label("{0} too large")] Span),
714
715 #[error("{0}")]
716 #[diagnostic()]
717 LabeledError(String, String, #[label("{1}")] Span),
718
719 #[error("{error}")]
720 #[diagnostic(help("{help}"))]
721 LabeledErrorWithHelp {
722 error: String,
723 label: String,
724 help: String,
725 #[label("{label}")]
726 span: Span,
727 },
728
729 #[error("Redirection can not be used with {0}.")]
730 #[diagnostic()]
731 RedirectingBuiltinCommand(
732 &'static str,
733 #[label("not allowed here")] Span,
734 #[label("...and here")] Option<Span>,
735 ),
736
737 #[error("This command does not have a ...rest parameter")]
738 #[diagnostic(
739 code(nu::parser::unexpected_spread_arg),
740 help(
741 "To spread arguments, the command needs to define a multi-positional parameter in its signature, such as ...rest"
742 )
743 )]
744 UnexpectedSpreadArg(String, #[label = "unexpected spread argument"] Span),
745
746 #[error("Assignment to an immutable variable.")]
752 #[diagnostic(
753 code(nu::parser::assignment_requires_mutable_variable),
754 help("declare the variable with `mut`, or shadow it again with `let`")
755 )]
756 AssignmentRequiresMutableVar(#[label("needs to be a mutable variable")] Span),
757
758 #[error("Assignment operations require a variable.")]
764 #[diagnostic(
765 code(nu::parser::assignment_requires_variable),
766 help("try assigning to a variable or a cell path of a variable")
767 )]
768 AssignmentRequiresVar(#[label("needs to be a variable")] Span),
769
770 #[error("Attributes must be followed by a definition.")]
771 #[diagnostic(
772 code(nu::parser::attribute_requires_definition),
773 help("try following this line with a `def` or `extern` definition")
774 )]
775 AttributeRequiresDefinition(#[label("must be followed by a definition")] Span),
776}
777
778impl ParseError {
779 pub fn opener_span(span: Span, len: usize) -> Span {
783 Span::new(span.start, span.start.saturating_add(len).min(span.end))
784 }
785
786 pub fn unclosed(
788 delimiter: impl Into<Cow<'static, str>>,
789 open_span: Span,
790 end_span: Span,
791 ) -> Self {
792 Self::unclosed_with_hint(delimiter, open_span, end_span, None)
793 }
794
795 pub fn unclosed_with_hint(
798 delimiter: impl Into<Cow<'static, str>>,
799 open_span: Span,
800 end_span: Span,
801 structure_hint: Option<&str>,
802 ) -> Self {
803 let delimiter = delimiter.into();
804 let help = default_unclosed_help(&delimiter, structure_hint);
805 Self::Unclosed(delimiter, open_span, end_span, help)
806 }
807
808 pub fn unbalanced(open: &'static str, close: &'static str, close_span: Span) -> Self {
810 Self::Unbalanced(
811 open,
812 close,
813 close_span,
814 default_unbalanced_help(open, close),
815 )
816 }
817
818 pub fn span(&self) -> Span {
819 match self {
820 ParseError::ExtraTokens(s) => *s,
821 ParseError::ExtraPositional(_, s) => *s,
822 ParseError::UnexpectedEof(_, s) => *s,
823 ParseError::Unclosed(_, _open, end, _) => *end,
825 ParseError::Unbalanced(_, _, close, _) => *close,
826 ParseError::Expected(_, s) => *s,
827 ParseError::ExpectedWithStringMsg(_, s) => *s,
828 ParseError::ExpectedWithDidYouMean(_, _, s) => *s,
829 ParseError::Mismatch(_, _, s) => *s,
830 ParseError::OperatorUnsupportedType { op_span, .. } => *op_span,
831 ParseError::OperatorIncompatibleTypes { op_span, .. } => *op_span,
832 ParseError::ExpectedKeyword(_, s) => *s,
833 ParseError::UnexpectedKeyword(_, s) => *s,
834 ParseError::CantAliasKeyword(_, s) => *s,
835 ParseError::CantAliasExpression(_, s) => *s,
836 ParseError::BuiltinCommandInPipeline(_, s) => *s,
837 ParseError::AssignInPipeline(_, _, _, s) => *s,
838 ParseError::NameIsBuiltinVar(_, s) => *s,
839 ParseError::NameIsKeyword(_, _, s) => *s,
840 ParseError::CaptureOfMutableVar(s) => *s,
841 ParseError::ColumnDefinedTwice(_, s, _) => *s,
842 ParseError::IncorrectValue(_, s, _) => *s,
843 ParseError::InvalidBinaryString(s, _) => *s,
844 ParseError::MultipleRestParams(s) => *s,
845 ParseError::VariableNotFound(_, s) => *s,
846 ParseError::EnvVarNotVar(_, s) => *s,
847 ParseError::VariableNotValid(s) => *s,
848 ParseError::AliasNotValid(s) => *s,
849 ParseError::CommandDefNotValid(s) => *s,
850 ParseError::ModuleNotFound(s, _) => *s,
851 ParseError::ModuleMissingModNuFile(_, s) => *s,
852 ParseError::NamedAsModule(_, _, _, s) => *s,
853 ParseError::ModuleDoubleMain(_, s) => *s,
854 ParseError::ExportMainAliasNotAllowed(s) => *s,
855 ParseError::CircularImport(_, s) => *s,
856 ParseError::ModuleOrOverlayNotFound(s) => *s,
857 ParseError::ActiveOverlayNotFound(s) => *s,
858 ParseError::OverlayPrefixMismatch(_, _, s) => *s,
859 ParseError::CantRemoveLastOverlay(s) => *s,
860 ParseError::CantHideDefaultOverlay(_, s) => *s,
861 ParseError::CantAddOverlayHelp(_, s) => *s,
862 ParseError::DuplicateCommandDef(s) => *s,
863 ParseError::UnknownCommand(s) => *s,
864 ParseError::NonUtf8(s) => *s,
865 ParseError::UnknownFlag(_, _, s, _) => *s,
866 ParseError::RequiredAfterOptional(_, s) => *s,
867 ParseError::PositionalAfterRest(_, s) => *s,
868 ParseError::DuplicateParameter(_, s, _) => *s,
869 ParseError::UnknownType(s) => *s,
870 ParseError::TypeAliasUsedBeforeDefinition(_, s, _) => *s,
871 ParseError::TypeAliasSelfReference(_, s) => *s,
872 ParseError::TypeAliasShadowsBuiltin(_, s) => *s,
873 ParseError::TypeAliasNameNotValid(s) => *s,
874 ParseError::TypeAliasWithParams(_, s) => *s,
875 ParseError::TypeAliasMissingEquals { span: s, .. } => *s,
876 ParseError::MissingFlagParam(_, s) => *s,
877 ParseError::OnlyLastFlagInBatchCanTakeArg(s) => *s,
878 ParseError::MissingPositional(_, s, _) => *s,
879 ParseError::KeywordMissingArgument(_, _, s) => *s,
880 ParseError::MissingType(s) => *s,
881 ParseError::TypeMismatch(_, _, s) => *s,
882 ParseError::TypeMismatchHelp(_, _, s, _) => *s,
883 ParseError::InputMismatch(_, s) => *s,
884 ParseError::OutputMismatch(_, _, s) => *s,
885 ParseError::MissingRequiredFlag(_, s) => *s,
886 ParseError::IncompleteMathExpression(s) => *s,
887 ParseError::UnknownState(_, s) => *s,
888 ParseError::InternalError(_, s) => *s,
889 ParseError::IncompleteParser(s) => *s,
890 ParseError::RestNeedsName(s) => *s,
891 ParseError::ParameterMismatchType(_, _, _, s) => *s,
892 ParseError::NonConstantDefaultValue(s) => *s,
893 ParseError::ExtraColumns(_, s) => *s,
894 ParseError::MissingColumns(_, s) => *s,
895 ParseError::AssignmentMismatch(_, _, s) => *s,
896 ParseError::WrongImportPattern(_, s) => *s,
897 ParseError::ExportNotFound(s) => *s,
898 ParseError::SourcedFileNotFound(_, s) => *s,
899 ParseError::ScriptFileTooLarge { span, .. } => *span,
900 ParseError::ScriptFileNotText { span, .. } => *span,
901 ParseError::RegisteredFileNotFound(_, s) => *s,
902 ParseError::FileNotFound(_, s) => *s,
903 ParseError::PluginNotFound { name_span, .. } => *name_span,
904 ParseError::LabeledError(_, _, s) => *s,
905 ParseError::ShellAndAnd(s) => *s,
906 ParseError::ShellOrOr(s) => *s,
907 ParseError::ShellErrRedirect(s) => *s,
908 ParseError::ShellOutErrRedirect(s) => *s,
909 ParseError::MultipleRedirections(_, _, s) => *s,
910 ParseError::UnexpectedRedirection { span } => *span,
911 ParseError::UnknownOperator(_, _, s) => *s,
912 ParseError::InvalidLiteral(_, _, s) => *s,
913 ParseError::LiteralTooLarge(_, s) => *s,
914 ParseError::LabeledErrorWithHelp { span: s, .. } => *s,
915 ParseError::RedirectingBuiltinCommand(_, s, _) => *s,
916 ParseError::UnexpectedSpreadArg(_, s) => *s,
917 ParseError::ExtraTokensAfterClosingDelimiter(s) => *s,
918 ParseError::AssignmentRequiresVar(s) => *s,
919 ParseError::AssignmentRequiresMutableVar(s) => *s,
920 ParseError::AttributeRequiresDefinition(s) => *s,
921 ParseError::KeywordShadowModuleMain(_, s) => *s,
922 }
923 }
924}
925
926fn default_unclosed_help(delimiter: &str, structure_hint: Option<&str>) -> String {
927 match structure_hint {
928 Some(hint) if !hint.is_empty() => format!(
929 "Add a matching `{delimiter}` to close {hint}, or check that an earlier closer closed the wrong block."
930 ),
931 _ => format!(
932 "Add a matching `{delimiter}` to close this delimiter, or check that an earlier closer closed the wrong block."
933 ),
934 }
935}
936
937fn default_unbalanced_help(open: &str, close: &str) -> String {
938 format!(
939 "Remove this `{close}` if it is extra, or add a matching `{open}` earlier. If you closed a block too early, the real mistake may be above."
940 )
941}
942
943#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
944pub struct DidYouMean(Option<String>);
945
946fn did_you_mean_impl(possibilities_bytes: &[&[u8]], input_bytes: &[u8]) -> Option<String> {
947 let input = from_utf8(input_bytes).ok()?;
948 let possibilities = possibilities_bytes
949 .iter()
950 .map(|p| from_utf8(p))
951 .collect::<Result<Vec<&str>, Utf8Error>>()
952 .ok()?;
953 did_you_mean(&possibilities, input)
954}
955impl DidYouMean {
956 pub fn new(possibilities_bytes: &[&[u8]], input_bytes: &[u8]) -> DidYouMean {
957 DidYouMean(did_you_mean_impl(possibilities_bytes, input_bytes))
958 }
959}
960
961impl From<Option<String>> for DidYouMean {
962 fn from(value: Option<String>) -> Self {
963 Self(value)
964 }
965}
966
967impl Display for DidYouMean {
968 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
969 if let Some(suggestion) = &self.0 {
970 write!(f, "Did you mean '{suggestion}'?")
971 } else {
972 write!(f, "")
973 }
974 }
975}