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

#[derive(Clone)]
pub struct While;

impl Command for While {
    fn name(&self) -> &str {
        "while"
    }

    fn usage(&self) -> &str {
        "Conditionally run a block in a loop."
    }

    fn signature(&self) -> nu_protocol::Signature {
        Signature::build("while")
            .input_output_types(vec![(Type::Nothing, Type::Nothing)])
            .allow_variants_without_examples(true)
            .required("cond", SyntaxShape::Expression, "condition to check")
            .required(
                "block",
                SyntaxShape::Block,
                "block to loop if check succeeds",
            )
            .category(Category::Core)
    }

    fn extra_usage(&self) -> &str {
        r#"This command is a parser keyword. For details, check:
  https://www.nushell.sh/book/thinking_in_nu.html"#
    }

    fn is_parser_keyword(&self) -> bool {
        true
    }

    fn run(
        &self,
        engine_state: &EngineState,
        stack: &mut Stack,
        call: &Call,
        _input: PipelineData,
    ) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
        let cond = call.positional_nth(0).expect("checked through parser");
        let block: Block = call.req(engine_state, stack, 1)?;

        loop {
            if nu_utils::ctrl_c::was_pressed(&engine_state.ctrlc) {
                break;
            }

            let result = eval_expression(engine_state, stack, cond)?;
            match &result {
                Value::Bool { val, .. } => {
                    if *val {
                        let block = engine_state.get_block(block.block_id);
                        match eval_block(
                            engine_state,
                            stack,
                            block,
                            PipelineData::empty(),
                            call.redirect_stdout,
                            call.redirect_stderr,
                        ) {
                            Err(ShellError::Break(_)) => {
                                break;
                            }
                            Err(ShellError::Continue(_)) => {
                                continue;
                            }
                            Err(err) => {
                                return Err(err);
                            }
                            Ok(pipeline) => {
                                let exit_code =
                                    pipeline.print(engine_state, stack, false, false)?;
                                if exit_code != 0 {
                                    break;
                                }
                            }
                        }
                    } else {
                        break;
                    }
                }
                x => {
                    return Err(ShellError::CantConvert(
                        "bool".into(),
                        x.get_type().to_string(),
                        result.span()?,
                        None,
                    ))
                }
            }
        }
        Ok(PipelineData::empty())
    }

    fn examples(&self) -> Vec<Example> {
        vec![Example {
            description: "Loop while a condition is true",
            example: "mut x = 0; while $x < 10 { $x = $x + 1 }",
            result: None,
        }]
    }
}

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

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

        test_examples(While {})
    }
}