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
146
use nu_engine::{eval_block, eval_expression, eval_expression_with_input, CallExt};
use nu_protocol::ast::{Call, Expr, Expression};
use nu_protocol::engine::{Command, EngineState, Matcher, Stack};
use nu_protocol::{
    Category, Example, PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
};

#[derive(Clone)]
pub struct Match;

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

    fn usage(&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 run(
        &self,
        engine_state: &EngineState,
        stack: &mut Stack,
        call: &Call,
        input: PipelineData,
    ) -> Result<PipelineData, ShellError> {
        let value: Value = call.req(engine_state, stack, 0)?;
        let block = call.positional_nth(1);

        if let Some(Expression {
            expr: Expr::MatchBlock(matches),
            ..
        }) = block
        {
            for match_ in matches {
                let mut match_variables = vec![];
                if match_.0.match_value(&value, &mut match_variables) {
                    // This case does match, go ahead and return the evaluated expression
                    for match_variable in match_variables {
                        stack.add_var(match_variable.0, match_variable.1);
                    }

                    let guard_matches = if let Some(guard) = &match_.0.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) = match_.1.as_block() {
                            let block = engine_state.get_block(block_id);
                            eval_block(
                                engine_state,
                                stack,
                                block,
                                input,
                                call.redirect_stdout,
                                call.redirect_stderr,
                            )
                        } else {
                            eval_expression_with_input(
                                engine_state,
                                stack,
                                &match_.1,
                                input,
                                call.redirect_stdout,
                                call.redirect_stderr,
                            )
                            .map(|x| x.0)
                        };
                    }
                }
            }
        }

        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 {})
    }
}