vrl/stdlib/
object.rs

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