2019-06-30 06:14:40 +00:00
|
|
|
use ansi_term::Color;
|
Extract core stuff into own crates
This commit extracts five new crates:
- nu-source, which contains the core source-code handling logic in Nu,
including Text, Span, and also the pretty.rs-based debug logic
- nu-parser, which is the parser and expander logic
- nu-protocol, which is the bulk of the types and basic conveniences
used by plugins
- nu-errors, which contains ShellError, ParseError and error handling
conveniences
- nu-textview, which is the textview plugin extracted into a crate
One of the major consequences of this refactor is that it's no longer
possible to `impl X for Spanned<Y>` outside of the `nu-source` crate, so
a lot of types became more concrete (Value became a concrete type
instead of Spanned<Value>, for example).
This also turned a number of inherent methods in the main nu crate into
plain functions (impl Value {} became a bunch of functions in the
`value` namespace in `crate::data::value`).
2019-11-26 02:30:48 +00:00
|
|
|
use bigdecimal::BigDecimal;
|
2019-05-10 16:59:12 +00:00
|
|
|
use derive_new::new;
|
2019-06-07 22:35:07 +00:00
|
|
|
use language_reporting::{Diagnostic, Label, Severity};
|
Extract core stuff into own crates
This commit extracts five new crates:
- nu-source, which contains the core source-code handling logic in Nu,
including Text, Span, and also the pretty.rs-based debug logic
- nu-parser, which is the parser and expander logic
- nu-protocol, which is the bulk of the types and basic conveniences
used by plugins
- nu-errors, which contains ShellError, ParseError and error handling
conveniences
- nu-textview, which is the textview plugin extracted into a crate
One of the major consequences of this refactor is that it's no longer
possible to `impl X for Spanned<Y>` outside of the `nu-source` crate, so
a lot of types became more concrete (Value became a concrete type
instead of Spanned<Value>, for example).
This also turned a number of inherent methods in the main nu crate into
plain functions (impl Value {} became a bunch of functions in the
`value` namespace in `crate::data::value`).
2019-11-26 02:30:48 +00:00
|
|
|
use nu_source::{b, DebugDocBuilder, PrettyDebug, Span, Spanned, SpannedItem, TracableContext};
|
|
|
|
use num_bigint::BigInt;
|
|
|
|
use num_traits::ToPrimitive;
|
2019-07-13 16:59:59 +00:00
|
|
|
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 19:21:03 +00:00
|
|
|
use std::fmt;
|
2019-11-04 15:47:03 +00:00
|
|
|
use std::ops::Range;
|
2019-05-10 16:59:12 +00:00
|
|
|
|
2019-12-02 16:14:05 +00:00
|
|
|
/// A structured reason for a ParseError. Note that parsing in nu is more like macro expansion in
|
|
|
|
/// other languages, so the kinds of errors that can occur during parsing are more contextual than
|
|
|
|
/// you might expect.
|
2019-10-28 14:46:50 +00:00
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
pub enum ParseErrorReason {
|
2019-12-02 16:14:05 +00:00
|
|
|
/// The parser encountered an EOF rather than what it was expecting
|
|
|
|
Eof { expected: &'static str, span: Span },
|
2019-12-04 21:14:52 +00:00
|
|
|
/// The parser expected to see the end of a token stream (possibly the token
|
|
|
|
/// stream from inside a delimited token node), but found something else.
|
|
|
|
ExtraTokens { actual: Spanned<String> },
|
2019-12-02 16:14:05 +00:00
|
|
|
/// The parser encountered something other than what it was expecting
|
2019-10-28 14:46:50 +00:00
|
|
|
Mismatch {
|
|
|
|
expected: &'static str,
|
2019-11-04 15:47:03 +00:00
|
|
|
actual: Spanned<String>,
|
2019-10-28 14:46:50 +00:00
|
|
|
},
|
2020-01-02 04:02:46 +00:00
|
|
|
|
|
|
|
/// An unexpected internal error has occurred
|
|
|
|
InternalError { message: Spanned<String> },
|
|
|
|
|
2019-12-02 16:14:05 +00:00
|
|
|
/// The parser tried to parse an argument for a command, but it failed for
|
|
|
|
/// some reason
|
2019-10-28 14:46:50 +00:00
|
|
|
ArgumentError {
|
2019-11-04 15:47:03 +00:00
|
|
|
command: Spanned<String>,
|
2019-10-28 14:46:50 +00:00
|
|
|
error: ArgumentError,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2019-12-02 16:14:05 +00:00
|
|
|
/// A newtype for `ParseErrorReason`
|
2019-10-28 14:46:50 +00:00
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
pub struct ParseError {
|
|
|
|
reason: ParseErrorReason,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ParseError {
|
2019-12-02 16:14:05 +00:00
|
|
|
/// Construct a [ParseErrorReason::Eof](ParseErrorReason::Eof)
|
2019-10-28 14:46:50 +00:00
|
|
|
pub fn unexpected_eof(expected: &'static str, span: Span) -> ParseError {
|
|
|
|
ParseError {
|
2019-11-04 15:47:03 +00:00
|
|
|
reason: ParseErrorReason::Eof { expected, span },
|
2019-10-28 14:46:50 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-04 21:14:52 +00:00
|
|
|
/// Construct a [ParseErrorReason::ExtraTokens](ParseErrorReason::ExtraTokens)
|
|
|
|
pub fn extra_tokens(actual: Spanned<impl Into<String>>) -> ParseError {
|
|
|
|
let Spanned { span, item } = actual;
|
|
|
|
|
|
|
|
ParseError {
|
|
|
|
reason: ParseErrorReason::ExtraTokens {
|
|
|
|
actual: item.into().spanned(span),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-02 16:14:05 +00:00
|
|
|
/// Construct a [ParseErrorReason::Mismatch](ParseErrorReason::Mismatch)
|
2019-11-04 15:47:03 +00:00
|
|
|
pub fn mismatch(expected: &'static str, actual: Spanned<impl Into<String>>) -> ParseError {
|
|
|
|
let Spanned { span, item } = actual;
|
2019-10-28 14:46:50 +00:00
|
|
|
|
|
|
|
ParseError {
|
|
|
|
reason: ParseErrorReason::Mismatch {
|
|
|
|
expected,
|
2019-11-04 15:47:03 +00:00
|
|
|
actual: item.into().spanned(span),
|
2019-10-28 14:46:50 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-02 04:02:46 +00:00
|
|
|
/// Construct a [ParseErrorReason::InternalError](ParseErrorReason::InternalError)
|
|
|
|
pub fn internal_error(message: Spanned<impl Into<String>>) -> ParseError {
|
|
|
|
ParseError {
|
|
|
|
reason: ParseErrorReason::InternalError {
|
|
|
|
message: message.item.into().spanned(message.span),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-02 16:14:05 +00:00
|
|
|
/// Construct a [ParseErrorReason::ArgumentError](ParseErrorReason::ArgumentError)
|
2019-11-04 15:47:03 +00:00
|
|
|
pub fn argument_error(command: Spanned<impl Into<String>>, kind: ArgumentError) -> ParseError {
|
2019-10-28 14:46:50 +00:00
|
|
|
ParseError {
|
|
|
|
reason: ParseErrorReason::ArgumentError {
|
2019-11-04 15:47:03 +00:00
|
|
|
command: command.item.into().spanned(command.span),
|
2019-10-28 14:46:50 +00:00
|
|
|
error: kind,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-02 16:14:05 +00:00
|
|
|
/// Convert a [ParseError](ParseError) into a [ShellError](ShellError)
|
2019-10-28 14:46:50 +00:00
|
|
|
impl From<ParseError> for ShellError {
|
|
|
|
fn from(error: ParseError) -> ShellError {
|
|
|
|
match error.reason {
|
2019-11-04 15:47:03 +00:00
|
|
|
ParseErrorReason::Eof { expected, span } => ShellError::unexpected_eof(expected, span),
|
2019-12-31 07:36:08 +00:00
|
|
|
ParseErrorReason::ExtraTokens { actual } => ShellError::type_error("nothing", actual),
|
2019-10-28 14:46:50 +00:00
|
|
|
ParseErrorReason::Mismatch { actual, expected } => {
|
2019-12-31 07:36:08 +00:00
|
|
|
ShellError::type_error(expected, actual)
|
2019-10-28 14:46:50 +00:00
|
|
|
}
|
2020-01-02 04:02:46 +00:00
|
|
|
ParseErrorReason::InternalError { message } => ShellError::labeled_error(
|
|
|
|
format!("Internal error: {}", message.item),
|
|
|
|
&message.item,
|
|
|
|
&message.span,
|
|
|
|
),
|
2019-11-04 15:47:03 +00:00
|
|
|
ParseErrorReason::ArgumentError { command, error } => {
|
|
|
|
ShellError::argument_error(command, error)
|
|
|
|
}
|
2019-10-28 14:46:50 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-02 16:14:05 +00:00
|
|
|
/// ArgumentError describes various ways that the parser could fail because of unexpected arguments.
|
|
|
|
/// Nu commands are like a combination of functions and macros, and these errors correspond to
|
|
|
|
/// problems that could be identified during expansion based on the syntactic signature of a
|
|
|
|
/// command.
|
2019-11-04 15:47:03 +00:00
|
|
|
#[derive(Debug, Eq, PartialEq, Clone, Ord, Hash, PartialOrd, Serialize, Deserialize)]
|
2019-06-30 06:14:40 +00:00
|
|
|
pub enum ArgumentError {
|
2019-12-02 16:14:05 +00:00
|
|
|
/// The command specified a mandatory flag, but it was missing.
|
2019-06-30 06:14:40 +00:00
|
|
|
MissingMandatoryFlag(String),
|
2019-12-02 16:14:05 +00:00
|
|
|
/// The command specified a mandatory positional argument, but it was missing.
|
2019-06-30 06:14:40 +00:00
|
|
|
MissingMandatoryPositional(String),
|
2019-12-02 16:14:05 +00:00
|
|
|
/// A flag was found, and it should have been followed by a value, but no value was found
|
2019-06-30 06:14:40 +00:00
|
|
|
MissingValueForName(String),
|
2019-12-02 16:14:05 +00:00
|
|
|
/// A sequence of characters was found that was not syntactically valid (but would have
|
|
|
|
/// been valid if the command was an external command)
|
2019-09-09 17:43:10 +00:00
|
|
|
InvalidExternalWord,
|
2019-06-30 06:14:40 +00:00
|
|
|
}
|
|
|
|
|
2019-11-25 18:07:20 +00:00
|
|
|
impl PrettyDebug for ArgumentError {
|
|
|
|
fn pretty(&self) -> DebugDocBuilder {
|
|
|
|
match self {
|
|
|
|
ArgumentError::MissingMandatoryFlag(flag) => {
|
|
|
|
b::description("missing `")
|
|
|
|
+ b::description(flag)
|
|
|
|
+ b::description("` as mandatory flag")
|
|
|
|
}
|
|
|
|
ArgumentError::MissingMandatoryPositional(pos) => {
|
|
|
|
b::description("missing `")
|
|
|
|
+ b::description(pos)
|
|
|
|
+ b::description("` as mandatory positional argument")
|
|
|
|
}
|
|
|
|
ArgumentError::MissingValueForName(name) => {
|
|
|
|
b::description("missing value for flag `")
|
|
|
|
+ b::description(name)
|
|
|
|
+ b::description("`")
|
|
|
|
}
|
|
|
|
ArgumentError::InvalidExternalWord => b::description("invalid word"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-02 16:14:05 +00:00
|
|
|
/// A `ShellError` is a proximate error and a possible cause, which could have its own cause,
|
|
|
|
/// creating a cause chain.
|
2019-11-04 15:47:03 +00:00
|
|
|
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone, Serialize, Deserialize, Hash)]
|
2019-07-09 04:31:26 +00:00
|
|
|
pub struct ShellError {
|
|
|
|
error: ProximateShellError,
|
2019-12-02 16:14:05 +00:00
|
|
|
cause: Option<Box<ShellError>>,
|
2019-05-13 17:30:51 +00:00
|
|
|
}
|
|
|
|
|
2019-12-31 07:36:08 +00:00
|
|
|
/// `PrettyDebug` is for internal debugging. For user-facing debugging, [into_diagnostic](ShellError::into_diagnostic)
|
2019-12-02 16:14:05 +00:00
|
|
|
/// is used, which prints an error, highlighting spans.
|
2019-11-25 18:07:20 +00:00
|
|
|
impl PrettyDebug for ShellError {
|
|
|
|
fn pretty(&self) -> DebugDocBuilder {
|
|
|
|
match &self.error {
|
|
|
|
ProximateShellError::SyntaxError { problem } => {
|
|
|
|
b::error("Syntax Error")
|
|
|
|
+ b::space()
|
|
|
|
+ b::delimit("(", b::description(&problem.item), ")")
|
|
|
|
}
|
|
|
|
ProximateShellError::UnexpectedEof { .. } => b::error("Unexpected end"),
|
|
|
|
ProximateShellError::TypeError { expected, actual } => {
|
|
|
|
b::error("Type Error")
|
|
|
|
+ b::space()
|
|
|
|
+ b::delimit(
|
|
|
|
"(",
|
|
|
|
b::description("expected:")
|
|
|
|
+ b::space()
|
|
|
|
+ b::description(expected)
|
|
|
|
+ b::description(",")
|
|
|
|
+ b::space()
|
|
|
|
+ b::description("actual:")
|
|
|
|
+ b::space()
|
2019-12-31 07:36:08 +00:00
|
|
|
+ b::option(actual.item.as_ref().map(b::description)),
|
2019-11-25 18:07:20 +00:00
|
|
|
")",
|
|
|
|
)
|
|
|
|
}
|
|
|
|
ProximateShellError::MissingProperty { subpath, expr } => {
|
|
|
|
b::error("Missing Property")
|
|
|
|
+ b::space()
|
|
|
|
+ b::delimit(
|
|
|
|
"(",
|
|
|
|
b::description("expr:")
|
|
|
|
+ b::space()
|
2019-12-02 16:14:05 +00:00
|
|
|
+ b::description(&expr.item)
|
2019-11-25 18:07:20 +00:00
|
|
|
+ b::description(",")
|
|
|
|
+ b::space()
|
|
|
|
+ b::description("subpath:")
|
|
|
|
+ b::space()
|
2019-12-02 16:14:05 +00:00
|
|
|
+ b::description(&subpath.item),
|
2019-11-25 18:07:20 +00:00
|
|
|
")",
|
|
|
|
)
|
|
|
|
}
|
|
|
|
ProximateShellError::InvalidIntegerIndex { subpath, .. } => {
|
|
|
|
b::error("Invalid integer index")
|
|
|
|
+ b::space()
|
|
|
|
+ b::delimit(
|
|
|
|
"(",
|
2019-12-02 16:14:05 +00:00
|
|
|
b::description("subpath:") + b::space() + b::description(&subpath.item),
|
2019-11-25 18:07:20 +00:00
|
|
|
")",
|
|
|
|
)
|
|
|
|
}
|
|
|
|
ProximateShellError::MissingValue { reason, .. } => {
|
|
|
|
b::error("Missing Value")
|
|
|
|
+ b::space()
|
|
|
|
+ b::delimit(
|
|
|
|
"(",
|
|
|
|
b::description("reason:") + b::space() + b::description(reason),
|
|
|
|
")",
|
|
|
|
)
|
|
|
|
}
|
|
|
|
ProximateShellError::ArgumentError { command, error } => {
|
|
|
|
b::error("Argument Error")
|
|
|
|
+ b::space()
|
|
|
|
+ b::delimit(
|
|
|
|
"(",
|
|
|
|
b::description("command:")
|
|
|
|
+ b::space()
|
|
|
|
+ b::description(&command.item)
|
|
|
|
+ b::description(",")
|
|
|
|
+ b::space()
|
|
|
|
+ b::description("error:")
|
|
|
|
+ b::space()
|
|
|
|
+ error.pretty(),
|
|
|
|
")",
|
|
|
|
)
|
|
|
|
}
|
|
|
|
ProximateShellError::RangeError {
|
|
|
|
kind,
|
|
|
|
actual_kind,
|
|
|
|
operation,
|
|
|
|
} => {
|
|
|
|
b::error("Range Error")
|
|
|
|
+ b::space()
|
|
|
|
+ b::delimit(
|
|
|
|
"(",
|
|
|
|
b::description("expected:")
|
|
|
|
+ b::space()
|
|
|
|
+ kind.pretty()
|
|
|
|
+ b::description(",")
|
|
|
|
+ b::space()
|
|
|
|
+ b::description("actual:")
|
|
|
|
+ b::space()
|
|
|
|
+ b::description(&actual_kind.item)
|
|
|
|
+ b::description(",")
|
|
|
|
+ b::space()
|
|
|
|
+ b::description("operation:")
|
|
|
|
+ b::space()
|
|
|
|
+ b::description(operation),
|
|
|
|
")",
|
|
|
|
)
|
|
|
|
}
|
|
|
|
ProximateShellError::Diagnostic(_) => b::error("diagnostic"),
|
|
|
|
ProximateShellError::CoerceError { left, right } => {
|
|
|
|
b::error("Coercion Error")
|
|
|
|
+ b::space()
|
|
|
|
+ b::delimit(
|
|
|
|
"(",
|
|
|
|
b::description("left:")
|
|
|
|
+ b::space()
|
|
|
|
+ b::description(&left.item)
|
|
|
|
+ b::description(",")
|
|
|
|
+ b::space()
|
|
|
|
+ b::description("right:")
|
|
|
|
+ b::space()
|
|
|
|
+ b::description(&right.item),
|
|
|
|
")",
|
|
|
|
)
|
|
|
|
}
|
|
|
|
ProximateShellError::UntaggedRuntimeError { reason } => {
|
|
|
|
b::error("Unknown Error") + b::delimit("(", b::description(reason), ")")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl std::fmt::Display for ShellError {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
write!(f, "{}", self.pretty().display())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-02 19:15:07 +00:00
|
|
|
impl serde::de::Error for ShellError {
|
|
|
|
fn custom<T>(msg: T) -> Self
|
|
|
|
where
|
|
|
|
T: std::fmt::Display,
|
|
|
|
{
|
Overhaul the coloring system
This commit replaces the previous naive coloring system with a coloring
system that is more aligned with the parser.
The main benefit of this change is that it allows us to use parsing
rules to decide how to color tokens.
For example, consider the following syntax:
```
$ ps | where cpu > 10
```
Ideally, we could color `cpu` like a column name and not a string,
because `cpu > 10` is a shorthand block syntax that expands to
`{ $it.cpu > 10 }`.
The way that we know that it's a shorthand block is that the `where`
command declares that its first parameter is a `SyntaxShape::Block`,
which allows the shorthand block form.
In order to accomplish this, we need to color the tokens in a way that
corresponds to their expanded semantics, which means that high-fidelity
coloring requires expansion.
This commit adds a `ColorSyntax` trait that corresponds to the
`ExpandExpression` trait. The semantics are fairly similar, with a few
differences.
First `ExpandExpression` consumes N tokens and returns a single
`hir::Expression`. `ColorSyntax` consumes N tokens and writes M
`FlatShape` tokens to the output.
Concretely, for syntax like `[1 2 3]`
- `ExpandExpression` takes a single token node and produces a single
`hir::Expression`
- `ColorSyntax` takes the same token node and emits 7 `FlatShape`s
(open delimiter, int, whitespace, int, whitespace, int, close
delimiter)
Second, `ColorSyntax` is more willing to plow through failures than
`ExpandExpression`.
In particular, consider syntax like
```
$ ps | where cpu >
```
In this case
- `ExpandExpression` will see that the `where` command is expecting a
block, see that it's not a literal block and try to parse it as a
shorthand block. It will successfully find a member followed by an
infix operator, but not a following expression. That means that the
entire pipeline part fails to parse and is a syntax error.
- `ColorSyntax` will also try to parse it as a shorthand block and
ultimately fail, but it will fall back to "backoff coloring mode",
which parsing any unidentified tokens in an unfallible, simple way. In
this case, `cpu` will color as a string and `>` will color as an
operator.
Finally, it's very important that coloring a pipeline infallibly colors
the entire string, doesn't fail, and doesn't get stuck in an infinite
loop.
In order to accomplish this, this PR separates `ColorSyntax`, which is
infallible from `FallibleColorSyntax`, which might fail. This allows the
type system to let us know if our coloring rules bottom out at at an
infallible rule.
It's not perfect: it's still possible for the coloring process to get
stuck or consume tokens non-atomically. I intend to reduce the
opportunity for those problems in a future commit. In the meantime, the
current system catches a number of mistakes (like trying to use a
fallible coloring rule in a loop without thinking about the possibility
that it will never terminate).
2019-10-06 20:22:50 +00:00
|
|
|
ShellError::untagged_runtime_error(msg.to_string())
|
2019-08-02 19:15:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-13 17:30:51 +00:00
|
|
|
impl ShellError {
|
Overhaul the coloring system
This commit replaces the previous naive coloring system with a coloring
system that is more aligned with the parser.
The main benefit of this change is that it allows us to use parsing
rules to decide how to color tokens.
For example, consider the following syntax:
```
$ ps | where cpu > 10
```
Ideally, we could color `cpu` like a column name and not a string,
because `cpu > 10` is a shorthand block syntax that expands to
`{ $it.cpu > 10 }`.
The way that we know that it's a shorthand block is that the `where`
command declares that its first parameter is a `SyntaxShape::Block`,
which allows the shorthand block form.
In order to accomplish this, we need to color the tokens in a way that
corresponds to their expanded semantics, which means that high-fidelity
coloring requires expansion.
This commit adds a `ColorSyntax` trait that corresponds to the
`ExpandExpression` trait. The semantics are fairly similar, with a few
differences.
First `ExpandExpression` consumes N tokens and returns a single
`hir::Expression`. `ColorSyntax` consumes N tokens and writes M
`FlatShape` tokens to the output.
Concretely, for syntax like `[1 2 3]`
- `ExpandExpression` takes a single token node and produces a single
`hir::Expression`
- `ColorSyntax` takes the same token node and emits 7 `FlatShape`s
(open delimiter, int, whitespace, int, whitespace, int, close
delimiter)
Second, `ColorSyntax` is more willing to plow through failures than
`ExpandExpression`.
In particular, consider syntax like
```
$ ps | where cpu >
```
In this case
- `ExpandExpression` will see that the `where` command is expecting a
block, see that it's not a literal block and try to parse it as a
shorthand block. It will successfully find a member followed by an
infix operator, but not a following expression. That means that the
entire pipeline part fails to parse and is a syntax error.
- `ColorSyntax` will also try to parse it as a shorthand block and
ultimately fail, but it will fall back to "backoff coloring mode",
which parsing any unidentified tokens in an unfallible, simple way. In
this case, `cpu` will color as a string and `>` will color as an
operator.
Finally, it's very important that coloring a pipeline infallibly colors
the entire string, doesn't fail, and doesn't get stuck in an infinite
loop.
In order to accomplish this, this PR separates `ColorSyntax`, which is
infallible from `FallibleColorSyntax`, which might fail. This allows the
type system to let us know if our coloring rules bottom out at at an
infallible rule.
It's not perfect: it's still possible for the coloring process to get
stuck or consume tokens non-atomically. I intend to reduce the
opportunity for those problems in a future commit. In the meantime, the
current system catches a number of mistakes (like trying to use a
fallible coloring rule in a loop without thinking about the possibility
that it will never terminate).
2019-10-06 20:22:50 +00:00
|
|
|
pub fn type_error(
|
2019-06-29 08:55:42 +00:00
|
|
|
expected: impl Into<String>,
|
2019-11-04 15:47:03 +00:00
|
|
|
actual: Spanned<impl Into<String>>,
|
2019-06-29 08:55:42 +00:00
|
|
|
) -> ShellError {
|
2019-07-09 04:31:26 +00:00
|
|
|
ProximateShellError::TypeError {
|
2019-06-29 08:55:42 +00:00
|
|
|
expected: expected.into(),
|
|
|
|
actual: actual.map(|i| Some(i.into())),
|
|
|
|
}
|
2019-07-09 04:31:26 +00:00
|
|
|
.start()
|
|
|
|
}
|
|
|
|
|
2019-11-04 15:47:03 +00:00
|
|
|
pub fn missing_property(
|
|
|
|
subpath: Spanned<impl Into<String>>,
|
|
|
|
expr: Spanned<impl Into<String>>,
|
|
|
|
) -> ShellError {
|
|
|
|
ProximateShellError::MissingProperty {
|
2019-12-02 16:14:05 +00:00
|
|
|
subpath: subpath.map(|s| s.into()),
|
|
|
|
expr: expr.map(|e| e.into()),
|
2019-11-04 15:47:03 +00:00
|
|
|
}
|
|
|
|
.start()
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn invalid_integer_index(
|
|
|
|
subpath: Spanned<impl Into<String>>,
|
|
|
|
integer: impl Into<Span>,
|
|
|
|
) -> ShellError {
|
|
|
|
ProximateShellError::InvalidIntegerIndex {
|
2019-12-02 16:14:05 +00:00
|
|
|
subpath: subpath.map(|s| s.into()),
|
2019-11-04 15:47:03 +00:00
|
|
|
integer: integer.into(),
|
|
|
|
}
|
|
|
|
.start()
|
|
|
|
}
|
|
|
|
|
Overhaul the coloring system
This commit replaces the previous naive coloring system with a coloring
system that is more aligned with the parser.
The main benefit of this change is that it allows us to use parsing
rules to decide how to color tokens.
For example, consider the following syntax:
```
$ ps | where cpu > 10
```
Ideally, we could color `cpu` like a column name and not a string,
because `cpu > 10` is a shorthand block syntax that expands to
`{ $it.cpu > 10 }`.
The way that we know that it's a shorthand block is that the `where`
command declares that its first parameter is a `SyntaxShape::Block`,
which allows the shorthand block form.
In order to accomplish this, we need to color the tokens in a way that
corresponds to their expanded semantics, which means that high-fidelity
coloring requires expansion.
This commit adds a `ColorSyntax` trait that corresponds to the
`ExpandExpression` trait. The semantics are fairly similar, with a few
differences.
First `ExpandExpression` consumes N tokens and returns a single
`hir::Expression`. `ColorSyntax` consumes N tokens and writes M
`FlatShape` tokens to the output.
Concretely, for syntax like `[1 2 3]`
- `ExpandExpression` takes a single token node and produces a single
`hir::Expression`
- `ColorSyntax` takes the same token node and emits 7 `FlatShape`s
(open delimiter, int, whitespace, int, whitespace, int, close
delimiter)
Second, `ColorSyntax` is more willing to plow through failures than
`ExpandExpression`.
In particular, consider syntax like
```
$ ps | where cpu >
```
In this case
- `ExpandExpression` will see that the `where` command is expecting a
block, see that it's not a literal block and try to parse it as a
shorthand block. It will successfully find a member followed by an
infix operator, but not a following expression. That means that the
entire pipeline part fails to parse and is a syntax error.
- `ColorSyntax` will also try to parse it as a shorthand block and
ultimately fail, but it will fall back to "backoff coloring mode",
which parsing any unidentified tokens in an unfallible, simple way. In
this case, `cpu` will color as a string and `>` will color as an
operator.
Finally, it's very important that coloring a pipeline infallibly colors
the entire string, doesn't fail, and doesn't get stuck in an infinite
loop.
In order to accomplish this, this PR separates `ColorSyntax`, which is
infallible from `FallibleColorSyntax`, which might fail. This allows the
type system to let us know if our coloring rules bottom out at at an
infallible rule.
It's not perfect: it's still possible for the coloring process to get
stuck or consume tokens non-atomically. I intend to reduce the
opportunity for those problems in a future commit. In the meantime, the
current system catches a number of mistakes (like trying to use a
fallible coloring rule in a loop without thinking about the possibility
that it will never terminate).
2019-10-06 20:22:50 +00:00
|
|
|
pub fn untagged_runtime_error(error: impl Into<String>) -> ShellError {
|
|
|
|
ProximateShellError::UntaggedRuntimeError {
|
|
|
|
reason: error.into(),
|
|
|
|
}
|
|
|
|
.start()
|
|
|
|
}
|
|
|
|
|
Extract core stuff into own crates
This commit extracts five new crates:
- nu-source, which contains the core source-code handling logic in Nu,
including Text, Span, and also the pretty.rs-based debug logic
- nu-parser, which is the parser and expander logic
- nu-protocol, which is the bulk of the types and basic conveniences
used by plugins
- nu-errors, which contains ShellError, ParseError and error handling
conveniences
- nu-textview, which is the textview plugin extracted into a crate
One of the major consequences of this refactor is that it's no longer
possible to `impl X for Spanned<Y>` outside of the `nu-source` crate, so
a lot of types became more concrete (Value became a concrete type
instead of Spanned<Value>, for example).
This also turned a number of inherent methods in the main nu crate into
plain functions (impl Value {} became a bunch of functions in the
`value` namespace in `crate::data::value`).
2019-11-26 02:30:48 +00:00
|
|
|
pub fn unexpected_eof(expected: impl Into<String>, span: impl Into<Span>) -> ShellError {
|
Overhaul the expansion system
The main thrust of this (very large) commit is an overhaul of the
expansion system.
The parsing pipeline is:
- Lightly parse the source file for atoms, basic delimiters and pipeline
structure into a token tree
- Expand the token tree into a HIR (high-level intermediate
representation) based upon the baseline syntax rules for expressions
and the syntactic shape of commands.
Somewhat non-traditionally, nu doesn't have an AST at all. It goes
directly from the token tree, which doesn't represent many important
distinctions (like the difference between `hello` and `5KB`) directly
into a high-level representation that doesn't have a direct
correspondence to the source code.
At a high level, nu commands work like macros, in the sense that the
syntactic shape of the invocation of a command depends on the
definition of a command.
However, commands do not have the ability to perform unrestricted
expansions of the token tree. Instead, they describe their arguments in
terms of syntactic shapes, and the expander expands the token tree into
HIR based upon that definition.
For example, the `where` command says that it takes a block as its first
required argument, and the description of the block syntactic shape
expands the syntax `cpu > 10` into HIR that represents
`{ $it.cpu > 10 }`.
This commit overhauls that system so that the syntactic shapes are
described in terms of a few new traits (`ExpandSyntax` and
`ExpandExpression` are the primary ones) that are more composable than
the previous system.
The first big win of this new system is the addition of the `ColumnPath`
shape, which looks like `cpu."max ghz"` or `package.version`.
Previously, while a variable path could look like `$it.cpu."max ghz"`,
the tail of a variable path could not be easily reused in other
contexts. Now, that tail is its own syntactic shape, and it can be used
as part of a command's signature.
This cleans up commands like `inc`, `add` and `edit` as well as
shorthand blocks, which can now look like `| where cpu."max ghz" > 10`
2019-09-17 22:26:27 +00:00
|
|
|
ProximateShellError::UnexpectedEof {
|
|
|
|
expected: expected.into(),
|
2019-11-04 15:47:03 +00:00
|
|
|
span: span.into(),
|
Overhaul the expansion system
The main thrust of this (very large) commit is an overhaul of the
expansion system.
The parsing pipeline is:
- Lightly parse the source file for atoms, basic delimiters and pipeline
structure into a token tree
- Expand the token tree into a HIR (high-level intermediate
representation) based upon the baseline syntax rules for expressions
and the syntactic shape of commands.
Somewhat non-traditionally, nu doesn't have an AST at all. It goes
directly from the token tree, which doesn't represent many important
distinctions (like the difference between `hello` and `5KB`) directly
into a high-level representation that doesn't have a direct
correspondence to the source code.
At a high level, nu commands work like macros, in the sense that the
syntactic shape of the invocation of a command depends on the
definition of a command.
However, commands do not have the ability to perform unrestricted
expansions of the token tree. Instead, they describe their arguments in
terms of syntactic shapes, and the expander expands the token tree into
HIR based upon that definition.
For example, the `where` command says that it takes a block as its first
required argument, and the description of the block syntactic shape
expands the syntax `cpu > 10` into HIR that represents
`{ $it.cpu > 10 }`.
This commit overhauls that system so that the syntactic shapes are
described in terms of a few new traits (`ExpandSyntax` and
`ExpandExpression` are the primary ones) that are more composable than
the previous system.
The first big win of this new system is the addition of the `ColumnPath`
shape, which looks like `cpu."max ghz"` or `package.version`.
Previously, while a variable path could look like `$it.cpu."max ghz"`,
the tail of a variable path could not be easily reused in other
contexts. Now, that tail is its own syntactic shape, and it can be used
as part of a command's signature.
This cleans up commands like `inc`, `add` and `edit` as well as
shorthand blocks, which can now look like `| where cpu."max ghz" > 10`
2019-09-17 22:26:27 +00:00
|
|
|
}
|
|
|
|
.start()
|
|
|
|
}
|
|
|
|
|
Extract core stuff into own crates
This commit extracts five new crates:
- nu-source, which contains the core source-code handling logic in Nu,
including Text, Span, and also the pretty.rs-based debug logic
- nu-parser, which is the parser and expander logic
- nu-protocol, which is the bulk of the types and basic conveniences
used by plugins
- nu-errors, which contains ShellError, ParseError and error handling
conveniences
- nu-textview, which is the textview plugin extracted into a crate
One of the major consequences of this refactor is that it's no longer
possible to `impl X for Spanned<Y>` outside of the `nu-source` crate, so
a lot of types became more concrete (Value became a concrete type
instead of Spanned<Value>, for example).
This also turned a number of inherent methods in the main nu crate into
plain functions (impl Value {} became a bunch of functions in the
`value` namespace in `crate::data::value`).
2019-11-26 02:30:48 +00:00
|
|
|
pub fn range_error(
|
2019-09-01 16:20:31 +00:00
|
|
|
expected: impl Into<ExpectedRange>,
|
2019-11-21 14:33:14 +00:00
|
|
|
actual: &Spanned<impl fmt::Debug>,
|
2019-11-04 15:47:03 +00:00
|
|
|
operation: impl Into<String>,
|
2019-08-30 17:29:04 +00:00
|
|
|
) -> ShellError {
|
|
|
|
ProximateShellError::RangeError {
|
|
|
|
kind: expected.into(),
|
2019-11-21 14:33:14 +00:00
|
|
|
actual_kind: format!("{:?}", actual.item).spanned(actual.span),
|
2019-11-04 15:47:03 +00:00
|
|
|
operation: operation.into(),
|
2019-08-30 17:29:04 +00:00
|
|
|
}
|
|
|
|
.start()
|
|
|
|
}
|
|
|
|
|
Extract core stuff into own crates
This commit extracts five new crates:
- nu-source, which contains the core source-code handling logic in Nu,
including Text, Span, and also the pretty.rs-based debug logic
- nu-parser, which is the parser and expander logic
- nu-protocol, which is the bulk of the types and basic conveniences
used by plugins
- nu-errors, which contains ShellError, ParseError and error handling
conveniences
- nu-textview, which is the textview plugin extracted into a crate
One of the major consequences of this refactor is that it's no longer
possible to `impl X for Spanned<Y>` outside of the `nu-source` crate, so
a lot of types became more concrete (Value became a concrete type
instead of Spanned<Value>, for example).
This also turned a number of inherent methods in the main nu crate into
plain functions (impl Value {} became a bunch of functions in the
`value` namespace in `crate::data::value`).
2019-11-26 02:30:48 +00:00
|
|
|
pub fn syntax_error(problem: Spanned<impl Into<String>>) -> ShellError {
|
2019-08-15 22:18:18 +00:00
|
|
|
ProximateShellError::SyntaxError {
|
|
|
|
problem: problem.map(|p| p.into()),
|
|
|
|
}
|
|
|
|
.start()
|
|
|
|
}
|
|
|
|
|
Extract core stuff into own crates
This commit extracts five new crates:
- nu-source, which contains the core source-code handling logic in Nu,
including Text, Span, and also the pretty.rs-based debug logic
- nu-parser, which is the parser and expander logic
- nu-protocol, which is the bulk of the types and basic conveniences
used by plugins
- nu-errors, which contains ShellError, ParseError and error handling
conveniences
- nu-textview, which is the textview plugin extracted into a crate
One of the major consequences of this refactor is that it's no longer
possible to `impl X for Spanned<Y>` outside of the `nu-source` crate, so
a lot of types became more concrete (Value became a concrete type
instead of Spanned<Value>, for example).
This also turned a number of inherent methods in the main nu crate into
plain functions (impl Value {} became a bunch of functions in the
`value` namespace in `crate::data::value`).
2019-11-26 02:30:48 +00:00
|
|
|
pub fn coerce_error(
|
2019-11-04 15:47:03 +00:00
|
|
|
left: Spanned<impl Into<String>>,
|
|
|
|
right: Spanned<impl Into<String>>,
|
2019-07-09 04:31:26 +00:00
|
|
|
) -> ShellError {
|
|
|
|
ProximateShellError::CoerceError {
|
|
|
|
left: left.map(|l| l.into()),
|
|
|
|
right: right.map(|r| r.into()),
|
|
|
|
}
|
|
|
|
.start()
|
|
|
|
}
|
|
|
|
|
Extract core stuff into own crates
This commit extracts five new crates:
- nu-source, which contains the core source-code handling logic in Nu,
including Text, Span, and also the pretty.rs-based debug logic
- nu-parser, which is the parser and expander logic
- nu-protocol, which is the bulk of the types and basic conveniences
used by plugins
- nu-errors, which contains ShellError, ParseError and error handling
conveniences
- nu-textview, which is the textview plugin extracted into a crate
One of the major consequences of this refactor is that it's no longer
possible to `impl X for Spanned<Y>` outside of the `nu-source` crate, so
a lot of types became more concrete (Value became a concrete type
instead of Spanned<Value>, for example).
This also turned a number of inherent methods in the main nu crate into
plain functions (impl Value {} became a bunch of functions in the
`value` namespace in `crate::data::value`).
2019-11-26 02:30:48 +00:00
|
|
|
pub fn argument_error(command: Spanned<impl Into<String>>, kind: ArgumentError) -> ShellError {
|
2019-07-09 04:31:26 +00:00
|
|
|
ProximateShellError::ArgumentError {
|
2019-11-04 15:47:03 +00:00
|
|
|
command: command.map(|c| c.into()),
|
2019-07-09 04:31:26 +00:00
|
|
|
error: kind,
|
|
|
|
}
|
|
|
|
.start()
|
2019-06-29 08:55:42 +00:00
|
|
|
}
|
|
|
|
|
Extract core stuff into own crates
This commit extracts five new crates:
- nu-source, which contains the core source-code handling logic in Nu,
including Text, Span, and also the pretty.rs-based debug logic
- nu-parser, which is the parser and expander logic
- nu-protocol, which is the bulk of the types and basic conveniences
used by plugins
- nu-errors, which contains ShellError, ParseError and error handling
conveniences
- nu-textview, which is the textview plugin extracted into a crate
One of the major consequences of this refactor is that it's no longer
possible to `impl X for Spanned<Y>` outside of the `nu-source` crate, so
a lot of types became more concrete (Value became a concrete type
instead of Spanned<Value>, for example).
This also turned a number of inherent methods in the main nu crate into
plain functions (impl Value {} became a bunch of functions in the
`value` namespace in `crate::data::value`).
2019-11-26 02:30:48 +00:00
|
|
|
pub fn parse_error(
|
2019-09-14 16:30:24 +00:00
|
|
|
error: nom::Err<(
|
Overhaul the expansion system
The main thrust of this (very large) commit is an overhaul of the
expansion system.
The parsing pipeline is:
- Lightly parse the source file for atoms, basic delimiters and pipeline
structure into a token tree
- Expand the token tree into a HIR (high-level intermediate
representation) based upon the baseline syntax rules for expressions
and the syntactic shape of commands.
Somewhat non-traditionally, nu doesn't have an AST at all. It goes
directly from the token tree, which doesn't represent many important
distinctions (like the difference between `hello` and `5KB`) directly
into a high-level representation that doesn't have a direct
correspondence to the source code.
At a high level, nu commands work like macros, in the sense that the
syntactic shape of the invocation of a command depends on the
definition of a command.
However, commands do not have the ability to perform unrestricted
expansions of the token tree. Instead, they describe their arguments in
terms of syntactic shapes, and the expander expands the token tree into
HIR based upon that definition.
For example, the `where` command says that it takes a block as its first
required argument, and the description of the block syntactic shape
expands the syntax `cpu > 10` into HIR that represents
`{ $it.cpu > 10 }`.
This commit overhauls that system so that the syntactic shapes are
described in terms of a few new traits (`ExpandSyntax` and
`ExpandExpression` are the primary ones) that are more composable than
the previous system.
The first big win of this new system is the addition of the `ColumnPath`
shape, which looks like `cpu."max ghz"` or `package.version`.
Previously, while a variable path could look like `$it.cpu."max ghz"`,
the tail of a variable path could not be easily reused in other
contexts. Now, that tail is its own syntactic shape, and it can be used
as part of a command's signature.
This cleans up commands like `inc`, `add` and `edit` as well as
shorthand blocks, which can now look like `| where cpu."max ghz" > 10`
2019-09-17 22:26:27 +00:00
|
|
|
nom_locate::LocatedSpanEx<&str, TracableContext>,
|
2019-09-14 16:30:24 +00:00
|
|
|
nom::error::ErrorKind,
|
|
|
|
)>,
|
2019-05-30 04:19:46 +00:00
|
|
|
) -> ShellError {
|
|
|
|
use language_reporting::*;
|
|
|
|
|
|
|
|
match error {
|
2019-08-27 21:20:18 +00:00
|
|
|
nom::Err::Incomplete(_) => {
|
|
|
|
// TODO: Get span of EOF
|
|
|
|
let diagnostic = Diagnostic::new(
|
|
|
|
Severity::Error,
|
2019-12-31 07:36:08 +00:00
|
|
|
"Parse Error: Unexpected end of line".to_string(),
|
2019-08-27 21:20:18 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
ShellError::diagnostic(diagnostic)
|
|
|
|
}
|
2019-06-22 03:43:37 +00:00
|
|
|
nom::Err::Failure(span) | nom::Err::Error(span) => {
|
2019-12-31 07:36:08 +00:00
|
|
|
let diagnostic = Diagnostic::new(Severity::Error, "Parse Error".to_string())
|
2019-10-13 04:12:43 +00:00
|
|
|
.with_label(Label::new_primary(Span::from(span.0)));
|
2019-05-30 04:19:46 +00:00
|
|
|
|
2019-06-07 22:35:07 +00:00
|
|
|
ShellError::diagnostic(diagnostic)
|
2019-07-09 04:31:26 +00:00
|
|
|
}
|
2019-05-30 04:19:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
Extract core stuff into own crates
This commit extracts five new crates:
- nu-source, which contains the core source-code handling logic in Nu,
including Text, Span, and also the pretty.rs-based debug logic
- nu-parser, which is the parser and expander logic
- nu-protocol, which is the bulk of the types and basic conveniences
used by plugins
- nu-errors, which contains ShellError, ParseError and error handling
conveniences
- nu-textview, which is the textview plugin extracted into a crate
One of the major consequences of this refactor is that it's no longer
possible to `impl X for Spanned<Y>` outside of the `nu-source` crate, so
a lot of types became more concrete (Value became a concrete type
instead of Spanned<Value>, for example).
This also turned a number of inherent methods in the main nu crate into
plain functions (impl Value {} became a bunch of functions in the
`value` namespace in `crate::data::value`).
2019-11-26 02:30:48 +00:00
|
|
|
pub fn diagnostic(diagnostic: Diagnostic<Span>) -> ShellError {
|
2019-07-09 04:31:26 +00:00
|
|
|
ProximateShellError::Diagnostic(ShellDiagnostic { diagnostic }).start()
|
2019-06-07 22:35:07 +00:00
|
|
|
}
|
|
|
|
|
2019-12-31 07:36:08 +00:00
|
|
|
pub fn into_diagnostic(self) -> Diagnostic<Span> {
|
2019-07-09 04:31:26 +00:00
|
|
|
match self.error {
|
2019-11-04 15:47:03 +00:00
|
|
|
ProximateShellError::MissingValue { span, reason } => {
|
2019-08-17 03:53:39 +00:00
|
|
|
let mut d = Diagnostic::new(
|
|
|
|
Severity::Bug,
|
|
|
|
format!("Internal Error (missing value) :: {}", reason),
|
|
|
|
);
|
|
|
|
|
2019-11-04 15:47:03 +00:00
|
|
|
if let Some(span) = span {
|
|
|
|
d = d.with_label(Label::new_primary(span));
|
2019-08-17 03:53:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
d
|
|
|
|
}
|
2019-07-09 04:31:26 +00:00
|
|
|
ProximateShellError::ArgumentError {
|
2019-07-03 20:31:15 +00:00
|
|
|
command,
|
|
|
|
error,
|
|
|
|
} => match error {
|
2019-09-09 17:43:10 +00:00
|
|
|
ArgumentError::InvalidExternalWord => Diagnostic::new(
|
|
|
|
Severity::Error,
|
2019-12-31 07:36:08 +00:00
|
|
|
"Invalid bare word for Nu command (did you intend to invoke an external command?)".to_string())
|
2019-11-04 15:47:03 +00:00
|
|
|
.with_label(Label::new_primary(command.span)),
|
2019-06-30 06:14:40 +00:00
|
|
|
ArgumentError::MissingMandatoryFlag(name) => Diagnostic::new(
|
|
|
|
Severity::Error,
|
|
|
|
format!(
|
2019-07-03 20:31:15 +00:00
|
|
|
"{} requires {}{}",
|
2019-11-04 15:47:03 +00:00
|
|
|
Color::Cyan.paint(&command.item),
|
2019-07-03 20:31:15 +00:00
|
|
|
Color::Black.bold().paint("--"),
|
|
|
|
Color::Black.bold().paint(name)
|
2019-06-30 06:14:40 +00:00
|
|
|
),
|
|
|
|
)
|
2019-11-04 15:47:03 +00:00
|
|
|
.with_label(Label::new_primary(command.span)),
|
2019-06-30 06:14:40 +00:00
|
|
|
ArgumentError::MissingMandatoryPositional(name) => Diagnostic::new(
|
|
|
|
Severity::Error,
|
2019-07-03 20:31:15 +00:00
|
|
|
format!(
|
2019-08-20 06:11:11 +00:00
|
|
|
"{} requires {} parameter",
|
2019-11-04 15:47:03 +00:00
|
|
|
Color::Cyan.paint(&command.item),
|
2019-08-20 06:11:11 +00:00
|
|
|
Color::Green.bold().paint(name.clone())
|
2019-07-03 20:31:15 +00:00
|
|
|
),
|
2019-06-30 06:14:40 +00:00
|
|
|
)
|
2019-08-20 06:11:11 +00:00
|
|
|
.with_label(
|
2019-11-04 15:47:03 +00:00
|
|
|
Label::new_primary(command.span).with_message(format!("requires {} parameter", name)),
|
2019-08-20 06:11:11 +00:00
|
|
|
),
|
2019-06-30 06:14:40 +00:00
|
|
|
ArgumentError::MissingValueForName(name) => Diagnostic::new(
|
|
|
|
Severity::Error,
|
|
|
|
format!(
|
2019-07-03 20:31:15 +00:00
|
|
|
"{} is missing value for flag {}{}",
|
2019-11-04 15:47:03 +00:00
|
|
|
Color::Cyan.paint(&command.item),
|
2019-07-03 20:31:15 +00:00
|
|
|
Color::Black.bold().paint("--"),
|
|
|
|
Color::Black.bold().paint(name)
|
2019-06-30 06:14:40 +00:00
|
|
|
),
|
|
|
|
)
|
2019-11-04 15:47:03 +00:00
|
|
|
.with_label(Label::new_primary(command.span)),
|
2019-06-30 06:14:40 +00:00
|
|
|
},
|
2019-07-09 04:31:26 +00:00
|
|
|
ProximateShellError::TypeError {
|
2019-06-29 08:55:42 +00:00
|
|
|
expected,
|
|
|
|
actual:
|
2019-11-04 15:47:03 +00:00
|
|
|
Spanned {
|
2019-06-29 08:55:42 +00:00
|
|
|
item: Some(actual),
|
2019-11-04 15:47:03 +00:00
|
|
|
span,
|
2019-06-29 08:55:42 +00:00
|
|
|
},
|
|
|
|
} => Diagnostic::new(Severity::Error, "Type Error").with_label(
|
2019-11-04 15:47:03 +00:00
|
|
|
Label::new_primary(span)
|
2019-06-29 08:55:42 +00:00
|
|
|
.with_message(format!("Expected {}, found {}", expected, actual)),
|
|
|
|
),
|
2019-07-09 04:31:26 +00:00
|
|
|
ProximateShellError::TypeError {
|
2019-06-29 08:55:42 +00:00
|
|
|
expected,
|
2019-08-01 01:58:42 +00:00
|
|
|
actual:
|
2019-11-04 15:47:03 +00:00
|
|
|
Spanned {
|
2019-08-01 01:58:42 +00:00
|
|
|
item: None,
|
2019-11-04 15:47:03 +00:00
|
|
|
span
|
2019-08-01 01:58:42 +00:00
|
|
|
},
|
2019-06-29 08:55:42 +00:00
|
|
|
} => Diagnostic::new(Severity::Error, "Type Error")
|
2019-11-04 15:47:03 +00:00
|
|
|
.with_label(Label::new_primary(span).with_message(expected)),
|
2019-06-24 00:55:31 +00:00
|
|
|
|
Overhaul the expansion system
The main thrust of this (very large) commit is an overhaul of the
expansion system.
The parsing pipeline is:
- Lightly parse the source file for atoms, basic delimiters and pipeline
structure into a token tree
- Expand the token tree into a HIR (high-level intermediate
representation) based upon the baseline syntax rules for expressions
and the syntactic shape of commands.
Somewhat non-traditionally, nu doesn't have an AST at all. It goes
directly from the token tree, which doesn't represent many important
distinctions (like the difference between `hello` and `5KB`) directly
into a high-level representation that doesn't have a direct
correspondence to the source code.
At a high level, nu commands work like macros, in the sense that the
syntactic shape of the invocation of a command depends on the
definition of a command.
However, commands do not have the ability to perform unrestricted
expansions of the token tree. Instead, they describe their arguments in
terms of syntactic shapes, and the expander expands the token tree into
HIR based upon that definition.
For example, the `where` command says that it takes a block as its first
required argument, and the description of the block syntactic shape
expands the syntax `cpu > 10` into HIR that represents
`{ $it.cpu > 10 }`.
This commit overhauls that system so that the syntactic shapes are
described in terms of a few new traits (`ExpandSyntax` and
`ExpandExpression` are the primary ones) that are more composable than
the previous system.
The first big win of this new system is the addition of the `ColumnPath`
shape, which looks like `cpu."max ghz"` or `package.version`.
Previously, while a variable path could look like `$it.cpu."max ghz"`,
the tail of a variable path could not be easily reused in other
contexts. Now, that tail is its own syntactic shape, and it can be used
as part of a command's signature.
This cleans up commands like `inc`, `add` and `edit` as well as
shorthand blocks, which can now look like `| where cpu."max ghz" > 10`
2019-09-17 22:26:27 +00:00
|
|
|
ProximateShellError::UnexpectedEof {
|
2019-11-04 15:47:03 +00:00
|
|
|
expected, span
|
2019-12-31 07:36:08 +00:00
|
|
|
} => Diagnostic::new(Severity::Error, "Unexpected end of input".to_string())
|
2019-11-04 15:47:03 +00:00
|
|
|
.with_label(Label::new_primary(span).with_message(format!("Expected {}", expected))),
|
Overhaul the expansion system
The main thrust of this (very large) commit is an overhaul of the
expansion system.
The parsing pipeline is:
- Lightly parse the source file for atoms, basic delimiters and pipeline
structure into a token tree
- Expand the token tree into a HIR (high-level intermediate
representation) based upon the baseline syntax rules for expressions
and the syntactic shape of commands.
Somewhat non-traditionally, nu doesn't have an AST at all. It goes
directly from the token tree, which doesn't represent many important
distinctions (like the difference between `hello` and `5KB`) directly
into a high-level representation that doesn't have a direct
correspondence to the source code.
At a high level, nu commands work like macros, in the sense that the
syntactic shape of the invocation of a command depends on the
definition of a command.
However, commands do not have the ability to perform unrestricted
expansions of the token tree. Instead, they describe their arguments in
terms of syntactic shapes, and the expander expands the token tree into
HIR based upon that definition.
For example, the `where` command says that it takes a block as its first
required argument, and the description of the block syntactic shape
expands the syntax `cpu > 10` into HIR that represents
`{ $it.cpu > 10 }`.
This commit overhauls that system so that the syntactic shapes are
described in terms of a few new traits (`ExpandSyntax` and
`ExpandExpression` are the primary ones) that are more composable than
the previous system.
The first big win of this new system is the addition of the `ColumnPath`
shape, which looks like `cpu."max ghz"` or `package.version`.
Previously, while a variable path could look like `$it.cpu."max ghz"`,
the tail of a variable path could not be easily reused in other
contexts. Now, that tail is its own syntactic shape, and it can be used
as part of a command's signature.
This cleans up commands like `inc`, `add` and `edit` as well as
shorthand blocks, which can now look like `| where cpu."max ghz" > 10`
2019-09-17 22:26:27 +00:00
|
|
|
|
2019-08-30 17:29:04 +00:00
|
|
|
ProximateShellError::RangeError {
|
|
|
|
kind,
|
2019-09-01 16:20:31 +00:00
|
|
|
operation,
|
2019-08-30 17:29:04 +00:00
|
|
|
actual_kind:
|
2019-11-04 15:47:03 +00:00
|
|
|
Spanned {
|
2019-08-30 17:29:04 +00:00
|
|
|
item,
|
2019-11-04 15:47:03 +00:00
|
|
|
span
|
2019-08-30 17:29:04 +00:00
|
|
|
},
|
|
|
|
} => Diagnostic::new(Severity::Error, "Range Error").with_label(
|
2019-11-04 15:47:03 +00:00
|
|
|
Label::new_primary(span).with_message(format!(
|
2019-09-01 16:20:31 +00:00
|
|
|
"Expected to convert {} to {} while {}, but it was out of range",
|
|
|
|
item,
|
2019-12-02 16:14:05 +00:00
|
|
|
kind.display(),
|
2019-09-01 16:20:31 +00:00
|
|
|
operation
|
2019-08-30 17:29:04 +00:00
|
|
|
)),
|
|
|
|
),
|
|
|
|
|
2019-08-15 22:18:18 +00:00
|
|
|
ProximateShellError::SyntaxError {
|
|
|
|
problem:
|
2019-11-04 15:47:03 +00:00
|
|
|
Spanned {
|
|
|
|
span,
|
Overhaul the expansion system
The main thrust of this (very large) commit is an overhaul of the
expansion system.
The parsing pipeline is:
- Lightly parse the source file for atoms, basic delimiters and pipeline
structure into a token tree
- Expand the token tree into a HIR (high-level intermediate
representation) based upon the baseline syntax rules for expressions
and the syntactic shape of commands.
Somewhat non-traditionally, nu doesn't have an AST at all. It goes
directly from the token tree, which doesn't represent many important
distinctions (like the difference between `hello` and `5KB`) directly
into a high-level representation that doesn't have a direct
correspondence to the source code.
At a high level, nu commands work like macros, in the sense that the
syntactic shape of the invocation of a command depends on the
definition of a command.
However, commands do not have the ability to perform unrestricted
expansions of the token tree. Instead, they describe their arguments in
terms of syntactic shapes, and the expander expands the token tree into
HIR based upon that definition.
For example, the `where` command says that it takes a block as its first
required argument, and the description of the block syntactic shape
expands the syntax `cpu > 10` into HIR that represents
`{ $it.cpu > 10 }`.
This commit overhauls that system so that the syntactic shapes are
described in terms of a few new traits (`ExpandSyntax` and
`ExpandExpression` are the primary ones) that are more composable than
the previous system.
The first big win of this new system is the addition of the `ColumnPath`
shape, which looks like `cpu."max ghz"` or `package.version`.
Previously, while a variable path could look like `$it.cpu."max ghz"`,
the tail of a variable path could not be easily reused in other
contexts. Now, that tail is its own syntactic shape, and it can be used
as part of a command's signature.
This cleans up commands like `inc`, `add` and `edit` as well as
shorthand blocks, which can now look like `| where cpu."max ghz" > 10`
2019-09-17 22:26:27 +00:00
|
|
|
item
|
2019-08-15 22:18:18 +00:00
|
|
|
},
|
|
|
|
} => Diagnostic::new(Severity::Error, "Syntax Error")
|
2019-11-04 15:47:03 +00:00
|
|
|
.with_label(Label::new_primary(span).with_message(item)),
|
2019-08-15 22:18:18 +00:00
|
|
|
|
Overhaul the coloring system
This commit replaces the previous naive coloring system with a coloring
system that is more aligned with the parser.
The main benefit of this change is that it allows us to use parsing
rules to decide how to color tokens.
For example, consider the following syntax:
```
$ ps | where cpu > 10
```
Ideally, we could color `cpu` like a column name and not a string,
because `cpu > 10` is a shorthand block syntax that expands to
`{ $it.cpu > 10 }`.
The way that we know that it's a shorthand block is that the `where`
command declares that its first parameter is a `SyntaxShape::Block`,
which allows the shorthand block form.
In order to accomplish this, we need to color the tokens in a way that
corresponds to their expanded semantics, which means that high-fidelity
coloring requires expansion.
This commit adds a `ColorSyntax` trait that corresponds to the
`ExpandExpression` trait. The semantics are fairly similar, with a few
differences.
First `ExpandExpression` consumes N tokens and returns a single
`hir::Expression`. `ColorSyntax` consumes N tokens and writes M
`FlatShape` tokens to the output.
Concretely, for syntax like `[1 2 3]`
- `ExpandExpression` takes a single token node and produces a single
`hir::Expression`
- `ColorSyntax` takes the same token node and emits 7 `FlatShape`s
(open delimiter, int, whitespace, int, whitespace, int, close
delimiter)
Second, `ColorSyntax` is more willing to plow through failures than
`ExpandExpression`.
In particular, consider syntax like
```
$ ps | where cpu >
```
In this case
- `ExpandExpression` will see that the `where` command is expecting a
block, see that it's not a literal block and try to parse it as a
shorthand block. It will successfully find a member followed by an
infix operator, but not a following expression. That means that the
entire pipeline part fails to parse and is a syntax error.
- `ColorSyntax` will also try to parse it as a shorthand block and
ultimately fail, but it will fall back to "backoff coloring mode",
which parsing any unidentified tokens in an unfallible, simple way. In
this case, `cpu` will color as a string and `>` will color as an
operator.
Finally, it's very important that coloring a pipeline infallibly colors
the entire string, doesn't fail, and doesn't get stuck in an infinite
loop.
In order to accomplish this, this PR separates `ColorSyntax`, which is
infallible from `FallibleColorSyntax`, which might fail. This allows the
type system to let us know if our coloring rules bottom out at at an
infallible rule.
It's not perfect: it's still possible for the coloring process to get
stuck or consume tokens non-atomically. I intend to reduce the
opportunity for those problems in a future commit. In the meantime, the
current system catches a number of mistakes (like trying to use a
fallible coloring rule in a loop without thinking about the possibility
that it will never terminate).
2019-10-06 20:22:50 +00:00
|
|
|
ProximateShellError::MissingProperty { subpath, expr, .. } => {
|
2019-06-24 00:55:31 +00:00
|
|
|
|
|
|
|
let mut diag = Diagnostic::new(Severity::Error, "Missing property");
|
|
|
|
|
2019-12-02 16:14:05 +00:00
|
|
|
if subpath.span == Span::unknown() {
|
|
|
|
diag.message = format!("Missing property (for {})", subpath.item);
|
|
|
|
} else {
|
|
|
|
let subpath = Label::new_primary(subpath.span).with_message(subpath.item);
|
|
|
|
diag = diag.with_label(subpath);
|
|
|
|
|
|
|
|
if expr.span != Span::unknown() {
|
|
|
|
let expr = Label::new_primary(expr.span).with_message(expr.item);
|
|
|
|
diag = diag.with_label(expr)
|
|
|
|
}
|
2019-06-24 00:55:31 +00:00
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
diag
|
|
|
|
}
|
|
|
|
|
2019-11-04 15:47:03 +00:00
|
|
|
ProximateShellError::InvalidIntegerIndex { subpath,integer } => {
|
|
|
|
let mut diag = Diagnostic::new(Severity::Error, "Invalid integer property");
|
|
|
|
|
2019-12-02 16:14:05 +00:00
|
|
|
if subpath.span == Span::unknown() {
|
|
|
|
diag.message = format!("Invalid integer property (for {})", subpath.item)
|
|
|
|
} else {
|
|
|
|
let label = Label::new_primary(subpath.span).with_message(subpath.item);
|
|
|
|
diag = diag.with_label(label)
|
2019-11-04 15:47:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
diag = diag.with_label(Label::new_secondary(integer).with_message("integer"));
|
|
|
|
|
|
|
|
diag
|
|
|
|
}
|
|
|
|
|
2019-07-09 04:31:26 +00:00
|
|
|
ProximateShellError::Diagnostic(diag) => diag.diagnostic,
|
|
|
|
ProximateShellError::CoerceError { left, right } => {
|
2019-06-24 00:55:31 +00:00
|
|
|
Diagnostic::new(Severity::Error, "Coercion error")
|
2019-11-04 15:47:03 +00: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 00:55:31 +00:00
|
|
|
}
|
Overhaul the coloring system
This commit replaces the previous naive coloring system with a coloring
system that is more aligned with the parser.
The main benefit of this change is that it allows us to use parsing
rules to decide how to color tokens.
For example, consider the following syntax:
```
$ ps | where cpu > 10
```
Ideally, we could color `cpu` like a column name and not a string,
because `cpu > 10` is a shorthand block syntax that expands to
`{ $it.cpu > 10 }`.
The way that we know that it's a shorthand block is that the `where`
command declares that its first parameter is a `SyntaxShape::Block`,
which allows the shorthand block form.
In order to accomplish this, we need to color the tokens in a way that
corresponds to their expanded semantics, which means that high-fidelity
coloring requires expansion.
This commit adds a `ColorSyntax` trait that corresponds to the
`ExpandExpression` trait. The semantics are fairly similar, with a few
differences.
First `ExpandExpression` consumes N tokens and returns a single
`hir::Expression`. `ColorSyntax` consumes N tokens and writes M
`FlatShape` tokens to the output.
Concretely, for syntax like `[1 2 3]`
- `ExpandExpression` takes a single token node and produces a single
`hir::Expression`
- `ColorSyntax` takes the same token node and emits 7 `FlatShape`s
(open delimiter, int, whitespace, int, whitespace, int, close
delimiter)
Second, `ColorSyntax` is more willing to plow through failures than
`ExpandExpression`.
In particular, consider syntax like
```
$ ps | where cpu >
```
In this case
- `ExpandExpression` will see that the `where` command is expecting a
block, see that it's not a literal block and try to parse it as a
shorthand block. It will successfully find a member followed by an
infix operator, but not a following expression. That means that the
entire pipeline part fails to parse and is a syntax error.
- `ColorSyntax` will also try to parse it as a shorthand block and
ultimately fail, but it will fall back to "backoff coloring mode",
which parsing any unidentified tokens in an unfallible, simple way. In
this case, `cpu` will color as a string and `>` will color as an
operator.
Finally, it's very important that coloring a pipeline infallibly colors
the entire string, doesn't fail, and doesn't get stuck in an infinite
loop.
In order to accomplish this, this PR separates `ColorSyntax`, which is
infallible from `FallibleColorSyntax`, which might fail. This allows the
type system to let us know if our coloring rules bottom out at at an
infallible rule.
It's not perfect: it's still possible for the coloring process to get
stuck or consume tokens non-atomically. I intend to reduce the
opportunity for those problems in a future commit. In the meantime, the
current system catches a number of mistakes (like trying to use a
fallible coloring rule in a loop without thinking about the possibility
that it will never terminate).
2019-10-06 20:22:50 +00:00
|
|
|
|
|
|
|
ProximateShellError::UntaggedRuntimeError { reason } => Diagnostic::new(Severity::Error, format!("Error: {}", reason))
|
2019-06-24 00:55:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-13 16:59:59 +00:00
|
|
|
pub fn labeled_error(
|
2019-06-07 22:35:07 +00:00
|
|
|
msg: impl Into<String>,
|
|
|
|
label: impl Into<String>,
|
2019-11-21 14:33:14 +00:00
|
|
|
span: impl Into<Span>,
|
2019-06-07 22:35:07 +00:00
|
|
|
) -> ShellError {
|
|
|
|
ShellError::diagnostic(
|
|
|
|
Diagnostic::new(Severity::Error, msg.into())
|
2019-11-21 14:33:14 +00:00
|
|
|
.with_label(Label::new_primary(span.into()).with_message(label.into())),
|
2019-06-07 22:35:07 +00:00
|
|
|
)
|
2019-05-30 04:19:46 +00:00
|
|
|
}
|
|
|
|
|
2019-08-05 08:54:29 +00:00
|
|
|
pub fn labeled_error_with_secondary(
|
2019-06-15 18:36:17 +00:00
|
|
|
msg: impl Into<String>,
|
2019-08-05 08:54:29 +00:00
|
|
|
primary_label: impl Into<String>,
|
2019-11-21 14:33:14 +00:00
|
|
|
primary_span: impl Into<Span>,
|
2019-08-05 08:54:29 +00:00
|
|
|
secondary_label: impl Into<String>,
|
2019-11-21 14:33:14 +00:00
|
|
|
secondary_span: impl Into<Span>,
|
2019-06-15 18:36:17 +00:00
|
|
|
) -> ShellError {
|
2019-08-05 08:54:29 +00:00
|
|
|
ShellError::diagnostic(
|
|
|
|
Diagnostic::new_error(msg.into())
|
|
|
|
.with_label(
|
2019-11-21 14:33:14 +00:00
|
|
|
Label::new_primary(primary_span.into()).with_message(primary_label.into()),
|
2019-09-14 16:30:24 +00:00
|
|
|
)
|
|
|
|
.with_label(
|
2019-11-21 14:33:14 +00:00
|
|
|
Label::new_secondary(secondary_span.into())
|
2019-09-14 16:30:24 +00:00
|
|
|
.with_message(secondary_label.into()),
|
2019-08-05 08:54:29 +00:00
|
|
|
),
|
|
|
|
)
|
2019-06-15 18:36:17 +00:00
|
|
|
}
|
|
|
|
|
Extract core stuff into own crates
This commit extracts five new crates:
- nu-source, which contains the core source-code handling logic in Nu,
including Text, Span, and also the pretty.rs-based debug logic
- nu-parser, which is the parser and expander logic
- nu-protocol, which is the bulk of the types and basic conveniences
used by plugins
- nu-errors, which contains ShellError, ParseError and error handling
conveniences
- nu-textview, which is the textview plugin extracted into a crate
One of the major consequences of this refactor is that it's no longer
possible to `impl X for Spanned<Y>` outside of the `nu-source` crate, so
a lot of types became more concrete (Value became a concrete type
instead of Spanned<Value>, for example).
This also turned a number of inherent methods in the main nu crate into
plain functions (impl Value {} became a bunch of functions in the
`value` namespace in `crate::data::value`).
2019-11-26 02:30:48 +00:00
|
|
|
pub fn unimplemented(title: impl Into<String>) -> ShellError {
|
Overhaul the coloring system
This commit replaces the previous naive coloring system with a coloring
system that is more aligned with the parser.
The main benefit of this change is that it allows us to use parsing
rules to decide how to color tokens.
For example, consider the following syntax:
```
$ ps | where cpu > 10
```
Ideally, we could color `cpu` like a column name and not a string,
because `cpu > 10` is a shorthand block syntax that expands to
`{ $it.cpu > 10 }`.
The way that we know that it's a shorthand block is that the `where`
command declares that its first parameter is a `SyntaxShape::Block`,
which allows the shorthand block form.
In order to accomplish this, we need to color the tokens in a way that
corresponds to their expanded semantics, which means that high-fidelity
coloring requires expansion.
This commit adds a `ColorSyntax` trait that corresponds to the
`ExpandExpression` trait. The semantics are fairly similar, with a few
differences.
First `ExpandExpression` consumes N tokens and returns a single
`hir::Expression`. `ColorSyntax` consumes N tokens and writes M
`FlatShape` tokens to the output.
Concretely, for syntax like `[1 2 3]`
- `ExpandExpression` takes a single token node and produces a single
`hir::Expression`
- `ColorSyntax` takes the same token node and emits 7 `FlatShape`s
(open delimiter, int, whitespace, int, whitespace, int, close
delimiter)
Second, `ColorSyntax` is more willing to plow through failures than
`ExpandExpression`.
In particular, consider syntax like
```
$ ps | where cpu >
```
In this case
- `ExpandExpression` will see that the `where` command is expecting a
block, see that it's not a literal block and try to parse it as a
shorthand block. It will successfully find a member followed by an
infix operator, but not a following expression. That means that the
entire pipeline part fails to parse and is a syntax error.
- `ColorSyntax` will also try to parse it as a shorthand block and
ultimately fail, but it will fall back to "backoff coloring mode",
which parsing any unidentified tokens in an unfallible, simple way. In
this case, `cpu` will color as a string and `>` will color as an
operator.
Finally, it's very important that coloring a pipeline infallibly colors
the entire string, doesn't fail, and doesn't get stuck in an infinite
loop.
In order to accomplish this, this PR separates `ColorSyntax`, which is
infallible from `FallibleColorSyntax`, which might fail. This allows the
type system to let us know if our coloring rules bottom out at at an
infallible rule.
It's not perfect: it's still possible for the coloring process to get
stuck or consume tokens non-atomically. I intend to reduce the
opportunity for those problems in a future commit. In the meantime, the
current system catches a number of mistakes (like trying to use a
fallible coloring rule in a loop without thinking about the possibility
that it will never terminate).
2019-10-06 20:22:50 +00:00
|
|
|
ShellError::untagged_runtime_error(&format!("Unimplemented: {}", title.into()))
|
2019-06-04 21:42:31 +00:00
|
|
|
}
|
|
|
|
|
Extract core stuff into own crates
This commit extracts five new crates:
- nu-source, which contains the core source-code handling logic in Nu,
including Text, Span, and also the pretty.rs-based debug logic
- nu-parser, which is the parser and expander logic
- nu-protocol, which is the bulk of the types and basic conveniences
used by plugins
- nu-errors, which contains ShellError, ParseError and error handling
conveniences
- nu-textview, which is the textview plugin extracted into a crate
One of the major consequences of this refactor is that it's no longer
possible to `impl X for Spanned<Y>` outside of the `nu-source` crate, so
a lot of types became more concrete (Value became a concrete type
instead of Spanned<Value>, for example).
This also turned a number of inherent methods in the main nu crate into
plain functions (impl Value {} became a bunch of functions in the
`value` namespace in `crate::data::value`).
2019-11-26 02:30:48 +00:00
|
|
|
pub fn unexpected(title: impl Into<String>) -> ShellError {
|
Overhaul the coloring system
This commit replaces the previous naive coloring system with a coloring
system that is more aligned with the parser.
The main benefit of this change is that it allows us to use parsing
rules to decide how to color tokens.
For example, consider the following syntax:
```
$ ps | where cpu > 10
```
Ideally, we could color `cpu` like a column name and not a string,
because `cpu > 10` is a shorthand block syntax that expands to
`{ $it.cpu > 10 }`.
The way that we know that it's a shorthand block is that the `where`
command declares that its first parameter is a `SyntaxShape::Block`,
which allows the shorthand block form.
In order to accomplish this, we need to color the tokens in a way that
corresponds to their expanded semantics, which means that high-fidelity
coloring requires expansion.
This commit adds a `ColorSyntax` trait that corresponds to the
`ExpandExpression` trait. The semantics are fairly similar, with a few
differences.
First `ExpandExpression` consumes N tokens and returns a single
`hir::Expression`. `ColorSyntax` consumes N tokens and writes M
`FlatShape` tokens to the output.
Concretely, for syntax like `[1 2 3]`
- `ExpandExpression` takes a single token node and produces a single
`hir::Expression`
- `ColorSyntax` takes the same token node and emits 7 `FlatShape`s
(open delimiter, int, whitespace, int, whitespace, int, close
delimiter)
Second, `ColorSyntax` is more willing to plow through failures than
`ExpandExpression`.
In particular, consider syntax like
```
$ ps | where cpu >
```
In this case
- `ExpandExpression` will see that the `where` command is expecting a
block, see that it's not a literal block and try to parse it as a
shorthand block. It will successfully find a member followed by an
infix operator, but not a following expression. That means that the
entire pipeline part fails to parse and is a syntax error.
- `ColorSyntax` will also try to parse it as a shorthand block and
ultimately fail, but it will fall back to "backoff coloring mode",
which parsing any unidentified tokens in an unfallible, simple way. In
this case, `cpu` will color as a string and `>` will color as an
operator.
Finally, it's very important that coloring a pipeline infallibly colors
the entire string, doesn't fail, and doesn't get stuck in an infinite
loop.
In order to accomplish this, this PR separates `ColorSyntax`, which is
infallible from `FallibleColorSyntax`, which might fail. This allows the
type system to let us know if our coloring rules bottom out at at an
infallible rule.
It's not perfect: it's still possible for the coloring process to get
stuck or consume tokens non-atomically. I intend to reduce the
opportunity for those problems in a future commit. In the meantime, the
current system catches a number of mistakes (like trying to use a
fallible coloring rule in a loop without thinking about the possibility
that it will never terminate).
2019-10-06 20:22:50 +00:00
|
|
|
ShellError::untagged_runtime_error(&format!("Unexpected: {}", title.into()))
|
2019-06-22 03:43:37 +00:00
|
|
|
}
|
2019-05-30 04:19:46 +00:00
|
|
|
}
|
2019-05-16 21:43:36 +00:00
|
|
|
|
2019-12-02 16:14:05 +00:00
|
|
|
/// `ExpectedRange` describes a range of values that was expected by a command. In addition
|
|
|
|
/// to typical ranges, this enum allows an error to specify that the range of allowed values
|
|
|
|
/// corresponds to a particular numeric type (which is a dominant use-case for the
|
|
|
|
/// [RangeError](ProximateShellError::RangeError) error type).
|
2019-11-04 15:47:03 +00:00
|
|
|
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone, Serialize, Deserialize)]
|
2019-09-01 16:20:31 +00:00
|
|
|
pub enum ExpectedRange {
|
|
|
|
I8,
|
|
|
|
I16,
|
|
|
|
I32,
|
|
|
|
I64,
|
|
|
|
I128,
|
|
|
|
U8,
|
|
|
|
U16,
|
|
|
|
U32,
|
|
|
|
U64,
|
|
|
|
U128,
|
|
|
|
F32,
|
|
|
|
F64,
|
2019-11-04 15:47:03 +00:00
|
|
|
Usize,
|
|
|
|
Size,
|
2019-09-01 16:20:31 +00:00
|
|
|
BigInt,
|
|
|
|
BigDecimal,
|
2019-11-04 15:47:03 +00:00
|
|
|
Range { start: usize, end: usize },
|
|
|
|
}
|
|
|
|
|
2019-12-02 16:14:05 +00:00
|
|
|
/// Convert a Rust range into an [ExpectedRange](ExpectedRange).
|
2019-11-04 15:47:03 +00:00
|
|
|
impl From<Range<usize>> for ExpectedRange {
|
|
|
|
fn from(range: Range<usize>) -> Self {
|
|
|
|
ExpectedRange::Range {
|
|
|
|
start: range.start,
|
|
|
|
end: range.end,
|
|
|
|
}
|
|
|
|
}
|
2019-09-01 16:20:31 +00:00
|
|
|
}
|
|
|
|
|
2019-11-25 18:07:20 +00:00
|
|
|
impl PrettyDebug for ExpectedRange {
|
|
|
|
fn pretty(&self) -> DebugDocBuilder {
|
2019-12-02 16:14:05 +00:00
|
|
|
b::description(match self {
|
2019-09-01 16:20:31 +00:00
|
|
|
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",
|
2019-11-04 15:47:03 +00:00
|
|
|
ExpectedRange::Usize => "an list index",
|
|
|
|
ExpectedRange::Size => "a list offset",
|
2019-09-01 16:20:31 +00:00
|
|
|
ExpectedRange::BigDecimal => "a decimal",
|
|
|
|
ExpectedRange::BigInt => "an integer",
|
2019-12-02 16:14:05 +00:00
|
|
|
ExpectedRange::Range { start, end } => {
|
|
|
|
return b::description(format!("{} to {}", start, end))
|
|
|
|
}
|
|
|
|
})
|
2019-09-01 16:20:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-04 15:47:03 +00:00
|
|
|
#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Serialize, Deserialize, Hash)]
|
2019-07-09 04:31:26 +00:00
|
|
|
pub enum ProximateShellError {
|
2019-08-15 22:18:18 +00:00
|
|
|
SyntaxError {
|
2019-11-04 15:47:03 +00:00
|
|
|
problem: Spanned<String>,
|
2019-08-15 22:18:18 +00:00
|
|
|
},
|
Overhaul the expansion system
The main thrust of this (very large) commit is an overhaul of the
expansion system.
The parsing pipeline is:
- Lightly parse the source file for atoms, basic delimiters and pipeline
structure into a token tree
- Expand the token tree into a HIR (high-level intermediate
representation) based upon the baseline syntax rules for expressions
and the syntactic shape of commands.
Somewhat non-traditionally, nu doesn't have an AST at all. It goes
directly from the token tree, which doesn't represent many important
distinctions (like the difference between `hello` and `5KB`) directly
into a high-level representation that doesn't have a direct
correspondence to the source code.
At a high level, nu commands work like macros, in the sense that the
syntactic shape of the invocation of a command depends on the
definition of a command.
However, commands do not have the ability to perform unrestricted
expansions of the token tree. Instead, they describe their arguments in
terms of syntactic shapes, and the expander expands the token tree into
HIR based upon that definition.
For example, the `where` command says that it takes a block as its first
required argument, and the description of the block syntactic shape
expands the syntax `cpu > 10` into HIR that represents
`{ $it.cpu > 10 }`.
This commit overhauls that system so that the syntactic shapes are
described in terms of a few new traits (`ExpandSyntax` and
`ExpandExpression` are the primary ones) that are more composable than
the previous system.
The first big win of this new system is the addition of the `ColumnPath`
shape, which looks like `cpu."max ghz"` or `package.version`.
Previously, while a variable path could look like `$it.cpu."max ghz"`,
the tail of a variable path could not be easily reused in other
contexts. Now, that tail is its own syntactic shape, and it can be used
as part of a command's signature.
This cleans up commands like `inc`, `add` and `edit` as well as
shorthand blocks, which can now look like `| where cpu."max ghz" > 10`
2019-09-17 22:26:27 +00:00
|
|
|
UnexpectedEof {
|
|
|
|
expected: String,
|
2019-11-04 15:47:03 +00:00
|
|
|
span: Span,
|
2019-08-15 22:18:18 +00:00
|
|
|
},
|
2019-07-09 04:31:26 +00:00
|
|
|
TypeError {
|
|
|
|
expected: String,
|
2019-11-04 15:47:03 +00:00
|
|
|
actual: Spanned<Option<String>>,
|
2019-07-09 04:31:26 +00:00
|
|
|
},
|
|
|
|
MissingProperty {
|
2019-12-02 16:14:05 +00:00
|
|
|
subpath: Spanned<String>,
|
|
|
|
expr: Spanned<String>,
|
2019-11-04 15:47:03 +00:00
|
|
|
},
|
|
|
|
InvalidIntegerIndex {
|
2019-12-02 16:14:05 +00:00
|
|
|
subpath: Spanned<String>,
|
2019-11-04 15:47:03 +00:00
|
|
|
integer: Span,
|
2019-07-09 04:31:26 +00:00
|
|
|
},
|
2019-08-17 03:53:39 +00:00
|
|
|
MissingValue {
|
2019-11-04 15:47:03 +00:00
|
|
|
span: Option<Span>,
|
2019-08-17 03:53:39 +00:00
|
|
|
reason: String,
|
|
|
|
},
|
2019-07-09 04:31:26 +00:00
|
|
|
ArgumentError {
|
2019-11-04 15:47:03 +00:00
|
|
|
command: Spanned<String>,
|
2019-07-09 04:31:26 +00:00
|
|
|
error: ArgumentError,
|
|
|
|
},
|
2019-08-30 17:29:04 +00:00
|
|
|
RangeError {
|
2019-09-01 16:20:31 +00:00
|
|
|
kind: ExpectedRange,
|
2019-11-04 15:47:03 +00:00
|
|
|
actual_kind: Spanned<String>,
|
2019-09-01 16:20:31 +00:00
|
|
|
operation: String,
|
2019-08-30 17:29:04 +00:00
|
|
|
},
|
2019-07-09 04:31:26 +00:00
|
|
|
Diagnostic(ShellDiagnostic),
|
|
|
|
CoerceError {
|
2019-11-04 15:47:03 +00:00
|
|
|
left: Spanned<String>,
|
|
|
|
right: Spanned<String>,
|
2019-07-09 04:31:26 +00:00
|
|
|
},
|
Overhaul the coloring system
This commit replaces the previous naive coloring system with a coloring
system that is more aligned with the parser.
The main benefit of this change is that it allows us to use parsing
rules to decide how to color tokens.
For example, consider the following syntax:
```
$ ps | where cpu > 10
```
Ideally, we could color `cpu` like a column name and not a string,
because `cpu > 10` is a shorthand block syntax that expands to
`{ $it.cpu > 10 }`.
The way that we know that it's a shorthand block is that the `where`
command declares that its first parameter is a `SyntaxShape::Block`,
which allows the shorthand block form.
In order to accomplish this, we need to color the tokens in a way that
corresponds to their expanded semantics, which means that high-fidelity
coloring requires expansion.
This commit adds a `ColorSyntax` trait that corresponds to the
`ExpandExpression` trait. The semantics are fairly similar, with a few
differences.
First `ExpandExpression` consumes N tokens and returns a single
`hir::Expression`. `ColorSyntax` consumes N tokens and writes M
`FlatShape` tokens to the output.
Concretely, for syntax like `[1 2 3]`
- `ExpandExpression` takes a single token node and produces a single
`hir::Expression`
- `ColorSyntax` takes the same token node and emits 7 `FlatShape`s
(open delimiter, int, whitespace, int, whitespace, int, close
delimiter)
Second, `ColorSyntax` is more willing to plow through failures than
`ExpandExpression`.
In particular, consider syntax like
```
$ ps | where cpu >
```
In this case
- `ExpandExpression` will see that the `where` command is expecting a
block, see that it's not a literal block and try to parse it as a
shorthand block. It will successfully find a member followed by an
infix operator, but not a following expression. That means that the
entire pipeline part fails to parse and is a syntax error.
- `ColorSyntax` will also try to parse it as a shorthand block and
ultimately fail, but it will fall back to "backoff coloring mode",
which parsing any unidentified tokens in an unfallible, simple way. In
this case, `cpu` will color as a string and `>` will color as an
operator.
Finally, it's very important that coloring a pipeline infallibly colors
the entire string, doesn't fail, and doesn't get stuck in an infinite
loop.
In order to accomplish this, this PR separates `ColorSyntax`, which is
infallible from `FallibleColorSyntax`, which might fail. This allows the
type system to let us know if our coloring rules bottom out at at an
infallible rule.
It's not perfect: it's still possible for the coloring process to get
stuck or consume tokens non-atomically. I intend to reduce the
opportunity for those problems in a future commit. In the meantime, the
current system catches a number of mistakes (like trying to use a
fallible coloring rule in a loop without thinking about the possibility
that it will never terminate).
2019-10-06 20:22:50 +00:00
|
|
|
UntaggedRuntimeError {
|
|
|
|
reason: String,
|
|
|
|
},
|
2019-07-09 04:31:26 +00: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 19:21:03 +00:00
|
|
|
|
2019-07-09 04:31:26 +00:00
|
|
|
impl ProximateShellError {
|
|
|
|
fn start(self) -> ShellError {
|
|
|
|
ShellError {
|
|
|
|
cause: None,
|
|
|
|
error: self,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-13 16:59:59 +00:00
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
2019-05-30 04:19:46 +00:00
|
|
|
pub struct ShellDiagnostic {
|
2019-10-13 04:12:43 +00:00
|
|
|
pub(crate) diagnostic: Diagnostic<Span>,
|
2019-05-30 04:19:46 +00:00
|
|
|
}
|
|
|
|
|
2019-11-04 15:47:03 +00:00
|
|
|
impl std::hash::Hash for ShellDiagnostic {
|
|
|
|
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
|
|
|
self.diagnostic.severity.hash(state);
|
|
|
|
self.diagnostic.code.hash(state);
|
|
|
|
self.diagnostic.message.hash(state);
|
|
|
|
|
|
|
|
for label in &self.diagnostic.labels {
|
|
|
|
label.span.hash(state);
|
|
|
|
label.message.hash(state);
|
|
|
|
match label.style {
|
|
|
|
language_reporting::LabelStyle::Primary => 0.hash(state),
|
|
|
|
language_reporting::LabelStyle::Secondary => 1.hash(state),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-30 04:19:46 +00:00
|
|
|
impl PartialEq for ShellDiagnostic {
|
|
|
|
fn eq(&self, _other: &ShellDiagnostic) -> bool {
|
|
|
|
false
|
2019-05-16 21:43:36 +00:00
|
|
|
}
|
2019-05-10 16:59:12 +00:00
|
|
|
}
|
|
|
|
|
2019-05-30 04:19:46 +00: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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-01 05:50:16 +00:00
|
|
|
#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, new, Clone, Serialize, Deserialize)]
|
2019-05-30 04:19:46 +00:00
|
|
|
pub struct StringError {
|
|
|
|
title: String,
|
2019-10-13 04:12:43 +00:00
|
|
|
error: String,
|
2019-05-30 04:19:46 +00:00
|
|
|
}
|
|
|
|
|
2019-05-10 16:59:12 +00:00
|
|
|
impl std::error::Error for ShellError {}
|
|
|
|
|
2019-08-21 12:08:23 +00:00
|
|
|
impl std::convert::From<Box<dyn std::error::Error>> for ShellError {
|
|
|
|
fn from(input: Box<dyn std::error::Error>) -> ShellError {
|
Overhaul the coloring system
This commit replaces the previous naive coloring system with a coloring
system that is more aligned with the parser.
The main benefit of this change is that it allows us to use parsing
rules to decide how to color tokens.
For example, consider the following syntax:
```
$ ps | where cpu > 10
```
Ideally, we could color `cpu` like a column name and not a string,
because `cpu > 10` is a shorthand block syntax that expands to
`{ $it.cpu > 10 }`.
The way that we know that it's a shorthand block is that the `where`
command declares that its first parameter is a `SyntaxShape::Block`,
which allows the shorthand block form.
In order to accomplish this, we need to color the tokens in a way that
corresponds to their expanded semantics, which means that high-fidelity
coloring requires expansion.
This commit adds a `ColorSyntax` trait that corresponds to the
`ExpandExpression` trait. The semantics are fairly similar, with a few
differences.
First `ExpandExpression` consumes N tokens and returns a single
`hir::Expression`. `ColorSyntax` consumes N tokens and writes M
`FlatShape` tokens to the output.
Concretely, for syntax like `[1 2 3]`
- `ExpandExpression` takes a single token node and produces a single
`hir::Expression`
- `ColorSyntax` takes the same token node and emits 7 `FlatShape`s
(open delimiter, int, whitespace, int, whitespace, int, close
delimiter)
Second, `ColorSyntax` is more willing to plow through failures than
`ExpandExpression`.
In particular, consider syntax like
```
$ ps | where cpu >
```
In this case
- `ExpandExpression` will see that the `where` command is expecting a
block, see that it's not a literal block and try to parse it as a
shorthand block. It will successfully find a member followed by an
infix operator, but not a following expression. That means that the
entire pipeline part fails to parse and is a syntax error.
- `ColorSyntax` will also try to parse it as a shorthand block and
ultimately fail, but it will fall back to "backoff coloring mode",
which parsing any unidentified tokens in an unfallible, simple way. In
this case, `cpu` will color as a string and `>` will color as an
operator.
Finally, it's very important that coloring a pipeline infallibly colors
the entire string, doesn't fail, and doesn't get stuck in an infinite
loop.
In order to accomplish this, this PR separates `ColorSyntax`, which is
infallible from `FallibleColorSyntax`, which might fail. This allows the
type system to let us know if our coloring rules bottom out at at an
infallible rule.
It's not perfect: it's still possible for the coloring process to get
stuck or consume tokens non-atomically. I intend to reduce the
opportunity for those problems in a future commit. In the meantime, the
current system catches a number of mistakes (like trying to use a
fallible coloring rule in a loop without thinking about the possibility
that it will never terminate).
2019-10-06 20:22:50 +00:00
|
|
|
ShellError::untagged_runtime_error(format!("{}", input))
|
2019-08-21 12:08:23 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-10 16:59:12 +00:00
|
|
|
impl std::convert::From<std::io::Error> for ShellError {
|
|
|
|
fn from(input: std::io::Error) -> ShellError {
|
Overhaul the coloring system
This commit replaces the previous naive coloring system with a coloring
system that is more aligned with the parser.
The main benefit of this change is that it allows us to use parsing
rules to decide how to color tokens.
For example, consider the following syntax:
```
$ ps | where cpu > 10
```
Ideally, we could color `cpu` like a column name and not a string,
because `cpu > 10` is a shorthand block syntax that expands to
`{ $it.cpu > 10 }`.
The way that we know that it's a shorthand block is that the `where`
command declares that its first parameter is a `SyntaxShape::Block`,
which allows the shorthand block form.
In order to accomplish this, we need to color the tokens in a way that
corresponds to their expanded semantics, which means that high-fidelity
coloring requires expansion.
This commit adds a `ColorSyntax` trait that corresponds to the
`ExpandExpression` trait. The semantics are fairly similar, with a few
differences.
First `ExpandExpression` consumes N tokens and returns a single
`hir::Expression`. `ColorSyntax` consumes N tokens and writes M
`FlatShape` tokens to the output.
Concretely, for syntax like `[1 2 3]`
- `ExpandExpression` takes a single token node and produces a single
`hir::Expression`
- `ColorSyntax` takes the same token node and emits 7 `FlatShape`s
(open delimiter, int, whitespace, int, whitespace, int, close
delimiter)
Second, `ColorSyntax` is more willing to plow through failures than
`ExpandExpression`.
In particular, consider syntax like
```
$ ps | where cpu >
```
In this case
- `ExpandExpression` will see that the `where` command is expecting a
block, see that it's not a literal block and try to parse it as a
shorthand block. It will successfully find a member followed by an
infix operator, but not a following expression. That means that the
entire pipeline part fails to parse and is a syntax error.
- `ColorSyntax` will also try to parse it as a shorthand block and
ultimately fail, but it will fall back to "backoff coloring mode",
which parsing any unidentified tokens in an unfallible, simple way. In
this case, `cpu` will color as a string and `>` will color as an
operator.
Finally, it's very important that coloring a pipeline infallibly colors
the entire string, doesn't fail, and doesn't get stuck in an infinite
loop.
In order to accomplish this, this PR separates `ColorSyntax`, which is
infallible from `FallibleColorSyntax`, which might fail. This allows the
type system to let us know if our coloring rules bottom out at at an
infallible rule.
It's not perfect: it's still possible for the coloring process to get
stuck or consume tokens non-atomically. I intend to reduce the
opportunity for those problems in a future commit. In the meantime, the
current system catches a number of mistakes (like trying to use a
fallible coloring rule in a loop without thinking about the possibility
that it will never terminate).
2019-10-06 20:22:50 +00:00
|
|
|
ShellError::untagged_runtime_error(format!("{}", input))
|
2019-05-10 16:59:12 +00:00
|
|
|
}
|
|
|
|
}
|
2019-05-24 04:34:43 +00:00
|
|
|
|
2019-05-24 07:29:16 +00:00
|
|
|
impl std::convert::From<subprocess::PopenError> for ShellError {
|
|
|
|
fn from(input: subprocess::PopenError) -> ShellError {
|
Overhaul the coloring system
This commit replaces the previous naive coloring system with a coloring
system that is more aligned with the parser.
The main benefit of this change is that it allows us to use parsing
rules to decide how to color tokens.
For example, consider the following syntax:
```
$ ps | where cpu > 10
```
Ideally, we could color `cpu` like a column name and not a string,
because `cpu > 10` is a shorthand block syntax that expands to
`{ $it.cpu > 10 }`.
The way that we know that it's a shorthand block is that the `where`
command declares that its first parameter is a `SyntaxShape::Block`,
which allows the shorthand block form.
In order to accomplish this, we need to color the tokens in a way that
corresponds to their expanded semantics, which means that high-fidelity
coloring requires expansion.
This commit adds a `ColorSyntax` trait that corresponds to the
`ExpandExpression` trait. The semantics are fairly similar, with a few
differences.
First `ExpandExpression` consumes N tokens and returns a single
`hir::Expression`. `ColorSyntax` consumes N tokens and writes M
`FlatShape` tokens to the output.
Concretely, for syntax like `[1 2 3]`
- `ExpandExpression` takes a single token node and produces a single
`hir::Expression`
- `ColorSyntax` takes the same token node and emits 7 `FlatShape`s
(open delimiter, int, whitespace, int, whitespace, int, close
delimiter)
Second, `ColorSyntax` is more willing to plow through failures than
`ExpandExpression`.
In particular, consider syntax like
```
$ ps | where cpu >
```
In this case
- `ExpandExpression` will see that the `where` command is expecting a
block, see that it's not a literal block and try to parse it as a
shorthand block. It will successfully find a member followed by an
infix operator, but not a following expression. That means that the
entire pipeline part fails to parse and is a syntax error.
- `ColorSyntax` will also try to parse it as a shorthand block and
ultimately fail, but it will fall back to "backoff coloring mode",
which parsing any unidentified tokens in an unfallible, simple way. In
this case, `cpu` will color as a string and `>` will color as an
operator.
Finally, it's very important that coloring a pipeline infallibly colors
the entire string, doesn't fail, and doesn't get stuck in an infinite
loop.
In order to accomplish this, this PR separates `ColorSyntax`, which is
infallible from `FallibleColorSyntax`, which might fail. This allows the
type system to let us know if our coloring rules bottom out at at an
infallible rule.
It's not perfect: it's still possible for the coloring process to get
stuck or consume tokens non-atomically. I intend to reduce the
opportunity for those problems in a future commit. In the meantime, the
current system catches a number of mistakes (like trying to use a
fallible coloring rule in a loop without thinking about the possibility
that it will never terminate).
2019-10-06 20:22:50 +00:00
|
|
|
ShellError::untagged_runtime_error(format!("{}", input))
|
2019-05-24 07:29:16 +00:00
|
|
|
}
|
|
|
|
}
|
2019-05-26 06:54:41 +00:00
|
|
|
|
2019-08-21 12:08:23 +00:00
|
|
|
impl std::convert::From<serde_yaml::Error> for ShellError {
|
|
|
|
fn from(input: serde_yaml::Error) -> ShellError {
|
Overhaul the coloring system
This commit replaces the previous naive coloring system with a coloring
system that is more aligned with the parser.
The main benefit of this change is that it allows us to use parsing
rules to decide how to color tokens.
For example, consider the following syntax:
```
$ ps | where cpu > 10
```
Ideally, we could color `cpu` like a column name and not a string,
because `cpu > 10` is a shorthand block syntax that expands to
`{ $it.cpu > 10 }`.
The way that we know that it's a shorthand block is that the `where`
command declares that its first parameter is a `SyntaxShape::Block`,
which allows the shorthand block form.
In order to accomplish this, we need to color the tokens in a way that
corresponds to their expanded semantics, which means that high-fidelity
coloring requires expansion.
This commit adds a `ColorSyntax` trait that corresponds to the
`ExpandExpression` trait. The semantics are fairly similar, with a few
differences.
First `ExpandExpression` consumes N tokens and returns a single
`hir::Expression`. `ColorSyntax` consumes N tokens and writes M
`FlatShape` tokens to the output.
Concretely, for syntax like `[1 2 3]`
- `ExpandExpression` takes a single token node and produces a single
`hir::Expression`
- `ColorSyntax` takes the same token node and emits 7 `FlatShape`s
(open delimiter, int, whitespace, int, whitespace, int, close
delimiter)
Second, `ColorSyntax` is more willing to plow through failures than
`ExpandExpression`.
In particular, consider syntax like
```
$ ps | where cpu >
```
In this case
- `ExpandExpression` will see that the `where` command is expecting a
block, see that it's not a literal block and try to parse it as a
shorthand block. It will successfully find a member followed by an
infix operator, but not a following expression. That means that the
entire pipeline part fails to parse and is a syntax error.
- `ColorSyntax` will also try to parse it as a shorthand block and
ultimately fail, but it will fall back to "backoff coloring mode",
which parsing any unidentified tokens in an unfallible, simple way. In
this case, `cpu` will color as a string and `>` will color as an
operator.
Finally, it's very important that coloring a pipeline infallibly colors
the entire string, doesn't fail, and doesn't get stuck in an infinite
loop.
In order to accomplish this, this PR separates `ColorSyntax`, which is
infallible from `FallibleColorSyntax`, which might fail. This allows the
type system to let us know if our coloring rules bottom out at at an
infallible rule.
It's not perfect: it's still possible for the coloring process to get
stuck or consume tokens non-atomically. I intend to reduce the
opportunity for those problems in a future commit. In the meantime, the
current system catches a number of mistakes (like trying to use a
fallible coloring rule in a loop without thinking about the possibility
that it will never terminate).
2019-10-06 20:22:50 +00:00
|
|
|
ShellError::untagged_runtime_error(format!("{:?}", input))
|
2019-08-21 12:08:23 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-01 05:50:16 +00:00
|
|
|
impl std::convert::From<toml::ser::Error> for ShellError {
|
|
|
|
fn from(input: toml::ser::Error) -> ShellError {
|
Overhaul the coloring system
This commit replaces the previous naive coloring system with a coloring
system that is more aligned with the parser.
The main benefit of this change is that it allows us to use parsing
rules to decide how to color tokens.
For example, consider the following syntax:
```
$ ps | where cpu > 10
```
Ideally, we could color `cpu` like a column name and not a string,
because `cpu > 10` is a shorthand block syntax that expands to
`{ $it.cpu > 10 }`.
The way that we know that it's a shorthand block is that the `where`
command declares that its first parameter is a `SyntaxShape::Block`,
which allows the shorthand block form.
In order to accomplish this, we need to color the tokens in a way that
corresponds to their expanded semantics, which means that high-fidelity
coloring requires expansion.
This commit adds a `ColorSyntax` trait that corresponds to the
`ExpandExpression` trait. The semantics are fairly similar, with a few
differences.
First `ExpandExpression` consumes N tokens and returns a single
`hir::Expression`. `ColorSyntax` consumes N tokens and writes M
`FlatShape` tokens to the output.
Concretely, for syntax like `[1 2 3]`
- `ExpandExpression` takes a single token node and produces a single
`hir::Expression`
- `ColorSyntax` takes the same token node and emits 7 `FlatShape`s
(open delimiter, int, whitespace, int, whitespace, int, close
delimiter)
Second, `ColorSyntax` is more willing to plow through failures than
`ExpandExpression`.
In particular, consider syntax like
```
$ ps | where cpu >
```
In this case
- `ExpandExpression` will see that the `where` command is expecting a
block, see that it's not a literal block and try to parse it as a
shorthand block. It will successfully find a member followed by an
infix operator, but not a following expression. That means that the
entire pipeline part fails to parse and is a syntax error.
- `ColorSyntax` will also try to parse it as a shorthand block and
ultimately fail, but it will fall back to "backoff coloring mode",
which parsing any unidentified tokens in an unfallible, simple way. In
this case, `cpu` will color as a string and `>` will color as an
operator.
Finally, it's very important that coloring a pipeline infallibly colors
the entire string, doesn't fail, and doesn't get stuck in an infinite
loop.
In order to accomplish this, this PR separates `ColorSyntax`, which is
infallible from `FallibleColorSyntax`, which might fail. This allows the
type system to let us know if our coloring rules bottom out at at an
infallible rule.
It's not perfect: it's still possible for the coloring process to get
stuck or consume tokens non-atomically. I intend to reduce the
opportunity for those problems in a future commit. In the meantime, the
current system catches a number of mistakes (like trying to use a
fallible coloring rule in a loop without thinking about the possibility
that it will never terminate).
2019-10-06 20:22:50 +00:00
|
|
|
ShellError::untagged_runtime_error(format!("{:?}", input))
|
2019-06-01 05:50:16 +00:00
|
|
|
}
|
|
|
|
}
|
2019-08-17 03:53:39 +00:00
|
|
|
|
|
|
|
impl std::convert::From<serde_json::Error> for ShellError {
|
|
|
|
fn from(input: serde_json::Error) -> ShellError {
|
Overhaul the coloring system
This commit replaces the previous naive coloring system with a coloring
system that is more aligned with the parser.
The main benefit of this change is that it allows us to use parsing
rules to decide how to color tokens.
For example, consider the following syntax:
```
$ ps | where cpu > 10
```
Ideally, we could color `cpu` like a column name and not a string,
because `cpu > 10` is a shorthand block syntax that expands to
`{ $it.cpu > 10 }`.
The way that we know that it's a shorthand block is that the `where`
command declares that its first parameter is a `SyntaxShape::Block`,
which allows the shorthand block form.
In order to accomplish this, we need to color the tokens in a way that
corresponds to their expanded semantics, which means that high-fidelity
coloring requires expansion.
This commit adds a `ColorSyntax` trait that corresponds to the
`ExpandExpression` trait. The semantics are fairly similar, with a few
differences.
First `ExpandExpression` consumes N tokens and returns a single
`hir::Expression`. `ColorSyntax` consumes N tokens and writes M
`FlatShape` tokens to the output.
Concretely, for syntax like `[1 2 3]`
- `ExpandExpression` takes a single token node and produces a single
`hir::Expression`
- `ColorSyntax` takes the same token node and emits 7 `FlatShape`s
(open delimiter, int, whitespace, int, whitespace, int, close
delimiter)
Second, `ColorSyntax` is more willing to plow through failures than
`ExpandExpression`.
In particular, consider syntax like
```
$ ps | where cpu >
```
In this case
- `ExpandExpression` will see that the `where` command is expecting a
block, see that it's not a literal block and try to parse it as a
shorthand block. It will successfully find a member followed by an
infix operator, but not a following expression. That means that the
entire pipeline part fails to parse and is a syntax error.
- `ColorSyntax` will also try to parse it as a shorthand block and
ultimately fail, but it will fall back to "backoff coloring mode",
which parsing any unidentified tokens in an unfallible, simple way. In
this case, `cpu` will color as a string and `>` will color as an
operator.
Finally, it's very important that coloring a pipeline infallibly colors
the entire string, doesn't fail, and doesn't get stuck in an infinite
loop.
In order to accomplish this, this PR separates `ColorSyntax`, which is
infallible from `FallibleColorSyntax`, which might fail. This allows the
type system to let us know if our coloring rules bottom out at at an
infallible rule.
It's not perfect: it's still possible for the coloring process to get
stuck or consume tokens non-atomically. I intend to reduce the
opportunity for those problems in a future commit. In the meantime, the
current system catches a number of mistakes (like trying to use a
fallible coloring rule in a loop without thinking about the possibility
that it will never terminate).
2019-10-06 20:22:50 +00:00
|
|
|
ShellError::untagged_runtime_error(format!("{:?}", input))
|
2019-08-17 03:53:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-24 19:36:19 +00: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 {
|
Overhaul the coloring system
This commit replaces the previous naive coloring system with a coloring
system that is more aligned with the parser.
The main benefit of this change is that it allows us to use parsing
rules to decide how to color tokens.
For example, consider the following syntax:
```
$ ps | where cpu > 10
```
Ideally, we could color `cpu` like a column name and not a string,
because `cpu > 10` is a shorthand block syntax that expands to
`{ $it.cpu > 10 }`.
The way that we know that it's a shorthand block is that the `where`
command declares that its first parameter is a `SyntaxShape::Block`,
which allows the shorthand block form.
In order to accomplish this, we need to color the tokens in a way that
corresponds to their expanded semantics, which means that high-fidelity
coloring requires expansion.
This commit adds a `ColorSyntax` trait that corresponds to the
`ExpandExpression` trait. The semantics are fairly similar, with a few
differences.
First `ExpandExpression` consumes N tokens and returns a single
`hir::Expression`. `ColorSyntax` consumes N tokens and writes M
`FlatShape` tokens to the output.
Concretely, for syntax like `[1 2 3]`
- `ExpandExpression` takes a single token node and produces a single
`hir::Expression`
- `ColorSyntax` takes the same token node and emits 7 `FlatShape`s
(open delimiter, int, whitespace, int, whitespace, int, close
delimiter)
Second, `ColorSyntax` is more willing to plow through failures than
`ExpandExpression`.
In particular, consider syntax like
```
$ ps | where cpu >
```
In this case
- `ExpandExpression` will see that the `where` command is expecting a
block, see that it's not a literal block and try to parse it as a
shorthand block. It will successfully find a member followed by an
infix operator, but not a following expression. That means that the
entire pipeline part fails to parse and is a syntax error.
- `ColorSyntax` will also try to parse it as a shorthand block and
ultimately fail, but it will fall back to "backoff coloring mode",
which parsing any unidentified tokens in an unfallible, simple way. In
this case, `cpu` will color as a string and `>` will color as an
operator.
Finally, it's very important that coloring a pipeline infallibly colors
the entire string, doesn't fail, and doesn't get stuck in an infinite
loop.
In order to accomplish this, this PR separates `ColorSyntax`, which is
infallible from `FallibleColorSyntax`, which might fail. This allows the
type system to let us know if our coloring rules bottom out at at an
infallible rule.
It's not perfect: it's still possible for the coloring process to get
stuck or consume tokens non-atomically. I intend to reduce the
opportunity for those problems in a future commit. In the meantime, the
current system catches a number of mistakes (like trying to use a
fallible coloring rule in a loop without thinking about the possibility
that it will never terminate).
2019-10-06 20:22:50 +00:00
|
|
|
ShellError::untagged_runtime_error(format!("{:?}", input))
|
2019-08-24 19:36:19 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-01 16:20:31 +00:00
|
|
|
pub trait CoerceInto<U> {
|
|
|
|
fn coerce_into(self, operation: impl Into<String>) -> Result<U, ShellError>;
|
2019-08-30 17:29:04 +00:00
|
|
|
}
|
2019-09-01 16:20:31 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-21 14:33:14 +00:00
|
|
|
impl CoerceInto<$ty> for nu_source::Tagged<BigInt> {
|
2019-09-01 16:20:31 +00:00
|
|
|
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(),
|
2019-11-21 14:33:14 +00:00
|
|
|
&self.item.spanned(self.tag.span),
|
2019-09-01 16:20:31 +00:00
|
|
|
operation.into(),
|
|
|
|
)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-21 14:33:14 +00:00
|
|
|
impl CoerceInto<$ty> for nu_source::Tagged<&BigInt> {
|
2019-09-01 16:20:31 +00:00
|
|
|
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(),
|
2019-11-21 14:33:14 +00:00
|
|
|
&self.item.spanned(self.tag.span),
|
2019-09-01 16:20:31 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-21 14:33:14 +00:00
|
|
|
impl CoerceInto<$ty> for nu_source::Tagged<BigDecimal> {
|
2019-09-01 16:20:31 +00:00
|
|
|
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(),
|
2019-11-21 14:33:14 +00:00
|
|
|
&self.item.spanned(self.tag.span),
|
2019-09-01 16:20:31 +00:00
|
|
|
operation.into(),
|
|
|
|
)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-21 14:33:14 +00:00
|
|
|
impl CoerceInto<$ty> for nu_source::Tagged<&BigDecimal> {
|
2019-09-01 16:20:31 +00:00
|
|
|
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(),
|
2019-11-21 14:33:14 +00:00
|
|
|
&self.item.spanned(self.tag.span),
|
2019-09-01 16:20:31 +00:00
|
|
|
operation.into(),
|
|
|
|
)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
ranged_decimal!(f32 -> to_f32 -> F32);
|
|
|
|
ranged_decimal!(f64 -> to_f64 -> F64);
|