nu_cmd_lang/core_commands/
const_.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
use nu_engine::command_prelude::*;
use nu_protocol::engine::CommandType;

#[derive(Clone)]
pub struct Const;

impl Command for Const {
    fn name(&self) -> &str {
        "const"
    }

    fn description(&self) -> &str {
        "Create a parse-time constant."
    }

    fn signature(&self) -> nu_protocol::Signature {
        Signature::build("const")
            .input_output_types(vec![(Type::Nothing, Type::Nothing)])
            .allow_variants_without_examples(true)
            .required("const_name", SyntaxShape::VarWithOptType, "Constant name.")
            .required(
                "initial_value",
                SyntaxShape::Keyword(b"=".to_vec(), Box::new(SyntaxShape::MathExpression)),
                "Equals sign followed by constant value.",
            )
            .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 search_terms(&self) -> Vec<&str> {
        vec!["set", "let"]
    }

    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 var_id = if let Some(id) = call.positional_nth(0).and_then(|pos| pos.as_var()) {
            id
        } else {
            return Err(ShellError::NushellFailedSpanned {
                msg: "Could not get variable".to_string(),
                label: "variable not added by the parser".to_string(),
                span: call.head,
            });
        };

        if let Some(constval) = &engine_state.get_var(var_id).const_val {
            stack.add_var(var_id, constval.clone());

            Ok(PipelineData::empty())
        } else {
            Err(ShellError::NushellFailedSpanned {
                msg: "Missing Constant".to_string(),
                label: "constant not added by the parser".to_string(),
                span: call.head,
            })
        }
    }

    fn examples(&self) -> Vec<Example> {
        vec![
            Example {
                description: "Create a new parse-time constant.",
                example: "const x = 10",
                result: None,
            },
            Example {
                description: "Create a composite constant value",
                example: "const x = { a: 10, b: 20 }",
                result: None,
            },
        ]
    }
}

#[cfg(test)]
mod test {
    use nu_protocol::engine::CommandType;

    use super::*;

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

        test_examples(Const {})
    }

    #[test]
    fn test_command_type() {
        assert!(matches!(Const.command_type(), CommandType::Keyword));
    }
}