Skip to main content

brrrty_js/
value.rs

1//! The `Value` type.
2
3use std::sync::Arc;
4
5use chrono::{DateTime, FixedOffset};
6use indexmap::IndexMap;
7
8use crate::number::{js_number_to_string, js_string_to_number};
9use crate::tz::Tz;
10
11/// A JavaScript-like value. Objects keep their insertion order.
12#[derive(Debug, Clone, PartialEq)]
13pub enum Value {
14    Undefined,
15    Null,
16    Bool(bool),
17    Number(f64),
18    String(Arc<str>),
19    Array(Arc<Vec<Value>>),
20    Object(Arc<IndexMap<String, Value>>),
21    Date(DateTime<FixedOffset>),
22    /// A function from JavaScript data, still in the runtime that made it.
23    /// Templates can call it; any other use of it is a trap (see
24    /// [`crate::functions`]).
25    Function(FnHandle),
26}
27
28/// A function value that stayed in the JavaScript runtime, to be called
29/// later.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31pub struct FnHandle(pub u32);
32
33impl Value {
34    /// Converts JSON, keeping object key order (relies on `serde_json`'s `preserve_order`).
35    pub fn from_json(v: &serde_json::Value) -> Value {
36        match v {
37            serde_json::Value::Null => Value::Null,
38            serde_json::Value::Bool(b) => Value::Bool(*b),
39            serde_json::Value::Number(n) => Value::Number(n.as_f64().unwrap_or(f64::NAN)),
40            serde_json::Value::String(s) => Value::String(s.as_str().into()),
41            serde_json::Value::Array(a) => {
42                Value::Array(Arc::new(a.iter().map(Value::from_json).collect()))
43            }
44            serde_json::Value::Object(o) => Value::Object(Arc::new(
45                o.iter()
46                    .map(|(k, v)| (k.clone(), Value::from_json(v)))
47                    .collect(),
48            )),
49        }
50    }
51
52    /// Liquid truthiness: only `false`, `null` and `undefined` are falsy.
53    pub fn liquid_truthy(&self) -> bool {
54        !matches!(self, Value::Undefined | Value::Null | Value::Bool(false))
55    }
56
57    /// JavaScript truthiness: `false`, `0`, `-0`, `NaN`, `""`, `null` and `undefined` are falsy.
58    pub fn js_truthy(&self) -> bool {
59        match self {
60            Value::Undefined | Value::Null => false,
61            Value::Bool(b) => *b,
62            Value::Number(n) => *n != 0.0 && !n.is_nan(),
63            Value::String(s) => !s.is_empty(),
64            Value::Array(_) | Value::Object(_) | Value::Date(_) | Value::Function(_) => true,
65        }
66    }
67
68    /// JavaScript's `String(v)`, printing a `Date` in UTC. Use
69    /// [`Value::to_js_string_in`] to print it in another zone.
70    pub fn to_js_string(&self) -> String {
71        self.to_js_string_in(Tz::Utc)
72    }
73
74    /// JavaScript's `String(v)`, printing a `Date` as
75    /// `Date.prototype.toString` does in `tz`, with the zone's long name:
76    /// `Tue Mar 03 2026 19:00:00 GMT-0500 (Eastern Standard Time)`.
77    pub fn to_js_string_in(&self, tz: Tz) -> String {
78        match self {
79            Value::Undefined => "undefined".into(),
80            Value::Null => "null".into(),
81            Value::Bool(b) => b.to_string(),
82            Value::Number(n) => js_number_to_string(*n),
83            Value::String(s) => s.to_string(),
84            // Array.prototype.toString: join(","), with null and undefined as empty strings.
85            Value::Array(a) => a
86                .iter()
87                .map(|v| match v {
88                    Value::Null | Value::Undefined => String::new(),
89                    v => v.to_js_string_in(tz),
90                })
91                .collect::<Vec<_>>()
92                .join(","),
93            Value::Object(_) => "[object Object]".into(),
94            Value::Date(d) => crate::tz::date_to_string(tz, d.timestamp_millis() as f64),
95            // JavaScript prints the function's source text.
96            Value::Function(_) => {
97                crate::functions::used_as_value("prints");
98                String::new()
99            }
100        }
101    }
102
103    /// JavaScript's `Number(v)`. Arrays and objects go through their
104    /// string form, as `ToPrimitive` does; a `Date` is its time in
105    /// milliseconds.
106    pub fn to_js_number(&self) -> f64 {
107        match self {
108            Value::Undefined => f64::NAN,
109            Value::Null => 0.0,
110            Value::Bool(b) => f64::from(u8::from(*b)),
111            Value::Number(n) => *n,
112            Value::String(s) => js_string_to_number(s),
113            Value::Array(_) | Value::Object(_) => js_string_to_number(&self.to_js_string()),
114            Value::Date(d) => d.timestamp_millis() as f64,
115            Value::Function(_) => {
116                crate::functions::used_as_value("reads a number from");
117                f64::NAN
118            }
119        }
120    }
121
122    /// An object's entries in JavaScript's own-key order: keys that are
123    /// array indexes (`"0"` to `"4294967294"`, written canonically) come
124    /// first in numeric order, then the other keys in insertion order. This
125    /// is the order `Object.keys` and `for...in` give.
126    pub fn js_entries(o: &IndexMap<String, Value>) -> Vec<(&String, &Value)> {
127        crate::traps::entries(o);
128        Self::js_order(o)
129    }
130
131    /// [`Value::js_entries`], or `None` when listing `o` is a trap (see
132    /// [`crate::traps::entries`]): a walk that meets one can stop, since the
133    /// render will be refused.
134    pub fn js_entries_or_trap(o: &IndexMap<String, Value>) -> Option<Vec<(&String, &Value)>> {
135        if crate::traps::entries(o) {
136            return None;
137        }
138        Some(Self::js_order(o))
139    }
140
141    fn js_order(o: &IndexMap<String, Value>) -> Vec<(&String, &Value)> {
142        let mut index: Vec<(u32, (&String, &Value))> = Vec::new();
143        let mut rest = Vec::new();
144        for (k, v) in o {
145            match array_index(k) {
146                Some(i) => index.push((i, (k, v))),
147                None => rest.push((k, v)),
148            }
149        }
150        index.sort_by_key(|(i, _)| *i);
151        index.into_iter().map(|(_, e)| e).chain(rest).collect()
152    }
153
154    /// Property lookup. Only `.length` is special-cased (UTF-16 length for strings); Liquid's
155    /// `.size`, `.first` and `.last` belong to `brrrty-liquid`.
156    pub fn get(&self, key: &str) -> Value {
157        match self {
158            Value::String(s) if key == "length" => Value::Number(s.encode_utf16().count() as f64),
159            Value::Array(a) if key == "length" => Value::Number(a.len() as f64),
160            Value::Object(o) => o.get(key).cloned().unwrap_or(Value::Undefined),
161            // A function has properties of its own (`length`, `name`).
162            Value::Function(_) => {
163                crate::functions::used_as_value("reads a property of");
164                Value::Undefined
165            }
166            _ => Value::Undefined,
167        }
168    }
169
170    /// Bracket lookup as LiquidJS does it: negative array indexes count from the end, and
171    /// numeric strings index arrays like property names do.
172    pub fn index(&self, i: &Value) -> Value {
173        if matches!(i, Value::Function(_)) {
174            crate::functions::used_as_value("uses as a key");
175            return Value::Undefined;
176        }
177        match self {
178            Value::Function(_) => {
179                crate::functions::used_as_value("reads a property of");
180                Value::Undefined
181            }
182            Value::Array(a) => match i {
183                Value::Number(n) => {
184                    let len = a.len() as f64;
185                    let idx = if *n < 0.0 { len + n } else { *n };
186                    if idx.fract() == 0.0 && idx >= 0.0 && idx < len {
187                        a[idx as usize].clone()
188                    } else {
189                        Value::Undefined
190                    }
191                }
192                Value::String(s) => match s.parse::<usize>() {
193                    Ok(n) if n.to_string() == **s => a.get(n).cloned().unwrap_or(Value::Undefined),
194                    _ => self.get(s),
195                },
196                _ => Value::Undefined,
197            },
198            Value::String(s) => match i {
199                Value::Number(n) if *n >= 0.0 && n.fract() == 0.0 => s
200                    .encode_utf16()
201                    .nth(*n as usize)
202                    .map(|u| Value::String(String::from_utf16_lossy(&[u]).into()))
203                    .unwrap_or(Value::Undefined),
204                Value::String(k) => self.get(k),
205                _ => Value::Undefined,
206            },
207            Value::Object(_) => match i {
208                Value::String(_) | Value::Number(_) | Value::Bool(_) => self.get(&i.to_js_string()),
209                _ => Value::Undefined,
210            },
211            _ => Value::Undefined,
212        }
213    }
214}
215
216/// `key` as an array index, if it is one written canonically: `"7"` but not
217/// `"07"`, `"-1"` or `"4294967295"`.
218pub fn array_index(key: &str) -> Option<u32> {
219    let n: u32 = key.parse().ok()?;
220    (n != u32::MAX && n.to_string() == key).then_some(n)
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226    use serde_json::json;
227
228    fn s(x: &str) -> Value {
229        Value::String(x.into())
230    }
231    fn arr(v: Vec<Value>) -> Value {
232        Value::Array(Arc::new(v))
233    }
234    fn obj(pairs: &[(&str, Value)]) -> Value {
235        Value::Object(Arc::new(
236            pairs
237                .iter()
238                .map(|(k, v)| (k.to_string(), v.clone()))
239                .collect(),
240        ))
241    }
242    fn date() -> Value {
243        Value::Date(DateTime::parse_from_rfc3339("1970-01-01T00:00:00+00:00").unwrap())
244    }
245
246    #[test]
247    fn truthiness_tables() {
248        let all = [
249            (Value::Undefined, false, false),
250            (Value::Null, false, false),
251            (Value::Bool(false), false, false),
252            (Value::Bool(true), true, true),
253            (Value::Number(0.0), true, false),
254            (Value::Number(-0.0), true, false),
255            (Value::Number(f64::NAN), true, false),
256            (Value::Number(2.0), true, true),
257            (s(""), true, false),
258            (s("0"), true, true),
259            (arr(vec![]), true, true),
260            (obj(&[]), true, true),
261            (date(), true, true),
262        ];
263        for (v, liquid, js) in all {
264            assert_eq!(v.liquid_truthy(), liquid, "liquid {v:?}");
265            assert_eq!(v.js_truthy(), js, "js {v:?}");
266        }
267    }
268
269    #[test]
270    fn from_json_keeps_key_order() {
271        let j: serde_json::Value =
272            serde_json::from_str(r#"{"b":1,"a":{"z":null,"y":[true,"x"]}}"#).unwrap();
273        let v = Value::from_json(&j);
274        let Value::Object(o) = &v else { panic!() };
275        assert_eq!(o.keys().collect::<Vec<_>>(), ["b", "a"]);
276        let Value::Object(inner) = &o["a"] else {
277            panic!()
278        };
279        assert_eq!(inner.keys().collect::<Vec<_>>(), ["z", "y"]);
280        assert_eq!(inner["z"], Value::Null);
281        assert_eq!(Value::from_json(&json!(1.5)), Value::Number(1.5));
282    }
283
284    #[test]
285    fn to_js_string_matches_node() {
286        // Verified with: node -e 'String([1,[2,3]]), String([null,undefined,1]), String({})'
287        assert_eq!(
288            arr(vec![
289                Value::Number(1.0),
290                arr(vec![Value::Number(2.0), Value::Number(3.0)])
291            ])
292            .to_js_string(),
293            "1,2,3"
294        );
295        assert_eq!(
296            arr(vec![Value::Null, Value::Undefined, Value::Number(1.0)]).to_js_string(),
297            ",,1"
298        );
299        assert_eq!(obj(&[("a", Value::Null)]).to_js_string(), "[object Object]");
300        assert_eq!(Value::Null.to_js_string(), "null");
301        assert_eq!(Value::Undefined.to_js_string(), "undefined");
302        assert_eq!(Value::Bool(true).to_js_string(), "true");
303        assert_eq!(Value::Number(1e21).to_js_string(), "1e+21");
304        assert_eq!(s("hi").to_js_string(), "hi");
305        assert_eq!(arr(vec![]).to_js_string(), "");
306    }
307
308    #[test]
309    fn to_js_number_matches_node() {
310        // node: Number(undefined), Number(null), Number(true), Number([2]),
311        // Number([1,2]), Number([]), Number({}), Number(new Date(0)), Number(' 0x10 ')
312        assert!(Value::Undefined.to_js_number().is_nan());
313        assert_eq!(Value::Null.to_js_number(), 0.0);
314        assert_eq!(Value::Bool(true).to_js_number(), 1.0);
315        assert_eq!(arr(vec![Value::Number(2.0)]).to_js_number(), 2.0);
316        assert!(
317            arr(vec![Value::Number(1.0), Value::Number(2.0)])
318                .to_js_number()
319                .is_nan()
320        );
321        assert_eq!(arr(vec![]).to_js_number(), 0.0);
322        assert!(obj(&[]).to_js_number().is_nan());
323        assert_eq!(date().to_js_number(), 0.0);
324        assert_eq!(s(" 0x10 ").to_js_number(), 16.0);
325    }
326
327    #[test]
328    fn js_entries_put_index_keys_first() {
329        // node: Object.keys({b:1,"1":2,a:3,"0":4,"4294967295":5,"4294967294":6,"-1":7,"01":8,"1.5":9})
330        let keys = [
331            "b",
332            "1",
333            "a",
334            "0",
335            "4294967295",
336            "4294967294",
337            "-1",
338            "01",
339            "1.5",
340        ];
341        let o: IndexMap<String, Value> =
342            keys.iter().map(|k| (k.to_string(), Value::Null)).collect();
343        let got: Vec<&str> = Value::js_entries(&o)
344            .iter()
345            .map(|(k, _)| k.as_str())
346            .collect();
347        assert_eq!(
348            got,
349            [
350                "0",
351                "1",
352                "4294967294",
353                "b",
354                "a",
355                "4294967295",
356                "-1",
357                "01",
358                "1.5"
359            ]
360        );
361    }
362
363    #[test]
364    fn get_length_is_utf16() {
365        assert_eq!(s("😀").get("length"), Value::Number(2.0));
366        assert_eq!(s("héllo😀").get("length"), Value::Number(7.0));
367        assert_eq!(arr(vec![Value::Null; 3]).get("length"), Value::Number(3.0));
368        assert_eq!(
369            obj(&[("k", Value::Number(1.0))]).get("k"),
370            Value::Number(1.0)
371        );
372        assert_eq!(
373            obj(&[("length", Value::Number(7.0))]).get("length"),
374            Value::Number(7.0)
375        );
376        assert_eq!(obj(&[]).get("nope"), Value::Undefined);
377        assert_eq!(Value::Null.get("x"), Value::Undefined);
378        assert_eq!(Value::Number(5.0).get("length"), Value::Undefined);
379        assert_eq!(date().get("length"), Value::Undefined);
380    }
381
382    #[test]
383    fn index_follows_liquidjs() {
384        // Probed against liquidjs 10.30.1: a[-1] is the last item, a[-4] and a[5] are empty,
385        // a['1'] and a['length'] work, s[0] is a char, s[-1] is empty.
386        let a = arr(vec![
387            Value::Number(10.0),
388            Value::Number(20.0),
389            Value::Number(30.0),
390        ]);
391        assert_eq!(a.index(&Value::Number(0.0)), Value::Number(10.0));
392        assert_eq!(a.index(&Value::Number(-1.0)), Value::Number(30.0));
393        assert_eq!(a.index(&Value::Number(-4.0)), Value::Undefined);
394        assert_eq!(a.index(&Value::Number(5.0)), Value::Undefined);
395        assert_eq!(a.index(&Value::Number(1.5)), Value::Undefined);
396        assert_eq!(a.index(&s("1")), Value::Number(20.0));
397        assert_eq!(a.index(&s("length")), Value::Number(3.0));
398        assert_eq!(a.index(&Value::Bool(true)), Value::Undefined);
399        assert_eq!(a.index(&Value::Null), Value::Undefined);
400        assert_eq!(s("héllo").index(&Value::Number(1.0)), s("é"));
401        assert_eq!(s("hi").index(&Value::Number(-1.0)), Value::Undefined);
402        assert_eq!(s("hi").index(&Value::Number(9.0)), Value::Undefined);
403        let o = obj(&[("k", Value::Number(1.0)), ("0", Value::Bool(true))]);
404        assert_eq!(o.index(&s("k")), Value::Number(1.0));
405        assert_eq!(o.index(&Value::Number(0.0)), Value::Bool(true));
406        assert_eq!(
407            Value::Number(5.0).index(&Value::Number(0.0)),
408            Value::Undefined
409        );
410    }
411}