vrl/stdlib/
array.rs

1use crate::compiler::prelude::*;
2
3fn array(value: Value) -> Resolved {
4    match value {
5        v @ Value::Array(_) => Ok(v),
6        v => Err(format!("expected array, got {}", v.kind()).into()),
7    }
8}
9
10#[derive(Clone, Copy, Debug)]
11pub struct Array;
12
13impl Function for Array {
14    fn identifier(&self) -> &'static str {
15        "array"
16    }
17
18    fn usage(&self) -> &'static str {
19        "Returns `value` if it is an array, otherwise returns an error. This enables the type checker to guarantee that the returned value is an array and can be used in any function that expects an array."
20    }
21
22    fn category(&self) -> &'static str {
23        Category::Type.as_ref()
24    }
25
26    fn internal_failure_reasons(&self) -> &'static [&'static str] {
27        &["`value` is not an array."]
28    }
29
30    fn return_kind(&self) -> u16 {
31        kind::ARRAY
32    }
33
34    fn return_rules(&self) -> &'static [&'static str] {
35        &[
36            "Returns the `value` if it's an array.",
37            "Raises an error if not an array.",
38        ]
39    }
40
41    fn parameters(&self) -> &'static [Parameter] {
42        const PARAMETERS: &[Parameter] = &[Parameter::required(
43            "value",
44            kind::ANY,
45            "The value to check if it is an array.",
46        )];
47        PARAMETERS
48    }
49
50    fn examples(&self) -> &'static [Example] {
51        &[
52            example! {
53                title: "Declare an array type",
54                source: "array!(.value)",
55                input: r#"{"value": [1, 2, 3]}"#,
56                result: Ok("[1,2,3]"),
57            },
58            example! {
59                title: "Valid array literal",
60                source: "array([1,2,3])",
61                result: Ok("[1,2,3]"),
62            },
63            example! {
64                title: "Invalid type",
65                source: "array!(true)",
66                result: Err(
67                    r#"function call error for "array" at (0:12): expected array, got boolean"#,
68                ),
69            },
70        ]
71    }
72
73    fn compile(
74        &self,
75        _state: &state::TypeState,
76        _ctx: &mut FunctionCompileContext,
77        arguments: ArgumentList,
78    ) -> Compiled {
79        let value = arguments.required("value");
80
81        Ok(ArrayFn { value }.as_expr())
82    }
83}
84
85#[derive(Debug, Clone)]
86struct ArrayFn {
87    value: Box<dyn Expression>,
88}
89
90impl FunctionExpression for ArrayFn {
91    fn resolve(&self, ctx: &mut Context) -> Resolved {
92        array(self.value.resolve(ctx)?)
93    }
94
95    fn type_def(&self, state: &state::TypeState) -> TypeDef {
96        self.value
97            .type_def(state)
98            .fallible_unless(Kind::array(Collection::any()))
99            .restrict_array()
100    }
101}