sosaku 0.2.0

Filtering DSL for JSON and JSON-like data formats.
Documentation
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use std::{
    borrow::Cow,
    fmt::{Debug, Display, Write},
};

use nom::Finish;

#[cfg(feature = "serde_json")]
use serde::Deserialize;

use crate::{
    VarAccessError,
    types::{
        env::Env,
        json::{JsonMap, JsonValue},
    },
};

use crate::parser::parse_variable_name;

/// A variable name, with an optional index for array access.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VarName {
    name: Box<str>,
    index: Option<usize>,
}

impl VarName {
    /// Create a new [`VarName`] with the given name and optional index.
    ///
    /// # Parameters
    ///
    /// - `name`: The name of the variable.
    /// - `index`: An optional index for array access,
    ///   if this variable name is used to access an array element
    ///   (e.g. `foo[0]` would have name "foo" and index 0).
    ///
    /// # Returns
    ///
    /// - A new [`VarName`] instance containing the provided name and index.
    pub fn new(name: impl Into<Box<str>>, index: Option<usize>) -> Self {
        Self {
            name: name.into(),
            index,
        }
    }

    /// The name of the variable.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The optional index for array access, if this variable name is used to access an array element.
    pub const fn index(&self) -> Option<usize> {
        self.index
    }

    fn access<'a, V: JsonValue + Debug>(
        &self,
        value: &'a V,
        resolve_obj_name: impl Fn() -> String,
    ) -> Result<&'a V, VarAccessError> {
        // Map into the object with the name
        if let Some(o) = value.as_object() {
            let out = o
                .get(self.name())
                .ok_or_else(|| VarAccessError::ObjectKeyError {
                    object: resolve_obj_name(),
                    key: self.name().to_string(),
                })?;
            // If we have an index, index into the array
            if self.index().is_some() {
                self.index_into(out, resolve_obj_name)
            } else {
                Ok(out)
            }
        } else {
            // Trying to varaccess into a non-object value is always an error
            Err(VarAccessError::ObjectKeyError {
                object: resolve_obj_name(),
                key: self.name().to_string(),
            })
        }
    }

    fn index_into<'a, V: JsonValue + Debug>(
        &self,
        value: &'a V,
        resolve_obj_name: impl Fn() -> String,
    ) -> Result<&'a V, VarAccessError> {
        if let Some(index) = self.index() {
            let arr = value.as_array().ok_or_else(|| VarAccessError::TypeError {
                message: format!(
                    "Expected array at '{}', found {:?}",
                    resolve_obj_name(),
                    value
                ),
            })?;

            arr.get(index)
                .ok_or_else(|| VarAccessError::IndexOutOfBounds {
                    message: format!(
                        "Index out of bounds at '{}' (index: {index}, length: {})",
                        resolve_obj_name(),
                        arr.len()
                    ),
                })
        } else {
            panic!("Called index_into on VarName without an index")
        }
    }
}

impl Display for VarName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.name)?;
        if let Some(index) = self.index {
            write!(f, "[{index}]")?;
        }
        Ok(())
    }
}

/// A variable access, which is a series of variable names.
///
/// Example: `foo.bar[0].baz` would be represented as a `VarAccess` with three `VarName`s:
/// - `foo` with no index
/// - `bar` with index 0
/// - `baz` with no index
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VarAccess {
    names: Vec<VarName>,
}

impl VarAccess {
    /// Create a new [`VarAccess`] from a vector of [`VarName`]s.
    ///
    /// # Panics
    ///
    /// This function will panic if the `names` vector is empty, as a variable access must have at least one name.
    pub fn new(names: impl Into<Vec<VarName>>) -> Self {
        let names = names.into();
        assert!(
            !names.is_empty(),
            "Variable access must have at least one name"
        );

        Self { names }
    }

    /// Get the sequence variable names in this access.
    pub fn names(&self) -> &[VarName] {
        &self.names
    }

