1#![allow(unused_assignments)]
2use super::chained_error::ChainedError;
3use crate::{
4 ConfigError, FromValue, LabeledError, ParseError, Span, Spanned, Type, Value,
5 ast::Operator,
6 engine::{Stack, StateWorkingSet},
7 format_cli_error, record,
8};
9use generic::GenericError;
10use job::JobError;
11use miette::{Diagnostic, LabeledSpan, NamedSource};
12use nu_utils::location::Location;
13use serde::{Deserialize, Serialize};
14use std::{error::Error as StdError, num::NonZeroI32, sync::Arc};
15use thiserror::Error;
16
17pub mod bridge;
18pub mod eval_block_with_input;
19pub mod generic;
20pub mod io;
21pub mod job;
22pub mod network;
23
24#[derive(Debug, Clone, Error, Diagnostic, PartialEq)]
28pub enum ShellError {
29 #[error("The '{op}' operator does not work on values of type '{unsupported}'.")]
31 #[diagnostic(code(nu::shell::operator_unsupported_type))]
32 OperatorUnsupportedType {
33 op: Operator,
34 unsupported: Type,
35 #[label = "does not support '{unsupported}'"]
36 op_span: Span,
37 #[label("{unsupported}")]
38 unsupported_span: Span,
39 #[help]
40 help: Option<&'static str>,
41 },
42
43 #[error("Types '{lhs}' and '{rhs}' are not compatible for the '{op}' operator.")]
45 #[diagnostic(code(nu::shell::operator_incompatible_types))]
46 OperatorIncompatibleTypes {
47 op: Operator,
48 lhs: Type,
49 rhs: Type,
50 #[label = "does not operate between '{lhs}' and '{rhs}'"]
51 op_span: Span,
52 #[label("{lhs}")]
53 lhs_span: Span,
54 #[label("{rhs}")]
55 rhs_span: Span,
56 #[help]
57 help: Option<&'static str>,
58 },
59
60 #[error("Operator overflow.")]
67 #[diagnostic(code(nu::shell::operator_overflow))]
68 OperatorOverflow {
69 msg: String,
70 #[label = "{msg}"]
71 span: Span,
72 #[help]
73 help: Option<String>,
74 },
75
76 #[error("Pipeline mismatch.")]
83 #[diagnostic(code(nu::shell::pipeline_mismatch))]
84 PipelineMismatch {
85 exp_input_type: String,
86 #[label("expected: {exp_input_type}")]
87 dst_span: Span,
88 #[label("value originates here")]
89 src_span: Span,
90 },
91
92 #[error("Input type not supported.")]
102 #[diagnostic(code(nu::shell::only_supports_this_input_type))]
103 OnlySupportsThisInputType {
104 exp_input_type: String,
105 wrong_type: String,
106 #[label("only {exp_input_type} input data is supported")]
107 dst_span: Span,
108 #[label("input type: {wrong_type}")]
109 src_span: Span,
110 },
111
112 #[error("Pipeline empty.")]
118 #[diagnostic(code(nu::shell::pipeline_mismatch))]
119 PipelineEmpty {
120 #[label("no input value was piped in")]
121 dst_span: Span,
122 },
123
124 #[error("Type mismatch.")]
131 #[diagnostic(code(nu::shell::type_mismatch))]
132 TypeMismatch {
133 err_message: String,
134 #[label = "{err_message}"]
135 span: Span,
136 },
137
138 #[error("Type mismatch")]
144 #[diagnostic(code(nu::shell::type_mismatch))]
145 RuntimeTypeMismatch {
146 expected: Type,
147 actual: Type,
148 #[label = "expected {expected}, but got {actual}"]
149 span: Span,
150 },
151
152 #[error("Invalid value")]
158 #[diagnostic(code(nu::shell::invalid_value))]
159 InvalidValue {
160 valid: String,
161 actual: String,
162 #[label = "expected {valid}, but got {actual}"]
163 span: Span,
164 },
165
166 #[error("Incorrect value.")]
172 #[diagnostic(code(nu::shell::incorrect_value))]
173 IncorrectValue {
174 msg: String,
175 #[label = "{msg}"]
176 val_span: Span,
177 #[label = "encountered here"]
178 call_span: Span,
179 },
180
181 #[error("Assignment operations require a variable.")]
187 #[diagnostic(code(nu::shell::assignment_requires_variable))]
188 AssignmentRequiresVar {
189 #[label = "needs to be a variable"]
190 lhs_span: Span,
191 },
192
193 #[error("Assignment to an immutable variable.")]
199 #[diagnostic(code(nu::shell::assignment_requires_mutable_variable))]
200 AssignmentRequiresMutableVar {
201 #[label = "needs to be a mutable variable"]
202 lhs_span: Span,
203 },
204
205 #[error("Unknown operator: {op_token}.")]
211 #[diagnostic(code(nu::shell::unknown_operator))]
212 UnknownOperator {
213 op_token: String,
214 #[label = "unknown operator"]
215 span: Span,
216 },
217
218 #[error("Missing parameter: {param_name}.")]
224 #[diagnostic(code(nu::shell::missing_parameter))]
225 MissingParameter {
226 param_name: String,
227 #[label = "missing parameter: {param_name}"]
228 span: Span,
229 },
230
231 #[error("Incompatible parameters.")]
237 #[diagnostic(code(nu::shell::incompatible_parameters))]
238 IncompatibleParameters {
239 left_message: String,
240 #[label("{left_message}")]
242 left_span: Span,
243 right_message: String,
244 #[label("{right_message}")]
245 right_span: Span,
246 },
247
248 #[error("Delimiter error")]
254 #[diagnostic(code(nu::shell::delimiter_error))]
255 DelimiterError {
256 msg: String,
257 #[label("{msg}")]
258 span: Span,
259 },
260
261 #[error("Incompatible parameters.")]
269 #[diagnostic(code(nu::shell::incompatible_parameters))]
270 IncompatibleParametersSingle {
271 msg: String,
272 #[label = "{msg}"]
273 span: Span,
274 },
275
276 #[error("Running external commands not supported")]
282 #[diagnostic(code(nu::shell::external_commands))]
283 ExternalNotSupported {
284 #[label = "external not supported"]
285 span: Span,
286 },
287
288 #[error("Invalid Probability.")]
295 #[diagnostic(code(nu::shell::invalid_probability))]
296 InvalidProbability {
297 #[label = "invalid probability: must be between 0 and 1"]
298 span: Span,
299 },
300
301 #[error("Invalid range {left_flank}..{right_flank}")]
307 #[diagnostic(code(nu::shell::invalid_range))]
308 InvalidRange {
309 left_flank: String,
310 right_flank: String,
311 #[label = "expected a valid range"]
312 span: Span,
313 },
314
315 #[error("Nushell failed: {msg}.")]
321 #[diagnostic(
322 code(nu::shell::nushell_failed),
323 help(
324 "This shouldn't happen. Please file an issue: https://github.com/nushell/nushell/issues"
325 )
326 )]
327 NushellFailed { msg: String },
329
330 #[error("Nushell failed: {msg}.")]
336 #[diagnostic(
337 code(nu::shell::nushell_failed_spanned),
338 help(
339 "This shouldn't happen. Please file an issue: https://github.com/nushell/nushell/issues"
340 )
341 )]
342 NushellFailedSpanned {
344 msg: String,
345 label: String,
346 #[label = "{label}"]
347 span: Span,
348 },
349
350 #[error("Nushell failed: {msg}.")]
356 #[diagnostic(code(nu::shell::nushell_failed_help))]
357 NushellFailedHelp {
359 msg: String,
360 #[help]
361 help: String,
362 },
363
364 #[error("Variable not found")]
370 #[diagnostic(code(nu::shell::variable_not_found))]
371 VariableNotFoundAtRuntime {
372 #[label = "variable not found"]
373 span: Span,
374 },
375
376 #[error("Environment variable '{envvar_name}' not found")]
382 #[diagnostic(code(nu::shell::env_variable_not_found))]
383 EnvVarNotFoundAtRuntime {
384 envvar_name: String,
385 #[label = "environment variable not found"]
386 span: Span,
387 },
388
389 #[error("Module '{mod_name}' not found")]
395 #[diagnostic(code(nu::shell::module_not_found))]
396 ModuleNotFoundAtRuntime {
397 mod_name: String,
398 #[label = "module not found"]
399 span: Span,
400 },
401
402 #[error("Overlay '{overlay_name}' not found")]
408 #[diagnostic(code(nu::shell::overlay_not_found))]
409 OverlayNotFoundAtRuntime {
410 overlay_name: String,
411 #[label = "overlay not found"]
412 span: Span,
413 },
414
415 #[error("Not found.")]
421 #[diagnostic(code(nu::parser::not_found))]
422 NotFound {
423 #[label = "did not find anything under this name"]
424 span: Span,
425 },
426
427 #[error("Can't convert to {to_type}.")]
433 #[diagnostic(code(nu::shell::cant_convert))]
434 CantConvert {
435 to_type: String,
436 from_type: String,
437 #[label("can't convert {from_type} to {to_type}")]
438 span: Span,
439 #[help]
440 help: Option<String>,
441 },
442
443 #[error("Can't convert {from_type} to the specified unit.")]
449 #[diagnostic(code(nu::shell::cant_convert_value_to_unit))]
450 CantConvertToUnit {
451 to_type: String,
452 from_type: String,
453 #[label("can't convert {from_type} to {to_type}")]
454 span: Span,
455 #[label("conversion originates here")]
456 unit_span: Span,
457 #[help]
458 help: Option<String>,
459 },
460
461 #[error("'{envvar_name}' is not representable as a string.")]
467 #[diagnostic(
468 code(nu::shell::env_var_not_a_string),
469 help(
470 "The '{envvar_name}' environment variable must be a string or be convertible to a string.
471 Either make sure '{envvar_name}' is a string, or add a 'to_string' entry for it in ENV_CONVERSIONS."
472 )
473 )]
474 EnvVarNotAString {
475 envvar_name: String,
476 #[label("value not representable as a string")]
477 span: Span,
478 },
479
480 #[error("'{}' cannot be changed manually.", .envvar_name.to_ascii_uppercase())]
486 #[diagnostic(
487 code(nu::shell::automatic_env_var_set_manually),
488 help(
489 "The environment variable '{}' is set automatically by Nushell and cannot be changed manually.",
490 .envvar_name.to_ascii_uppercase()
491 )
492 )]
493 AutomaticEnvVarSetManually {
494 envvar_name: String,
495 #[label("cannot change '{}' manually", .envvar_name.to_ascii_uppercase())]
496 span: Span,
497 },
498
499 #[error("'config' cannot be hidden.")]
505 #[diagnostic(
506 code(nu::shell::cannot_hide_config_env_var),
507 help("Assign a new record to `$env.config` instead of hiding it.")
508 )]
509 CannotHideConfigEnvVar {
510 #[label("cannot hide 'config'")]
511 span: Span,
512 },
513
514 #[error("Cannot replace environment.")]
521 #[diagnostic(
522 code(nu::shell::cannot_replace_env),
523 help("Assigning a value to '$env' is not allowed.")
524 )]
525 CannotReplaceEnv {
526 #[label("setting '$env' not allowed")]
527 span: Span,
528 },
529
530 #[error("Division by zero.")]
536 #[diagnostic(code(nu::shell::division_by_zero))]
537 DivisionByZero {
538 #[label("division by zero")]
539 span: Span,
540 },
541
542 #[error("Can't convert range to countable values")]
550 #[diagnostic(code(nu::shell::range_to_countable))]
551 CannotCreateRange {
552 #[label = "can't convert to countable values"]
553 span: Span,
554 },
555
556 #[error("Row number too large (max: {max_idx}).")]
562 #[diagnostic(code(nu::shell::access_beyond_end))]
563 AccessBeyondEnd {
564 max_idx: usize,
565 #[label = "index too large (max: {max_idx})"]
566 span: Span,
567 },
568
569 #[error("Inserted at wrong row number (should be {available_idx}).")]
575 #[diagnostic(code(nu::shell::access_beyond_end))]
576 InsertAfterNextFreeIndex {
577 available_idx: usize,
578 #[label = "can't insert at index (the next available index is {available_idx})"]
579 span: Span,
580 },
581
582 #[error("Cannot access empty content.")]
588 #[diagnostic(code(nu::shell::access_empty_content))]
589 AccessEmptyContent {
590 #[label = "content is empty"]
591 span: Span,
592 },
593
594 #[error("Row number too large.")]
601 #[diagnostic(code(nu::shell::access_beyond_end_of_stream))]
602 AccessBeyondEndOfStream {
603 #[label = "index too large"]
604 span: Span,
605 },
606
607 #[error("Data cannot be accessed with a cell path")]
613 #[diagnostic(code(nu::shell::incompatible_path_access))]
614 IncompatiblePathAccess {
615 type_name: String,
616 #[label("{type_name} doesn't support cell paths")]
617 span: Span,
618 },
619
620 #[error("Cannot find column '{col_name}'")]
626 #[diagnostic(
627 code(nu::shell::column_not_found),
628 help = "If some rows have this column, try using '{col_name}?' for optional access, or pre-fill using the `default` command"
629 )]
630 CantFindColumn {
631 col_name: String,
632 #[label = "column '{col_name}' is missing in one or more values"]
633 span: Option<Span>,
634 #[label = "value originates here"]
635 src_span: Span,
636 },
637
638 #[error("Column already exists")]
644 #[diagnostic(code(nu::shell::column_already_exists))]
645 ColumnAlreadyExists {
646 col_name: String,
647 #[label = "column '{col_name}' already exists"]
648 span: Span,
649 #[label = "value originates here"]
650 src_span: Span,
651 },
652
653 #[error("Not a list value")]
659 #[diagnostic(code(nu::shell::not_a_list))]
660 NotAList {
661 #[label = "value not a list"]
662 dst_span: Span,
663 #[label = "value originates here"]
664 src_span: Span,
665 },
666
667 #[error("Record field or table column used twice: {col_name}")]
675 #[diagnostic(code(nu::shell::column_defined_twice))]
676 ColumnDefinedTwice {
677 col_name: String,
678 #[label = "field redefined here"]
679 second_use: Span,
680 #[label = "field first defined here"]
681 first_use: Span,
682 #[help]
685 help: Option<String>,
686 },
687
688 #[error("Attempted to create a record from different number of columns and values")]
694 #[diagnostic(code(nu::shell::record_cols_vals_mismatch))]
695 RecordColsValsMismatch {
696 #[label = "problematic value"]
697 bad_value: Span,
698 #[label = "attempted to create the record here"]
699 creation_site: Span,
700 },
701
702 #[error("Failed to detect columns")]
708 #[diagnostic(code(nu::shell::failed_to_detect_columns))]
709 ColumnDetectionFailure {
710 #[label = "value coming from here"]
711 bad_value: Span,
712 #[label = "tried to detect columns here"]
713 failure_site: Span,
714 },
715
716 #[error("Relative range values cannot be used with streams that don't have a known length")]
722 #[diagnostic(code(nu::shell::relative_range_on_infinite_stream))]
723 RelativeRangeOnInfiniteStream {
724 #[label = "Relative range values cannot be used with streams that don't have a known length"]
725 span: Span,
726 },
727
728 #[error("External command failed")]
734 #[diagnostic(code(nu::shell::external_command), help("{help}"))]
735 ExternalCommand {
736 label: String,
737 help: String,
738 #[label("{label}")]
739 span: Span,
740 },
741
742 #[error("External command had a non-zero exit code")]
748 #[diagnostic(code(nu::shell::non_zero_exit_code))]
749 NonZeroExitCode {
750 exit_code: NonZeroI32,
751 #[label("exited with code {exit_code}")]
752 span: Span,
753 },
754
755 #[cfg(unix)]
756 #[error("External command was terminated by a signal")]
762 #[diagnostic(code(nu::shell::terminated_by_signal))]
763 TerminatedBySignal {
764 signal_name: String,
765 signal: i32,
766 #[label("terminated by {signal_name} ({signal})")]
767 span: Span,
768 },
769
770 #[cfg(unix)]
771 #[error("External command core dumped")]
777 #[diagnostic(code(nu::shell::core_dumped))]
778 CoreDumped {
779 signal_name: String,
780 signal: i32,
781 #[label("core dumped with {signal_name} ({signal})")]
782 span: Span,
783 },
784
785 #[error("Unsupported input")]
791 #[diagnostic(code(nu::shell::unsupported_input))]
792 UnsupportedInput {
793 msg: String,
794 input: String,
795 #[label("{msg}")]
796 msg_span: Span,
797 #[label("{input}")]
798 input_span: Span,
799 },
800
801 #[error("Unable to parse datetime: [{msg}].")]
816 #[diagnostic(
817 code(nu::shell::datetime_parse_error),
818 help(
819 r#"Examples of supported inputs:
820 * "5 pm"
821 * "2020/12/4"
822 * "2020.12.04 22:10 +2"
823 * "2020-04-12 22:10:57 +02:00"
824 * "2020-04-12T22:10:57.213231+02:00"
825 * "Tue, 1 Jul 2003 10:52:37 +0200""#
826 )
827 )]
828 DatetimeParseError {
829 msg: String,
830 #[label("datetime parsing failed")]
831 span: Span,
832 },
833
834 #[error("Network failure")]
840 #[diagnostic(code(nu::shell::network_failure))]
841 NetworkFailure {
842 msg: String,
843 #[label("{msg}")]
844 span: Span,
845 },
846
847 #[error("HTTP Error {code} ({reason}): {url}")]
853 #[diagnostic(code(nu::shell::http_error))]
854 HttpError {
855 code: u16,
856 reason: &'static str,
857 url: String,
858 msg: String,
859 #[label("{msg}")]
860 span: Span,
861 },
862
863 #[error(transparent)]
864 #[diagnostic(transparent)]
865 Network(#[from] network::NetworkError),
866
867 #[error("Command not found")]
873 #[diagnostic(code(nu::shell::command_not_found))]
874 CommandNotFound {
875 #[label("command not found")]
876 span: Span,
877 },
878
879 #[error("Alias not found")]
885 #[diagnostic(code(nu::shell::alias_not_found))]
886 AliasNotFound {
887 #[label("alias not found")]
888 span: Span,
889 },
890
891 #[error("The registered plugin data for `{plugin_name}` is invalid")]
897 #[diagnostic(code(nu::shell::plugin_registry_data_invalid))]
898 PluginRegistryDataInvalid {
899 plugin_name: String,
900 #[label("plugin `{plugin_name}` loaded here")]
901 span: Option<Span>,
902 #[help(
903 "the format in the plugin registry file is not compatible with this version of Nushell.\n\nTry adding the plugin again with `{}`"
904 )]
905 add_command: String,
906 },
907
908 #[error("Plugin failed to load: {msg}")]
914 #[diagnostic(code(nu::shell::plugin_failed_to_load))]
915 PluginFailedToLoad { msg: String },
916
917 #[error("Plugin failed to encode: {msg}")]
923 #[diagnostic(code(nu::shell::plugin_failed_to_encode))]
924 PluginFailedToEncode { msg: String },
925
926 #[error("Plugin failed to decode: {msg}")]
932 #[diagnostic(code(nu::shell::plugin_failed_to_decode))]
933 PluginFailedToDecode { msg: String },
934
935 #[error("Custom value `{name}` cannot be sent to plugin")]
942 #[diagnostic(code(nu::shell::custom_value_incorrect_for_plugin))]
943 CustomValueIncorrectForPlugin {
944 name: String,
945 #[label("the `{dest_plugin}` plugin does not support this kind of value")]
946 span: Span,
947 dest_plugin: String,
948 #[help("this value came from the `{}` plugin")]
949 src_plugin: Option<String>,
950 },
951
952 #[error("Custom value failed to encode")]
959 #[diagnostic(code(nu::shell::custom_value_failed_to_encode))]
960 CustomValueFailedToEncode {
961 msg: String,
962 #[label("{msg}")]
963 span: Span,
964 },
965
966 #[error("Custom value failed to decode")]
973 #[diagnostic(code(nu::shell::custom_value_failed_to_decode))]
974 #[diagnostic(help("the plugin may have been updated and no longer support this custom value"))]
975 CustomValueFailedToDecode {
976 msg: String,
977 #[label("{msg}")]
978 span: Span,
979 },
980
981 #[error(transparent)]
987 #[diagnostic(transparent)]
988 Io(#[from] io::IoError),
989
990 #[error("Name not found")]
996 #[diagnostic(code(nu::shell::name_not_found))]
997 DidYouMean {
998 suggestion: String,
999 #[label("did you mean '{suggestion}'?")]
1000 span: Span,
1001 },
1002
1003 #[error("{msg}")]
1009 #[diagnostic(code(nu::shell::did_you_mean_custom))]
1010 DidYouMeanCustom {
1011 msg: String,
1012 suggestion: String,
1013 #[label("did you mean '{suggestion}'?")]
1014 span: Span,
1015 },
1016
1017 #[error("Non-UTF8 string")]
1023 #[diagnostic(
1024 code(nu::parser::non_utf8),
1025 help("see `decode` for handling character sets other than UTF-8")
1026 )]
1027 NonUtf8 {
1028 #[label("non-UTF8 string")]
1029 span: Span,
1030 },
1031
1032 #[error("Non-UTF8 string")]
1038 #[diagnostic(
1039 code(nu::parser::non_utf8_custom),
1040 help("see `decode` for handling character sets other than UTF-8")
1041 )]
1042 NonUtf8Custom {
1043 msg: String,
1044 #[label("{msg}")]
1045 span: Span,
1046 },
1047
1048 #[error("Encountered {} error(s) when updating config", errors.len())]
1054 #[diagnostic(code(nu::shell::invalid_config))]
1055 InvalidConfig {
1056 #[related]
1057 errors: Vec<ConfigError>,
1058 },
1059
1060 #[error("Value is missing a required '{column}' column")]
1066 #[diagnostic(code(nu::shell::missing_required_column))]
1067 MissingRequiredColumn {
1068 column: &'static str,
1069 #[label("has no '{column}' column")]
1070 span: Span,
1071 },
1072
1073 #[error("Negative value passed when positive one is required")]
1079 #[diagnostic(code(nu::shell::needs_positive_value))]
1080 NeedsPositiveValue {
1081 #[label("use a positive value")]
1082 span: Span,
1083 },
1084
1085 #[error(transparent)]
1087 #[diagnostic(transparent)]
1088 Generic(#[from] generic::GenericError),
1089
1090 #[error("{error}")]
1092 #[diagnostic(code(nu::shell::outsidespan))]
1093 OutsideSpannedLabeledError {
1094 #[source_code]
1095 src: String,
1096 error: String,
1097 msg: String,
1098 #[label("{msg}")]
1099 span: Span,
1100 },
1101
1102 #[error("{msg}")]
1105 #[diagnostic(code(nu::shell::outside), url("{url}"))]
1106 OutsideSource {
1107 #[source_code]
1108 src: NamedSource<String>,
1109 msg: String,
1110 url: String,
1111 #[help]
1112 help: Option<String>,
1113 #[label(collection, "")]
1115 labels: Vec<LabeledSpan>,
1116 #[related]
1117 inner: Vec<ShellError>,
1118 },
1119
1120 #[error("{msg}")]
1123 #[diagnostic(code(nu::shell::outside))]
1124 OutsideSourceNoUrl {
1125 #[source_code]
1126 src: NamedSource<String>,
1127 msg: String,
1128 #[help]
1129 help: Option<String>,
1130 #[label(collection, "")]
1132 labels: Vec<LabeledSpan>,
1133 #[related]
1134 inner: Vec<ShellError>,
1135 },
1136
1137 #[error(transparent)]
1139 #[diagnostic(transparent)]
1140 LabeledError(#[from] Box<super::LabeledError>),
1141
1142 #[error("Removed command: {removed}")]
1148 #[diagnostic(code(nu::shell::removed_command))]
1149 RemovedCommand {
1150 removed: String,
1151 replacement: String,
1152 #[label("'{removed}' has been removed from Nushell. Please use '{replacement}' instead.")]
1153 span: Span,
1154 },
1155
1156 #[error(transparent)]
1161 #[diagnostic(transparent)]
1162 EvalBlockWithInput(eval_block_with_input::EvalBlockWithInputError),
1163
1164 #[error("Break used outside of loop")]
1166 Break {
1167 #[label("used outside of loop")]
1168 span: Span,
1169 },
1170
1171 #[error("Continue used outside of loop")]
1173 Continue {
1174 #[label("used outside of loop")]
1175 span: Span,
1176 },
1177
1178 #[deprecated(
1185 since = "0.114.2",
1186 note = "the engine no longer raises this; an early `return` now flows out through `PipelineExecutionData::early_return`"
1187 )]
1188 #[error("Return used outside of custom command or closure")]
1189 Return {
1190 #[label("used outside of custom command or closure")]
1191 span: Span,
1192 value: Box<Value>,
1193 },
1194
1195 #[error("Exit doesn't catch internally")]
1197 #[diagnostic(
1198 code(nu::shell::exit),
1199 help(
1200 "This shouldn't happen. Please file an issue: https://github.com/nushell/nushell/issues"
1201 )
1202 )]
1203 Exit { code: i32, abort: bool },
1204
1205 #[error("Recursion limit ({recursion_limit}) reached")]
1211 #[diagnostic(code(nu::shell::recursion_limit_reached))]
1212 RecursionLimitReached {
1213 recursion_limit: u64,
1214 #[label("This called itself too many times")]
1215 span: Option<Span>,
1216 },
1217
1218 #[error("Operation interrupted")]
1220 Interrupted {
1221 #[label("This operation was interrupted")]
1222 span: Span,
1223 },
1224
1225 #[error("Match guard not bool")]
1228 #[diagnostic(
1229 code(nu::shell::match_guard_not_bool),
1230 help("Match guards should evaluate to a boolean")
1231 )]
1232 MatchGuardNotBool {
1233 #[label("not a boolean expression")]
1234 span: Span,
1235 },
1236
1237 #[error("Missing const eval implementation")]
1242 #[diagnostic(
1243 code(nu::shell::missing_const_eval_implementation),
1244 help(
1245 "The command lacks an implementation for constant evaluation. \
1246This is an internal Nushell error, please file an issue https://github.com/nushell/nushell/issues."
1247 )
1248 )]
1249 MissingConstEvalImpl {
1250 #[label("command lacks constant implementation")]
1251 span: Span,
1252 },
1253
1254 #[error("Found parsing error in expression.")]
1262 #[diagnostic(
1263 code(nu::shell::parse_error_in_constant),
1264 help(
1265 "This expression is supposed to be evaluated into a constant, which means error-free."
1266 )
1267 )]
1268 ParseErrorInConstant {
1269 #[label("Parsing error detected in expression")]
1270 span: Span,
1271 },
1272
1273 #[error("Not a constant.")]
1279 #[diagnostic(
1280 code(nu::shell::not_a_constant),
1281 help(
1282 "Only a subset of expressions are allowed constants during parsing. Try using the 'const' command or typing the value literally."
1283 )
1284 )]
1285 NotAConstant {
1286 #[label("Value is not a parse-time constant")]
1287 span: Span,
1288 },
1289
1290 #[error("Not a const command.")]
1297 #[diagnostic(
1298 code(nu::shell::not_a_const_command),
1299 help("Only a subset of builtin commands can run at parse time.")
1300 )]
1301 NotAConstCommand {
1302 #[label("This command cannot run at parse time.")]
1303 span: Span,
1304 },
1305
1306 #[error("Help message not a constant.")]
1312 #[diagnostic(
1313 code(nu::shell::not_a_const_help),
1314 help("Help messages are currently not supported to be constants.")
1315 )]
1316 NotAConstHelp {
1317 #[label("This command cannot run at parse time.")]
1318 span: Span,
1319 },
1320
1321 #[error("Invalid glob pattern")]
1327 #[diagnostic(
1328 code(nu::shell::invalid_glob_pattern),
1329 help("Refer to xxx for help on nushell glob patterns.")
1330 )]
1331 InvalidGlobPattern {
1332 msg: String,
1333 #[label("{msg}")]
1334 span: Span,
1335 },
1336
1337 #[error("Invalid unit")]
1343 #[diagnostic(
1344 code(nu::shell::invalid_unit),
1345 help("Supported units are: {supported_units}")
1346 )]
1347 InvalidUnit {
1348 supported_units: String,
1349 #[label("encountered here")]
1350 span: Span,
1351 },
1352
1353 #[error("Not a list")]
1359 #[diagnostic(
1360 code(nu::shell::cannot_spread_as_list),
1361 help(
1362 "Only lists can be spread inside lists and command calls. Try converting the value to a list before spreading."
1363 )
1364 )]
1365 CannotSpreadAsList {
1366 #[label = "cannot spread value"]
1367 span: Span,
1368 },
1369
1370 #[error("Not a record")]
1376 #[diagnostic(
1377 code(nu::shell::cannot_spread_as_record),
1378 help(
1379 "Only records can be spread inside records. Try converting the value to a record before spreading."
1380 )
1381 )]
1382 CannotSpreadAsRecord {
1383 #[label = "cannot spread value"]
1384 span: Span,
1385 },
1386
1387 #[error("Lists are not automatically spread when calling external commands")]
1393 #[diagnostic(
1394 code(nu::shell::cannot_pass_list_to_external),
1395 help("Either convert the list to a string or use the spread operator, like so: ...{arg}")
1396 )]
1397 CannotPassListToExternal {
1398 arg: String,
1399 #[label = "Spread operator (...) is necessary to spread lists"]
1400 span: Span,
1401 },
1402
1403 #[error(
1409 "The selected range {left_flank}..{right_flank} is out of the bounds of the provided input"
1410 )]
1411 #[diagnostic(code(nu::shell::out_of_bounds))]
1412 OutOfBounds {
1413 left_flank: String,
1414 right_flank: String,
1415 #[label = "byte index is not a char boundary or is out of bounds of the input"]
1416 span: Span,
1417 },
1418
1419 #[error("The config directory could not be found")]
1421 #[diagnostic(
1422 code(nu::shell::config_dir_not_found),
1423 help(
1424 r#"On Linux, this would be $XDG_CONFIG_HOME or $HOME/.config.
1425On MacOS, this would be `$HOME/Library/Application Support`.
1426On Windows, this would be %USERPROFILE%\AppData\Roaming"#
1427 )
1428 )]
1429 ConfigDirNotFound {
1430 #[label = "Could not find config directory"]
1431 span: Span,
1432 },
1433
1434 #[error(
1436 "$env.XDG_CONFIG_HOME ({xdg}) is invalid, using default config directory instead: {default}"
1437 )]
1438 #[diagnostic(
1439 code(nu::shell::xdg_config_home_invalid),
1440 help("Set XDG_CONFIG_HOME to an absolute path, or set it to an empty string to ignore it")
1441 )]
1442 InvalidXdgConfig { xdg: String, default: String },
1443
1444 #[error("IR evaluation error: {msg}")]
1451 #[diagnostic(
1452 code(nu::shell::ir_eval_error),
1453 help(
1454 "this is a bug, please report it at https://github.com/nushell/nushell/issues/new along with the code you were running if able"
1455 )
1456 )]
1457 IrEvalError {
1458 msg: String,
1459 #[label = "while running this code"]
1460 span: Option<Span>,
1461 },
1462
1463 #[error("OS feature is disabled: {msg}")]
1464 #[diagnostic(
1465 code(nu::shell::os_disabled),
1466 help("You're probably running outside an OS like a browser, we cannot support this")
1467 )]
1468 DisabledOsSupport {
1469 msg: String,
1470 #[label = "while running this code"]
1471 span: Span,
1472 },
1473
1474 #[error(transparent)]
1475 #[diagnostic(transparent)]
1476 Job(#[from] JobError),
1477
1478 #[error(transparent)]
1479 #[diagnostic(transparent)]
1480 ChainedError(ChainedError),
1481}
1482
1483impl ShellError {
1484 pub const RECORD_SPREAD_DUPLICATE_HELP: &'static str = "A record literal can't contain the same key twice, including keys brought in with `...`. To replace a field, use `merge` or `update`.";
1487
1488 pub fn external_exit_code(&self) -> Option<Spanned<i32>> {
1489 let (item, span) = match *self {
1490 Self::NonZeroExitCode { exit_code, span } => (exit_code.into(), span),
1491 #[cfg(unix)]
1492 Self::TerminatedBySignal { signal, span, .. }
1493 | Self::CoreDumped { signal, span, .. } => (-signal, span),
1494 Self::EvalBlockWithInput(ref err) => return err.error.external_exit_code(),
1496 _ => return None,
1497 };
1498 Some(Spanned { item, span })
1499 }
1500
1501 pub fn is_interrupt(&self) -> bool {
1504 #[cfg(unix)]
1505 if matches!(self, Self::TerminatedBySignal { .. }) {
1506 return true;
1507 }
1508 matches!(self, Self::Interrupted { .. })
1509 }
1510
1511 pub fn exit_code(&self) -> Option<i32> {
1512 #[allow(deprecated)]
1514 match self {
1515 Self::Return { .. } | Self::Break { .. } | Self::Continue { .. } => None,
1516 _ => self.external_exit_code().map(|e| e.item).or(Some(1)),
1517 }
1518 }
1519
1520 pub fn into_full_value(
1521 self,
1522 working_set: &StateWorkingSet,
1523 stack: &Stack,
1524 span: Span,
1525 ) -> Value {
1526 let exit_code = self.external_exit_code();
1527
1528 let mut record = record! {
1529 "msg" => Value::string(self.to_string(), span),
1530 "debug" => Value::string(format!("{self:?}"), span),
1531 "raw" => Value::error(self.clone(), span),
1532 "rendered" => Value::string(format_cli_error(Some(stack), working_set, &self, Some("nu::shell::error")), span),
1533 "details" => LabeledError::from(self).into_value(span, working_set),
1534 };
1535
1536 if let Some(code) = exit_code {
1537 record.push("exit_code", Value::int(code.item.into(), code.span));
1538 }
1539
1540 Value::record(record, span)
1541 }
1542
1543 pub fn wrap(self, working_set: &StateWorkingSet, span: Span) -> ParseError {
1545 let msg = format_cli_error(None, working_set, &self, None);
1546 ParseError::LabeledError(
1547 msg,
1548 "Encountered error during parse-time evaluation".into(),
1549 span,
1550 )
1551 }
1552
1553 pub fn into_chained(self, span: Span) -> Self {
1555 Self::ChainedError(match self {
1556 Self::ChainedError(inner) => ChainedError::new_chained(inner, span),
1557 other => {
1558 let error = other.clone();
1561 let mut now = ChainedError::new(other, span);
1562 if let Some(related) = error.related() {
1563 let mapped = related
1564 .map(|s| {
1565 let shellerror: Self = Self::from_diagnostic(s);
1566 shellerror
1567 })
1568 .collect::<Vec<_>>();
1569 if !mapped.is_empty() {
1570 now.sources = [now.sources, mapped].concat();
1571 };
1572 }
1573 now
1574 }
1575 })
1576 }
1577
1578 pub fn from_diagnostic(diag: &(impl miette::Diagnostic + ?Sized)) -> Self {
1579 Self::LabeledError(LabeledError::from_diagnostic(diag).into())
1580 }
1581}
1582
1583impl FromValue for ShellError {
1584 fn from_value(v: Value) -> Result<Self, ShellError> {
1585 let from_type = v.get_type();
1586 match v {
1587 Value::Error { error, .. } => Ok(*error),
1588 Value::Record {
1590 val, internal_span, ..
1591 } => Self::from_value(
1592 (*val)
1593 .get("raw")
1594 .ok_or(ShellError::CantConvert {
1595 to_type: Self::expected_type().to_string(),
1596 from_type: from_type.to_string(),
1597 span: internal_span,
1598 help: None,
1599 })?
1600 .clone(),
1601 ),
1602 Value::Nothing { internal_span } => Ok(Self::Generic(GenericError::new(
1603 "error",
1604 "is nothing",
1605 internal_span,
1606 ))),
1607 _ => Err(ShellError::CantConvert {
1608 to_type: Self::expected_type().to_string(),
1609 from_type: v.get_type().to_string(),
1610 span: v.span(),
1611 help: None,
1612 }),
1613 }
1614 }
1615}
1616
1617impl From<Box<dyn std::error::Error>> for ShellError {
1618 fn from(error: Box<dyn std::error::Error>) -> ShellError {
1619 ShellError::Generic(GenericError::new_internal(
1620 format!("{error:?}"),
1621 error.to_string(),
1622 ))
1623 }
1624}
1625
1626impl From<Box<dyn std::error::Error + Send + Sync>> for ShellError {
1627 fn from(error: Box<dyn std::error::Error + Send + Sync>) -> ShellError {
1628 ShellError::Generic(GenericError::new_internal(
1629 format!("{error:?}"),
1630 error.to_string(),
1631 ))
1632 }
1633}
1634
1635impl From<super::LabeledError> for ShellError {
1636 fn from(error: super::LabeledError) -> Self {
1637 ShellError::LabeledError(Box::new(error))
1638 }
1639}
1640
1641impl Serialize for ShellError {
1643 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1644 where
1645 S: serde::Serializer,
1646 {
1647 LabeledError::from_diagnostic(self).serialize(serializer)
1648 }
1649}
1650
1651impl<'de> Deserialize<'de> for ShellError {
1654 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1655 where
1656 D: serde::Deserializer<'de>,
1657 {
1658 LabeledError::deserialize(deserializer).map(ShellError::from)
1659 }
1660}
1661
1662#[test]
1663fn shell_error_serialize_roundtrip() {
1664 let original_error = ShellError::CantConvert {
1667 span: Span::new(100, 200),
1668 to_type: "Foo".into(),
1669 from_type: "Bar".into(),
1670 help: Some("this is a test".into()),
1671 };
1672 println!("orig_error = {original_error:#?}");
1673
1674 let serialized =
1675 serde_json::to_string_pretty(&original_error).expect("serde_json::to_string_pretty failed");
1676 println!("serialized = {serialized}");
1677
1678 let deserialized: ShellError =
1679 serde_json::from_str(&serialized).expect("serde_json::from_str failed");
1680 println!("deserialized = {deserialized:#?}");
1681
1682 assert_eq!(original_error.to_string(), deserialized.to_string());
1685
1686 assert_eq!(
1687 original_error.code().map(|c| c.to_string()),
1688 deserialized.code().map(|c| c.to_string())
1689 );
1690
1691 let orig_labels = original_error
1692 .labels()
1693 .into_iter()
1694 .flatten()
1695 .collect::<Vec<_>>();
1696 let deser_labels = deserialized
1697 .labels()
1698 .into_iter()
1699 .flatten()
1700 .collect::<Vec<_>>();
1701
1702 assert_eq!(orig_labels, deser_labels);
1703
1704 assert_eq!(
1705 original_error.help().map(|c| c.to_string()),
1706 deserialized.help().map(|c| c.to_string())
1707 );
1708}
1709
1710#[derive(Debug, Clone, Eq, PartialEq)]
1716pub enum ErrorSite {
1717 Span(Span),
1719
1720 Location(String),
1724}
1725
1726impl From<Span> for ErrorSite {
1727 fn from(span: Span) -> Self {
1728 Self::Span(span)
1729 }
1730}
1731
1732impl From<Location> for ErrorSite {
1733 fn from(location: Location) -> Self {
1734 Self::Location(location.to_string())
1735 }
1736}
1737
1738#[derive(Debug, Error, Clone, Diagnostic)]
1740#[error(transparent)]
1741pub struct ErrorSource(Arc<dyn StdError + Send + Sync>);
1742
1743impl PartialEq for ErrorSource {
1744 fn eq(&self, other: &Self) -> bool {
1745 self.0.to_string() == other.0.to_string()
1747 }
1748}
1749
1750#[cfg(test)]
1751mod test {
1752 use super::*;
1753
1754 impl From<std::io::Error> for ShellError {
1755 fn from(_: std::io::Error) -> ShellError {
1756 unimplemented!(
1757 "This implementation is defined in the test module to ensure no other implementation exists."
1758 )
1759 }
1760 }
1761
1762 impl From<Spanned<std::io::Error>> for ShellError {
1763 fn from(_: Spanned<std::io::Error>) -> Self {
1764 unimplemented!(
1765 "This implementation is defined in the test module to ensure no other implementation exists."
1766 )
1767 }
1768 }
1769
1770 impl From<ShellError> for std::io::Error {
1771 fn from(_: ShellError) -> Self {
1772 unimplemented!(
1773 "This implementation is defined in the test module to ensure no other implementation exists."
1774 )
1775 }
1776 }
1777}