Skip to main content

logicaffeine_compile/semantics/
compare.rs

1//! Equality and relational comparison.
2
3use logicaffeine_base::numeric;
4use logicaffeine_base::{BigInt, Rational};
5
6use crate::ast::stmt::BinaryOpKind;
7use crate::interpreter::RuntimeValue;
8
9/// Value equality for the `equals`/`==` operator, set/list membership, and
10/// map keys (`RuntimeValue`'s `PartialEq` delegates here — ONE equality).
11///
12/// - Floats compare by IEEE `==` (`NaN != NaN`, `-0.0 == 0.0`) — identical to
13///   what compiled Rust emits, on every engine.
14/// - Cross-type numeric equality is EXACT (mathematical value, never a lossy
15///   cast): `1 == 1.0`, but `9007199254740993 != 9007199254740993.0` because
16///   that float literal IS `2^53`. Coheres with `compare` and with the
17///   unified numeric hash (`base::numeric`).
18/// - Collections, tuples, and structs compare STRUCTURALLY (same shape, all
19///   parts equal), with an `Rc` identity fast path and a depth cap against
20///   cyclic values.
21/// - Decimal/Complex/Modular keep their documented within-type equality
22///   (they have no cross-type ordering, so there is no coherence to break).
23/// `left = right` (or `≠` when `negate`) as a program asks it: decided exactly where a theorem
24/// decides it, residue-dependent where the answer depends on `⌈1/dt⌉`, and a loud error where two
25/// computable reals agree to the budget and nothing decides them. Every other value compares by
26/// [`values_equal`].
27pub fn equality(left: &RuntimeValue, right: &RuntimeValue, negate: bool) -> Result<RuntimeValue, String> {
28    let rel = if negate { super::exact::Rel::NotEq } else { super::exact::Rel::Eq };
29    if let Some(r) = super::exact::relation(rel, left, right, &exact_relation_recurse) {
30        return r;
31    }
32    Ok(RuntimeValue::Bool(values_equal(left, right) != negate))
33}
34
35/// The relational entry the exact types re-enter to lift a comparison over residue branches.
36fn exact_relation_recurse(
37    rel: super::exact::Rel,
38    a: RuntimeValue,
39    b: RuntimeValue,
40) -> Result<RuntimeValue, String> {
41    use super::exact::Rel;
42    match rel {
43        Rel::Eq => equality(&a, &b, false),
44        Rel::NotEq => equality(&a, &b, true),
45        Rel::Lt => compare(BinaryOpKind::Lt, &a, &b),
46        Rel::Gt => compare(BinaryOpKind::Gt, &a, &b),
47        Rel::LtEq => compare(BinaryOpKind::LtEq, &a, &b),
48        Rel::GtEq => compare(BinaryOpKind::GtEq, &a, &b),
49    }
50}
51
52pub fn values_equal(left: &RuntimeValue, right: &RuntimeValue) -> bool {
53    values_equal_depth(left, right, 0)
54}
55
56/// Cyclic values (a list pushed into itself) bottom out here instead of
57/// overflowing the stack; 256 levels is far beyond any real data shape.
58const EQ_MAX_DEPTH: usize = 256;
59
60/// A CRDT counter (`ConvergentCount`/`Tally`) reads as its integer value everywhere a scalar is
61/// expected — comparison and equality see the number, not the CRDT wrapper. Non-counter CRDTs
62/// (sets/sequences/registers) return `None` and keep their own structural comparison.
63fn counter_as_int(v: &RuntimeValue) -> Option<RuntimeValue> {
64    match v {
65        RuntimeValue::Crdt(c) => c.borrow().counter_value().map(RuntimeValue::Int),
66        _ => None,
67    }
68}
69
70fn values_equal_depth(left: &RuntimeValue, right: &RuntimeValue, depth: usize) -> bool {
71    if depth > EQ_MAX_DEPTH {
72        return false;
73    }
74    if let Some(same) = super::exact::structurally_equal(left, right) {
75        return same;
76    }
77    let (lc, rc) = (counter_as_int(left), counter_as_int(right));
78    let (left, right) = (lc.as_ref().unwrap_or(left), rc.as_ref().unwrap_or(right));
79    match (left, right) {
80        (RuntimeValue::Int(a), RuntimeValue::Int(b)) => a == b,
81        // BigInt holds only out-of-i64 values, so a BigInt never equals an Int; two
82        // BigInts compare by exact magnitude (the `_ => false` arm would be wrong).
83        (RuntimeValue::BigInt(a), RuntimeValue::BigInt(b)) => a == b,
84        // A Rational is never whole, so it never equals an Int/BigInt; Rational==Rational
85        // is exact (reduced form is canonical).
86        (RuntimeValue::Rational(a), RuntimeValue::Rational(b)) => a == b,
87        // Decimal equality is by VALUE (`1.0 == 1.00`); like Int vs Float, a Decimal is
88        // never `==` a value of a different numeric type.
89        (RuntimeValue::Decimal(a), RuntimeValue::Decimal(b)) => a == b,
90        // Complex equality is exact and structural; complex numbers have no ordering, so
91        // `compare` (`< > …`) deliberately falls through to a type error.
92        (RuntimeValue::Complex(a), RuntimeValue::Complex(b)) => a == b,
93        // Floating-point complex: IEEE equality on both parts (like `Float`; NaN parts unequal).
94        // Also unordered, so `compare` falls through to a type error.
95        (RuntimeValue::ComplexF(a), RuntimeValue::ComplexF(b)) => a == b,
96        // Modular equality is per-ring (same residue AND modulus); ℤ/nℤ has no total order,
97        // so `compare` falls through to a type error.
98        (RuntimeValue::Modular(a), RuntimeValue::Modular(b)) => a == b,
99        // IEEE float equality — what the compiled backend emits.
100        (RuntimeValue::Float(a), RuntimeValue::Float(b)) => a == b,
101        // Exact cross-type numeric equality (mathematical values).
102        (RuntimeValue::Int(a), RuntimeValue::Float(b))
103        | (RuntimeValue::Float(b), RuntimeValue::Int(a)) => {
104            numeric::cmp_i64_f64_exact(*a, *b) == Some(std::cmp::Ordering::Equal)
105        }
106        (RuntimeValue::BigInt(a), RuntimeValue::Float(b))
107        | (RuntimeValue::Float(b), RuntimeValue::BigInt(a)) => {
108            numeric::cmp_bigint_f64_exact(a, *b) == Some(std::cmp::Ordering::Equal)
109        }
110        (RuntimeValue::Rational(a), RuntimeValue::Float(b))
111        | (RuntimeValue::Float(b), RuntimeValue::Rational(a)) => {
112            numeric::cmp_rational_f64_exact(a, *b) == Some(std::cmp::Ordering::Equal)
113        }
114        (RuntimeValue::Bool(a), RuntimeValue::Bool(b)) => a == b,
115        (RuntimeValue::Text(a), RuntimeValue::Text(b)) => **a == **b,
116        (RuntimeValue::Char(a), RuntimeValue::Char(b)) => a == b,
117        (RuntimeValue::Nothing, RuntimeValue::Nothing) => true,
118        // ★ R2 — ABSENCE IS ONE THING, however it was spelled.
119        //
120        // `nothing` and `none` are different AST nodes (`Literal::Nothing` vs `Expr::OptionNone`)
121        // and, now that an Option carries a real tag, different runtime values. They must still
122        // compare equal: `x is equal to nothing` is the spelling every `Try to receive`, `Pop` and
123        // `storageGet` result is tested with, and the wasm tier compiles it to a handle test. A
124        // present Option is never equal to `nothing` — that is the whole point of the change.
125        (RuntimeValue::Nothing, RuntimeValue::Inductive(i))
126        | (RuntimeValue::Inductive(i), RuntimeValue::Nothing) => {
127            i.inductive_type == "Option" && i.constructor == "None"
128        }
129        (RuntimeValue::Duration(a), RuntimeValue::Duration(b)) => a == b,
130        (RuntimeValue::Date(a), RuntimeValue::Date(b)) => a == b,
131        (RuntimeValue::Moment(a), RuntimeValue::Moment(b)) => a == b,
132        (
133            RuntimeValue::Span {
134                months: m1,
135                days: d1,
136            },
137            RuntimeValue::Span {
138                months: m2,
139                days: d2,
140            },
141        ) => m1 == m2 && d1 == d2,
142        (RuntimeValue::Time(a), RuntimeValue::Time(b)) => a == b,
143        // Words are equal only at the same width and value (`WordVal`'s derived `Eq`).
144        (RuntimeValue::Word(a), RuntimeValue::Word(b)) => a == b,
145        // Money is value-equal by currency + amount; a Quantity by physical magnitude (display unit
146        // ignored, so `2 inches == 5.08 cm`); a Uuid by its 128 bits.
147        (RuntimeValue::Money(a), RuntimeValue::Money(b)) => a == b,
148        (RuntimeValue::Quantity(a), RuntimeValue::Quantity(b)) => a.q == b.q,
149        (RuntimeValue::Uuid(a), RuntimeValue::Uuid(b)) => a == b,
150        (RuntimeValue::Inductive(a), RuntimeValue::Inductive(b)) => {
151            a.inductive_type == b.inductive_type
152                && a.constructor == b.constructor
153                && a.args.len() == b.args.len()
154                && a.args
155                    .iter()
156                    .zip(b.args.iter())
157                    .all(|(x, y)| values_equal_depth(x, y, depth + 1))
158        }
159        // ── Structural equality ─────────────────────────────────────────
160        (RuntimeValue::List(a), RuntimeValue::List(b)) => {
161            if std::rc::Rc::ptr_eq(a, b) {
162                return true;
163            }
164            let (a, b) = (a.borrow(), b.borrow());
165            a.len() == b.len()
166                && (0..a.len()).all(|i| match (a.get(i), b.get(i)) {
167                    (Some(x), Some(y)) => values_equal_depth(&x, &y, depth + 1),
168                    _ => false,
169                })
170        }
171        (RuntimeValue::Tuple(a), RuntimeValue::Tuple(b)) => {
172            a.len() == b.len()
173                && a.iter()
174                    .zip(b.iter())
175                    .all(|(x, y)| values_equal_depth(x, y, depth + 1))
176        }
177        // Sets compare by CONTENT, order-insensitive (both sides are deduped,
178        // so equal length + one-sided containment is a bijection).
179        (RuntimeValue::Set(a), RuntimeValue::Set(b)) => {
180            if std::rc::Rc::ptr_eq(a, b) {
181                return true;
182            }
183            let (a, b) = (a.borrow(), b.borrow());
184            a.len() == b.len()
185                && a.iter()
186                    .all(|x| b.iter().any(|y| values_equal_depth(x, y, depth + 1)))
187        }
188        // Maps compare by CONTENT, insertion order ignored (like Python dicts).
189        (RuntimeValue::Map(a), RuntimeValue::Map(b)) => {
190            if std::rc::Rc::ptr_eq(a, b) {
191                return true;
192            }
193            let (a, b) = (a.borrow(), b.borrow());
194            a.len() == b.len()
195                && a.iter().all(|(k, va)| {
196                    b.get(k)
197                        .is_some_and(|vb| values_equal_depth(va, vb, depth + 1))
198                })
199        }
200        (RuntimeValue::Struct(a), RuntimeValue::Struct(b)) => {
201            a.type_name == b.type_name
202                && a.fields.len() == b.fields.len()
203                && a.fields.iter().all(|(name, va)| {
204                    b.fields
205                        .get(name)
206                        .is_some_and(|vb| values_equal_depth(va, vb, depth + 1))
207                })
208        }
209        // ── Identity-style values (moved from the old `PartialEq` impl so
210        //    this function is the TOTAL equality it delegates to) ─────────
211        (RuntimeValue::Chan(a), RuntimeValue::Chan(b)) => a == b,
212        (RuntimeValue::TaskHandle(a), RuntimeValue::TaskHandle(b)) => a == b,
213        (RuntimeValue::Peer(a), RuntimeValue::Peer(b)) => **a == **b,
214        (RuntimeValue::Function(a), RuntimeValue::Function(b)) => a.body_index == b.body_index,
215        // Two CRDTs are equal when they observe the same elements (a sequence also
216        // compares order) — the convergence-relevant view, ignoring internal tags.
217        (RuntimeValue::Crdt(a), RuntimeValue::Crdt(b)) => {
218            crate::semantics::crdt::crdt_values_equal(&a.borrow(), &b.borrow())
219        }
220        // Lane vectors compare by value (all lanes equal), consistent with Hash.
221        (RuntimeValue::Lanes(a), RuntimeValue::Lanes(b)) => a == b,
222        _ => false,
223    }
224}
225
226/// Relational comparison (`< > <= >=`).
227///
228/// Floats use IEEE 754 semantics — NaN is unordered (every relational
229/// comparison with a NaN is `false`) and `-0.0 == 0.0` — matching Rust's `f64`
230/// ordering, which is what the compile-to-Rust path emits. Integer and
231/// temporal types use the natural total order; a Moment compares against a
232/// Time by its time-of-day.
233pub fn compare(
234    op: BinaryOpKind,
235    left: &RuntimeValue,
236    right: &RuntimeValue,
237) -> Result<RuntimeValue, String> {
238    use std::cmp::Ordering;
239
240    let rel = match op {
241        BinaryOpKind::Lt => Some(super::exact::Rel::Lt),
242        BinaryOpKind::Gt => Some(super::exact::Rel::Gt),
243        BinaryOpKind::LtEq => Some(super::exact::Rel::LtEq),
244        BinaryOpKind::GtEq => Some(super::exact::Rel::GtEq),
245        _ => None,
246    };
247    if let Some(rel) = rel {
248        if let Some(r) = super::exact::relation(rel, left, right, &exact_relation_recurse) {
249            return r;
250        }
251    }
252
253    // A counter compares by its integer value (the CRDT wrapper is transparent to `< > <= >=`).
254    let (lc, rc) = (counter_as_int(left), counter_as_int(right));
255    let (left, right) = (lc.as_ref().unwrap_or(left), rc.as_ref().unwrap_or(right));
256
257    // Map an `Ordering` (or `None` for an unordered/NaN pair) to the operator.
258    let rel = |ord: Option<Ordering>| -> bool {
259        match ord {
260            None => false,
261            Some(o) => match op {
262                BinaryOpKind::Lt => o == Ordering::Less,
263                BinaryOpKind::Gt => o == Ordering::Greater,
264                BinaryOpKind::LtEq => o != Ordering::Greater,
265                BinaryOpKind::GtEq => o != Ordering::Less,
266                _ => false,
267            },
268        }
269    };
270    let int_rel = |a: i64, b: i64| rel(Some(a.cmp(&b)));
271
272    match (left, right) {
273        (RuntimeValue::Int(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Bool(int_rel(*a, *b))),
274        // Exact integer ordering across the narrow/wide boundary: compare as BigInts.
275        (RuntimeValue::BigInt(a), RuntimeValue::BigInt(b)) => {
276            Ok(RuntimeValue::Bool(rel(Some((**a).cmp(b)))))
277        }
278        (RuntimeValue::BigInt(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Bool(rel(Some(
279            (**a).cmp(&BigInt::from_i64(*b)),
280        )))),
281        (RuntimeValue::Int(a), RuntimeValue::BigInt(b)) => {
282            Ok(RuntimeValue::Bool(rel(Some(BigInt::from_i64(*a).cmp(b)))))
283        }
284        // Cross-type numeric ordering is EXACT — mathematical values, never a
285        // lossy as-f64 view (which rounds above 2^53). NaN stays unordered.
286        (RuntimeValue::BigInt(a), RuntimeValue::Float(b)) => Ok(RuntimeValue::Bool(rel(
287            numeric::cmp_bigint_f64_exact(a, *b),
288        ))),
289        (RuntimeValue::Float(a), RuntimeValue::BigInt(b)) => Ok(RuntimeValue::Bool(rel(
290            numeric::cmp_bigint_f64_exact(b, *a).map(std::cmp::Ordering::reverse),
291        ))),
292        // Exact rational ordering (cross-multiply, no rounding) including the
293        // narrow/wide boundary; vs Float uses IEEE partial order on the f64 view.
294        (RuntimeValue::Rational(a), RuntimeValue::Rational(b)) => {
295            Ok(RuntimeValue::Bool(rel(Some((**a).cmp(b)))))
296        }
297        (RuntimeValue::Rational(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Bool(rel(Some(
298            (**a).cmp(&Rational::from_i64(*b)),
299        )))),
300        (RuntimeValue::Int(a), RuntimeValue::Rational(b)) => {
301            Ok(RuntimeValue::Bool(rel(Some(Rational::from_i64(*a).cmp(b)))))
302        }
303        (RuntimeValue::Rational(a), RuntimeValue::BigInt(b)) => Ok(RuntimeValue::Bool(rel(Some(
304            (**a).cmp(&Rational::from_bigint((**b).clone())),
305        )))),
306        (RuntimeValue::BigInt(a), RuntimeValue::Rational(b)) => Ok(RuntimeValue::Bool(rel(Some(
307            Rational::from_bigint((**a).clone()).cmp(b),
308        )))),
309        (RuntimeValue::Rational(a), RuntimeValue::Float(b)) => Ok(RuntimeValue::Bool(rel(
310            numeric::cmp_rational_f64_exact(a, *b),
311        ))),
312        (RuntimeValue::Float(a), RuntimeValue::Rational(b)) => Ok(RuntimeValue::Bool(rel(
313            numeric::cmp_rational_f64_exact(b, *a).map(std::cmp::Ordering::reverse),
314        ))),
315        (RuntimeValue::Float(a), RuntimeValue::Float(b)) => {
316            Ok(RuntimeValue::Bool(rel(a.partial_cmp(b))))
317        }
318        (RuntimeValue::Int(a), RuntimeValue::Float(b)) => {
319            Ok(RuntimeValue::Bool(rel(numeric::cmp_i64_f64_exact(*a, *b))))
320        }
321        (RuntimeValue::Float(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Bool(rel(
322            numeric::cmp_i64_f64_exact(*b, *a).map(std::cmp::Ordering::reverse),
323        ))),
324        (RuntimeValue::Duration(a), RuntimeValue::Duration(b)) => {
325            Ok(RuntimeValue::Bool(int_rel(*a, *b)))
326        }
327        (RuntimeValue::Date(a), RuntimeValue::Date(b)) => {
328            Ok(RuntimeValue::Bool(int_rel(*a as i64, *b as i64)))
329        }
330        (RuntimeValue::Moment(a), RuntimeValue::Moment(b)) => {
331            Ok(RuntimeValue::Bool(int_rel(*a, *b)))
332        }
333        (RuntimeValue::Time(a), RuntimeValue::Time(b)) => Ok(RuntimeValue::Bool(int_rel(*a, *b))),
334        // Moment vs Time: extract time-of-day from Moment. Use Euclidean
335        // remainder so a pre-epoch (negative) Moment yields a 0..86399 ns
336        // time-of-day, not a negative one.
337        (RuntimeValue::Moment(m), RuntimeValue::Time(t)) => {
338            let nanos_per_day = 86_400_000_000_000i64;
339            Ok(RuntimeValue::Bool(int_rel(m.rem_euclid(nanos_per_day), *t)))
340        }
341        (RuntimeValue::Time(t), RuntimeValue::Moment(m)) => {
342            let nanos_per_day = 86_400_000_000_000i64;
343            Ok(RuntimeValue::Bool(int_rel(*t, m.rem_euclid(nanos_per_day))))
344        }
345        // Two physical quantities order by their EXACT SI magnitude when their dimensions match;
346        // ordering across dimensions (Length vs Mass) is a typed error, mirroring the AOT `PartialOrd`
347        // (cross-dimension → `None` → not orderable). `==`/`!=` go through value equality elsewhere.
348        (RuntimeValue::Quantity(a), RuntimeValue::Quantity(b)) => {
349            if a.q.dimension() != b.q.dimension() {
350                return Err(logicaffeine_data::failure::quantities_uncomparable(
351                    a.q.dimension(),
352                    b.q.dimension(),
353                ));
354            }
355            Ok(RuntimeValue::Bool(rel(Some(
356                a.q.magnitude_si().cmp(b.q.magnitude_si()),
357            ))))
358        }
359        // Money orders by amount within the SAME currency; ordering across currencies is meaningless
360        // without a rate context, so it is a typed error (the dimension-mismatch precedent).
361        (RuntimeValue::Money(a), RuntimeValue::Money(b)) => {
362            if a.currency != b.currency {
363                return Err(logicaffeine_data::failure::currencies_differ(
364                    "compare",
365                    a.currency.code,
366                    b.currency.code,
367                ));
368            }
369            Ok(RuntimeValue::Bool(rel(Some(
370                a.amount.to_rational().cmp(&b.amount.to_rational()),
371            ))))
372        }
373        // UUIDs order by their 128 bits — so v6/v7 (time-ordered) ids sort chronologically.
374        (RuntimeValue::Uuid(a), RuntimeValue::Uuid(b)) => {
375            Ok(RuntimeValue::Bool(rel(Some(a.cmp(b)))))
376        }
377        // Machine words order by UNSIGNED magnitude when their widths match — exactly the
378        // AOT newtype's `u32`/`u64` `PartialOrd`. Mixing widths (Word32 vs Word64) is a typed
379        // error, mirroring Word arithmetic (`Word32 + Word64` errors, never silently coerces).
380        (RuntimeValue::Word(a), RuntimeValue::Word(b)) => {
381            if a.width() != b.width() {
382                return Err(format!(
383                    "cannot compare Word{} and Word{} — width mismatch",
384                    a.width(),
385                    b.width()
386                ));
387            }
388            Ok(RuntimeValue::Bool(rel(Some(a.to_u64().cmp(&b.to_u64())))))
389        }
390        // A Decimal orders by EXACT value against any exact number (Int/BigInt/Rational/
391        // Decimal); against a Float it compares on the f64 view (IEEE partial order).
392        (l, r)
393            if matches!(l, RuntimeValue::Decimal(_)) || matches!(r, RuntimeValue::Decimal(_)) =>
394        {
395            let rat_view = |v: &RuntimeValue| -> Option<Rational> {
396                match v {
397                    RuntimeValue::Int(n) => Some(Rational::from_i64(*n)),
398                    RuntimeValue::BigInt(b) => Some(Rational::from_bigint((**b).clone())),
399                    RuntimeValue::Rational(r) => Some((**r).clone()),
400                    RuntimeValue::Decimal(d) => Some(d.to_rational()),
401                    _ => None,
402                }
403            };
404            if let (Some(a), Some(b)) = (rat_view(l), rat_view(r)) {
405                Ok(RuntimeValue::Bool(rel(Some(a.cmp(&b)))))
406            } else {
407                let f64_view = |v: &RuntimeValue| -> Option<f64> {
408                    match v {
409                        RuntimeValue::Float(f) => Some(*f),
410                        other => rat_view(other).map(|x| x.to_f64()),
411                    }
412                };
413                match (f64_view(l), f64_view(r)) {
414                    (Some(a), Some(b)) => Ok(RuntimeValue::Bool(rel(a.partial_cmp(&b)))),
415                    _ => Err(format!(
416                        "Cannot compare {} and {}",
417                        l.type_name(),
418                        r.type_name()
419                    )),
420                }
421            }
422        }
423        _ => Err(format!(
424            "Cannot compare {} and {}",
425            left.type_name(),
426            right.type_name()
427        )),
428    }
429}
430
431#[cfg(test)]
432#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/semantics/compare/tests.rs"]
433mod tests;