Skip to main content

predicator_rs/
value.rs

1//! The value domain: what a context holds, an instruction pushes and an
2//! evaluation answers.
3
4use crate::{Date, DateTime, Duration, Key, Map};
5use core::cmp::Ordering;
6use core::fmt;
7
8/// A predicator value.
9///
10/// `Null` and `Undefined` are both values and neither is the other:
11/// undefined is an absence (no value was ever supplied), null is a value
12/// that is present and empty. An integer is an `i64`; a float an `f64`.
13///
14/// Equality (`==`) is strict: two values are equal when they are the same
15/// kind and the same value, so `Integer(1)` and `Float(1.0)` are not equal,
16/// two instants are equal when they are the same instant, and lists and
17/// maps are equal member by member. Ordering (`partial_cmp`) agrees with
18/// it: integers and floats order by number (an integer and a float at the
19/// same number are unordered, being unequal), strings by codepoint, `false`
20/// before `true`, dates and instants chronologically, lists member by
21/// member with a proper prefix first; two maps, two durations or two values
22/// of other kinds are unordered unless equal. The `compare` instruction's
23/// own rules are the evaluator's, not these.
24///
25/// Equality, ordering, cloning, `Debug` and dropping walk a value without
26/// recursion, so a value nested deeper than the stack is compared, copied,
27/// printed and dropped without exhausting it. Because `Value` implements
28/// `Drop`, a member is taken out of a value with [`core::mem::replace`]
29/// rather than moved out of a pattern.
30///
31/// ```
32/// use predicator_rs::Value;
33///
34/// let list = Value::from(vec![Value::from(1), Value::from("x"), Value::Null]);
35/// assert_eq!(list, Value::List(vec![1.into(), "x".into(), Value::Null]));
36/// assert_ne!(Value::from(1), Value::from(1.0));
37/// assert!(Value::from(1) < Value::from(1.5));
38/// assert_ne!(Value::Null, Value::Undefined);
39/// ```
40#[non_exhaustive]
41pub enum Value {
42    /// A value that is present and empty.
43    Null,
44    /// An absence: no value was ever supplied.
45    Undefined,
46    /// `true` or `false`.
47    Bool(bool),
48    /// An integer.
49    Integer(i64),
50    /// A float.
51    Float(f64),
52    /// A string.
53    String(String),
54    /// A list.
55    List(Vec<Value>),
56    /// A map from [`Key`]s.
57    Map(Map),
58    /// A civil date.
59    Date(Date),
60    /// An instant in UTC.
61    DateTime(DateTime),
62    /// A duration.
63    Duration(Duration),
64}
65
66/// Moves the members of a list or a map out of `value` onto `into`.
67fn take_members(value: &mut Value, into: &mut Vec<Value>) {
68    match value {
69        Value::List(items) => into.append(items),
70        Value::Map(map) => into.extend(core::mem::take(&mut map.entries).into_values()),
71        _ => {}
72    }
73}
74
75impl Drop for Value {
76    /// Drops the members of a list or a map from a work list rather than by
77    /// recursion: each member is emptied of its own members before it is
78    /// dropped.
79    fn drop(&mut self) {
80        let mut pending = Vec::new();
81        take_members(self, &mut pending);
82        while let Some(mut member) = pending.pop() {
83            take_members(&mut member, &mut pending);
84        }
85    }
86}
87
88/// A copy of a value that is neither a list nor a map; a list or a map
89/// comes back empty, its members built by the caller.
90fn shallow_copy(value: &Value) -> Value {
91    match value {
92        Value::Null => Value::Null,
93        Value::Undefined => Value::Undefined,
94        Value::Bool(flag) => Value::Bool(*flag),
95        Value::Integer(number) => Value::Integer(*number),
96        Value::Float(number) => Value::Float(*number),
97        Value::String(text) => Value::String(text.clone()),
98        Value::List(_) => Value::List(Vec::new()),
99        Value::Map(_) => Value::Map(Map::new()),
100        Value::Date(date) => Value::Date(*date),
101        Value::DateTime(instant) => Value::DateTime(*instant),
102        Value::Duration(duration) => Value::Duration(*duration),
103    }
104}
105
106/// One step of an iterative copy.
107enum Copy<'a> {
108    /// Copy this value onto the built stack.
109    Visit(&'a Value),
110    /// Gather the last `count` built values into a list.
111    List(usize),
112    /// Gather the last built values, one per key, into a map.
113    Map(Vec<&'a Key>),
114}
115
116impl Clone for Value {
117    fn clone(&self) -> Value {
118        let mut work = vec![Copy::Visit(self)];
119        let mut built: Vec<Value> = Vec::new();
120        while let Some(step) = work.pop() {
121            match step {
122                Copy::Visit(Value::List(items)) => {
123                    work.push(Copy::List(items.len()));
124                    work.extend(items.iter().rev().map(Copy::Visit));
125                }
126                Copy::Visit(Value::Map(map)) => {
127                    work.push(Copy::Map(map.entries.keys().collect()));
128                    work.extend(map.entries.values().rev().map(Copy::Visit));
129                }
130                Copy::Visit(value) => built.push(shallow_copy(value)),
131                Copy::List(count) => {
132                    let items = built.split_off(built.len().saturating_sub(count));
133                    built.push(Value::List(items));
134                }
135                Copy::Map(keys) => {
136                    let values = built.split_off(built.len().saturating_sub(keys.len()));
137                    let entries = keys.into_iter().cloned().zip(values).collect();
138                    built.push(Value::Map(Map { entries }));
139                }
140            }
141        }
142        built.pop().unwrap_or(Value::Null)
143    }
144}
145
146/// Whether two values that are not both lists nor both maps are equal.
147fn scalar_equal(left: &Value, right: &Value) -> bool {
148    match (left, right) {
149        (Value::Null, Value::Null) | (Value::Undefined, Value::Undefined) => true,
150        (Value::Bool(a), Value::Bool(b)) => a == b,
151        (Value::Integer(a), Value::Integer(b)) => a == b,
152        (Value::Float(a), Value::Float(b)) => a == b,
153        (Value::String(a), Value::String(b)) => a == b,
154        (Value::Date(a), Value::Date(b)) => a == b,
155        (Value::DateTime(a), Value::DateTime(b)) => a == b,
156        (Value::Duration(a), Value::Duration(b)) => a == b,
157        _ => false,
158    }
159}
160
161impl PartialEq for Value {
162    fn eq(&self, other: &Value) -> bool {
163        let mut pending = vec![(self, other)];
164        while let Some(pair) = pending.pop() {
165            match pair {
166                (Value::List(left), Value::List(right)) => {
167                    if left.len() != right.len() {
168                        return false;
169                    }
170                    pending.extend(left.iter().zip(right));
171                }
172                (Value::Map(left), Value::Map(right)) => {
173                    if left.len() != right.len() {
174                        return false;
175                    }
176                    for ((left_key, left), (right_key, right)) in
177                        left.entries.iter().zip(&right.entries)
178                    {
179                        if left_key != right_key {
180                            return false;
181                        }
182                        pending.push((left, right));
183                    }
184                }
185                (left, right) => {
186                    if !scalar_equal(left, right) {
187                        return false;
188                    }
189                }
190            }
191        }
192        true
193    }
194}
195
196/// How an integer stands to a finite float, by number: exactly, with no
197/// rounding of the integer to a float.
198pub(crate) fn integer_against_float(integer: i64, float: f64) -> Option<Ordering> {
199    // 2^63, exactly representable as a float.
200    const LIMIT: f64 = 9_223_372_036_854_775_808.0;
201    if float.is_nan() {
202        return None;
203    }
204    if float >= LIMIT {
205        return Some(Ordering::Less);
206    }
207    if float < -LIMIT {
208        return Some(Ordering::Greater);
209    }
210    let whole = float.trunc();
211    // In range and whole, so the cast is exact; at the same whole number
212    // the fraction decides.
213    match integer.cmp(&(whole as i64)) {
214        Ordering::Equal => 0.0_f64.partial_cmp(&(float - whole)),
215        decided => Some(decided),
216    }
217}
218
219/// How two values that are not both lists stand to each other; `None` when
220/// they are unordered.
221fn scalar_order(left: &Value, right: &Value) -> Option<Ordering> {
222    let unequal = |ordering: Option<Ordering>| ordering.filter(|&o| o != Ordering::Equal);
223    match (left, right) {
224        (Value::Bool(a), Value::Bool(b)) => Some(a.cmp(b)),
225        (Value::Integer(a), Value::Integer(b)) => Some(a.cmp(b)),
226        (Value::Float(a), Value::Float(b)) => a.partial_cmp(b),
227        (Value::Integer(a), Value::Float(b)) => unequal(integer_against_float(*a, *b)),
228        (Value::Float(a), Value::Integer(b)) => {
229            unequal(integer_against_float(*b, *a)).map(Ordering::reverse)
230        }
231        (Value::String(a), Value::String(b)) => Some(a.cmp(b)),
232        (Value::Date(a), Value::Date(b)) => Some(a.cmp(b)),
233        (Value::DateTime(a), Value::DateTime(b)) => Some(a.cmp(b)),
234        _ => (left == right).then_some(Ordering::Equal),
235    }
236}
237
238impl PartialOrd for Value {
239    fn partial_cmp(&self, other: &Value) -> Option<Ordering> {
240        // Each frame is a pair of lists and the index of the next member
241        // pair to compare.
242        let mut frames: Vec<(&[Value], &[Value], usize)> = Vec::new();
243        let mut current = (self, other);
244        loop {
245            match current {
246                (Value::List(left), Value::List(right)) => frames.push((left, right, 0)),
247                (left, right) => match scalar_order(left, right) {
248                    Some(Ordering::Equal) => {}
249                    decided => return decided,
250                },
251            }
252            loop {
253                let Some((left, right, index)) = frames.last_mut() else {
254                    return Some(Ordering::Equal);
255                };
256                match (left.get(*index), right.get(*index)) {
257                    (Some(left), Some(right)) => {
258                        *index += 1;
259                        current = (left, right);
260                        break;
261                    }
262                    (None, Some(_)) => return Some(Ordering::Less),
263                    (Some(_), None) => return Some(Ordering::Greater),
264                    (None, None) => {
265                        frames.pop();
266                    }
267                }
268            }
269        }
270    }
271}
272
273/// One piece of an iterative `Debug` print.
274enum Piece<'a> {
275    Value(&'a Value),
276    Text(&'static str),
277    Key(&'a Key),
278}
279
280impl fmt::Debug for Value {
281    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282        let mut work = vec![Piece::Value(self)];
283        while let Some(piece) = work.pop() {
284            match piece {
285                Piece::Text(text) => f.write_str(text)?,
286                Piece::Key(key) => write!(f, "{key:?}: ")?,
287                Piece::Value(Value::List(items)) => {
288                    f.write_str("List([")?;
289                    work.push(Piece::Text("])"));
290                    for (index, item) in items.iter().enumerate().rev() {
291                        work.push(Piece::Value(item));
292                        if index > 0 {
293                            work.push(Piece::Text(", "));
294                        }
295                    }
296                }
297                Piece::Value(Value::Map(map)) => {
298                    f.write_str("Map({")?;
299                    work.push(Piece::Text("})"));
300                    for (index, (key, item)) in map.entries.iter().enumerate().rev() {
301                        work.push(Piece::Value(item));
302                        work.push(Piece::Key(key));
303                        if index > 0 {
304                            work.push(Piece::Text(", "));
305                        }
306                    }
307                }
308                Piece::Value(Value::Null) => f.write_str("Null")?,
309                Piece::Value(Value::Undefined) => f.write_str("Undefined")?,
310                Piece::Value(Value::Bool(flag)) => write!(f, "Bool({flag})")?,
311                Piece::Value(Value::Integer(number)) => write!(f, "Integer({number})")?,
312                Piece::Value(Value::Float(number)) => write!(f, "Float({number:?})")?,
313                Piece::Value(Value::String(text)) => write!(f, "String({text:?})")?,
314                Piece::Value(Value::Date(date)) => write!(f, "{date:?}")?,
315                Piece::Value(Value::DateTime(instant)) => write!(f, "{instant:?}")?,
316                Piece::Value(Value::Duration(duration)) => write!(f, "{duration:?}")?,
317            }
318        }
319        Ok(())
320    }
321}
322
323impl From<bool> for Value {
324    fn from(flag: bool) -> Value {
325        Value::Bool(flag)
326    }
327}
328
329impl From<i64> for Value {
330    fn from(number: i64) -> Value {
331        Value::Integer(number)
332    }
333}
334
335impl From<f64> for Value {
336    fn from(number: f64) -> Value {
337        Value::Float(number)
338    }
339}
340
341impl From<&str> for Value {
342    fn from(text: &str) -> Value {
343        Value::String(text.to_owned())
344    }
345}
346
347impl From<String> for Value {
348    fn from(text: String) -> Value {
349        Value::String(text)
350    }
351}
352
353impl From<Vec<Value>> for Value {
354    fn from(items: Vec<Value>) -> Value {
355        Value::List(items)
356    }
357}
358
359impl From<Map> for Value {
360    fn from(map: Map) -> Value {
361        Value::Map(map)
362    }
363}
364
365impl From<Date> for Value {
366    fn from(date: Date) -> Value {
367        Value::Date(date)
368    }
369}
370
371impl From<DateTime> for Value {
372    fn from(instant: DateTime) -> Value {
373        Value::DateTime(instant)
374    }
375}
376
377impl From<Duration> for Value {
378    fn from(duration: Duration) -> Value {
379        Value::Duration(duration)
380    }
381}
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386
387    fn date(year: i32, month: u32, day: u32) -> Date {
388        Date::new(year, month, day).unwrap()
389    }
390
391    fn every_kind() -> Vec<Value> {
392        let instant = DateTime::new(date(2026, 8, 9), 10, 30, 0, 500_000).unwrap();
393        vec![
394            Value::Null,
395            Value::Undefined,
396            Value::from(true),
397            Value::from(-7),
398            Value::from(2.5),
399            Value::from("x"),
400            Value::from(vec![Value::from(1), Value::Null]),
401            Value::from([("a", Value::from(1))].into_iter().collect::<Map>()),
402            Value::from(date(2026, 8, 9)),
403            Value::from(instant),
404            Value::from(Duration {
405                days: 3,
406                ..Duration::default()
407            }),
408        ]
409    }
410
411    // Sabotage: with scalar_equal's Duration arm answering true for any two
412    // durations, this test fails.
413    #[test]
414    fn each_kind_equals_itself_and_no_other_kind() {
415        let values = every_kind();
416        for (i, left) in values.iter().enumerate() {
417            for (j, right) in values.iter().enumerate() {
418                assert_eq!(left == right, i == j, "{left:?} against {right:?}");
419            }
420            assert_eq!(&left.clone(), left);
421        }
422        assert_ne!(Value::from(1), Value::from(1.0));
423        assert_ne!(Value::from("x"), Value::from("y"));
424        assert_ne!(
425            Value::from(Duration {
426                days: 3,
427                ..Duration::default()
428            }),
429            Value::from(Duration {
430                days: 4,
431                ..Duration::default()
432            })
433        );
434        assert_ne!(Value::from(vec![Value::from(1)]), Value::from(vec![]));
435        let map = |key: &str| Value::from([(key, Value::Null)].into_iter().collect::<Map>());
436        assert_ne!(map("a"), map("b"));
437        assert_ne!(map("a"), Value::from(Map::new()));
438        let keyed = |key: Key| Value::from([(key, Value::Null)].into_iter().collect::<Map>());
439        assert_ne!(keyed(Key::from(1)), keyed(Key::from("1")));
440        assert_ne!(keyed(Key::from(true)), keyed(Key::from("true")));
441        assert_eq!(keyed(Key::Undefined), keyed(Key::Undefined));
442        assert_ne!(
443            Value::from([("a", Value::from(1))].into_iter().collect::<Map>()),
444            Value::from([("a", Value::from(2))].into_iter().collect::<Map>())
445        );
446    }
447
448    // Sabotage: with the reverse dropped from the Float-Integer arm of
449    // scalar_order, this test fails.
450    #[test]
451    fn values_order_within_their_kind_and_numbers_across_two() {
452        let order = |a: Value, b: Value| a.partial_cmp(&b);
453        assert_eq!(order(1.into(), 2.into()), Some(Ordering::Less));
454        assert_eq!(order(2.5.into(), 1.5.into()), Some(Ordering::Greater));
455        assert_eq!(order(1.into(), 1.5.into()), Some(Ordering::Less));
456        assert_eq!(order(1.5.into(), 1.into()), Some(Ordering::Greater));
457        assert_eq!(order(2.into(), 1.5.into()), Some(Ordering::Greater));
458        assert_eq!(order((-2).into(), (-1.5).into()), Some(Ordering::Less));
459        assert_eq!(order(1.into(), 1.0.into()), None);
460        assert_eq!(order(i64::MAX.into(), 9.3e18.into()), Some(Ordering::Less));
461        assert_eq!(
462            order(i64::MAX.into(), (i64::MAX as f64).into()),
463            Some(Ordering::Less)
464        );
465        assert_eq!(
466            order(i64::MIN.into(), (-9.3e18).into()),
467            Some(Ordering::Greater)
468        );
469        assert_eq!(order(1.into(), f64::NAN.into()), None);
470        assert_eq!(order("b".into(), "a".into()), Some(Ordering::Greater));
471        assert_eq!(order("Z".into(), "a".into()), Some(Ordering::Less));
472        assert_eq!(order(false.into(), true.into()), Some(Ordering::Less));
473        assert_eq!(
474            order(date(2026, 1, 1).into(), date(2025, 12, 31).into()),
475            Some(Ordering::Greater)
476        );
477        let instant = |seconds| Value::from(DateTime::from_unix(seconds, 0).unwrap());
478        assert_eq!(order(instant(0), instant(1)), Some(Ordering::Less));
479        assert_eq!(order(Value::Null, Value::Null), Some(Ordering::Equal));
480        assert_eq!(order(Value::Null, Value::Undefined), None);
481        assert_eq!(order(1.into(), "1".into()), None);
482        let days = |days| {
483            Value::from(Duration {
484                days,
485                ..Duration::default()
486            })
487        };
488        assert_eq!(order(days(1), days(2)), None);
489        assert_eq!(order(days(1), days(1)), Some(Ordering::Equal));
490        let map = |n: i64| Value::from([("a", Value::from(n))].into_iter().collect::<Map>());
491        assert_eq!(order(map(1), map(2)), None);
492        assert_eq!(order(map(1), map(1)), Some(Ordering::Equal));
493    }
494
495    // Sabotage: with a proper prefix ordered after the longer list, this
496    // test fails.
497    #[test]
498    fn lists_order_member_by_member() {
499        let list = |items: Vec<Value>| Value::from(items);
500        let order = |a: Value, b: Value| a.partial_cmp(&b);
501        assert_eq!(
502            order(
503                list(vec![1.into(), 2.into()]),
504                list(vec![1.into(), 3.into()])
505            ),
506            Some(Ordering::Less)
507        );
508        assert_eq!(
509            order(list(vec![1.into()]), list(vec![1.into(), 0.into()])),
510            Some(Ordering::Less)
511        );
512        assert_eq!(
513            order(list(vec![1.into(), 0.into()]), list(vec![1.into()])),
514            Some(Ordering::Greater)
515        );
516        assert_eq!(
517            order(
518                list(vec![list(vec![]), 2.into()]),
519                list(vec![list(vec![]), 2.into()])
520            ),
521            Some(Ordering::Equal)
522        );
523        assert_eq!(
524            order(
525                list(vec![list(vec![1.into()]), 0.into()]),
526                list(vec![list(vec![2.into()])])
527            ),
528            Some(Ordering::Less)
529        );
530        assert_eq!(order(list(vec![1.into()]), list(vec!["a".into()])), None);
531        assert_eq!(order(list(vec![]), 1.into()), None);
532    }
533
534    // Sabotage: with the separator pushed before every list member, the
535    // first included, this test fails.
536    #[test]
537    fn debug_prints_every_kind() {
538        let printed = format!("{:?}", Value::from(every_kind()));
539        assert_eq!(
540            printed,
541            "List([Null, Undefined, Bool(true), Integer(-7), Float(2.5), String(\"x\"), \
542             List([Integer(1), Null]), Map({\"a\": Integer(1)}), Date(2026-08-09), \
543             DateTime(2026-08-09T10:30:00.500000Z), Duration { years: 0, months: 0, weeks: 0, \
544             days: 3, hours: 0, minutes: 0, seconds: 0, milliseconds: 0 }])"
545        );
546        let map: Map = [("a", Value::Null), ("b", Value::Null)]
547            .into_iter()
548            .collect();
549        assert_eq!(
550            format!("{:?}", Value::from(map)),
551            "Map({\"a\": Null, \"b\": Null})"
552        );
553    }
554
555    // Sabotage: with Clone's list step gathering one member fewer, this
556    // test fails.
557    #[test]
558    fn a_clone_is_equal_and_separate() {
559        let original = Value::from(vec![
560            Value::from(every_kind()),
561            Value::from(
562                [("k", Value::from(every_kind()))]
563                    .into_iter()
564                    .collect::<Map>(),
565            ),
566        ]);
567        let mut copy = original.clone();
568        assert!(copy == original);
569        if let Value::List(items) = &mut copy {
570            items.push(Value::Null);
571        }
572        assert!(copy != original);
573    }
574}