Skip to main content

nu_protocol/errors/shell_error/
mod.rs

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/// The fundamental error type for the evaluation engine. These cases represent different kinds of errors
25/// the evaluator might face, along with helpful spans to label. An error renderer will take this error value
26/// and pass it into an error viewer to display to the user.
27#[derive(Debug, Clone, Error, Diagnostic, PartialEq)]
28pub enum ShellError {
29    /// One or more of the values have types not supported by the operator.
30    #[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    /// The operator supports the types of both values, but not the specific combination of their types.
44    #[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    /// An arithmetic operation's resulting value overflowed its possible size.
61    ///
62    /// ## Resolution
63    ///
64    /// Check the inputs to the operation and add guards for their sizes.
65    /// Integers are generally of size i64, floats are generally f64.
66    #[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    /// The pipelined input into a command was not of the expected type. For example, it might
77    /// expect a string input, but received a table instead.
78    ///
79    /// ## Resolution
80    ///
81    /// Check the relevant pipeline and extract or convert values as needed.
82    #[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    // TODO: properly unify
93    /// The pipelined input into a command was not of the expected type. For example, it might
94    /// expect a string input, but received a table instead.
95    ///
96    /// (duplicate of [`ShellError::PipelineMismatch`] that reports the observed type)
97    ///
98    /// ## Resolution
99    ///
100    /// Check the relevant pipeline and extract or convert values as needed.
101    #[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    /// No input value was piped into the command.
113    ///
114    /// ## Resolution
115    ///
116    /// Only use this command to process values from a previous expression.
117    #[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    // TODO: remove non type error usages
125    /// A command received an argument of the wrong type.
126    ///
127    /// ## Resolution
128    ///
129    /// Convert the argument type before passing it in, or change the command to accept the type.
130    #[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    /// A value's type did not match the expected type.
139    ///
140    /// ## Resolution
141    ///
142    /// Convert the value to the correct type or provide a value of the correct type.
143    #[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    /// A value had the correct type but is otherwise invalid.
153    ///
154    /// ## Resolution
155    ///
156    /// Ensure the value meets the criteria in the error message.
157    #[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    /// A command received an argument with correct type but incorrect value.
167    ///
168    /// ## Resolution
169    ///
170    /// Correct the argument value before passing it in or change the command.
171    #[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    /// Invalid assignment left-hand side
182    ///
183    /// ## Resolution
184    ///
185    /// Assignment requires that you assign to a variable or variable cell path.
186    #[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    /// Invalid assignment left-hand side
194    ///
195    /// ## Resolution
196    ///
197    /// Assignment requires that you assign to a mutable variable or cell path.
198    #[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    /// An operator was not recognized during evaluation.
206    ///
207    /// ## Resolution
208    ///
209    /// Did you write the correct operator?
210    #[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    /// An expected command parameter is missing.
219    ///
220    /// ## Resolution
221    ///
222    /// Add the expected parameter and try again.
223    #[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    /// Two parameters conflict with each other or are otherwise mutually exclusive.
232    ///
233    /// ## Resolution
234    ///
235    /// Remove one of the parameters/options and try again.
236    #[error("Incompatible parameters.")]
237    #[diagnostic(code(nu::shell::incompatible_parameters))]
238    IncompatibleParameters {
239        left_message: String,
240        // Be cautious, as flags can share the same span, resulting in a panic (ex: `rm -pt`)
241        #[label("{left_message}")]
242        left_span: Span,
243        right_message: String,
244        #[label("{right_message}")]
245        right_span: Span,
246    },
247
248    /// There's some issue with number or matching of delimiters in an expression.
249    ///
250    /// ## Resolution
251    ///
252    /// Check your syntax for mismatched braces, RegExp syntax errors, etc, based on the specific error message.
253    #[error("Delimiter error")]
254    #[diagnostic(code(nu::shell::delimiter_error))]
255    DelimiterError {
256        msg: String,
257        #[label("{msg}")]
258        span: Span,
259    },
260
261    /// An operation received parameters with some sort of incompatibility
262    /// (for example, different number of rows in a table, incompatible column names, etc).
263    ///
264    /// ## Resolution
265    ///
266    /// Refer to the specific error message for details on what's incompatible and then fix your
267    /// inputs to make sure they match that way.
268    #[error("Incompatible parameters.")]
269    #[diagnostic(code(nu::shell::incompatible_parameters))]
270    IncompatibleParametersSingle {
271        msg: String,
272        #[label = "{msg}"]
273        span: Span,
274    },
275
276    /// You're trying to run an unsupported external command.
277    ///
278    /// ## Resolution
279    ///
280    /// Make sure there's an appropriate `run-external` declaration for this external command.
281    #[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    // TODO: consider moving to a more generic error variant for invalid values
289    /// The given probability input is invalid. The probability must be between 0 and 1.
290    ///
291    /// ## Resolution
292    ///
293    /// Make sure the probability is between 0 and 1 and try again.
294    #[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    /// The first value in a `..` range must be compatible with the second one.
302    ///
303    /// ## Resolution
304    ///
305    /// Check to make sure both values are compatible, and that the values are enumerable in Nushell.
306    #[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    /// Catastrophic nushell failure. This reflects a completely unexpected or unrecoverable error.
316    ///
317    /// ## Resolution
318    ///
319    /// It is very likely that this is a bug. Please file an issue at <https://github.com/nushell/nushell/issues> with relevant information.
320    #[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    // Only use this one if Nushell completely falls over and hits a state that isn't possible or isn't recoverable
328    NushellFailed { msg: String },
329
330    /// Catastrophic nushell failure. This reflects a completely unexpected or unrecoverable error.
331    ///
332    /// ## Resolution
333    ///
334    /// It is very likely that this is a bug. Please file an issue at <https://github.com/nushell/nushell/issues> with relevant information.
335    #[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    // Only use this one if Nushell completely falls over and hits a state that isn't possible or isn't recoverable
343    NushellFailedSpanned {
344        msg: String,
345        label: String,
346        #[label = "{label}"]
347        span: Span,
348    },
349
350    /// Catastrophic nushell failure. This reflects a completely unexpected or unrecoverable error.
351    ///
352    /// ## Resolution
353    ///
354    /// It is very likely that this is a bug. Please file an issue at <https://github.com/nushell/nushell/issues> with relevant information.
355    #[error("Nushell failed: {msg}.")]
356    #[diagnostic(code(nu::shell::nushell_failed_help))]
357    // Only use this one if Nushell completely falls over and hits a state that isn't possible or isn't recoverable
358    NushellFailedHelp {
359        msg: String,
360        #[help]
361        help: String,
362    },
363
364    /// A referenced variable was not found at runtime.
365    ///
366    /// ## Resolution
367    ///
368    /// Check the variable name. Did you typo it? Did you forget to declare it? Is the casing right?
369    #[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    /// A referenced environment variable was not found at runtime.
377    ///
378    /// ## Resolution
379    ///
380    /// Check the environment variable name. Did you typo it? Did you forget to declare it? Is the casing right?
381    #[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    /// A referenced module was not found at runtime.
390    ///
391    /// ## Resolution
392    ///
393    /// Check the module name. Did you typo it? Did you forget to declare it? Is the casing right?
394    #[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    /// A referenced overlay was not found at runtime.
403    ///
404    /// ## Resolution
405    ///
406    /// Check the overlay name. Did you typo it? Did you forget to declare it? Is the casing right?
407    #[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    /// The given item was not found. This is a fairly generic error that depends on context.
416    ///
417    /// ## Resolution
418    ///
419    /// This error is triggered in various places, and simply signals that "something" was not found. Refer to the specific error message for further details.
420    #[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    /// Failed to convert a value of one type into a different type.
428    ///
429    /// ## Resolution
430    ///
431    /// Not all values can be coerced this way. Check the supported type(s) and try again.
432    #[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    /// Failed to convert a value of one type into a different type by specifying a unit.
444    ///
445    /// ## Resolution
446    ///
447    /// Check that the provided value can be converted in the provided: only Durations can be converted to duration units, and only Filesize can be converted to filesize units.
448    #[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    /// An environment variable cannot be represented as a string.
462    ///
463    /// ## Resolution
464    ///
465    /// Not all types can be converted to environment variable values, which must be strings. Check the input type and try again.
466    #[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    /// This environment variable cannot be changed manually.
481    ///
482    /// ## Resolution
483    ///
484    /// This environment variable is set automatically by Nushell and cannot be set manually or hidden.
485    #[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    /// The config environment variable cannot be hidden.
500    ///
501    /// ## Resolution
502    ///
503    /// Assign a new record to `$env.config` instead of hiding it.
504    #[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    /// It is not possible to replace the entire environment at once
515    ///
516    /// ## Resolution
517    ///
518    /// Setting the entire environment is not allowed. Change environment variables individually
519    /// instead.
520    #[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    /// Division by zero is not a thing.
531    ///
532    /// ## Resolution
533    ///
534    /// Add a guard of some sort to check whether a denominator input to this division is zero, and branch off if that's the case.
535    #[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    /// An error happened while trying to create a range.
543    ///
544    /// This can happen in various unexpected situations, for example if the range would loop forever (as would be the case with a 0-increment).
545    ///
546    /// ## Resolution
547    ///
548    /// Check your range values to make sure they're countable and would not loop forever.
549    #[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    /// You attempted to access an index beyond the available length of a value.
557    ///
558    /// ## Resolution
559    ///
560    /// Check your lengths and try again.
561    #[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    /// You attempted to insert data at a list position higher than the end.
570    ///
571    /// ## Resolution
572    ///
573    /// To insert data into a list, assign to the last used index + 1.
574    #[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    /// You attempted to access a value from empty content.
583    ///
584    /// ## Resolution
585    ///
586    /// Check that the content is not empty and try again.
587    #[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    // TODO: check to be taken over by `AccessBeyondEnd`
595    /// You attempted to access an index beyond the available length of a stream.
596    ///
597    /// ## Resolution
598    ///
599    /// Check your lengths and try again.
600    #[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    /// Tried to index into a type that does not support pathed access.
608    ///
609    /// ## Resolution
610    ///
611    /// Check your types. Only composite types can be pathed into.
612    #[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    /// The requested column does not exist.
621    ///
622    /// ## Resolution
623    ///
624    /// Check the spelling of your column name. Did you forget to rename a column somewhere?
625    #[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    /// Attempted to insert a column into a table, but a column with that name already exists.
639    ///
640    /// ## Resolution
641    ///
642    /// Drop or rename the existing column (check `rename -h`) and try again.
643    #[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    /// The given operation can only be performed on lists.
654    ///
655    /// ## Resolution
656    ///
657    /// Check the input type to this command. Are you sure it's a list?
658    #[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    /// Fields can only be defined once
668    ///
669    /// ## Resolution
670    ///
671    /// Check the record to ensure you aren't reusing the same field name. A record literal can't
672    /// contain the same key twice, including keys brought in with `...`. To replace a field, use
673    /// `merge` or `update`.
674    #[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        /// Set by record literals when a spread is involved, see
683        /// [`ShellError::RECORD_SPREAD_DUPLICATE_HELP`].
684        #[help]
685        help: Option<String>,
686    },
687
688    /// Attempted to create a record from different number of columns and values
689    ///
690    /// ## Resolution
691    ///
692    /// Check the record has the same number of columns as values
693    #[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    /// Failed to detect columns
703    ///
704    /// ## Resolution
705    ///
706    /// Use `detect columns --guess` or `parse` instead
707    #[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    /// Attempted to us a relative range on an infinite stream
717    ///
718    /// ## Resolution
719    ///
720    /// Ensure that either the range is absolute or the stream has a known length.
721    #[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    /// An error happened while performing an external command.
729    ///
730    /// ## Resolution
731    ///
732    /// This error is fairly generic. Refer to the specific error message for further details.
733    #[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    /// An external command exited with a non-zero exit code.
743    ///
744    /// ## Resolution
745    ///
746    /// Check the external command's error message.
747    #[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    /// An external command exited due to a signal.
757    ///
758    /// ## Resolution
759    ///
760    /// Check why the signal was sent or triggered.
761    #[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    /// An external command core dumped.
772    ///
773    /// ## Resolution
774    ///
775    /// Check why the core dumped was triggered.
776    #[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    /// An operation was attempted with an input unsupported for some reason.
786    ///
787    /// ## Resolution
788    ///
789    /// This error is fairly generic. Refer to the specific error message for further details.
790    #[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    /// Failed to parse an input into a datetime value.
802    ///
803    /// ## Resolution
804    ///
805    /// Make sure your datetime input format is correct.
806    ///
807    /// For example, these are some valid formats:
808    ///
809    /// * "5 pm"
810    /// * "2020/12/4"
811    /// * "2020.12.04 22:10 +2"
812    /// * "2020-04-12 22:10:57 +02:00"
813    /// * "2020-04-12T22:10:57.213231+02:00"
814    /// * "Tue, 1 Jul 2003 10:52:37 +0200""#
815    #[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    /// A network operation failed.
835    ///
836    /// ## Resolution
837    ///
838    /// It's always DNS.
839    #[error("Network failure")]
840    #[diagnostic(code(nu::shell::network_failure))]
841    NetworkFailure {
842        msg: String,
843        #[label("{msg}")]
844        span: Span,
845    },
846
847    /// An HTTP request return an error code.
848    ///
849    /// ## Resolution
850    ///
851    /// Check the response body for more details.
852    #[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    /// Help text for this command could not be found.
868    ///
869    /// ## Resolution
870    ///
871    /// Check the spelling for the requested command and try again. Are you sure it's defined and your configurations are loading correctly? Can you execute it?
872    #[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    /// This alias could not be found
880    ///
881    /// ## Resolution
882    ///
883    /// The alias does not exist in the current scope. It might exist in another scope or overlay or be hidden.
884    #[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    /// The registered plugin data for a plugin is invalid.
892    ///
893    /// ## Resolution
894    ///
895    /// `plugin add` the plugin again to update the data, or remove it with `plugin rm`.
896    #[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    /// A plugin failed to load.
909    ///
910    /// ## Resolution
911    ///
912    /// This is a fairly generic error. Refer to the specific error message for further details.
913    #[error("Plugin failed to load: {msg}")]
914    #[diagnostic(code(nu::shell::plugin_failed_to_load))]
915    PluginFailedToLoad { msg: String },
916
917    /// A message from a plugin failed to encode.
918    ///
919    /// ## Resolution
920    ///
921    /// This is likely a bug with the plugin itself.
922    #[error("Plugin failed to encode: {msg}")]
923    #[diagnostic(code(nu::shell::plugin_failed_to_encode))]
924    PluginFailedToEncode { msg: String },
925
926    /// A message to a plugin failed to decode.
927    ///
928    /// ## Resolution
929    ///
930    /// This is either an issue with the inputs to a plugin (bad JSON?) or a bug in the plugin itself. Fix or report as appropriate.
931    #[error("Plugin failed to decode: {msg}")]
932    #[diagnostic(code(nu::shell::plugin_failed_to_decode))]
933    PluginFailedToDecode { msg: String },
934
935    /// A custom value cannot be sent to the given plugin.
936    ///
937    /// ## Resolution
938    ///
939    /// Custom values can only be used with the plugin they came from. Use a command from that
940    /// plugin instead.
941    #[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    /// The plugin failed to encode a custom value.
953    ///
954    /// ## Resolution
955    ///
956    /// This is likely a bug with the plugin itself. The plugin may have tried to send a custom
957    /// value that is not serializable.
958    #[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    /// The plugin failed to encode a custom value.
967    ///
968    /// ## Resolution
969    ///
970    /// This may be a bug within the plugin, or the plugin may have been updated in between the
971    /// creation of the custom value and its use.
972    #[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    /// An I/O operation failed.
982    ///
983    /// ## Resolution
984    ///
985    /// This is the main I/O error, for further details check the error kind and additional context.
986    #[error(transparent)]
987    #[diagnostic(transparent)]
988    Io(#[from] io::IoError),
989
990    /// A name was not found. Did you mean a different name?
991    ///
992    /// ## Resolution
993    ///
994    /// The error message will suggest a possible match for what you meant.
995    #[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    /// A name was not found. Did you mean a different name?
1004    ///
1005    /// ## Resolution
1006    ///
1007    /// The error message will suggest a possible match for what you meant.
1008    #[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    /// The given input must be valid UTF-8 for further processing.
1018    ///
1019    /// ## Resolution
1020    ///
1021    /// Check your input's encoding. Are there any funny characters/bytes?
1022    #[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    /// The given input must be valid UTF-8 for further processing.
1033    ///
1034    /// ## Resolution
1035    ///
1036    /// Check your input's encoding. Are there any funny characters/bytes?
1037    #[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    /// Failed to update the config due to one or more errors.
1049    ///
1050    /// ## Resolution
1051    ///
1052    /// Refer to the error messages for specific details.
1053    #[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    /// A value was missing a required column.
1061    ///
1062    /// ## Resolution
1063    ///
1064    /// Make sure the value has the required column.
1065    #[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    /// Negative value passed when positive one is required.
1074    ///
1075    /// ## Resolution
1076    ///
1077    /// Guard against negative values or check your inputs.
1078    #[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    /// This is a generic error type used for different situations.
1086    #[error(transparent)]
1087    #[diagnostic(transparent)]
1088    Generic(#[from] generic::GenericError),
1089
1090    /// This is a generic error type used for different situations.
1091    #[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    /// This is a generic error type used for different situations that need
1103    /// multiple labels.
1104    #[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        // Defaults to an empty string so it just underlines
1114        #[label(collection, "")]
1115        labels: Vec<LabeledSpan>,
1116        #[related]
1117        inner: Vec<ShellError>,
1118    },
1119
1120    /// This is a generic error type used for different situations that need
1121    /// multiple labels, minus the URL
1122    #[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        // Defaults to an empty string so it just underlines
1131        #[label(collection, "")]
1132        labels: Vec<LabeledSpan>,
1133        #[related]
1134        inner: Vec<ShellError>,
1135    },
1136
1137    /// This is a generic error type used for user and plugin-generated errors.
1138    #[error(transparent)]
1139    #[diagnostic(transparent)]
1140    LabeledError(#[from] Box<super::LabeledError>),
1141
1142    /// Attempted to use a command that has been removed from Nushell.
1143    ///
1144    /// ## Resolution
1145    ///
1146    /// Check the help for the new suggested command and update your script accordingly.
1147    #[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    /// A closure failed while running on one pipeline input value.
1157    ///
1158    /// Reports as the closure's error, with an extra label at the input value.
1159    /// See [`EvalBlockWithInputError`](eval_block_with_input::EvalBlockWithInputError).
1160    #[error(transparent)]
1161    #[diagnostic(transparent)]
1162    EvalBlockWithInput(eval_block_with_input::EvalBlockWithInputError),
1163
1164    /// Break event, which may become an error if used outside of a loop
1165    #[error("Break used outside of loop")]
1166    Break {
1167        #[label("used outside of loop")]
1168        span: Span,
1169    },
1170
1171    /// Continue event, which may become an error if used outside of a loop
1172    #[error("Continue used outside of loop")]
1173    Continue {
1174        #[label("used outside of loop")]
1175        span: Span,
1176    },
1177
1178    /// Return event, which may become an error if used outside of a custom command or closure
1179    ///
1180    /// This is no longer raised by the engine: an early `return` now leaves the block through the
1181    /// same path as a value in tail position, preserving pipeline metadata and streams (see
1182    /// `PipelineExecutionData::early_return`). The variant is kept temporarily for compatibility
1183    /// and will be removed in a future release.
1184    #[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    /// Exit event, it can still be caught by `try {..} finally {..}` block.
1196    #[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    /// The code being executed nested custom command or closure calls too deeply.
1206    ///
1207    /// ## Resolution
1208    ///
1209    /// Adjust your Nu code to recurse less deeply, or raise `$env.config.recursion_limit`.
1210    #[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    /// Operation interrupted
1219    #[error("Operation interrupted")]
1220    Interrupted {
1221        #[label("This operation was interrupted")]
1222        span: Span,
1223    },
1224
1225    /// An attempt to use, as a match guard, an expression that
1226    /// does not resolve into a boolean
1227    #[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    /// An attempt to run a command marked for constant evaluation lacking the const. eval.
1238    /// implementation.
1239    ///
1240    /// This is an internal Nushell error, please file an issue.
1241    #[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    /// TODO: Get rid of this error by moving the check before evaluation
1255    ///
1256    /// Tried evaluating of a subexpression with parsing error
1257    ///
1258    /// ## Resolution
1259    ///
1260    /// Fix the parsing error first.
1261    #[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    /// Tried assigning non-constant value to a constant
1274    ///
1275    /// ## Resolution
1276    ///
1277    /// Only a subset of expressions are allowed to be assigned as a constant during parsing.
1278    #[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    // TODO: Update help text once custom const commands are supported
1291    /// Tried running a command that is not const-compatible
1292    ///
1293    /// ## Resolution
1294    ///
1295    /// Only a subset of builtin commands can run at parse time.
1296    #[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    /// Tried getting a help message at parse time.
1307    ///
1308    /// ## Resolution
1309    ///
1310    /// Help messages are not supported at parse time.
1311    #[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    /// Invalid glob pattern
1322    ///
1323    /// ## Resolution
1324    ///
1325    /// Correct glob pattern
1326    #[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    /// Invalid unit
1338    ///
1339    /// ## Resolution
1340    ///
1341    /// Correct unit
1342    #[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    /// Tried spreading a non-list inside a list or command call.
1354    ///
1355    /// ## Resolution
1356    ///
1357    /// Only lists can be spread inside lists and command calls. Try converting the value to a list before spreading.
1358    #[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    /// Tried spreading a non-record inside a record.
1371    ///
1372    /// ## Resolution
1373    ///
1374    /// Only records can be spread inside records. Try converting the value to a record before spreading.
1375    #[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    /// Lists are not automatically spread when calling external commands
1388    ///
1389    /// ## Resolution
1390    ///
1391    /// Use the spread operator (put a '...' before the argument)
1392    #[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    /// Out of bounds.
1404    ///
1405    /// ## Resolution
1406    ///
1407    /// Make sure the range is within the bounds of the input.
1408    #[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    /// The config directory could not be found
1420    #[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    /// XDG_CONFIG_HOME was set to an invalid path
1435    #[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    /// An unexpected error occurred during IR evaluation.
1445    ///
1446    /// ## Resolution
1447    ///
1448    /// This is most likely a correctness issue with the IR compiler or evaluator. Please file a
1449    /// bug with the minimum code needed to reproduce the issue, if possible.
1450    #[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    /// Help for [`ShellError::ColumnDefinedTwice`] when a record literal spreads in a key that is
1485    /// already present, or redefines a key that a spread brought in.
1486    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            // Reports as the closure's error, so it carries that error's exit code too.
1495            Self::EvalBlockWithInput(ref err) => return err.error.external_exit_code(),
1496            _ => return None,
1497        };
1498        Some(Spanned { item, span })
1499    }
1500
1501    /// Whether this error comes from an interrupt: ctrl-c, or an external process ended by a
1502    /// signal.
1503    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        // `Return` is deprecated but still a valid variant to match on here.
1513        #[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    // TODO: Implement as From trait
1544    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    /// Convert self error to a [`ShellError::ChainedError`] variant.
1554    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                // If it's not already a chained error, it could have more errors below
1559                // it that we want to chain together
1560                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            // Also let it come from the into_full_value record.
1589            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
1641/// `ShellError` always serializes as [`LabeledError`].
1642impl 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
1651/// `ShellError` always deserializes as if it were [`LabeledError`], resulting in a
1652/// [`ShellError::LabeledError`] variant.
1653impl<'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    // Ensure that we can serialize and deserialize `ShellError`, and check that it basically would
1665    // look the same
1666    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    // We don't expect the deserialized error to be the same as the original error, but its miette
1683    // properties should be comparable
1684    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/// Represents where an error originated.
1711///
1712/// Most user-facing errors should point to a [`Span`].
1713/// When no user span is available (for internal errors), store a
1714/// [`Location`] string instead.
1715#[derive(Debug, Clone, Eq, PartialEq)]
1716pub enum ErrorSite {
1717    /// A span in user-provided Nushell code.
1718    Span(Span),
1719
1720    /// A [`Location`] string from Rust code where the error originated.
1721    ///
1722    /// For usage with [`miette`] it's easier to hold a string here instead of a [`Location`].
1723    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// TODO: implement further chaining than just one
1739#[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        // TODO: implement this less wasteful
1746        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}