nushell/src/plugins/add.rs
Yehuda Katz c2c10e2bc0 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-10 19:30:04 -07:00

93 lines
2.8 KiB
Rust

use itertools::Itertools;
use nu::{
serve_plugin, CallInfo, Plugin, ReturnSuccess, ReturnValue, ShellError, Signature, SyntaxShape,
Tagged, TaggedItem, Value,
};
pub type ColumnPath = Vec<Tagged<String>>;
struct Add {
field: Option<ColumnPath>,
value: Option<Value>,
}
impl Add {
fn new() -> Add {
Add {
field: None,
value: None,
}
}
fn add(&self, value: Tagged<Value>) -> Result<Tagged<Value>, ShellError> {
let value_tag = value.tag();
match (value.item, self.value.clone()) {
(obj @ Value::Row(_), Some(v)) => match &self.field {
Some(f) => match obj.insert_data_at_column_path(value_tag, &f, v) {
Some(v) => return Ok(v),
None => {
return Err(ShellError::labeled_error(
format!(
"add could not find place to insert field {:?} {}",
obj,
f.iter().map(|i| &i.item).join(".")
),
"column name",
value_tag,
))
}
},
None => Err(ShellError::labeled_error(
"add needs a column name when adding a value to a table",
"column name",
value_tag,
)),
},
(value, _) => Err(ShellError::type_error(
"row",
value.type_name().tagged(value_tag),
)),
}
}
}
impl Plugin for Add {
fn config(&mut self) -> Result<Signature, ShellError> {
Ok(Signature::build("add")
.desc("Add a new field to the table.")
.required("Field", SyntaxShape::ColumnPath)
.required("Value", SyntaxShape::String)
.rest(SyntaxShape::String)
.filter())
}
fn begin_filter(&mut self, call_info: CallInfo) -> Result<Vec<ReturnValue>, ShellError> {
if let Some(args) = call_info.args.positional {
match &args[0] {
table @ Tagged {
item: Value::Table(_),
..
} => {
self.field = Some(table.as_column_path()?.item);
}
value => return Err(ShellError::type_error("table", value.tagged_type_name())),
}
match &args[1] {
Tagged { item: v, .. } => {
self.value = Some(v.clone());
}
}
}
Ok(vec![])
}
fn filter(&mut self, input: Tagged<Value>) -> Result<Vec<ReturnValue>, ShellError> {
Ok(vec![ReturnSuccess::value(self.add(input)?)])
}
}
fn main() {
serve_plugin(&mut Add::new());
}