forked from extern/nushell
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:
201
crates/nu-protocol/src/engine/pattern_match.rs
Normal file
201
crates/nu-protocol/src/engine/pattern_match.rs
Normal file
@ -0,0 +1,201 @@
|
||||
use crate::{
|
||||
ast::{Expr, MatchPattern, Pattern, RangeInclusion},
|
||||
Unit, Value, VarId,
|
||||
};
|
||||
|
||||
pub trait Matcher {
|
||||
fn match_value(&self, value: &Value, matches: &mut Vec<(VarId, Value)>) -> bool;
|
||||
}
|
||||
|
||||
impl Matcher for MatchPattern {
|
||||
fn match_value(&self, value: &Value, matches: &mut Vec<(VarId, Value)>) -> bool {
|
||||
self.pattern.match_value(value, matches)
|
||||
}
|
||||
}
|
||||
|
||||
impl Matcher for Pattern {
|
||||
fn match_value(&self, value: &Value, matches: &mut Vec<(VarId, Value)>) -> bool {
|
||||
match self {
|
||||
Pattern::Garbage => false,
|
||||
Pattern::IgnoreValue => true,
|
||||
Pattern::Record(field_patterns) => match value {
|
||||
Value::Record { cols, vals, .. } => {
|
||||
'top: for field_pattern in field_patterns {
|
||||
for (col_idx, col) in cols.iter().enumerate() {
|
||||
if col == &field_pattern.0 {
|
||||
// We have found the field
|
||||
let result = field_pattern.1.match_value(&vals[col_idx], matches);
|
||||
if !result {
|
||||
return false;
|
||||
} else {
|
||||
continue 'top;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
Pattern::Variable(var_id) => {
|
||||
// TODO: FIXME: This needs the span of this variable
|
||||
matches.push((*var_id, value.clone()));
|
||||
true
|
||||
}
|
||||
Pattern::List(items) => match &value {
|
||||
Value::List { vals, .. } => {
|
||||
if items.len() > vals.len() {
|
||||
// We need more items in our pattern than are available in the Value
|
||||
return false;
|
||||
}
|
||||
|
||||
for (val_idx, val) in vals.iter().enumerate() {
|
||||
// We require that the pattern and the value have the same number of items, or the pattern does not match
|
||||
// The only exception is if the pattern includes a `..` pattern
|
||||
|
||||
if let Some(pattern) = items.get(val_idx) {
|
||||
if !pattern.match_value(val, matches) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
Pattern::Value(pattern_value) => {
|
||||
// TODO: Fill this out with the rest of them
|
||||
match &pattern_value.expr {
|
||||
Expr::Int(x) => {
|
||||
if let Value::Int { val, .. } = &value {
|
||||
x == val
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
Expr::Binary(x) => {
|
||||
if let Value::Binary { val, .. } = &value {
|
||||
x == val
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
Expr::Bool(x) => {
|
||||
if let Value::Bool { val, .. } = &value {
|
||||
x == val
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
Expr::ValueWithUnit(amount, unit) => {
|
||||
if let Value::Filesize { val, .. } = &value {
|
||||
// FIXME: we probably want this math in one place that both the
|
||||
// pattern matcher and the eval engine can get to it
|
||||
match &amount.expr {
|
||||
Expr::Int(amount) => match &unit.item {
|
||||
Unit::Byte => amount == val,
|
||||
Unit::Kilobyte => *val == amount * 1000,
|
||||
Unit::Megabyte => *val == amount * 1000 * 1000,
|
||||
Unit::Gigabyte => *val == amount * 1000 * 1000 * 1000,
|
||||
Unit::Petabyte => *val == amount * 1000 * 1000 * 1000 * 1000,
|
||||
Unit::Exabyte => {
|
||||
*val == amount * 1000 * 1000 * 1000 * 1000 * 1000
|
||||
}
|
||||
Unit::Zettabyte => {
|
||||
*val == amount * 1000 * 1000 * 1000 * 1000 * 1000 * 1000
|
||||
}
|
||||
Unit::Kibibyte => *val == amount * 1024,
|
||||
Unit::Mebibyte => *val == amount * 1024 * 1024,
|
||||
Unit::Gibibyte => *val == amount * 1024 * 1024 * 1024,
|
||||
Unit::Pebibyte => *val == amount * 1024 * 1024 * 1024 * 1024,
|
||||
Unit::Exbibyte => {
|
||||
*val == amount * 1024 * 1024 * 1024 * 1024 * 1024
|
||||
}
|
||||
Unit::Zebibyte => {
|
||||
*val == amount * 1024 * 1024 * 1024 * 1024 * 1024 * 1024
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
} else if let Value::Duration { val, .. } = &value {
|
||||
// FIXME: we probably want this math in one place that both the
|
||||
// pattern matcher and the eval engine can get to it
|
||||
match &amount.expr {
|
||||
Expr::Int(amount) => match &unit.item {
|
||||
Unit::Nanosecond => val == amount,
|
||||
Unit::Microsecond => *val == amount * 1000,
|
||||
Unit::Millisecond => *val == amount * 1000 * 1000,
|
||||
Unit::Second => *val == amount * 1000 * 1000 * 1000,
|
||||
Unit::Minute => *val == amount * 1000 * 1000 * 1000 * 60,
|
||||
Unit::Hour => *val == amount * 1000 * 1000 * 1000 * 60 * 60,
|
||||
Unit::Day => *val == amount * 1000 * 1000 * 1000 * 60 * 60 * 24,
|
||||
Unit::Week => {
|
||||
*val == amount * 1000 * 1000 * 1000 * 60 * 60 * 24 * 7
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
Expr::Range(start, step, end, inclusion) => {
|
||||
// TODO: Add support for floats
|
||||
|
||||
let start = if let Some(start) = &start {
|
||||
match &start.expr {
|
||||
Expr::Int(start) => *start,
|
||||
_ => return false,
|
||||
}
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
let end = if let Some(end) = &end {
|
||||
match &end.expr {
|
||||
Expr::Int(end) => *end,
|
||||
_ => return false,
|
||||
}
|
||||
} else {
|
||||
i64::MAX
|
||||
};
|
||||
|
||||
let step = if let Some(step) = step {
|
||||
match &step.expr {
|
||||
Expr::Int(step) => *step - start,
|
||||
_ => return false,
|
||||
}
|
||||
} else if end < start {
|
||||
-1
|
||||
} else {
|
||||
1
|
||||
};
|
||||
|
||||
let (start, end) = if end < start {
|
||||
(end, start)
|
||||
} else {
|
||||
(start, end)
|
||||
};
|
||||
|
||||
if let Value::Int { val, .. } = &value {
|
||||
if matches!(inclusion.inclusion, RangeInclusion::RightExclusive) {
|
||||
*val >= start && *val < end && ((*val - start) % step) == 0
|
||||
} else {
|
||||
*val >= start && *val <= end && ((*val - start) % step) == 0
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user