nu_protocol/ast/
match_pattern.rs

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