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

@ -1,7 +1,7 @@
use chrono::FixedOffset;
use serde::{Deserialize, Serialize};
use super::{Call, CellPath, Expression, FullCellPath, Operator, RangeOperator};
use super::{Call, CellPath, Expression, FullCellPath, MatchPattern, Operator, RangeOperator};
use crate::{ast::ImportPattern, BlockId, Signature, Span, Spanned, Unit, VarId};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@ -27,6 +27,7 @@ pub enum Expr {
Subexpression(BlockId),
Block(BlockId),
Closure(BlockId),
MatchBlock(Vec<(MatchPattern, Expression)>),
List(Vec<Expression>),
Table(Vec<Expression>, Vec<Vec<Expression>>),
Record(Vec<(Expression, Expression)>),
@ -43,6 +44,7 @@ pub enum Expr {
Overlay(Option<BlockId>), // block ID of the overlay's origin module
Signature(Box<Signature>),
StringInterpolation(Vec<Expression>),
MatchPattern(Box<MatchPattern>),
Nothing,
Garbage,
}

View File

@ -221,7 +221,9 @@ impl Expression {
}
false
}
Expr::MatchPattern(_) => false,
Expr::Operator(_) => false,
Expr::MatchBlock(_) => false,
Expr::Range(left, middle, right, ..) => {
if let Some(left) = &left {
if left.has_in_variable(working_set) {
@ -395,6 +397,8 @@ impl Expression {
Expr::Nothing => {}
Expr::GlobPattern(_) => {}
Expr::Int(_) => {}
Expr::MatchPattern(_) => {}
Expr::MatchBlock(_) => {}
Expr::Keyword(_, _, expr) => expr.replace_in_variable(working_set, new_var_id),
Expr::List(list) => {
for l in list {
@ -554,6 +558,8 @@ impl Expression {
Expr::Garbage => {}
Expr::Nothing => {}
Expr::GlobPattern(_) => {}
Expr::MatchPattern(_) => {}
Expr::MatchBlock(_) => {}
Expr::Int(_) => {}
Expr::Keyword(_, _, expr) => expr.replace_span(working_set, replaced, new_span),
Expr::List(list) => {

View File

@ -0,0 +1,21 @@
use serde::{Deserialize, Serialize};
use crate::{Span, VarId};
use super::Expression;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MatchPattern {
pub pattern: Pattern,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Pattern {
Record(Vec<(String, MatchPattern)>),
List(Vec<MatchPattern>),
Value(Expression),
Variable(VarId),
IgnoreValue, // the _ pattern
Garbage,
}

View File

@ -4,6 +4,7 @@ mod cell_path;
mod expr;
mod expression;
mod import_pattern;
mod match_pattern;
mod operator;
mod pipeline;
@ -13,5 +14,6 @@ pub use cell_path::*;
pub use expr::*;
pub use expression::*;
pub use import_pattern::*;
pub use match_pattern::*;
pub use operator::*;
pub use pipeline::*;