nu_cmd_lang/core_commands/
for_.rs1use nu_engine::command_prelude::*;
2use nu_protocol::engine::CommandType;
3
4#[derive(Clone)]
5pub struct For;
6
7impl Command for For {
8 fn name(&self) -> &str {
9 "for"
10 }
11
12 fn description(&self) -> &str {
13 "Loop over a range."
14 }
15
16 fn signature(&self) -> nu_protocol::Signature {
17 Signature::build("for")
18 .input_output_types(vec![(Type::Nothing, Type::Nothing)])
19 .allow_variants_without_examples(true)
20 .required(
21 "var_name",
22 SyntaxShape::VarWithOptType,
23 "Name of the looping variable.",
24 )
25 .required(
26 "range",
27 SyntaxShape::Keyword(b"in".to_vec(), Box::new(SyntaxShape::Any)),
28 "Range of the loop.",
29 )
30 .required("block", SyntaxShape::Block, "The block to run.")
31 .category(Category::Core)
32 }
33
34 fn extra_description(&self) -> &str {
35 r#"This command is a parser keyword. For details, check:
36 https://www.nushell.sh/book/thinking_in_nu.html"#
37 }
38
39 fn command_type(&self) -> CommandType {
40 CommandType::Keyword
41 }
42
43 fn run(
44 &self,
45 _engine_state: &EngineState,
46 _stack: &mut Stack,
47 _call: &Call,
48 _input: PipelineData,
49 ) -> Result<PipelineData, ShellError> {
50 eprintln!(
53 "Tried to execute 'run' for the 'for' command: this code path should never be reached in IR mode"
54 );
55 unreachable!()
56 }
57
58 fn examples(&self) -> Vec<Example<'_>> {
59 vec![
60 Example {
61 description: "Print the square of each integer",
62 example: "for x in [1 2 3] { print ($x * $x) }",
63 result: None,
64 },
65 Example {
66 description: "Work with elements of a range",
67 example: "for $x in 1..3 { print $x }",
68 result: None,
69 },
70 Example {
71 description: "Number each item and print a message",
72 example: r#"for $it in (['bob' 'fred'] | enumerate) { print $"($it.index) is ($it.item)" }"#,
73 result: None,
74 },
75 ]
76 }
77}
78
79#[cfg(test)]
80mod test {
81 use super::*;
82
83 #[test]
84 fn test_examples() {
85 use crate::test_examples;
86
87 test_examples(For {})
88 }
89}