    fn access_names<'a, V: JsonValue + Debug>(
        mut names: &[VarName],
        value: &'a V,
        ignore_first: bool,
    ) -> Result<&'a V, VarAccessError> {
        // (curr_value, curr_name), root_name)
        let (mut current, root) = if ignore_first {
            let root = names
                .first()
                .expect("Variable access must have at least one name");
            names = names.get(1..).ok_or(VarAccessError::EmptyAccess)?;
            ((value, root), Some(root))
        } else {
            let val = names
                .first()
                .expect("Variable access must have at least one name");
            ((value, val), None)
        };

        // Join the previous variable names to indicate the
        // path to the current object being accessed, for better error messages
        let resolve_name_until = |i: usize| {
            if i == 0 {
                #[expect(clippy::or_fun_call)]
                root.unwrap_or(&VarName::new("<root>", None)).to_string()
            } else {
                let names = names[..i]
                    .iter()
                    .map(ToString::to_string)
                    .collect::<Vec<_>>();

                if let Some(r) = root {
                    format!("{}.{}", r, names.join("."))
                } else {
                    names.join(".")
                }
            }
        };

        // Reduce "current" by accessing each variable name in the access path
        for (i, var) in names.iter().enumerate() {
            current = (var.access(current.0, || resolve_name_until(i))?, var);
        }

        // Account for edge-case where if ignore_first is true and the first variable name has an index,
        // we need to access that index in the root value
        if names.is_empty() && ignore_first && current.1.index().is_some() {
            current.0 = current
                .1
                .index_into(current.0, || resolve_name_until(names.len()))?;
        }

        Ok(current.0)
    }

    /// Access the value denoted by this accessor from the given JSON value.
    ///
    /// # Returns
    /// The value accessed from the provided JSON value according to
    /// the variable access specified by this [`VarAccess`].
    ///
    /// # Errors
    /// - If there was an error accessing the value, such as a type mismatch or index out of bounds
    pub fn access<'a, V: JsonValue + Debug>(&self, value: &'a V) -> Result<&'a V, VarAccessError> {
        Self::access_names(&self.names, value, false)
    }

    /// Access the value denoted by this accessor from the given JSON value.
    ///
    /// # Returns
    /// The value accessed from the provided JSON value according to
    /// the variable access specified by this [`VarAccess`].
    ///
    /// # Errors
    /// - If there was an error accessing the value, such as a type mismatch or index out of bounds
    pub fn access_from_bindings<'a, V: JsonValue + Debug + Clone>(
        &self,
        env: &'a Env<'a, V>,
    ) -> Result<Cow<'a, V>, VarAccessError> {
        if self.names.is_empty() {
            return Ok(Cow::Owned(V::null()));
        }

        let first_name = self.names[0].name();
        let value =
            env.bindings()
                .get(first_name)
                .ok_or_else(|| VarAccessError::VariableNotFound {
                    variable: first_name.to_string(),
                })?;

        Self::access_names(&self.names, value.as_ref(), true).map(Cow::Borrowed)
    }
}

impl Display for VarAccess {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for (i, name) in self.names.iter().enumerate() {
            if i > 0 {
                f.write_char('.')?;
            }
            write!(f, "{name}")?;
        }
        Ok(())
    }
}

impl<'a> TryFrom<&'a str> for VarAccess {
    type Error = nom::error::Error<&'a str>;

    fn try_from(s: &'a str) -> Result<Self, Self::Error> {
        match parse_variable_name(s).finish() {
            Ok(("", var_access)) => Ok(var_access),
            Ok((remaining, _)) => Err(nom::error::Error::new(
                remaining,
                nom::error::ErrorKind::Eof,
            )),
            Err(e) => Err(e),
        }
    }
}

