nushell/src/errors.rs

682 lines
21 KiB
Rust
Raw Normal View History

use crate::prelude::*;
2019-06-22 05:43:37 +02:00
use ansi_term::Color;
2019-05-10 18:59:12 +02:00
use derive_new::new;
2019-06-08 00:35:07 +02:00
use language_reporting::{Diagnostic, Label, Severity};
use serde::{Deserialize, Serialize};
Add support for ~ expansion This ended up being a bit of a yak shave. The basic idea in this commit is to expand `~` in paths, but only in paths. The way this is accomplished is by doing the expansion inside of the code that parses literal syntax for `SyntaxType::Path`. As a quick refresher: every command is entitled to expand its arguments in a custom way. While this could in theory be used for general-purpose macros, today the expansion facility is limited to syntactic hints. For example, the syntax `where cpu > 0` expands under the hood to `where { $it.cpu > 0 }`. This happens because the first argument to `where` is defined as a `SyntaxType::Block`, and the parser coerces binary expressions whose left-hand-side looks like a member into a block when the command is expecting one. This is mildly more magical than what most programming languages would do, but we believe that it makes sense to allow commands to fine-tune the syntax because of the domain nushell is in (command-line shells). The syntactic expansions supported by this facility are relatively limited. For example, we don't allow `$it` to become a bare word, simply because the command asks for a string in the relevant position. That would quickly become more confusing than it's worth. This PR adds a new `SyntaxType` rule: `SyntaxType::Path`. When a command declares a parameter as a `SyntaxType::Path`, string literals and bare words passed as an argument to that parameter are processed using the path expansion rules. Right now, that only means that `~` is expanded into the home directory, but additional rules are possible in the future. By restricting this expansion to a syntactic expansion when passed as an argument to a command expecting a path, we avoid making `~` a generally reserved character. This will also allow us to give good tab completion for paths with `~` characters in them when a command is expecting a path. In order to accomplish the above, this commit changes the parsing functions to take a `Context` instead of just a `CommandRegistry`. From the perspective of macro expansion, you can think of the `CommandRegistry` as a dictionary of in-scope macros, and the `Context` as the compile-time state used in expansion. This could gain additional functionality over time as we find more uses for the expansion system.
2019-08-26 21:21:03 +02:00
use std::fmt;
2019-05-10 18:59:12 +02:00
2019-06-24 02:55:31 +02:00
#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Serialize, Deserialize)]
pub enum Description {
2019-08-01 03:58:42 +02:00
Source(Tagged<String>),
2019-06-24 02:55:31 +02:00
Synthetic(String),
}
impl Description {
2019-08-01 03:58:42 +02:00
pub fn from(value: Tagged<impl Into<String>>) -> Description {
let value_span = value.span();
let value_tag = value.tag();
2019-08-01 03:58:42 +02:00
match value_span {
Span { start: 0, end: 0 } => Description::Synthetic(value.item.into()),
_ => Description::Source(Tagged::from_item(value.item.into(), value_tag)),
2019-06-24 02:55:31 +02:00
}
}
}
impl Description {
fn into_label(self) -> Result<Label<Span>, String> {
match self {
2019-08-01 03:58:42 +02:00
Description::Source(s) => Ok(Label::new_primary(s.span()).with_message(s.item)),
2019-06-24 02:55:31 +02:00
Description::Synthetic(s) => Err(s),
}
}
}
#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Serialize, Deserialize)]
pub enum ArgumentError {
MissingMandatoryFlag(String),
MissingMandatoryPositional(String),
MissingValueForName(String),
InvalidExternalWord,
}
#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Serialize, Deserialize)]
2019-07-09 06:31:26 +02:00
pub struct ShellError {
error: ProximateShellError,
cause: Option<Box<ProximateShellError>>,
}
Add support for ~ expansion This ended up being a bit of a yak shave. The basic idea in this commit is to expand `~` in paths, but only in paths. The way this is accomplished is by doing the expansion inside of the code that parses literal syntax for `SyntaxType::Path`. As a quick refresher: every command is entitled to expand its arguments in a custom way. While this could in theory be used for general-purpose macros, today the expansion facility is limited to syntactic hints. For example, the syntax `where cpu > 0` expands under the hood to `where { $it.cpu > 0 }`. This happens because the first argument to `where` is defined as a `SyntaxType::Block`, and the parser coerces binary expressions whose left-hand-side looks like a member into a block when the command is expecting one. This is mildly more magical than what most programming languages would do, but we believe that it makes sense to allow commands to fine-tune the syntax because of the domain nushell is in (command-line shells). The syntactic expansions supported by this facility are relatively limited. For example, we don't allow `$it` to become a bare word, simply because the command asks for a string in the relevant position. That would quickly become more confusing than it's worth. This PR adds a new `SyntaxType` rule: `SyntaxType::Path`. When a command declares a parameter as a `SyntaxType::Path`, string literals and bare words passed as an argument to that parameter are processed using the path expansion rules. Right now, that only means that `~` is expanded into the home directory, but additional rules are possible in the future. By restricting this expansion to a syntactic expansion when passed as an argument to a command expecting a path, we avoid making `~` a generally reserved character. This will also allow us to give good tab completion for paths with `~` characters in them when a command is expecting a path. In order to accomplish the above, this commit changes the parsing functions to take a `Context` instead of just a `CommandRegistry`. From the perspective of macro expansion, you can think of the `CommandRegistry` as a dictionary of in-scope macros, and the `Context` as the compile-time state used in expansion. This could gain additional functionality over time as we find more uses for the expansion system.
2019-08-26 21:21:03 +02:00
impl ToDebug for ShellError {
fn fmt_debug(&self, f: &mut fmt::Formatter, source: &str) -> fmt::Result {
self.error.fmt_debug(f, source)
}
}
2019-08-02 21:15:07 +02:00
impl serde::de::Error for ShellError {
fn custom<T>(msg: T) -> Self
where
T: std::fmt::Display,
{
ShellError::string(msg.to_string())
}
}
impl ShellError {
pub(crate) fn type_error(
expected: impl Into<String>,
2019-08-01 03:58:42 +02:00
actual: Tagged<impl Into<String>>,
) -> ShellError {
2019-07-09 06:31:26 +02:00
ProximateShellError::TypeError {
expected: expected.into(),
actual: actual.map(|i| Some(i.into())),
}
2019-07-09 06:31:26 +02:00
.start()
}
pub(crate) fn range_error(
expected: impl Into<ExpectedRange>,
actual: &Tagged<impl fmt::Debug>,
operation: String,
) -> ShellError {
ProximateShellError::RangeError {
kind: expected.into(),
actual_kind: actual.copy_span(format!("{:?}", actual.item)),
operation,
}
.start()
}
pub(crate) fn syntax_error(problem: Tagged<impl Into<String>>) -> ShellError {
ProximateShellError::SyntaxError {
problem: problem.map(|p| p.into()),
}
.start()
}
pub(crate) fn invalid_command(problem: impl Into<Tag>) -> ShellError {
ProximateShellError::InvalidCommand {
command: problem.into(),
}
.start()
}
pub(crate) fn coerce_error(
2019-08-01 03:58:42 +02:00
left: Tagged<impl Into<String>>,
right: Tagged<impl Into<String>>,
2019-07-09 06:31:26 +02:00
) -> ShellError {
ProximateShellError::CoerceError {
left: left.map(|l| l.into()),
right: right.map(|r| r.into()),
}
.start()
}
pub(crate) fn missing_property(subpath: Description, expr: Description) -> ShellError {
2019-07-09 06:31:26 +02:00
ProximateShellError::MissingProperty { subpath, expr }.start()
}
pub(crate) fn missing_value(span: Option<Span>, reason: impl Into<String>) -> ShellError {
ProximateShellError::MissingValue {
span,
reason: reason.into(),
}
.start()
}
pub(crate) fn argument_error(
2019-07-09 06:31:26 +02:00
command: impl Into<String>,
kind: ArgumentError,
span: Span,
) -> ShellError {
ProximateShellError::ArgumentError {
command: command.into(),
error: kind,
span,
2019-07-09 06:31:26 +02:00
}
.start()
}
pub(crate) fn invalid_external_word(span: Span) -> ShellError {
ProximateShellError::ArgumentError {
command: "Invalid argument to Nu command (did you mean to call an external command?)"
.into(),
error: ArgumentError::InvalidExternalWord,
span,
}
.start()
}
pub(crate) fn parse_error(
2019-07-16 21:10:25 +02:00
error: nom::Err<(nom5_locate::LocatedSpan<&str>, nom::error::ErrorKind)>,
) -> ShellError {
use language_reporting::*;
match error {
nom::Err::Incomplete(_) => {
// TODO: Get span of EOF
let diagnostic = Diagnostic::new(
Severity::Error,
format!("Parse Error: Unexpected end of line"),
);
ShellError::diagnostic(diagnostic)
}
2019-06-22 05:43:37 +02:00
nom::Err::Failure(span) | nom::Err::Error(span) => {
let diagnostic = Diagnostic::new(Severity::Error, format!("Parse Error"))
.with_label(Label::new_primary(Span::from(span.0)));
2019-06-08 00:35:07 +02:00
ShellError::diagnostic(diagnostic)
2019-07-09 06:31:26 +02:00
}
}
}
pub(crate) fn diagnostic(diagnostic: Diagnostic<Span>) -> ShellError {
2019-07-09 06:31:26 +02:00
ProximateShellError::Diagnostic(ShellDiagnostic { diagnostic }).start()
2019-06-08 00:35:07 +02:00
}
pub(crate) fn to_diagnostic(self) -> Diagnostic<Span> {
2019-07-09 06:31:26 +02:00
match self.error {
ProximateShellError::String(StringError { title, .. }) => {
2019-06-24 02:55:31 +02:00
Diagnostic::new(Severity::Error, title)
}
ProximateShellError::InvalidCommand { command } => {
Diagnostic::new(Severity::Error, "Invalid command")
.with_label(Label::new_primary(command.span))
}
ProximateShellError::MissingValue { span, reason } => {
let mut d = Diagnostic::new(
Severity::Bug,
format!("Internal Error (missing value) :: {}", reason),
);
if let Some(span) = span {
d = d.with_label(Label::new_primary(span));
}
d
}
2019-07-09 06:31:26 +02:00
ProximateShellError::ArgumentError {
command,
error,
span,
} => match error {
ArgumentError::InvalidExternalWord => Diagnostic::new(
Severity::Error,
format!("Invalid bare word for Nu command (did you intend to invoke an external command?)"))
.with_label(Label::new_primary(span)),
ArgumentError::MissingMandatoryFlag(name) => Diagnostic::new(
Severity::Error,
format!(
"{} requires {}{}",
Color::Cyan.paint(command),
Color::Black.bold().paint("--"),
Color::Black.bold().paint(name)
),
)
.with_label(Label::new_primary(span)),
ArgumentError::MissingMandatoryPositional(name) => Diagnostic::new(
Severity::Error,
format!(
2019-08-20 08:11:11 +02:00
"{} requires {} parameter",
Color::Cyan.paint(command),
2019-08-20 08:11:11 +02:00
Color::Green.bold().paint(name.clone())
),
)
2019-08-20 08:11:11 +02:00
.with_label(
Label::new_primary(span).with_message(format!("requires {} parameter", name)),
),
ArgumentError::MissingValueForName(name) => Diagnostic::new(
Severity::Error,
format!(
"{} is missing value for flag {}{}",
Color::Cyan.paint(command),
Color::Black.bold().paint("--"),
Color::Black.bold().paint(name)
),
)
.with_label(Label::new_primary(span)),
},
2019-07-09 06:31:26 +02:00
ProximateShellError::TypeError {
expected,
actual:
2019-08-01 03:58:42 +02:00
Tagged {
item: Some(actual),
tag: Tag { span, .. },
},
} => Diagnostic::new(Severity::Error, "Type Error").with_label(
Label::new_primary(span)
.with_message(format!("Expected {}, found {}", expected, actual)),
),
2019-07-09 06:31:26 +02:00
ProximateShellError::TypeError {
expected,
2019-08-01 03:58:42 +02:00
actual:
Tagged {
item: None,
tag: Tag { span, .. },
2019-08-01 03:58:42 +02:00
},
} => Diagnostic::new(Severity::Error, "Type Error")
.with_label(Label::new_primary(span).with_message(expected)),
2019-06-24 02:55:31 +02:00
ProximateShellError::RangeError {
kind,
operation,
actual_kind:
Tagged {
item,
tag: Tag { span, .. },
},
} => Diagnostic::new(Severity::Error, "Range Error").with_label(
Label::new_primary(span).with_message(format!(
"Expected to convert {} to {} while {}, but it was out of range",
item,
kind.desc(),
operation
)),
),
ProximateShellError::SyntaxError {
problem:
Tagged {
tag: Tag { span, .. },
..
},
} => Diagnostic::new(Severity::Error, "Syntax Error")
.with_label(Label::new_primary(span).with_message("Unexpected external command")),
2019-07-09 06:31:26 +02:00
ProximateShellError::MissingProperty { subpath, expr } => {
2019-06-24 02:55:31 +02:00
let subpath = subpath.into_label();
let expr = expr.into_label();
let mut diag = Diagnostic::new(Severity::Error, "Missing property");
match subpath {
Ok(label) => diag = diag.with_label(label),
Err(ty) => diag.message = format!("Missing property (for {})", ty),
}
if let Ok(label) = expr {
2019-08-15 18:49:07 +02:00
diag = diag.with_label(label);
2019-06-24 02:55:31 +02:00
}
diag
}
2019-07-09 06:31:26 +02:00
ProximateShellError::Diagnostic(diag) => diag.diagnostic,
ProximateShellError::CoerceError { left, right } => {
2019-06-24 02:55:31 +02:00
Diagnostic::new(Severity::Error, "Coercion error")
2019-08-01 03:58:42 +02:00
.with_label(Label::new_primary(left.span()).with_message(left.item))
.with_label(Label::new_secondary(right.span()).with_message(right.item))
2019-06-24 02:55:31 +02:00
}
}
}
pub fn labeled_error(
2019-06-08 00:35:07 +02:00
msg: impl Into<String>,
label: impl Into<String>,
span: impl Into<Span>,
2019-06-08 00:35:07 +02:00
) -> ShellError {
ShellError::diagnostic(
Diagnostic::new(Severity::Error, msg.into())
.with_label(Label::new_primary(span.into()).with_message(label.into())),
2019-06-08 00:35:07 +02:00
)
}
pub fn labeled_error_with_secondary(
2019-06-15 20:36:17 +02:00
msg: impl Into<String>,
primary_label: impl Into<String>,
primary_span: Span,
secondary_label: impl Into<String>,
secondary_span: Span,
2019-06-15 20:36:17 +02:00
) -> ShellError {
ShellError::diagnostic(
Diagnostic::new_error(msg.into())
.with_label(Label::new_primary(primary_span).with_message(primary_label.into()))
.with_label(
Label::new_secondary(secondary_span).with_message(secondary_label.into()),
),
)
2019-06-15 20:36:17 +02:00
}
2019-06-27 06:56:48 +02:00
pub fn string(title: impl Into<String>) -> ShellError {
2019-07-09 06:31:26 +02:00
ProximateShellError::String(StringError::new(title.into(), Value::nothing())).start()
}
pub(crate) fn unimplemented(title: impl Into<String>) -> ShellError {
2019-06-04 23:42:31 +02:00
ShellError::string(&format!("Unimplemented: {}", title.into()))
}
pub(crate) fn unexpected(title: impl Into<String>) -> ShellError {
2019-06-22 05:43:37 +02:00
ShellError::string(&format!("Unexpected: {}", title.into()))
}
}
2019-05-16 23:43:36 +02:00
#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Serialize, Deserialize)]
pub enum ExpectedRange {
I8,
I16,
I32,
I64,
I128,
U8,
U16,
U32,
U64,
U128,
F32,
F64,
BigInt,
BigDecimal,
}
impl ExpectedRange {
fn desc(&self) -> &'static str {
match self {
ExpectedRange::I8 => "an 8-bit signed integer",
ExpectedRange::I16 => "a 16-bit signed integer",
ExpectedRange::I32 => "a 32-bit signed integer",
ExpectedRange::I64 => "a 64-bit signed integer",
ExpectedRange::I128 => "a 128-bit signed integer",
ExpectedRange::U8 => "an 8-bit unsigned integer",
ExpectedRange::U16 => "a 16-bit unsigned integer",
ExpectedRange::U32 => "a 32-bit unsigned integer",
ExpectedRange::U64 => "a 64-bit unsigned integer",
ExpectedRange::U128 => "a 128-bit unsigned integer",
ExpectedRange::F32 => "a 32-bit float",
ExpectedRange::F64 => "a 64-bit float",
ExpectedRange::BigDecimal => "a decimal",
ExpectedRange::BigInt => "an integer",
}
}
}
2019-07-09 06:31:26 +02:00
#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Serialize, Deserialize)]
pub enum ProximateShellError {
String(StringError),
SyntaxError {
problem: Tagged<String>,
},
InvalidCommand {
command: Tag,
},
2019-07-09 06:31:26 +02:00
TypeError {
expected: String,
2019-08-01 03:58:42 +02:00
actual: Tagged<Option<String>>,
2019-07-09 06:31:26 +02:00
},
MissingProperty {
subpath: Description,
expr: Description,
},
MissingValue {
span: Option<Span>,
reason: String,
},
2019-07-09 06:31:26 +02:00
ArgumentError {
command: String,
error: ArgumentError,
span: Span,
},
RangeError {
kind: ExpectedRange,
actual_kind: Tagged<String>,
operation: String,
},
2019-07-09 06:31:26 +02:00
Diagnostic(ShellDiagnostic),
CoerceError {
2019-08-01 03:58:42 +02:00
left: Tagged<String>,
right: Tagged<String>,
2019-07-09 06:31:26 +02:00
},
}
Add support for ~ expansion This ended up being a bit of a yak shave. The basic idea in this commit is to expand `~` in paths, but only in paths. The way this is accomplished is by doing the expansion inside of the code that parses literal syntax for `SyntaxType::Path`. As a quick refresher: every command is entitled to expand its arguments in a custom way. While this could in theory be used for general-purpose macros, today the expansion facility is limited to syntactic hints. For example, the syntax `where cpu > 0` expands under the hood to `where { $it.cpu > 0 }`. This happens because the first argument to `where` is defined as a `SyntaxType::Block`, and the parser coerces binary expressions whose left-hand-side looks like a member into a block when the command is expecting one. This is mildly more magical than what most programming languages would do, but we believe that it makes sense to allow commands to fine-tune the syntax because of the domain nushell is in (command-line shells). The syntactic expansions supported by this facility are relatively limited. For example, we don't allow `$it` to become a bare word, simply because the command asks for a string in the relevant position. That would quickly become more confusing than it's worth. This PR adds a new `SyntaxType` rule: `SyntaxType::Path`. When a command declares a parameter as a `SyntaxType::Path`, string literals and bare words passed as an argument to that parameter are processed using the path expansion rules. Right now, that only means that `~` is expanded into the home directory, but additional rules are possible in the future. By restricting this expansion to a syntactic expansion when passed as an argument to a command expecting a path, we avoid making `~` a generally reserved character. This will also allow us to give good tab completion for paths with `~` characters in them when a command is expecting a path. In order to accomplish the above, this commit changes the parsing functions to take a `Context` instead of just a `CommandRegistry`. From the perspective of macro expansion, you can think of the `CommandRegistry` as a dictionary of in-scope macros, and the `Context` as the compile-time state used in expansion. This could gain additional functionality over time as we find more uses for the expansion system.
2019-08-26 21:21:03 +02:00
2019-07-09 06:31:26 +02:00
impl ProximateShellError {
fn start(self) -> ShellError {
ShellError {
cause: None,
error: self,
}
}
}
Add support for ~ expansion This ended up being a bit of a yak shave. The basic idea in this commit is to expand `~` in paths, but only in paths. The way this is accomplished is by doing the expansion inside of the code that parses literal syntax for `SyntaxType::Path`. As a quick refresher: every command is entitled to expand its arguments in a custom way. While this could in theory be used for general-purpose macros, today the expansion facility is limited to syntactic hints. For example, the syntax `where cpu > 0` expands under the hood to `where { $it.cpu > 0 }`. This happens because the first argument to `where` is defined as a `SyntaxType::Block`, and the parser coerces binary expressions whose left-hand-side looks like a member into a block when the command is expecting one. This is mildly more magical than what most programming languages would do, but we believe that it makes sense to allow commands to fine-tune the syntax because of the domain nushell is in (command-line shells). The syntactic expansions supported by this facility are relatively limited. For example, we don't allow `$it` to become a bare word, simply because the command asks for a string in the relevant position. That would quickly become more confusing than it's worth. This PR adds a new `SyntaxType` rule: `SyntaxType::Path`. When a command declares a parameter as a `SyntaxType::Path`, string literals and bare words passed as an argument to that parameter are processed using the path expansion rules. Right now, that only means that `~` is expanded into the home directory, but additional rules are possible in the future. By restricting this expansion to a syntactic expansion when passed as an argument to a command expecting a path, we avoid making `~` a generally reserved character. This will also allow us to give good tab completion for paths with `~` characters in them when a command is expecting a path. In order to accomplish the above, this commit changes the parsing functions to take a `Context` instead of just a `CommandRegistry`. From the perspective of macro expansion, you can think of the `CommandRegistry` as a dictionary of in-scope macros, and the `Context` as the compile-time state used in expansion. This could gain additional functionality over time as we find more uses for the expansion system.
2019-08-26 21:21:03 +02:00
impl ToDebug for ProximateShellError {
fn fmt_debug(&self, f: &mut fmt::Formatter, _source: &str) -> fmt::Result {
// TODO: Custom debug for inner spans
write!(f, "{:?}", self)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShellDiagnostic {
pub(crate) diagnostic: Diagnostic<Span>,
}
impl PartialEq for ShellDiagnostic {
fn eq(&self, _other: &ShellDiagnostic) -> bool {
false
2019-05-16 23:43:36 +02:00
}
2019-05-10 18:59:12 +02:00
}
impl Eq for ShellDiagnostic {}
impl std::cmp::PartialOrd for ShellDiagnostic {
fn partial_cmp(&self, _other: &Self) -> Option<std::cmp::Ordering> {
Some(std::cmp::Ordering::Less)
}
}
impl std::cmp::Ord for ShellDiagnostic {
fn cmp(&self, _other: &Self) -> std::cmp::Ordering {
std::cmp::Ordering::Less
}
}
#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, new, Clone, Serialize, Deserialize)]
pub struct StringError {
title: String,
error: Value,
}
2019-05-10 18:59:12 +02:00
impl std::fmt::Display for ShellError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
2019-07-09 06:31:26 +02:00
match &self.error {
ProximateShellError::String(s) => write!(f, "{}", &s.title),
ProximateShellError::MissingValue { .. } => write!(f, "MissingValue"),
ProximateShellError::InvalidCommand { .. } => write!(f, "InvalidCommand"),
2019-07-09 06:31:26 +02:00
ProximateShellError::TypeError { .. } => write!(f, "TypeError"),
ProximateShellError::RangeError { .. } => write!(f, "RangeError"),
ProximateShellError::SyntaxError { .. } => write!(f, "SyntaxError"),
2019-07-09 06:31:26 +02:00
ProximateShellError::MissingProperty { .. } => write!(f, "MissingProperty"),
ProximateShellError::ArgumentError { .. } => write!(f, "ArgumentError"),
ProximateShellError::Diagnostic(_) => write!(f, "<diagnostic>"),
ProximateShellError::CoerceError { .. } => write!(f, "CoerceError"),
}
2019-05-10 18:59:12 +02:00
}
}
impl std::error::Error for ShellError {}
2019-08-21 14:08:23 +02:00
impl std::convert::From<Box<dyn std::error::Error>> for ShellError {
fn from(input: Box<dyn std::error::Error>) -> ShellError {
ProximateShellError::String(StringError {
title: format!("{}", input),
error: Value::nothing(),
})
.start()
}
}
2019-05-10 18:59:12 +02:00
impl std::convert::From<std::io::Error> for ShellError {
fn from(input: std::io::Error) -> ShellError {
2019-07-09 06:31:26 +02:00
ProximateShellError::String(StringError {
2019-05-10 18:59:12 +02:00
title: format!("{}", input),
error: Value::nothing(),
})
2019-07-09 06:31:26 +02:00
.start()
2019-05-10 18:59:12 +02:00
}
}
2019-05-24 06:34:43 +02:00
2019-05-24 09:29:16 +02:00
impl std::convert::From<subprocess::PopenError> for ShellError {
fn from(input: subprocess::PopenError) -> ShellError {
2019-07-09 06:31:26 +02:00
ProximateShellError::String(StringError {
2019-05-24 09:29:16 +02:00
title: format!("{}", input),
error: Value::nothing(),
})
2019-07-09 06:31:26 +02:00
.start()
2019-05-24 09:29:16 +02:00
}
}
2019-05-26 08:54:41 +02:00
2019-08-21 14:08:23 +02:00
impl std::convert::From<serde_yaml::Error> for ShellError {
fn from(input: serde_yaml::Error) -> ShellError {
ProximateShellError::String(StringError {
title: format!("{:?}", input),
error: Value::nothing(),
})
.start()
}
}
impl std::convert::From<toml::ser::Error> for ShellError {
fn from(input: toml::ser::Error) -> ShellError {
2019-07-09 06:31:26 +02:00
ProximateShellError::String(StringError {
title: format!("{:?}", input),
error: Value::nothing(),
})
2019-07-09 06:31:26 +02:00
.start()
}
}
impl std::convert::From<serde_json::Error> for ShellError {
fn from(input: serde_json::Error) -> ShellError {
ProximateShellError::String(StringError {
title: format!("{:?}", input),
error: Value::nothing(),
})
.start()
}
}
impl std::convert::From<regex::Error> for ShellError {
fn from(input: regex::Error) -> ShellError {
ProximateShellError::String(StringError {
title: format!("{:?}", input),
error: Value::nothing(),
})
.start()
}
}
2019-08-24 21:36:19 +02:00
impl std::convert::From<Box<dyn std::error::Error + Send + Sync>> for ShellError {
fn from(input: Box<dyn std::error::Error + Send + Sync>) -> ShellError {
ProximateShellError::String(StringError {
title: format!("{:?}", input),
error: Value::nothing(),
})
.start()
}
}
pub trait ShellErrorUtils<T> {
fn unwrap_error(self, desc: impl Into<String>) -> Result<T, ShellError>;
}
impl<T> ShellErrorUtils<Tagged<T>> for Option<Tagged<T>> {
fn unwrap_error(self, desc: impl Into<String>) -> Result<Tagged<T>, ShellError> {
match self {
Some(value) => Ok(value),
None => Err(ShellError::missing_value(None, desc.into())),
}
}
}
pub trait CoerceInto<U> {
fn coerce_into(self, operation: impl Into<String>) -> Result<U, ShellError>;
}
trait ToExpectedRange {
fn to_expected_range() -> ExpectedRange;
}
macro_rules! ranged_int {
($ty:tt -> $op:tt -> $variant:tt) => {
impl ToExpectedRange for $ty {
fn to_expected_range() -> ExpectedRange {
ExpectedRange::$variant
}
}
impl CoerceInto<$ty> for Tagged<BigInt> {
fn coerce_into(self, operation: impl Into<String>) -> Result<$ty, ShellError> {
match self.$op() {
Some(v) => Ok(v),
None => Err(ShellError::range_error(
$ty::to_expected_range(),
&self,
operation.into(),
)),
}
}
}
impl CoerceInto<$ty> for Tagged<&BigInt> {
fn coerce_into(self, operation: impl Into<String>) -> Result<$ty, ShellError> {
match self.$op() {
Some(v) => Ok(v),
None => Err(ShellError::range_error(
$ty::to_expected_range(),
&self,
operation.into(),
)),
}
}
}
};
}
ranged_int!(u8 -> to_u8 -> U8);
ranged_int!(u16 -> to_u16 -> U16);
ranged_int!(u32 -> to_u32 -> U32);
ranged_int!(u64 -> to_u64 -> U64);
ranged_int!(i8 -> to_i8 -> I8);
ranged_int!(i16 -> to_i16 -> I16);
ranged_int!(i32 -> to_i32 -> I32);
ranged_int!(i64 -> to_i64 -> I64);
macro_rules! ranged_decimal {
($ty:tt -> $op:tt -> $variant:tt) => {
impl ToExpectedRange for $ty {
fn to_expected_range() -> ExpectedRange {
ExpectedRange::$variant
}
}
impl CoerceInto<$ty> for Tagged<BigDecimal> {
fn coerce_into(self, operation: impl Into<String>) -> Result<$ty, ShellError> {
match self.$op() {
Some(v) => Ok(v),
None => Err(ShellError::range_error(
$ty::to_expected_range(),
&self,
operation.into(),
)),
}
}
}
impl CoerceInto<$ty> for Tagged<&BigDecimal> {
fn coerce_into(self, operation: impl Into<String>) -> Result<$ty, ShellError> {
match self.$op() {
Some(v) => Ok(v),
None => Err(ShellError::range_error(
$ty::to_expected_range(),
&self,
operation.into(),
)),
}
}
}
};
}
ranged_decimal!(f32 -> to_f32 -> F32);
ranged_decimal!(f64 -> to_f64 -> F64);