Add pattern matching (#8590)

# Description

This adds `match` and basic pattern matching.

An example:

```
match $x {
  1..10 => { print "Value is between 1 and 10" }
  { foo: $bar } => { print $"Value has a 'foo' field with value ($bar)" }
  [$a, $b] => { print $"Value is a list with two items: ($a) and ($b)" }
  _ => { print "Value is none of the above" }
}
```

Like the recent changes to `if` to allow it to be used as an expression,
`match` can also be used as an expression. This allows you to assign the
result to a variable, eg) `let xyz = match ...`

I've also included a short-hand pattern for matching records, as I think
it might help when doing a lot of record patterns: `{$foo}` which is
equivalent to `{foo: $foo}`.

There are still missing components, so consider this the first step in
full pattern matching support. Currently missing:
* Patterns for strings
* Or-patterns (like the `|` in Rust)
* Patterns for tables (unclear how we want to match a table, so it'll
need some design)
* Patterns for binary values
* And much more

# User-Facing Changes

[see above]

# Tests + Formatting

Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```

# After Submitting

If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
This commit is contained in:
JT
2023-03-24 14:52:01 +13:00
committed by GitHub
parent be52f7fb07
commit 2c3aade057
30 changed files with 955 additions and 7 deletions

View File

@ -0,0 +1,128 @@
use nu_engine::{eval_block, eval_expression_with_input, CallExt};
use nu_protocol::ast::{Call, Expr, Expression};
use nu_protocol::engine::{Command, EngineState, Matcher, Stack};
use nu_protocol::{
Category, Example, PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
};
#[derive(Clone)]
pub struct Match;
impl Command for Match {
fn name(&self) -> &str {
"match"
}
fn usage(&self) -> &str {
"Conditionally run a block on a matched value."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("match")
.input_output_types(vec![(Type::Any, Type::Any)])
.required("value", SyntaxShape::Any, "value to check")
.required(
"match_block",
SyntaxShape::MatchBlock,
"block to run if check succeeds",
)
.category(Category::Core)
}
fn extra_usage(&self) -> &str {
r#"This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html"#
}
fn is_parser_keyword(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let value: Value = call.req(engine_state, stack, 0)?;
let block = call.positional_nth(1);
if let Some(Expression {
expr: Expr::MatchBlock(matches),
..
}) = block
{
for match_ in matches {
let mut match_variables = vec![];
if match_.0.match_value(&value, &mut match_variables) {
// This case does match, go ahead and return the evaluated expression
for match_variable in match_variables {
stack.add_var(match_variable.0, match_variable.1);
}
if let Some(block_id) = match_.1.as_block() {
let block = engine_state.get_block(block_id);
return eval_block(
engine_state,
stack,
block,
input,
call.redirect_stdout,
call.redirect_stderr,
);
} else {
return eval_expression_with_input(
engine_state,
stack,
&match_.1,
input,
call.redirect_stdout,
call.redirect_stderr,
)
.map(|x| x.0);
}
}
}
}
Ok(PipelineData::Empty)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Match on a value in range",
example: "match 3 { 1..10 => 'yes!' }",
result: Some(Value::test_string("yes!")),
},
Example {
description: "Match on a field in a record",
example: "match {a: 100} { {a: $my_value} => { $my_value } }",
result: Some(Value::test_int(100)),
},
Example {
description: "Match with a catch-all",
example: "match 3 { 1 => { 'yes!' }, _ => { 'no!' } }",
result: Some(Value::test_string("no!")),
},
Example {
description: "Match against a list",
example: "match [1, 2, 3] { [$a, $b, $c] => { $a + $b + $c }, _ => 0 }",
result: Some(Value::test_int(6)),
},
]
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Match {})
}
}

View File

@ -29,6 +29,7 @@ mod if_;
mod ignore;
mod let_;
mod loop_;
mod match_;
mod module;
mod mut_;
pub(crate) mod overlay;
@ -69,6 +70,7 @@ pub use if_::If;
pub use ignore::Ignore;
pub use let_::Let;
pub use loop_::Loop;
pub use match_::Match;
pub use module::Module;
pub use mut_::Mut;
pub use overlay::*;

View File

@ -52,6 +52,7 @@ pub fn create_default_context() -> EngineState {
OverlayHide,
Let,
Loop,
Match,
Module,
Mut,
Return,