#[cfg(feature = "serde_json")]
impl<'a> Deserialize<'a> for VarAccess {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'a>,
    {
        let s = String::deserialize(deserializer)?;
        Self::try_from(s.as_str()).map_err(serde::de::Error::custom)
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
#[cfg(feature = "serde_json")]
mod tests {
    use std::sync::LazyLock;

    use serde_json::json;

    use super::*;

    static TEST_VALUE_1: LazyLock<serde_json::Value> = LazyLock::new(|| {
        serde_json::json!(
            {
                "foo": {
                    "bar": [
                        {"baz": 42},
                        {"baz": 43}
                    ]
                }
            }
        )
    });

    static TEST_VALUE_2: LazyLock<serde_json::Value> = LazyLock::new(|| {
        serde_json::json!(
            {
                "foo": {
                    "bar": [
                        {"baz": 42},
                        {"baz": 43}
                    ]
                },
                "arr": [1, 2, 3],
                "null_value": null,
                "string_value": "hello",
                "bool_value": true,
                "float_value": 3.145
            }
        )
    });

    #[test]
    fn test_var_access() {
        let var_access = VarAccess::try_from("foo.bar[0].baz").unwrap();
        let result = var_access.access(&*TEST_VALUE_1).unwrap();
        assert_eq!(*result, json!(42));
    }

    #[test]
    fn test_var_access_root_index() {
        let var_access = VarAccess::try_from("arr[1]").unwrap();
        let result = var_access.access(&*TEST_VALUE_2).unwrap();
        assert_eq!(*result, json!(2));
    }

    #[test]
    fn test_var_access_array() {
        let var_access = VarAccess::try_from("foo.bar").unwrap();
        let result = var_access.access(&*TEST_VALUE_1).unwrap();
        assert_eq!(*result, json!([{"baz": 42}, {"baz": 43}]));
    }

    #[test]
    fn test_var_access_object() {
        let var_access = VarAccess::try_from("foo").unwrap();
        let result = var_access.access(&*TEST_VALUE_1).unwrap();
        assert_eq!(
            *result,
            json!({
                "bar": [
                    {"baz": 42},
                    {"baz": 43}
                ]
            })
        );
    }

    #[test]
    fn test_var_access_null() {
        let var_access = VarAccess::try_from("null_value").unwrap();
        let result = var_access.access(&*TEST_VALUE_2).unwrap();
        assert_eq!(*result, json!(null));
    }

    #[test]
    fn test_var_access_from_bindings() {
        let env = Env::<serde_json::Value>::new()
            .bind_ref("test", &TEST_VALUE_1)
            .bind_ref("other", &TEST_VALUE_2)
            .build();

        let var_access = VarAccess::try_from("test.foo.bar[1].baz").unwrap();
        let result = var_access.access_from_bindings(&env).unwrap();
        assert_eq!(*result, json!(43));

        let var_access = VarAccess::try_from("other.arr[1]").unwrap();
        let result = var_access.access_from_bindings(&env).unwrap();
        assert_eq!(*result, json!(2));
    }

    #[test]
    fn test_var_access_errors() {
        let var_access = VarAccess::try_from("foo.bar[2].baz").unwrap();
        let result = var_access.access(&*TEST_VALUE_1);
        assert!(matches!(
            result,
            Err(VarAccessError::IndexOutOfBounds { .. })
        ));

        let var_access = VarAccess::try_from("foo.baz").unwrap();
        let result = var_access.access(&*TEST_VALUE_1);
        assert!(matches!(result, Err(VarAccessError::ObjectKeyError { .. })));

        let var_access = VarAccess::try_from("foo.bar[0].baz.qux").unwrap();
        let result = var_access.access(&*TEST_VALUE_1);
        assert!(matches!(result, Err(VarAccessError::ObjectKeyError { .. })));

        let var_access = VarAccess::try_from("foo[0]").unwrap();
        let result = var_access.access(&*TEST_VALUE_1);
        assert!(matches!(result, Err(VarAccessError::TypeError { .. })));
    }
}