nu_cmd_lang/core_commands/
match_.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
use nu_engine::{
    command_prelude::*, get_eval_block, get_eval_expression, get_eval_expression_with_input,
};
use nu_protocol::engine::{CommandType, Matcher};

#[derive(Clone)]
pub struct Match;

impl Command for Match {
    fn name(&self) -> &str {
        "match"
    }

    fn description(&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_description(&self) -> &str {
        r#"This command is a parser keyword. For details, check:
  https://www.nushell.sh/book/thinking_in_nu.html"#
    }

    fn command_type(&self) -> CommandType {
        CommandType::Keyword
    }

    fn run(
        &self,
        engine_state: &EngineState,
        stack: &mut Stack,
        call: &Call,
        input: PipelineData,
    ) -> Result<PipelineData, ShellError> {
        // This is compiled specially by the IR compiler. The code here is never used when
        // running in IR mode.
        let call = call.assert_ast_call()?;
        let value: Value = call.req(engine_state, stack, 0)?;
        let matches = call
            .positional_nth(1)
            .expect("checked through parser")
            .as_match_block()
            .expect("missing match block");

        let eval_expression = get_eval_expression(engine_state);
        let eval_expression_with_input = get_eval_expression_with_input(engine_state);
        let eval_block = get_eval_block(engine_state);

        let mut match_variables = vec![];
        for (pattern, expr) in matches {
            if pattern.match_value(&value, &mut match_variables) {
                // This case does match, go ahead and return the evaluated expression
                for (id, value) in match_variables.drain(..) {
                    stack.add_var(id, value);
                }

                let guard_matches = if let Some(guard) = &pattern.guard {
                    let Value::Bool { val, .. } = eval_expression(engine_state, stack, guard)?
                    else {
                        return Err(ShellError::MatchGuardNotBool { span: guard.span });
                    };

                    val
                } else {
                    true
                };

                if guard_matches {
                    return if let Some(block_id) = expr.as_block() {
                        let block = engine_state.get_block(block_id);
                        eval_block(engine_state, stack, block, input)
                    } else {
                        eval_expression_with_input(engine_state, stack, expr, input)
                    };
                }
            } else {
                match_variables.clear();
            }
        }

        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)),
            },
            Example {
                description: "Match against pipeline input",
                example: "{a: {b: 3}} | match $in {{a: { $b }} => ($b + 10) }",
                result: Some(Value::test_int(13)),
            },
            Example {
                description: "Match with a guard",
                example: "match [1 2 3] {
        [$x, ..$y] if $x == 1 => { 'good list' },
        _ => { 'not a very good list' }
    }
    ",
                result: Some(Value::test_string("good list")),
            },
        ]
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_examples() {
        use crate::test_examples;

        test_examples(Match {})
    }
}