nushell/src/parser/registry.rs

294 lines
7.5 KiB
Rust
Raw Normal View History

2019-07-24 00:22:11 +02:00
// TODO: Temporary redirect
pub(crate) use crate::context::CommandRegistry;
2019-06-22 03:36:57 +02:00
use crate::evaluate::{evaluate_baseline_expr, Scope};
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 crate::parser::{hir, hir::SyntaxShape};
2019-05-28 08:45:18 +02:00
use crate::prelude::*;
2019-06-22 03:36:57 +02:00
use derive_new::new;
2019-05-26 08:54:41 +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
2019-07-02 09:56:20 +02:00
use serde::{Deserialize, Serialize};
2019-05-26 08:54:41 +02:00
2019-07-16 09:08:35 +02:00
#[derive(Debug, Serialize, Deserialize, Clone)]
2019-05-28 08:45:18 +02:00
pub enum NamedType {
Switch,
Mandatory(SyntaxShape),
Optional(SyntaxShape),
2019-05-26 08:54:41 +02:00
}
2019-07-02 09:56:20 +02:00
#[derive(Debug, Clone, Serialize, Deserialize)]
2019-05-28 08:45:18 +02:00
pub enum PositionalType {
Mandatory(String, SyntaxShape),
Optional(String, SyntaxShape),
2019-05-28 08:45:18 +02:00
}
impl PositionalType {
pub fn mandatory(name: &str, ty: SyntaxShape) -> PositionalType {
2019-07-15 23:16:27 +02:00
PositionalType::Mandatory(name.to_string(), ty)
}
pub fn mandatory_any(name: &str) -> PositionalType {
PositionalType::Mandatory(name.to_string(), SyntaxShape::Any)
2019-07-13 04:07:06 +02:00
}
2019-07-16 21:10:25 +02:00
pub fn mandatory_block(name: &str) -> PositionalType {
PositionalType::Mandatory(name.to_string(), SyntaxShape::Block)
2019-07-16 21:10:25 +02:00
}
pub fn optional(name: &str, ty: SyntaxShape) -> PositionalType {
2019-07-16 09:25:48 +02:00
PositionalType::Optional(name.to_string(), ty)
}
pub fn optional_any(name: &str) -> PositionalType {
PositionalType::Optional(name.to_string(), SyntaxShape::Any)
2019-07-16 09:25:48 +02:00
}
pub(crate) fn name(&self) -> &str {
match self {
PositionalType::Mandatory(s, _) => s,
PositionalType::Optional(s, _) => s,
}
}
2019-07-15 23:16:27 +02:00
pub(crate) fn syntax_type(&self) -> SyntaxShape {
2019-07-15 23:16:27 +02:00
match *self {
PositionalType::Mandatory(_, t) => t,
PositionalType::Optional(_, t) => t,
}
}
2019-05-28 08:45:18 +02:00
}
2019-10-28 06:15:35 +01:00
type Description = String;
2019-11-18 04:12:37 +01:00
#[derive(Debug, Serialize, Deserialize, Clone)]
2019-08-02 21:15:07 +02:00
pub struct Signature {
2019-07-02 09:56:20 +02:00
pub name: String,
pub usage: String,
2019-10-28 06:15:35 +01:00
pub positional: Vec<(PositionalType, Description)>,
pub rest_positional: Option<(SyntaxShape, Description)>,
pub named: IndexMap<String, (NamedType, Description)>,
2019-07-02 09:56:20 +02:00
pub is_filter: bool,
2019-05-28 08:45:18 +02:00
}
2019-08-02 21:15:07 +02:00
impl Signature {
2019-11-18 04:12:37 +01:00
pub fn new(name: String) -> Signature {
Signature {
name,
usage: String::new(),
positional: vec![],
rest_positional: None,
named: IndexMap::new(),
is_filter: false,
}
}
2019-08-02 21:15:07 +02:00
pub fn build(name: impl Into<String>) -> Signature {
Signature::new(name.into())
2019-07-24 06:10:48 +02:00
}
pub fn desc(mut self, usage: impl Into<String>) -> Signature {
self.usage = usage.into();
self
}
2019-10-28 06:15:35 +01:00
pub fn required(
mut self,
name: impl Into<String>,
ty: impl Into<SyntaxShape>,
desc: impl Into<String>,
) -> Signature {
self.positional.push((
PositionalType::Mandatory(name.into(), ty.into()),
desc.into(),
));
2019-07-24 06:10:48 +02:00
self
}
2019-10-28 06:15:35 +01:00
pub fn optional(
mut self,
name: impl Into<String>,
ty: impl Into<SyntaxShape>,
desc: impl Into<String>,
) -> Signature {
self.positional.push((
PositionalType::Optional(name.into(), ty.into()),
desc.into(),
));
2019-07-24 06:10:48 +02:00
self
}
2019-10-28 06:15:35 +01:00
pub fn named(
mut self,
name: impl Into<String>,
ty: impl Into<SyntaxShape>,
desc: impl Into<String>,
) -> Signature {
2019-08-02 21:15:07 +02:00
self.named
2019-10-28 06:15:35 +01:00
.insert(name.into(), (NamedType::Optional(ty.into()), desc.into()));
2019-08-02 21:15:07 +02:00
self
}
pub fn required_named(
mut self,
name: impl Into<String>,
ty: impl Into<SyntaxShape>,
2019-10-28 06:15:35 +01:00
desc: impl Into<String>,
2019-08-02 21:15:07 +02:00
) -> Signature {
self.named
2019-10-28 06:15:35 +01:00
.insert(name.into(), (NamedType::Mandatory(ty.into()), desc.into()));
2019-08-02 21:15:07 +02:00
self
}
2019-10-28 06:15:35 +01:00
pub fn switch(mut self, name: impl Into<String>, desc: impl Into<String>) -> Signature {
self.named
.insert(name.into(), (NamedType::Switch, desc.into()));
2019-07-24 06:10:48 +02:00
self
}
2019-08-02 21:15:07 +02:00
pub fn filter(mut self) -> Signature {
self.is_filter = true;
self
}
2019-10-28 06:15:35 +01:00
pub fn rest(mut self, ty: SyntaxShape, desc: impl Into<String>) -> Signature {
self.rest_positional = Some((ty, desc.into()));
2019-08-02 21:15:07 +02:00
self
}
2019-07-24 06:10:48 +02:00
}
#[derive(Debug, Default, new, Serialize, Deserialize, Clone)]
2019-07-24 00:22:11 +02:00
pub struct EvaluatedArgs {
2019-08-01 03:58:42 +02:00
pub positional: Option<Vec<Tagged<Value>>>,
pub named: Option<IndexMap<String, Tagged<Value>>>,
2019-06-22 03:36:57 +02:00
}
impl EvaluatedArgs {
pub fn slice_from(&self, from: usize) -> Vec<Tagged<Value>> {
let positional = &self.positional;
match positional {
None => vec![],
Some(list) => list[from..].to_vec(),
}
}
}
2019-07-24 00:22:11 +02:00
impl EvaluatedArgs {
2019-08-01 03:58:42 +02:00
pub fn nth(&self, pos: usize) -> Option<&Tagged<Value>> {
2019-06-22 03:36:57 +02:00
match &self.positional {
None => None,
Some(array) => array.iter().nth(pos),
}
}
2019-08-01 03:58:42 +02:00
pub fn expect_nth(&self, pos: usize) -> Result<&Tagged<Value>, ShellError> {
2019-06-22 03:36:57 +02:00
match &self.positional {
None => Err(ShellError::unimplemented("Better error: expect_nth")),
Some(array) => match array.iter().nth(pos) {
None => Err(ShellError::unimplemented("Better error: expect_nth")),
Some(item) => Ok(item),
},
}
}
pub fn len(&self) -> usize {
match &self.positional {
None => 0,
Some(array) => array.len(),
}
}
pub fn has(&self, name: &str) -> bool {
match &self.named {
None => false,
Some(named) => named.contains_key(name),
}
}
2019-08-01 03:58:42 +02:00
pub fn get(&self, name: &str) -> Option<&Tagged<Value>> {
2019-06-22 03:36:57 +02:00
match &self.named {
None => None,
Some(named) => named.get(name),
}
}
pub fn positional_iter(&self) -> PositionalIter<'_> {
2019-06-22 03:36:57 +02:00
match &self.positional {
None => PositionalIter::Empty,
Some(v) => {
let iter = v.iter();
PositionalIter::Array(iter)
}
}
}
}
pub enum PositionalIter<'a> {
Empty,
2019-08-01 03:58:42 +02:00
Array(std::slice::Iter<'a, Tagged<Value>>),
2019-06-22 03:36:57 +02:00
}
impl<'a> Iterator for PositionalIter<'a> {
2019-08-01 03:58:42 +02:00
type Item = &'a Tagged<Value>;
2019-06-22 03:36:57 +02:00
fn next(&mut self) -> Option<Self::Item> {
match self {
PositionalIter::Empty => None,
PositionalIter::Array(iter) => iter.next(),
}
}
}
pub(crate) fn evaluate_args(
2019-07-24 00:22:11 +02:00
call: &hir::Call,
registry: &CommandRegistry,
2019-06-22 03:36:57 +02:00
scope: &Scope,
2019-06-22 22:46:16 +02:00
source: &Text,
2019-07-24 00:22:11 +02:00
) -> Result<EvaluatedArgs, ShellError> {
let positional: Result<Option<Vec<_>>, _> = call
2019-06-22 03:36:57 +02:00
.positional()
.as_ref()
.map(|p| {
p.iter()
2019-08-15 07:02:02 +02:00
.map(|e| evaluate_baseline_expr(e, registry, scope, source))
2019-06-22 03:36:57 +02:00
.collect()
})
.transpose();
let positional = positional?;
2019-08-09 06:51:21 +02:00
let named: Result<Option<IndexMap<String, Tagged<Value>>>, ShellError> = call
2019-06-22 03:36:57 +02:00
.named()
.as_ref()
.map(|n| {
let mut results = IndexMap::new();
for (name, value) in n.named.iter() {
match value {
hir::named::NamedValue::PresentSwitch(tag) => {
results.insert(name.clone(), Value::boolean(true).tagged(tag));
2019-06-22 03:36:57 +02:00
}
hir::named::NamedValue::Value(expr) => {
results.insert(
name.clone(),
evaluate_baseline_expr(expr, registry, scope, source)?,
);
}
2019-06-22 03:36:57 +02:00
_ => {}
};
}
2019-06-22 03:36:57 +02:00
Ok(results)
})
.transpose();
2019-06-22 03:36:57 +02:00
let named = named?;
2019-07-24 00:22:11 +02:00
Ok(EvaluatedArgs::new(positional, named))
2019-05-26 08:54:41 +02:00
}