nushell/src/evaluate/evaluator.rs

225 lines
7.6 KiB
Rust
Raw Normal View History

use crate::data::base::Block;
2019-09-23 22:24:51 +02:00
use crate::errors::ArgumentError;
use crate::evaluate::operator::apply_operator;
use crate::parser::hir::path::{ColumnPath, UnspannedPathMember};
2019-06-22 03:36:57 +02:00
use crate::parser::{
hir::{self, Expression, RawExpression},
CommandRegistry,
2019-06-22 03:36:57 +02:00
};
2019-05-28 08:45:18 +02:00
use crate::prelude::*;
2019-10-28 18:51:08 +01:00
use crate::TaggedDictBuilder;
2019-06-03 07:11:21 +02:00
use indexmap::IndexMap;
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-18 00:26:27 +02:00
use log::trace;
use nu_source::Text;
2019-05-28 08:45:18 +02:00
#[derive(Debug)]
2019-07-24 00:22:11 +02:00
pub struct Scope {
it: Value,
vars: IndexMap<String, Value>,
2019-05-28 08:45:18 +02:00
}
2019-11-18 04:12:37 +01:00
impl Scope {
pub fn new(it: Value) -> Scope {
2019-11-18 04:12:37 +01:00
Scope {
it,
vars: IndexMap::new(),
}
}
}
2019-05-28 08:45:18 +02:00
impl Scope {
pub(crate) fn empty() -> Scope {
2019-05-28 08:45:18 +02:00
Scope {
it: UntaggedValue::nothing().into_untagged_value(),
2019-06-03 07:11:21 +02:00
vars: IndexMap::new(),
2019-05-28 08:45:18 +02:00
}
}
2019-07-24 00:22:11 +02:00
pub(crate) fn it_value(value: Value) -> Scope {
2019-07-24 00:22:11 +02:00
Scope {
it: value,
vars: IndexMap::new(),
}
}
2019-05-28 08:45:18 +02:00
}
pub(crate) fn evaluate_baseline_expr(
2019-06-22 03:36:57 +02:00
expr: &Expression,
2019-07-24 00:22:11 +02:00
registry: &CommandRegistry,
2019-06-08 00:35:07 +02:00
scope: &Scope,
2019-06-22 22:46:16 +02:00
source: &Text,
) -> Result<Value, ShellError> {
let tag = Tag {
span: expr.span,
anchor: None,
};
match &expr.expr {
RawExpression::Literal(literal) => Ok(evaluate_literal(literal, source)),
RawExpression::ExternalWord => Err(ShellError::argument_error(
2019-11-04 16:47:03 +01:00
"Invalid external word".spanned(tag.span),
ArgumentError::InvalidExternalWord,
)),
RawExpression::FilePath(path) => Ok(UntaggedValue::path(path.clone()).into_value(tag)),
2019-09-13 03:54:17 +02:00
RawExpression::Synthetic(hir::Synthetic::String(s)) => {
Ok(UntaggedValue::string(s).into_untagged_value())
2019-09-13 03:54:17 +02:00
}
RawExpression::Variable(var) => evaluate_reference(var, scope, source, tag),
RawExpression::Command(_) => evaluate_command(tag, scope, source),
RawExpression::ExternalCommand(external) => evaluate_external(external, scope, source),
2019-06-22 03:36:57 +02:00
RawExpression::Binary(binary) => {
let left = evaluate_baseline_expr(binary.left(), registry, scope, source)?;
let right = evaluate_baseline_expr(binary.right(), registry, scope, source)?;
2019-05-28 08:45:18 +02:00
trace!("left={:?} right={:?}", left.value, right.value);
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-18 00:26:27 +02:00
match apply_operator(binary.op(), &left, &right) {
Ok(result) => Ok(result.into_value(tag)),
2019-07-09 06:31:26 +02:00
Err((left_type, right_type)) => Err(ShellError::coerce_error(
2019-11-04 16:47:03 +01:00
left_type.spanned(binary.left().span),
right_type.spanned(binary.right().span),
2019-07-09 06:31:26 +02:00
)),
2019-06-22 03:36:57 +02:00
}
}
2019-08-02 21:15:07 +02:00
RawExpression::List(list) => {
let mut exprs = vec![];
for expr in list {
let expr = evaluate_baseline_expr(expr, registry, scope, source)?;
exprs.push(expr);
}
Ok(UntaggedValue::Table(exprs).into_value(tag))
}
RawExpression::Block(block) => {
Ok(
UntaggedValue::Block(Block::new(block.clone(), source.clone(), tag.clone()))
.into_value(&tag),
)
2019-08-02 21:15:07 +02:00
}
2019-06-22 03:36:57 +02:00
RawExpression::Path(path) => {
let value = evaluate_baseline_expr(path.head(), registry, scope, source)?;
2019-06-24 02:55:31 +02:00
let mut item = value;
2019-05-28 08:45:18 +02:00
2019-11-04 16:47:03 +01:00
for member in path.tail() {
let next = item.get_data_by_member(member);
2019-05-28 08:45:18 +02:00
2019-06-22 03:36:57 +02:00
match next {
2019-11-04 16:47:03 +01:00
Err(err) => {
2019-09-23 22:24:51 +02:00
let possibilities = item.data_descriptors();
if let UnspannedPathMember::String(name) = &member.unspanned {
2019-11-04 16:47:03 +01:00
let mut possible_matches: Vec<_> = possibilities
.iter()
.map(|x| (natural::distance::levenshtein_distance(x, &name), x))
.collect();
possible_matches.sort();
if possible_matches.len() > 0 {
return Err(ShellError::labeled_error(
"Unknown column",
format!("did you mean '{}'?", possible_matches[0].1),
&tag,
));
} else {
return Err(err);
}
}
2019-06-24 02:55:31 +02:00
}
2019-11-04 16:47:03 +01:00
Ok(next) => {
item = next.clone().value.into_value(&tag);
2019-06-24 02:55:31 +02:00
}
2019-06-22 03:36:57 +02:00
};
}
2019-05-28 08:45:18 +02:00
Ok(item.value.clone().into_value(tag))
2019-06-22 03:36:57 +02:00
}
RawExpression::Boolean(_boolean) => unimplemented!(),
2019-05-28 08:45:18 +02:00
}
}
fn evaluate_literal(literal: &hir::Literal, source: &Text) -> Value {
match &literal.literal {
hir::RawLiteral::ColumnPath(path) => {
2019-11-04 16:47:03 +01:00
let members = path
.iter()
.map(|member| member.to_path_member(source))
.collect();
UntaggedValue::Primitive(Primitive::ColumnPath(ColumnPath::new(members)))
.into_value(&literal.span)
2019-11-04 16:47:03 +01:00
}
hir::RawLiteral::Number(int) => UntaggedValue::number(int.clone()).into_value(literal.span),
hir::RawLiteral::Size(int, unit) => unit.compute(&int).into_value(literal.span),
hir::RawLiteral::String(tag) => {
UntaggedValue::string(tag.slice(source)).into_value(literal.span)
}
hir::RawLiteral::GlobPattern(pattern) => {
UntaggedValue::pattern(pattern).into_value(literal.span)
}
hir::RawLiteral::Bare => {
UntaggedValue::string(literal.span.slice(source)).into_value(literal.span)
}
}
2019-05-28 08:45:18 +02:00
}
2019-06-22 03:36:57 +02:00
fn evaluate_reference(
name: &hir::Variable,
scope: &Scope,
2019-06-22 22:46:16 +02:00
source: &Text,
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-18 00:26:27 +02:00
tag: Tag,
) -> Result<Value, ShellError> {
trace!("Evaluating {:?} with Scope {:?}", name, scope);
2019-06-22 03:36:57 +02:00
match name {
hir::Variable::It(_) => Ok(scope.it.value.clone().into_value(tag)),
2019-10-28 18:51:08 +01:00
hir::Variable::Other(inner) => match inner.slice(source) {
x if x == "nu:env" => {
let mut dict = TaggedDictBuilder::new(&tag);
for v in std::env::vars() {
2019-11-02 04:41:58 +01:00
if v.0 != "PATH" && v.0 != "Path" {
dict.insert_untagged(v.0, UntaggedValue::string(v.1));
2019-11-02 04:41:58 +01:00
}
2019-10-28 18:51:08 +01:00
}
Ok(dict.into_value())
2019-10-28 18:51:08 +01:00
}
x if x == "nu:config" => {
let config = crate::data::config::read(tag.clone(), &None)?;
Ok(UntaggedValue::row(config).into_value(tag))
2019-10-28 18:51:08 +01:00
}
2019-10-28 19:40:34 +01:00
x if x == "nu:path" => {
let mut table = vec![];
match std::env::var_os("PATH") {
Some(paths) => {
for path in std::env::split_paths(&paths) {
table.push(UntaggedValue::path(path).into_value(&tag));
2019-10-28 19:40:34 +01:00
}
}
_ => {}
}
Ok(UntaggedValue::table(&table).into_value(tag))
2019-10-28 19:40:34 +01:00
}
2019-10-28 18:51:08 +01:00
x => Ok(scope
.vars
.get(x)
.map(|v| v.clone())
.unwrap_or_else(|| UntaggedValue::nothing().into_value(tag))),
2019-10-28 18:51:08 +01:00
},
2019-05-28 08:45:18 +02:00
}
}
fn evaluate_external(
external: &hir::ExternalCommand,
_scope: &Scope,
_source: &Text,
) -> Result<Value, ShellError> {
Err(ShellError::syntax_error(
2019-11-04 16:47:03 +01:00
"Unexpected external command".spanned(*external.name()),
))
}
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-18 00:26:27 +02:00
fn evaluate_command(tag: Tag, _scope: &Scope, _source: &Text) -> Result<Value, ShellError> {
2019-11-04 16:47:03 +01:00
Err(ShellError::syntax_error(
"Unexpected command".spanned(tag.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-18 00:26:27 +02:00
}