nu_cmd_lang/core_commands/
while_.rs

1use nu_engine::command_prelude::*;
2use nu_protocol::engine::CommandType;
3
4#[derive(Clone)]
5pub struct While;
6
7impl Command for While {
8    fn name(&self) -> &str {
9        "while"
10    }
11
12    fn description(&self) -> &str {
13        "Conditionally run a block in a loop."
14    }
15
16    fn signature(&self) -> nu_protocol::Signature {
17        Signature::build("while")
18            .input_output_types(vec![(Type::Nothing, Type::Nothing)])
19            .allow_variants_without_examples(true)
20            .required("cond", SyntaxShape::MathExpression, "Condition to check.")
21            .required(
22                "block",
23                SyntaxShape::Block,
24                "Block to loop if check succeeds.",
25            )
26            .category(Category::Core)
27    }
28
29    fn search_terms(&self) -> Vec<&str> {
30        vec!["loop"]
31    }
32
33    fn extra_description(&self) -> &str {
34        r#"This command is a parser keyword. For details, check:
35  https://www.nushell.sh/book/thinking_in_nu.html"#
36    }
37
38    fn command_type(&self) -> CommandType {
39        CommandType::Keyword
40    }
41
42    fn run(
43        &self,
44        _engine_state: &EngineState,
45        _stack: &mut Stack,
46        _call: &Call,
47        _input: PipelineData,
48    ) -> Result<PipelineData, ShellError> {
49        // This is compiled specially by the IR compiler. The code here is never used when
50        // running in IR mode.
51        eprintln!(
52            "Tried to execute 'run' for the 'while' command: this code path should never be reached in IR mode"
53        );
54        unreachable!()
55    }
56
57    fn examples(&self) -> Vec<Example<'_>> {
58        vec![Example {
59            description: "Loop while a condition is true",
60            example: "mut x = 0; while $x < 10 { $x = $x + 1 }",
61            result: None,
62        }]
63    }
64}
65
66#[cfg(test)]
67mod test {
68    use super::*;
69
70    #[test]
71    fn test_examples() {
72        use crate::test_examples;
73
74        test_examples(While {})
75    }
76}