nu_protocol/ast/match_pattern.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
use super::Expression;
use crate::{Span, Value, VarId};
use serde::{Deserialize, Serialize};
/// AST Node for match arm with optional match guard
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MatchPattern {
pub pattern: Pattern,
pub guard: Option<Box<Expression>>,
pub span: Span,
}
impl MatchPattern {
pub fn variables(&self) -> Vec<VarId> {
self.pattern.variables()
}
}
/// AST Node for pattern matching rules
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Pattern {
/// Destructuring of records
Record(Vec<(String, MatchPattern)>),
/// List destructuring
List(Vec<MatchPattern>),
/// Matching against a literal (from expression result)
// TODO: it would be nice if this didn't depend on AST
// maybe const evaluation can get us to a Value instead?
Expression(Box<Expression>),
/// Matching against a literal (pure value)
Value(Value),
/// binding to a variable
Variable(VarId),
/// the `pattern1 \ pattern2` or-pattern
Or(Vec<MatchPattern>),
/// the `..$foo` pattern
Rest(VarId),
/// the `..` pattern
IgnoreRest,
/// the `_` pattern
IgnoreValue,
/// Failed parsing of a pattern
Garbage,
}
impl Pattern {
pub fn variables(&self) -> Vec<VarId> {
let mut output = vec![];
match self {
Pattern::Record(items) => {
for item in items {
output.append(&mut item.1.variables());
}
}
Pattern::List(items) => {
for item in items {
output.append(&mut item.variables());
}
}
Pattern::Variable(var_id) => output.push(*var_id),
Pattern::Or(patterns) => {
for pattern in patterns {
output.append(&mut pattern.variables());
}
}
Pattern::Rest(var_id) => output.push(*var_id),
Pattern::Expression(_)
| Pattern::Value(_)
| Pattern::IgnoreValue
| Pattern::Garbage
| Pattern::IgnoreRest => {}
}
output
}
}