Skip to main content

logicaffeine_compile/semantics/
arith.rs

1//! Arithmetic, logical, and bitwise operators.
2
3use std::rc::Rc;
4
5use logicaffeine_base::{BigInt, Complex, ComplexF, Decimal, Modular, Rational, WordVal};
6
7use crate::ast::stmt::BinaryOpKind;
8use crate::interpreter::RuntimeValue;
9
10use super::compare::{compare, values_equal};
11use super::exact;
12use super::temporal::date_add_span;
13
14/// View an exact number — `Int`, `BigInt`, `Rational`, or `Decimal` — as a `Rational`,
15/// for the exact-arithmetic path that integer division "overflows" into. `Float` is
16/// inexact by choice and returns `None`.
17fn rat_of(v: &RuntimeValue) -> Option<Rational> {
18    match v {
19        RuntimeValue::Int(n) => Some(Rational::from_i64(*n)),
20        RuntimeValue::BigInt(b) => Some(Rational::from_bigint((**b).clone())),
21        RuntimeValue::Rational(r) => Some((**r).clone()),
22        RuntimeValue::Decimal(d) => Some(d.to_rational()),
23        _ => None,
24    }
25}
26
27/// View an integer-or-decimal value as a `Decimal`, for the decimal-PRESERVING path:
28/// `Decimal ∘ {Decimal, Int, BigInt}` stays an exact `Decimal` (money keeps its scale).
29/// `Rational`/`Float` return `None` so those operands route to the rational/float paths.
30fn dec_of(v: &RuntimeValue) -> Option<Decimal> {
31    match v {
32        RuntimeValue::Int(n) => Some(Decimal::from_i64(*n)),
33        RuntimeValue::BigInt(b) => Some(Decimal::from_bigint((**b).clone())),
34        RuntimeValue::Decimal(d) => Some((**d).clone()),
35        _ => None,
36    }
37}
38
39/// View any number — exact or `Float` — as an `f64`, for the inexact path a `Float`
40/// operand forces. `None` for non-numbers.
41fn num_f64(v: &RuntimeValue) -> Option<f64> {
42    match v {
43        RuntimeValue::Int(n) => Some(*n as f64),
44        RuntimeValue::BigInt(b) => Some(b.to_f64()),
45        RuntimeValue::Rational(r) => Some(r.to_f64()),
46        RuntimeValue::Decimal(d) => Some(d.to_rational().to_f64()),
47        RuntimeValue::Float(f) => Some(*f),
48        _ => None,
49    }
50}
51
52/// View an exact number — `Int`, `BigInt`, `Rational`, `Decimal`, or `Complex` — as a
53/// `Complex`. `Float` is inexact and returns `None` (an exact `Complex` does not absorb a
54/// float), so `Complex ∘ Float` is a typed error rather than a silent lossy coercion.
55fn complex_of(v: &RuntimeValue) -> Option<Complex> {
56    match v {
57        RuntimeValue::Int(n) => Some(Complex::from_i64(*n)),
58        RuntimeValue::BigInt(b) => {
59            Some(Complex::from_rational(Rational::from_bigint((**b).clone())))
60        }
61        RuntimeValue::Rational(r) => Some(Complex::from_rational((**r).clone())),
62        RuntimeValue::Decimal(d) => Some(Complex::from_rational(d.to_rational())),
63        RuntimeValue::Complex(c) => Some((**c).clone()),
64        _ => None,
65    }
66}
67
68/// Modular-operand dispatch shared by `add`/`subtract`/`multiply`: a `Modular` combines ONLY
69/// with another `Modular` of the same modulus (no auto-lift — a bare integer has no modulus).
70/// `None` when neither side is a `Modular`; `Some(Err)` on a non-Modular operand or a modulus
71/// mismatch (`f` returns `None` for a mismatch, like a Word width mismatch).
72fn modular_binop(
73    left: &RuntimeValue,
74    right: &RuntimeValue,
75    op_name: &str,
76    f: impl Fn(&Modular, &Modular) -> Option<Modular>,
77) -> Option<Result<RuntimeValue, String>> {
78    if !matches!(left, RuntimeValue::Modular(_)) && !matches!(right, RuntimeValue::Modular(_)) {
79        return None;
80    }
81    Some(match (left, right) {
82        (RuntimeValue::Modular(a), RuntimeValue::Modular(b)) => match f(a, b) {
83            Some(r) => Ok(RuntimeValue::Modular(Rc::new(r))),
84            None => Err(logicaffeine_data::failure::modular_rings_differ(op_name)),
85        },
86        _ => Err(format!(
87            "Cannot {} {} and {} (modular arithmetic needs two ℤ/nℤ values of the same modulus)",
88            op_name,
89            left.type_name(),
90            right.type_name()
91        )),
92    })
93}
94
95/// Complex-operand dispatch shared by `add`/`subtract`/`multiply`: when either side is a
96/// `Complex`, the result is `Complex` (a real embeds as `re + 0i`). `None` when no operand
97/// is a `Complex` (fall through); `Some(Err)` when an operand is inexact (`Float`).
98fn complex_binop(
99    left: &RuntimeValue,
100    right: &RuntimeValue,
101    op_name: &str,
102    f: impl Fn(&Complex, &Complex) -> Complex,
103) -> Option<Result<RuntimeValue, String>> {
104    if !matches!(left, RuntimeValue::Complex(_)) && !matches!(right, RuntimeValue::Complex(_)) {
105        return None;
106    }
107    Some(match (complex_of(left), complex_of(right)) {
108        (Some(a), Some(b)) => Ok(RuntimeValue::Complex(Rc::new(f(&a, &b)))),
109        _ => Err(format!(
110            "Cannot {} {} and {} (Complex combines only with exact numbers)",
111            op_name,
112            left.type_name(),
113            right.type_name()
114        )),
115    })
116}
117
118/// View any real or complex value as a floating-point `ComplexF`: the whole real tower
119/// (Int/BigInt/Rational/Decimal/Float) plus exact `Complex` and `ComplexF` itself promote here.
120fn complexf_of(v: &RuntimeValue) -> Option<ComplexF> {
121    match v {
122        RuntimeValue::Float(f) => Some(ComplexF::from_f64(*f)),
123        RuntimeValue::ComplexF(c) => Some(**c),
124        RuntimeValue::Complex(c) => Some(ComplexF::new(c.re().to_f64(), c.im().to_f64())),
125        other => complex_of(other).map(|c| ComplexF::new(c.re().to_f64(), c.im().to_f64())),
126    }
127}
128
129/// Floating-point-complex dispatch shared by `add`/`subtract`/`multiply`/`divide`: the result is
130/// `ComplexF` when either side already is one, OR when an exact `Complex` meets a `Float` — the
131/// promotion `Rational + Float → Float` extended to the complex plane. `None` (fall through to the
132/// exact `complex_binop`) otherwise, so two exact complexes stay exact. `f` returns `None` only for
133/// division by zero.
134fn complexf_binop(
135    left: &RuntimeValue,
136    right: &RuntimeValue,
137    op_name: &str,
138    f: impl Fn(&ComplexF, &ComplexF) -> Option<ComplexF>,
139) -> Option<Result<RuntimeValue, String>> {
140    let is_cf = |v: &RuntimeValue| matches!(v, RuntimeValue::ComplexF(_));
141    let is_c = |v: &RuntimeValue| matches!(v, RuntimeValue::Complex(_));
142    let is_f = |v: &RuntimeValue| matches!(v, RuntimeValue::Float(_));
143    let fires =
144        is_cf(left) || is_cf(right) || (is_c(left) && is_f(right)) || (is_f(left) && is_c(right));
145    if !fires {
146        return None;
147    }
148    Some(match (complexf_of(left), complexf_of(right)) {
149        (Some(a), Some(b)) => match f(&a, &b) {
150            Some(r) => Ok(RuntimeValue::ComplexF(Rc::new(r))),
151            None => Err(format!(
152                "Cannot {} {} and {} (division by zero)",
153                op_name,
154                left.type_name(),
155                right.type_name()
156            )),
157        },
158        _ => Err(format!(
159            "Cannot {} {} and {} (complex combines only with numbers)",
160            op_name,
161            left.type_name(),
162            right.type_name()
163        )),
164    })
165}
166
167/// Decimal-operand dispatch shared by `add`/`subtract`/`multiply`: when either side is a
168/// `Decimal`, `Decimal ∘ {Decimal,Int,BigInt}` stays exact `Decimal` (via `dec`), a
169/// `Rational` operand promotes to exact `Rational`, and a `Float` operand yields `Float`.
170/// Returns `None` when no operand is a `Decimal` (fall through to the existing paths).
171fn decimal_binop(
172    left: &RuntimeValue,
173    right: &RuntimeValue,
174    dec: impl Fn(&Decimal, &Decimal) -> Decimal,
175    rat: impl Fn(&Rational, &Rational) -> Rational,
176    flt: impl Fn(f64, f64) -> f64,
177) -> Option<RuntimeValue> {
178    if !matches!(left, RuntimeValue::Decimal(_)) && !matches!(right, RuntimeValue::Decimal(_)) {
179        return None;
180    }
181    if let (Some(a), Some(b)) = (dec_of(left), dec_of(right)) {
182        return Some(RuntimeValue::Decimal(Rc::new(dec(&a, &b))));
183    }
184    if let (Some(a), Some(b)) = (rat_of(left), rat_of(right)) {
185        return Some(RuntimeValue::from_rational(rat(&a, &b)));
186    }
187    let (a, b) = (num_f64(left)?, num_f64(right)?);
188    Some(RuntimeValue::Float(flt(a, b)))
189}
190
191/// Physical-quantity arithmetic. `+ −` require equal dimensions (the result keeps the LEFT operand's
192/// display unit), `× ÷` combine dimensions (the result is shown in SI/dimension form), and a quantity
193/// may be scaled by a dimensionless number under `× ÷` (its unit preserved). Returns `None` when
194/// neither operand is a `Quantity` (so the normal numeric dispatch runs); `Some(Err)` on a dimension
195/// mismatch or division by zero. The magnitude rides the exact rational tower, so it never drifts.
196fn quantity_binop(
197    left: &RuntimeValue,
198    right: &RuntimeValue,
199    op: char,
200) -> Option<Result<RuntimeValue, String>> {
201    use crate::interpreter::QuantityValue;
202    use logicaffeine_base::{Quantity, Unit};
203    if !matches!(left, RuntimeValue::Quantity(_)) && !matches!(right, RuntimeValue::Quantity(_)) {
204        return None;
205    }
206    let mk = |q: Quantity, unit: Unit| RuntimeValue::Quantity(Rc::new(QuantityValue { q, unit }));
207    // A synthetic SI-base unit (empty symbol) for a combined dimension — `display` renders it as the
208    // magnitude plus the dimension signature until a named compound unit is chosen.
209    let si_unit = |q: &Quantity| Unit::linear("", q.dimension(), Rational::one());
210    Some(match (left, right) {
211        (RuntimeValue::Quantity(a), RuntimeValue::Quantity(b)) => match op {
212            '+' => a.q.add(&b.q).map(|q| mk(q, a.unit.clone())).ok_or_else(|| {
213                logicaffeine_data::failure::quantities_differ(
214                    "add",
215                    a.q.dimension(),
216                    b.q.dimension(),
217                )
218            }),
219            '-' => a.q.sub(&b.q).map(|q| mk(q, a.unit.clone())).ok_or_else(|| {
220                logicaffeine_data::failure::quantities_differ(
221                    "subtract",
222                    a.q.dimension(),
223                    b.q.dimension(),
224                )
225            }),
226            '*' => {
227                let q = a.q.mul(&b.q);
228                let u = si_unit(&q);
229                Ok(mk(q, u))
230            }
231            '/' => match a.q.div(&b.q) {
232                Some(q) => {
233                    let u = si_unit(&q);
234                    Ok(mk(q, u))
235                }
236                None => Err(logicaffeine_data::failure::DIVIDE_BY_ZERO_QUANTITY.to_string()),
237            },
238            _ => unreachable!("quantity_binop only handles + - * /"),
239        },
240        // Scale a quantity by a dimensionless number, preserving its unit: `q * k`, `q / k`.
241        (RuntimeValue::Quantity(a), scalar) if matches!(op, '*' | '/') => match rat_of(scalar) {
242            Some(k) => {
243                let mag = if op == '*' {
244                    a.q.magnitude_si().mul(&k)
245                } else {
246                    match a.q.magnitude_si().div(&k) {
247                        Some(m) => m,
248                        None => {
249                            return Some(Err(
250                                logicaffeine_data::failure::DIVIDE_QUANTITY_BY_ZERO.to_string()
251                            ))
252                        }
253                    }
254                };
255                Ok(mk(Quantity::si(mag, a.q.dimension()), a.unit.clone()))
256            }
257            None => return None,
258        },
259        // `k * q` — scalar on the left (multiplication commutes).
260        (scalar, RuntimeValue::Quantity(b)) if op == '*' => match rat_of(scalar) {
261            Some(k) => Ok(mk(
262                Quantity::si(b.q.magnitude_si().mul(&k), b.q.dimension()),
263                b.unit.clone(),
264            )),
265            None => return None,
266        },
267        _ => return None,
268    })
269}
270
271/// Money arithmetic. `+ −` require the SAME currency (a typed error otherwise, like a dimension
272/// mismatch); `×` and `÷` scale by an exact number (Int/Decimal), re-quantised to the currency's
273/// minor unit; a same-currency `Money ÷ Money` is the dimensionless ratio. Returns `None` when
274/// neither operand is Money (so the normal numeric dispatch runs); `Some(Err)` on a currency mismatch.
275fn money_binop(
276    left: &RuntimeValue,
277    right: &RuntimeValue,
278    op: char,
279) -> Option<Result<RuntimeValue, String>> {
280    use logicaffeine_base::{Decimal, Money, RoundingMode};
281    if !matches!(left, RuntimeValue::Money(_)) && !matches!(right, RuntimeValue::Money(_)) {
282        return None;
283    }
284    // An exact base-10 scalar (Int or Decimal); a Float or non-terminating Rational is refused.
285    let dec_of = |v: &RuntimeValue| -> Option<Decimal> {
286        match v {
287            RuntimeValue::Int(n) => Some(Decimal::from_i64(*n)),
288            RuntimeValue::Decimal(d) => Some((**d).clone()),
289            _ => None,
290        }
291    };
292    let mk = |m: Money| RuntimeValue::Money(Rc::new(m));
293    let mismatch = |a: &Money, b: &Money, verb: &str| {
294        logicaffeine_data::failure::currencies_differ(verb, a.currency.code, b.currency.code)
295    };
296    Some(match (left, right) {
297        (RuntimeValue::Money(a), RuntimeValue::Money(b)) => match op {
298            '+' => a.add(b).map(mk).ok_or_else(|| mismatch(a, b, "add")),
299            '-' => a.sub(b).map(mk).ok_or_else(|| mismatch(a, b, "subtract")),
300            '/' => match a.ratio(b) {
301                Some(r) => Ok(RuntimeValue::from_rational(r)),
302                None if a.currency != b.currency => Err(mismatch(a, b, "compare")),
303                None => Err(logicaffeine_data::failure::DIVIDE_MONEY_BY_ZERO_AMOUNT.to_string()),
304            },
305            '*' => Err("cannot multiply money by money — scale by a number instead".to_string()),
306            _ => unreachable!("money_binop only handles + - * /"),
307        },
308        // Scale money by an exact number (`19.99 USD × 3`, `price × 1.5`), re-quantised; `×` commutes.
309        (RuntimeValue::Money(a), scalar) | (scalar, RuntimeValue::Money(a)) if op == '*' => {
310            match dec_of(scalar) {
311                Some(s) => Ok(mk(Money::of(a.amount.mul(&s), a.currency))),
312                None => Err(format!("cannot multiply money by {}", scalar.type_name())),
313            }
314        }
315        // Divide money by an exact number (e.g. split a bill), re-quantised to the currency.
316        (RuntimeValue::Money(a), scalar) if op == '/' => match dec_of(scalar) {
317            Some(s) => match a.amount.div(&s, a.currency.scale, RoundingMode::HalfEven) {
318                Some(d) => Ok(mk(Money::of(d, a.currency))),
319                None => Err(logicaffeine_data::failure::DIVIDE_MONEY_BY_ZERO.to_string()),
320            },
321            None => Err(format!("cannot divide money by {}", scalar.type_name())),
322        },
323        _ => return None,
324    })
325}
326
327/// Apply a binary operator to two already-evaluated values.
328///
329/// NOTE on `And`/`Or`: these are the *eager* semantics (both operands already
330/// evaluated) — bitwise for Int×Int, truthiness otherwise. Short-circuit
331/// evaluation order is the engine's responsibility: evaluate the left operand,
332/// and only consult the right when the left is an Int (bitwise) or when
333/// truthiness requires it.
334/// The error for combining two words of different widths — a type error, never a coercion.
335fn word_width_err(a: WordVal, b: WordVal) -> String {
336    format!(
337        "cannot combine Word{} and Word{} — width mismatch",
338        a.width(),
339        b.width()
340    )
341}
342
343/// Extract a shift count as `u32` from an `Int` or `Word`.
344fn shift_count(v: &RuntimeValue) -> Option<u32> {
345    match v {
346        RuntimeValue::Int(n) => Some(*n as u32),
347        RuntimeValue::Word(w) => Some(w.to_u64() as u32),
348        _ => None,
349    }
350}
351
352/// Word-operand dispatch for [`binary_op`]: `Some(result)` when handled as a ring-of-ℤ/2ᵏ op,
353/// `None` to fall through to the generic numeric/comparison path, `Err` on a width mismatch.
354/// Arithmetic/bitwise require both operands at the same width; shifts take an integer count.
355fn word_binary_op(
356    op: BinaryOpKind,
357    left: &RuntimeValue,
358    right: &RuntimeValue,
359) -> Result<Option<RuntimeValue>, String> {
360    use BinaryOpKind::*;
361    if matches!(op, Shl | Shr) {
362        if let RuntimeValue::Word(a) = left {
363            let n =
364                shift_count(right).ok_or_else(|| "shift count must be an integer".to_string())?;
365            let r = if matches!(op, Shl) {
366                a.shl(n)
367            } else {
368                a.shr(n)
369            };
370            return Ok(Some(RuntimeValue::Word(r)));
371        }
372        return Ok(None);
373    }
374    let (RuntimeValue::Word(a), RuntimeValue::Word(b)) = (left, right) else {
375        return Ok(None);
376    };
377    let combined = match op {
378        // Add/Subtract/Multiply are handled in `add`/`subtract`/`multiply` (the VM calls those
379        // directly), so both tiers share ONE Word path; fall through to them here.
380        And | BitAnd => a.bitand(*b),
381        Or | BitOr => a.bitor(*b),
382        BitXor => a.bitxor(*b),
383        _ => return Ok(None),
384    };
385    match combined {
386        Some(w) => Ok(Some(RuntimeValue::Word(w))),
387        None => Err(word_width_err(*a, *b)),
388    }
389}
390
391/// Lane-operand dispatch for [`binary_op`]: a SIMD lane vector op is the same operator applied to
392/// every lane (the scalar-lane spec; AOT lowers it to the matching AVX2 intrinsic). `None` falls
393/// through, `Err` on a lane-config mismatch.
394fn lanes_binary_op(
395    op: BinaryOpKind,
396    left: &RuntimeValue,
397    right: &RuntimeValue,
398) -> Result<Option<RuntimeValue>, String> {
399    let (RuntimeValue::Lanes(a), RuntimeValue::Lanes(b)) = (left, right) else {
400        return Ok(None);
401    };
402    let combined = match op {
403        BinaryOpKind::BitXor => a.bitxor(**b),
404        _ => return Ok(None),
405    };
406    match combined {
407        Some(v) => Ok(Some(RuntimeValue::Lanes(std::rc::Rc::new(v)))),
408        None => Err(format!(
409            "cannot combine {} and {} — lane-config mismatch",
410            a.type_name(),
411            b.type_name()
412        )),
413    }
414}
415
416/// The arithmetic entry the exact types re-enter to lift an operation over residue branches and
417/// provisional values.
418fn exact_recurse(op: exact::Op, a: RuntimeValue, b: RuntimeValue) -> Result<RuntimeValue, String> {
419    match op {
420        exact::Op::Add => add(a, b),
421        exact::Op::Sub => subtract(a, b),
422        exact::Op::Mul => multiply(a, b),
423        exact::Op::Div => divide(a, b),
424        exact::Op::ExactDiv => exact_divide(a, b),
425        exact::Op::FloorDiv => floor_divide(a, b),
426        exact::Op::Mod => modulo(a, b),
427        exact::Op::Pow => power(a, b),
428    }
429}
430
431pub fn binary_op(
432    op: BinaryOpKind,
433    left: RuntimeValue,
434    right: RuntimeValue,
435) -> Result<RuntimeValue, String> {
436    // Fixed-width wrapping fast path: an op on words stays in the ring ℤ/2ᵏ (wrapping, never
437    // promoting). Equality/comparison fall through to the generic path below.
438    if let Some(result) = word_binary_op(op, &left, &right)? {
439        return Ok(result);
440    }
441    // SIMD lane vectors: the op applies lane-wise (the scalar-lane spec).
442    if let Some(result) = lanes_binary_op(op, &left, &right)? {
443        return Ok(result);
444    }
445    match op {
446        BinaryOpKind::Add => add(left, right),
447        BinaryOpKind::Subtract => subtract(left, right),
448        BinaryOpKind::Multiply => multiply(left, right),
449        BinaryOpKind::Pow => power(left, right),
450        BinaryOpKind::Divide => divide(left, right),
451        BinaryOpKind::ExactDivide => exact_divide(left, right),
452        BinaryOpKind::FloorDivide => floor_divide(left, right),
453        BinaryOpKind::Modulo => modulo(left, right),
454        BinaryOpKind::Eq => super::compare::equality(&left, &right, false),
455        BinaryOpKind::NotEq => super::compare::equality(&left, &right, true),
456        BinaryOpKind::ApproxEq => approx_eq(left, right),
457        BinaryOpKind::Lt | BinaryOpKind::Gt | BinaryOpKind::LtEq | BinaryOpKind::GtEq => {
458            compare(op, &left, &right)
459        }
460        // Logical words: truthiness in, Bool out. The bitwise spellings are `&`/`|` (BitAnd/BitOr).
461        BinaryOpKind::And => Ok(RuntimeValue::Bool(left.decided_truth()? && right.decided_truth()?)),
462        BinaryOpKind::Or => Ok(RuntimeValue::Bool(left.decided_truth()? || right.decided_truth()?)),
463        BinaryOpKind::Concat => concat(left, right),
464        BinaryOpKind::SeqConcat => seq_concat(left, right),
465        BinaryOpKind::BitXor => match (&left, &right) {
466            (RuntimeValue::Int(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Int(a ^ b)),
467            // Boolean XOR (`a ≠ b`) — matches the codegen's `a ^ b` on Rust `bool`, so the tiers
468            // agree. (Word and lane XOR are taken on the fast paths above.)
469            (RuntimeValue::Bool(a), RuntimeValue::Bool(b)) => Ok(RuntimeValue::Bool(a ^ b)),
470            // On Sets, `^` is the symmetric difference.
471            (RuntimeValue::Set(_), RuntimeValue::Set(_)) => {
472                set_binop(&left, &right, SetOp::SymmetricDifference)
473            }
474            _ => Err(logicaffeine_data::failure::BITXOR_OPERANDS.to_string()),
475        },
476        // `&` — bitwise AND on Int, intersection on Sets.
477        BinaryOpKind::BitAnd => match (&left, &right) {
478            (RuntimeValue::Int(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Int(a & b)),
479            // A low-bit mask `2^k - 1` AND a NON-NEGATIVE BigInt: this is exactly the
480            // `x % 2^k → x & (2^k-1)` lowering firing on a widening-loop bignum. For `x >= 0`,
481            // `x & (2^k-1) == x mod 2^k`, computed bignum-exact so the optimized VM matches the
482            // tree-walker's `Op::Mod`. (A negative bignum, or a non-mask AND, has no i64-bit meaning
483            // and still falls through to the loud error, exactly as before.)
484            (RuntimeValue::BigInt(big), RuntimeValue::Int(m))
485            | (RuntimeValue::Int(m), RuntimeValue::BigInt(big))
486                if *m >= 0
487                    && (*m as u64).wrapping_add(1).is_power_of_two()
488                    && !big.is_negative() =>
489            {
490                let modulus = BigInt::from_i64(*m).add(&BigInt::from_i64(1));
491                match big.div_rem(&modulus) {
492                    Some((_, r)) => Ok(RuntimeValue::from_bigint(r)),
493                    None => Ok(RuntimeValue::Int(0)),
494                }
495            }
496            (RuntimeValue::Bool(a), RuntimeValue::Bool(b)) => Ok(RuntimeValue::Bool(a & b)),
497            (RuntimeValue::Set(_), RuntimeValue::Set(_)) => {
498                set_binop(&left, &right, SetOp::Intersection)
499            }
500            _ => Err(logicaffeine_data::failure::BITAND_OPERANDS.to_string()),
501        },
502        // `|` — bitwise OR on Int, union on Sets.
503        BinaryOpKind::BitOr => match (&left, &right) {
504            (RuntimeValue::Int(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Int(a | b)),
505            (RuntimeValue::Bool(a), RuntimeValue::Bool(b)) => Ok(RuntimeValue::Bool(a | b)),
506            (RuntimeValue::Set(_), RuntimeValue::Set(_)) => set_binop(&left, &right, SetOp::Union),
507            _ => Err(logicaffeine_data::failure::BITOR_OPERANDS.to_string()),
508        },
509        // Shift counts are truncated to u32 and masked mod 64 (the wrapping spec).
510        BinaryOpKind::Shl => match (left, right) {
511            (RuntimeValue::Int(a), RuntimeValue::Int(b)) => {
512                Ok(RuntimeValue::Int(a.wrapping_shl(b as u32)))
513            }
514            _ => Err(logicaffeine_data::failure::SHL_OPERANDS.to_string()),
515        },
516        BinaryOpKind::Shr => match (left, right) {
517            (RuntimeValue::Int(a), RuntimeValue::Int(b)) => {
518                Ok(RuntimeValue::Int(a.wrapping_shr(b as u32)))
519            }
520            _ => Err(logicaffeine_data::failure::SHR_OPERANDS.to_string()),
521        },
522    }
523}
524
525pub fn add(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
526    if let Some(r) = exact::arith(exact::Op::Add, &left, &right, &exact_recurse) {
527        return r;
528    }
529    // Words add in the ring ℤ/2ᵏ (wrapping). Here as well as in `binary_op` so the VM, which
530    // calls `add` directly, stays byte-identical to the tree-walker on the Word path.
531    if let (RuntimeValue::Word(a), RuntimeValue::Word(b)) = (&left, &right) {
532        return a
533            .add(*b)
534            .map(RuntimeValue::Word)
535            .ok_or_else(|| word_width_err(*a, *b));
536    }
537    // SIMD lane vectors add lane-wise in ℤ/2³² (the ChaCha quarter-round's `a += b`).
538    if let (RuntimeValue::Lanes(a), RuntimeValue::Lanes(b)) = (&left, &right) {
539        return a
540            .add(**b)
541            .map(|v| RuntimeValue::Lanes(std::rc::Rc::new(v)))
542            .ok_or_else(|| {
543                format!(
544                    "cannot add {} and {} — lane-config mismatch",
545                    a.type_name(),
546                    b.type_name()
547                )
548            });
549    }
550    if let Some(r) = quantity_binop(&left, &right, '+') {
551        return r;
552    }
553    if let Some(r) = money_binop(&left, &right, '+') {
554        return r;
555    }
556    if let Some(r) = modular_binop(&left, &right, "add", |a, b| a.add(b)) {
557        return r;
558    }
559    if let Some(r) = complexf_binop(&left, &right, "add", |a, b| Some(a.add(b))) {
560        return r;
561    }
562    if let Some(r) = complex_binop(&left, &right, "add", |a, b| a.add(b)) {
563        return r;
564    }
565    if let Some(r) = decimal_binop(
566        &left,
567        &right,
568        |a, b| a.add(b),
569        |a, b| a.add(b),
570        |a, b| a + b,
571    ) {
572        return Ok(r);
573    }
574    match (&left, &right) {
575        // Integer addition is EXACT: on i64 overflow it promotes to BigInt instead of
576        // wrapping (the silent `i64::MAX + 1 == i64::MIN` corruption is the bug this
577        // fixes). The result downsizes back to Int whenever it fits (`from_bigint`).
578        (RuntimeValue::Int(a), RuntimeValue::Int(b)) => Ok(match a.checked_add(*b) {
579            Some(s) => RuntimeValue::Int(s),
580            None => RuntimeValue::from_bigint(BigInt::from_i64(*a).add(&BigInt::from_i64(*b))),
581        }),
582        (RuntimeValue::BigInt(a), RuntimeValue::BigInt(b)) => {
583            Ok(RuntimeValue::from_bigint(a.add(b)))
584        }
585        (RuntimeValue::BigInt(a), RuntimeValue::Int(b)) => {
586            Ok(RuntimeValue::from_bigint(a.add(&BigInt::from_i64(*b))))
587        }
588        (RuntimeValue::Int(a), RuntimeValue::BigInt(b)) => {
589            Ok(RuntimeValue::from_bigint(BigInt::from_i64(*a).add(b)))
590        }
591        (RuntimeValue::Float(a), RuntimeValue::Float(b)) => Ok(RuntimeValue::Float(a + b)),
592        (RuntimeValue::Int(a), RuntimeValue::Float(b)) => Ok(RuntimeValue::Float(*a as f64 + b)),
593        (RuntimeValue::Float(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Float(a + *b as f64)),
594        (RuntimeValue::BigInt(a), RuntimeValue::Float(b)) => {
595            Ok(RuntimeValue::Float(a.to_f64() + b))
596        }
597        (RuntimeValue::Float(a), RuntimeValue::BigInt(b)) => {
598            Ok(RuntimeValue::Float(a + b.to_f64()))
599        }
600        // Rational keeps arithmetic EXACT: any Int/BigInt/Rational mix involving a
601        // Rational stays exact (downsized to Int when it reduces to a whole number); a
602        // Float operand makes the result Float (floats are inexact by choice).
603        (RuntimeValue::Rational(a), RuntimeValue::Rational(b)) => {
604            Ok(RuntimeValue::from_rational(a.add(b)))
605        }
606        (RuntimeValue::Rational(_), RuntimeValue::Int(_))
607        | (RuntimeValue::Int(_), RuntimeValue::Rational(_))
608        | (RuntimeValue::Rational(_), RuntimeValue::BigInt(_))
609        | (RuntimeValue::BigInt(_), RuntimeValue::Rational(_)) => Ok(RuntimeValue::from_rational(
610            rat_of(&left).unwrap().add(&rat_of(&right).unwrap()),
611        )),
612        (RuntimeValue::Rational(r), RuntimeValue::Float(b)) => {
613            Ok(RuntimeValue::Float(r.to_f64() + b))
614        }
615        (RuntimeValue::Float(a), RuntimeValue::Rational(r)) => {
616            Ok(RuntimeValue::Float(a + r.to_f64()))
617        }
618        (RuntimeValue::Text(a), RuntimeValue::Text(b)) => {
619            Ok(RuntimeValue::Text(Rc::new(format!("{}{}", a, b))))
620        }
621        (RuntimeValue::Text(a), other) => Ok(RuntimeValue::Text(Rc::new(format!(
622            "{}{}",
623            a,
624            other.to_display_string()
625        )))),
626        (other, RuntimeValue::Text(b)) => Ok(RuntimeValue::Text(Rc::new(format!(
627            "{}{}",
628            other.to_display_string(),
629            b
630        )))),
631        (RuntimeValue::Duration(a), RuntimeValue::Duration(b)) => {
632            Ok(RuntimeValue::Duration(a.wrapping_add(*b)))
633        }
634        (
635            RuntimeValue::Date(days),
636            RuntimeValue::Span {
637                months,
638                days: span_days,
639            },
640        ) => Ok(RuntimeValue::Date(date_add_span(
641            *days, *months, *span_days,
642        ))),
643        // A Moment plus a CIVIL Span is calendar arithmetic (`m + 1 month` clamps end-of-month,
644        // respects leap years, keeps the wall time); commutes. Contrast the physical Duration below.
645        (
646            RuntimeValue::Moment(nanos),
647            RuntimeValue::Span {
648                months,
649                days: span_days,
650            },
651        )
652        | (
653            RuntimeValue::Span {
654                months,
655                days: span_days,
656            },
657            RuntimeValue::Moment(nanos),
658        ) => Ok(RuntimeValue::Moment(super::temporal::moment_add_span(
659            *nanos, *months, *span_days,
660        ))),
661        // A Moment plus a physical Duration is a later Moment (e.g. `m + 90 seconds`); commutes.
662        (RuntimeValue::Moment(nanos), RuntimeValue::Duration(d))
663        | (RuntimeValue::Duration(d), RuntimeValue::Moment(nanos)) => {
664            Ok(RuntimeValue::Moment(nanos.wrapping_add(*d)))
665        }
666        // `xs + ys` concatenates sequences — exactly `xs followed by ys`
667        // (a fresh sequence; neither operand is mutated).
668        (RuntimeValue::List(_), RuntimeValue::List(_)) => seq_concat(left.clone(), right.clone()),
669        _ => Err(format!(
670            "Cannot add {} and {}",
671            left.type_name(),
672            right.type_name()
673        )),
674    }
675}
676
677pub fn concat(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
678    Ok(RuntimeValue::Text(Rc::new(format!(
679        "{}{}",
680        left.to_display_string(),
681        right.to_display_string()
682    ))))
683}
684
685/// The Set operations behind `| & ^ -` on Set operands. Results are FRESH
686/// sets in first-operand-then-second insertion order, deduped by
687/// `values_equal` — the same equality the language uses everywhere.
688enum SetOp {
689    Union,
690    Intersection,
691    Difference,
692    SymmetricDifference,
693}
694
695fn set_binop(left: &RuntimeValue, right: &RuntimeValue, op: SetOp) -> Result<RuntimeValue, String> {
696    let (RuntimeValue::Set(a), RuntimeValue::Set(b)) = (left, right) else {
697        return Err("set operation requires two Sets".to_string());
698    };
699    let (a, b) = (a.borrow(), b.borrow());
700    let contains = |xs: &[RuntimeValue], v: &RuntimeValue| xs.iter().any(|x| values_equal(x, v));
701    let mut out: Vec<RuntimeValue> = Vec::new();
702    match op {
703        SetOp::Union => {
704            out.extend(a.iter().cloned());
705            for v in b.iter() {
706                if !contains(&out, v) {
707                    out.push(v.clone());
708                }
709            }
710        }
711        SetOp::Intersection => {
712            for v in a.iter() {
713                if contains(&b, v) {
714                    out.push(v.clone());
715                }
716            }
717        }
718        SetOp::Difference => {
719            for v in a.iter() {
720                if !contains(&b, v) {
721                    out.push(v.clone());
722                }
723            }
724        }
725        SetOp::SymmetricDifference => {
726            for v in a.iter() {
727                if !contains(&b, v) {
728                    out.push(v.clone());
729                }
730            }
731            for v in b.iter() {
732                if !contains(&a, v) {
733                    out.push(v.clone());
734                }
735            }
736        }
737    }
738    Ok(RuntimeValue::Set(Rc::new(std::cell::RefCell::new(out))))
739}
740
741/// `a is approximately b` — the TOLERANT numeric comparison (`==` is IEEE
742/// bit-exact). Both operands coerce to f64 (approximation is inherently
743/// tolerant, so the lossy view is correct here) and compare with the ONE
744/// shared isclose definition (`logicaffeine_data::ops::logos_approx_eq`).
745pub fn approx_eq(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
746    let as_f64 = |v: &RuntimeValue| -> Option<f64> {
747        match v {
748            RuntimeValue::Float(f) => Some(*f),
749            RuntimeValue::Int(n) => Some(*n as f64),
750            RuntimeValue::BigInt(b) => Some(b.to_f64()),
751            RuntimeValue::Rational(r) => Some(r.to_f64()),
752            _ => None,
753        }
754    };
755    match (as_f64(&left), as_f64(&right)) {
756        (Some(a), Some(b)) => Ok(RuntimeValue::Bool(logicaffeine_data::ops::logos_approx_eq(
757            a, b,
758        ))),
759        _ => Err(format!(
760            "`is approximately` compares numbers, got {} and {}",
761            left.type_name(),
762            right.type_name()
763        )),
764    }
765}
766
767/// `a followed by b` — merge two sequences into one fresh sequence. Element order is preserved:
768/// all of `a`, then all of `b`. Operands must both be sequences.
769pub fn seq_concat(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
770    use crate::interpreter::ListRepr;
771    match (&left, &right) {
772        (RuntimeValue::List(a), RuntimeValue::List(b)) => {
773            let mut items = a.borrow().to_values();
774            items.extend(b.borrow().to_values());
775            Ok(RuntimeValue::List(Rc::new(std::cell::RefCell::new(
776                ListRepr::from_values(items),
777            ))))
778        }
779        _ => Err("`followed by` requires two sequences (merge two sequences into one)".to_string()),
780    }
781}
782
783pub fn subtract(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
784    if let Some(r) = exact::arith(exact::Op::Sub, &left, &right, &exact_recurse) {
785        return r;
786    }
787    // `a - b` on Sets is the difference (`a without b` is the English form).
788    if matches!(
789        (&left, &right),
790        (RuntimeValue::Set(_), RuntimeValue::Set(_))
791    ) {
792        return set_binop(&left, &right, SetOp::Difference);
793    }
794    if let (RuntimeValue::Word(a), RuntimeValue::Word(b)) = (&left, &right) {
795        return a
796            .sub(*b)
797            .map(RuntimeValue::Word)
798            .ok_or_else(|| word_width_err(*a, *b));
799    }
800    // SIMD lane vectors subtract lane-wise (the NTT butterfly's `a - t` over Word16 lanes).
801    if let (RuntimeValue::Lanes(a), RuntimeValue::Lanes(b)) = (&left, &right) {
802        return a
803            .sub(**b)
804            .map(|v| RuntimeValue::Lanes(std::rc::Rc::new(v)))
805            .ok_or_else(|| {
806                format!(
807                    "cannot subtract {} and {} — lane-config mismatch",
808                    a.type_name(),
809                    b.type_name()
810                )
811            });
812    }
813    if let Some(r) = quantity_binop(&left, &right, '-') {
814        return r;
815    }
816    if let Some(r) = money_binop(&left, &right, '-') {
817        return r;
818    }
819    if let Some(r) = modular_binop(&left, &right, "subtract", |a, b| a.sub(b)) {
820        return r;
821    }
822    if let Some(r) = complexf_binop(&left, &right, "subtract", |a, b| Some(a.sub(b))) {
823        return r;
824    }
825    if let Some(r) = complex_binop(&left, &right, "subtract", |a, b| a.sub(b)) {
826        return r;
827    }
828    if let Some(r) = decimal_binop(
829        &left,
830        &right,
831        |a, b| a.sub(b),
832        |a, b| a.sub(b),
833        |a, b| a - b,
834    ) {
835        return Ok(r);
836    }
837    match (&left, &right) {
838        (RuntimeValue::Int(a), RuntimeValue::Int(b)) => Ok(match a.checked_sub(*b) {
839            Some(s) => RuntimeValue::Int(s),
840            None => RuntimeValue::from_bigint(BigInt::from_i64(*a).sub(&BigInt::from_i64(*b))),
841        }),
842        (RuntimeValue::BigInt(a), RuntimeValue::BigInt(b)) => {
843            Ok(RuntimeValue::from_bigint(a.sub(b)))
844        }
845        (RuntimeValue::BigInt(a), RuntimeValue::Int(b)) => {
846            Ok(RuntimeValue::from_bigint(a.sub(&BigInt::from_i64(*b))))
847        }
848        (RuntimeValue::Int(a), RuntimeValue::BigInt(b)) => {
849            Ok(RuntimeValue::from_bigint(BigInt::from_i64(*a).sub(b)))
850        }
851        (RuntimeValue::Float(a), RuntimeValue::Float(b)) => Ok(RuntimeValue::Float(a - b)),
852        (RuntimeValue::Int(a), RuntimeValue::Float(b)) => Ok(RuntimeValue::Float(*a as f64 - b)),
853        (RuntimeValue::Float(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Float(a - *b as f64)),
854        (RuntimeValue::BigInt(a), RuntimeValue::Float(b)) => {
855            Ok(RuntimeValue::Float(a.to_f64() - b))
856        }
857        (RuntimeValue::Float(a), RuntimeValue::BigInt(b)) => {
858            Ok(RuntimeValue::Float(a - b.to_f64()))
859        }
860        (RuntimeValue::Rational(a), RuntimeValue::Rational(b)) => {
861            Ok(RuntimeValue::from_rational(a.sub(b)))
862        }
863        (RuntimeValue::Rational(_), RuntimeValue::Int(_))
864        | (RuntimeValue::Int(_), RuntimeValue::Rational(_))
865        | (RuntimeValue::Rational(_), RuntimeValue::BigInt(_))
866        | (RuntimeValue::BigInt(_), RuntimeValue::Rational(_)) => Ok(RuntimeValue::from_rational(
867            rat_of(&left).unwrap().sub(&rat_of(&right).unwrap()),
868        )),
869        (RuntimeValue::Rational(r), RuntimeValue::Float(b)) => {
870            Ok(RuntimeValue::Float(r.to_f64() - b))
871        }
872        (RuntimeValue::Float(a), RuntimeValue::Rational(r)) => {
873            Ok(RuntimeValue::Float(a - r.to_f64()))
874        }
875        (RuntimeValue::Duration(a), RuntimeValue::Duration(b)) => {
876            Ok(RuntimeValue::Duration(a.wrapping_sub(*b)))
877        }
878        (
879            RuntimeValue::Date(days),
880            RuntimeValue::Span {
881                months,
882                days: span_days,
883            },
884        ) => Ok(RuntimeValue::Date(date_add_span(
885            *days,
886            -*months,
887            -*span_days,
888        ))),
889        // A Moment minus a CIVIL Span steps the calendar backward (`m - 1 month`), mirroring the add.
890        (
891            RuntimeValue::Moment(nanos),
892            RuntimeValue::Span {
893                months,
894                days: span_days,
895            },
896        ) => Ok(RuntimeValue::Moment(super::temporal::moment_add_span(
897            *nanos,
898            -*months,
899            -*span_days,
900        ))),
901        // A Moment minus a Duration is an earlier Moment. (Moment − Moment → elapsed Duration is
902        // deferred until Duration has a signed i64-nanos AOT representation, so the tiers stay in
903        // lock-step; `the seconds between a and b` already covers elapsed time naturally.)
904        (RuntimeValue::Moment(nanos), RuntimeValue::Duration(d)) => {
905            Ok(RuntimeValue::Moment(nanos.wrapping_sub(*d)))
906        }
907        _ => Err(format!(
908            "Cannot subtract {} from {}",
909            right.type_name(),
910            left.type_name()
911        )),
912    }
913}
914
915/// `base ** exp` — exponentiation. Integer power is EXACT (i64 fast path,
916/// promoting to BigInt on overflow); a Float operand takes the `f64::powf`
917/// path; a Rational base with an integer exponent stays exact; a NEGATIVE
918/// integer exponent on an integer base is a loud error (an Int can't hold the
919/// fractional result — use a Float base). ONE definition, shared by tw/VM/JIT.
920pub fn power(base: RuntimeValue, exp: RuntimeValue) -> Result<RuntimeValue, String> {
921    if let Some(r) = exact::arith(exact::Op::Pow, &base, &exp, &exact_recurse) {
922        return r;
923    }
924    // Any Float operand → inexact f64 power.
925    if matches!(base, RuntimeValue::Float(_)) || matches!(exp, RuntimeValue::Float(_)) {
926        let b = num_f64(&base)
927            .ok_or_else(|| format!("cannot raise {} to a power", base.type_name()))?;
928        let e =
929            num_f64(&exp).ok_or_else(|| format!("cannot raise to a {} power", exp.type_name()))?;
930        return Ok(RuntimeValue::Float(b.powf(e)));
931    }
932    match (&base, &exp) {
933        (RuntimeValue::Int(b), RuntimeValue::Int(e)) => int_power(*b, *e),
934        (RuntimeValue::BigInt(b), RuntimeValue::Int(e)) => {
935            let ue = u32::try_from(*e).map_err(|_| {
936                "negative or too-large exponent on an integer (use a Float base)".to_string()
937            })?;
938            Ok(RuntimeValue::from_bigint(b.pow(ue)))
939        }
940        (RuntimeValue::Rational(b), RuntimeValue::Int(e)) => {
941            let ie = i32::try_from(*e).map_err(|_| "exponent too large".to_string())?;
942            b.pow(ie)
943                .map(RuntimeValue::from_rational)
944                .ok_or_else(|| "zero raised to a negative power".to_string())
945        }
946        _ => Err(format!(
947            "cannot raise {} to the {} power",
948            base.type_name(),
949            exp.type_name()
950        )),
951    }
952}
953
954/// Exact `base^exp` for non-negative integer exponents; promotes to BigInt on
955/// i64 overflow. A negative exponent is a loud error.
956fn int_power(base: i64, exp: i64) -> Result<RuntimeValue, String> {
957    if exp < 0 {
958        return Err(
959            "negative exponent on an integer (an Int can't hold a fraction — use a Float base)"
960                .to_string(),
961        );
962    }
963    let e = u32::try_from(exp).map_err(|_| "exponent too large".to_string())?;
964    match base.checked_pow(e) {
965        Some(r) => Ok(RuntimeValue::Int(r)),
966        None => Ok(RuntimeValue::from_bigint(BigInt::from_i64(base).pow(e))),
967    }
968}
969
970pub fn multiply(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
971    if let Some(r) = exact::arith(exact::Op::Mul, &left, &right, &exact_recurse) {
972        return r;
973    }
974    if let (RuntimeValue::Word(a), RuntimeValue::Word(b)) = (&left, &right) {
975        return a
976            .mul(*b)
977            .map(RuntimeValue::Word)
978            .ok_or_else(|| word_width_err(*a, *b));
979    }
980    // SIMD lane vectors multiply lane-wise low-16 (`vpmullw`, the NTT's `*` over Word16 lanes).
981    if let (RuntimeValue::Lanes(a), RuntimeValue::Lanes(b)) = (&left, &right) {
982        return a
983            .mullo(**b)
984            .map(|v| RuntimeValue::Lanes(std::rc::Rc::new(v)))
985            .ok_or_else(|| {
986                format!(
987                    "cannot multiply {} and {} — lane op undefined",
988                    a.type_name(),
989                    b.type_name()
990                )
991            });
992    }
993    if let Some(r) = quantity_binop(&left, &right, '*') {
994        return r;
995    }
996    if let Some(r) = money_binop(&left, &right, '*') {
997        return r;
998    }
999    if let Some(r) = modular_binop(&left, &right, "multiply", |a, b| a.mul(b)) {
1000        return r;
1001    }
1002    if let Some(r) = complexf_binop(&left, &right, "multiply", |a, b| Some(a.mul(b))) {
1003        return r;
1004    }
1005    if let Some(r) = complex_binop(&left, &right, "multiply", |a, b| a.mul(b)) {
1006        return r;
1007    }
1008    if let Some(r) = decimal_binop(
1009        &left,
1010        &right,
1011        |a, b| a.mul(b),
1012        |a, b| a.mul(b),
1013        |a, b| a * b,
1014    ) {
1015        return Ok(r);
1016    }
1017    match (&left, &right) {
1018        (RuntimeValue::Int(a), RuntimeValue::Int(b)) => Ok(match a.checked_mul(*b) {
1019            Some(p) => RuntimeValue::Int(p),
1020            None => RuntimeValue::from_bigint(BigInt::from_i64(*a).mul(&BigInt::from_i64(*b))),
1021        }),
1022        (RuntimeValue::BigInt(a), RuntimeValue::BigInt(b)) => {
1023            Ok(RuntimeValue::from_bigint(a.mul(b)))
1024        }
1025        (RuntimeValue::BigInt(a), RuntimeValue::Int(b)) => {
1026            Ok(RuntimeValue::from_bigint(a.mul(&BigInt::from_i64(*b))))
1027        }
1028        (RuntimeValue::Int(a), RuntimeValue::BigInt(b)) => {
1029            Ok(RuntimeValue::from_bigint(BigInt::from_i64(*a).mul(b)))
1030        }
1031        (RuntimeValue::Float(a), RuntimeValue::Float(b)) => Ok(RuntimeValue::Float(a * b)),
1032        (RuntimeValue::Int(a), RuntimeValue::Float(b)) => Ok(RuntimeValue::Float(*a as f64 * b)),
1033        (RuntimeValue::Float(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Float(a * *b as f64)),
1034        (RuntimeValue::BigInt(a), RuntimeValue::Float(b)) => {
1035            Ok(RuntimeValue::Float(a.to_f64() * b))
1036        }
1037        (RuntimeValue::Float(a), RuntimeValue::BigInt(b)) => {
1038            Ok(RuntimeValue::Float(a * b.to_f64()))
1039        }
1040        (RuntimeValue::Rational(a), RuntimeValue::Rational(b)) => {
1041            Ok(RuntimeValue::from_rational(a.mul(b)))
1042        }
1043        (RuntimeValue::Rational(_), RuntimeValue::Int(_))
1044        | (RuntimeValue::Int(_), RuntimeValue::Rational(_))
1045        | (RuntimeValue::Rational(_), RuntimeValue::BigInt(_))
1046        | (RuntimeValue::BigInt(_), RuntimeValue::Rational(_)) => Ok(RuntimeValue::from_rational(
1047            rat_of(&left).unwrap().mul(&rat_of(&right).unwrap()),
1048        )),
1049        (RuntimeValue::Rational(r), RuntimeValue::Float(b)) => {
1050            Ok(RuntimeValue::Float(r.to_f64() * b))
1051        }
1052        (RuntimeValue::Float(a), RuntimeValue::Rational(r)) => {
1053            Ok(RuntimeValue::Float(a * r.to_f64()))
1054        }
1055        // `xs * n` / `n * xs` — repeat a sequence n times into a FRESH
1056        // sequence. Each slot deep-copies its element (a repeated inner
1057        // collection is n INDEPENDENT rows, never n aliases of one — the
1058        // classic `[[0]]*3` footgun is designed out). n ≤ 0 is empty.
1059        (RuntimeValue::List(items), RuntimeValue::Int(n))
1060        | (RuntimeValue::Int(n), RuntimeValue::List(items)) => {
1061            use crate::interpreter::ListRepr;
1062            let src = items.borrow().to_values();
1063            let count = (*n).max(0) as usize;
1064            let mut out = Vec::with_capacity(src.len() * count);
1065            for _ in 0..count {
1066                out.extend(src.iter().map(|v| v.deep_clone()));
1067            }
1068            Ok(RuntimeValue::List(Rc::new(std::cell::RefCell::new(
1069                ListRepr::from_values(out),
1070            ))))
1071        }
1072        _ => Err(format!(
1073            "Cannot multiply {} and {}",
1074            left.type_name(),
1075            right.type_name()
1076        )),
1077    }
1078}
1079
1080pub fn divide(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
1081    if let Some(r) = exact::arith(exact::Op::Div, &left, &right, &exact_recurse) {
1082        return r;
1083    }
1084    if let (RuntimeValue::Word(a), RuntimeValue::Word(b)) = (&left, &right) {
1085        if a.width() != b.width() {
1086            return Err(word_width_err(*a, *b));
1087        }
1088        if b.to_u64() == 0 {
1089            return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1090        }
1091        return Ok(RuntimeValue::Word(a.div(*b).expect("width checked above")));
1092    }
1093    if let Some(r) = quantity_binop(&left, &right, '/') {
1094        return r;
1095    }
1096    if let Some(r) = money_binop(&left, &right, '/') {
1097        return r;
1098    }
1099    // Modular division = multiply by the modular inverse: the operands must share a modulus
1100    // and the divisor must be a unit (coprime to the modulus), else there is no inverse.
1101    if matches!(left, RuntimeValue::Modular(_)) || matches!(right, RuntimeValue::Modular(_)) {
1102        return match (&left, &right) {
1103            (RuntimeValue::Modular(a), RuntimeValue::Modular(b)) => {
1104                if a.modulus() != b.modulus() {
1105                    Err(logicaffeine_data::failure::modular_rings_differ("divide"))
1106                } else {
1107                    a.div(b)
1108                        .map(|r| RuntimeValue::Modular(Rc::new(r)))
1109                        .ok_or_else(|| logicaffeine_data::failure::NO_MODULAR_INVERSE.to_string())
1110                }
1111            }
1112            _ => Err(format!(
1113                "Cannot divide {} by {}",
1114                left.type_name(),
1115                right.type_name()
1116            )),
1117        };
1118    }
1119    // Floating-point-complex division (promotes when a float meets a complex); `None` on a zero
1120    // divisor. Checked before the exact path so two exact complexes still divide exactly.
1121    if let Some(r) = complexf_binop(&left, &right, "divide", |a, b| a.div(b)) {
1122        return r;
1123    }
1124    // Complex division stays Complex (the field is closed); `None` on a zero divisor.
1125    if matches!(left, RuntimeValue::Complex(_)) || matches!(right, RuntimeValue::Complex(_)) {
1126        return match (complex_of(&left), complex_of(&right)) {
1127            (Some(a), Some(b)) => a
1128                .div(&b)
1129                .map(|c| RuntimeValue::Complex(Rc::new(c)))
1130                .ok_or_else(|| logicaffeine_data::failure::DIVISION_BY_ZERO.to_string()),
1131            _ => Err(format!(
1132                "Cannot divide {} by {}",
1133                left.type_name(),
1134                right.type_name()
1135            )),
1136        };
1137    }
1138    // A Decimal divides EXACTLY into the Rational tower (base-10 division need not
1139    // terminate, so it does not stay a Decimal); a Float operand divides as Float.
1140    if matches!(left, RuntimeValue::Decimal(_)) || matches!(right, RuntimeValue::Decimal(_)) {
1141        if let (Some(a), Some(b)) = (rat_of(&left), rat_of(&right)) {
1142            return a
1143                .div(&b)
1144                .map(RuntimeValue::from_rational)
1145                .ok_or_else(|| logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1146        }
1147        if let (Some(a), Some(b)) = (num_f64(&left), num_f64(&right)) {
1148            if b == 0.0 {
1149                return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1150            }
1151            return Ok(RuntimeValue::Float(a / b));
1152        }
1153    }
1154    match (&left, &right) {
1155        (RuntimeValue::Int(a), RuntimeValue::Int(b)) => {
1156            if *b == 0 {
1157                return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1158            }
1159            // checked_div is None only for i64::MIN / -1, whose true quotient
1160            // (2^63) overflows i64 → promote rather than wrap.
1161            Ok(match a.checked_div(*b) {
1162                Some(q) => RuntimeValue::Int(q),
1163                None => RuntimeValue::from_bigint(int_div(*a, *b).0),
1164            })
1165        }
1166        (RuntimeValue::BigInt(a), RuntimeValue::BigInt(b)) => Ok(RuntimeValue::from_bigint(
1167            a.div_rem(b).expect("BigInt divisor is never zero").0,
1168        )),
1169        (RuntimeValue::BigInt(a), RuntimeValue::Int(b)) => {
1170            if *b == 0 {
1171                return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1172            }
1173            Ok(RuntimeValue::from_bigint(
1174                a.div_rem(&BigInt::from_i64(*b)).unwrap().0,
1175            ))
1176        }
1177        (RuntimeValue::Int(a), RuntimeValue::BigInt(b)) => Ok(RuntimeValue::from_bigint(
1178            BigInt::from_i64(*a).div_rem(b).unwrap().0,
1179        )),
1180        (RuntimeValue::Float(a), RuntimeValue::Float(b)) => {
1181            if *b == 0.0 {
1182                return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1183            }
1184            Ok(RuntimeValue::Float(a / b))
1185        }
1186        (RuntimeValue::Int(a), RuntimeValue::Float(b)) => {
1187            if *b == 0.0 {
1188                return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1189            }
1190            Ok(RuntimeValue::Float(*a as f64 / b))
1191        }
1192        (RuntimeValue::Float(a), RuntimeValue::Int(b)) => {
1193            if *b == 0 {
1194                return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1195            }
1196            Ok(RuntimeValue::Float(a / *b as f64))
1197        }
1198        (RuntimeValue::BigInt(a), RuntimeValue::Float(b)) => {
1199            if *b == 0.0 {
1200                return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1201            }
1202            Ok(RuntimeValue::Float(a.to_f64() / b))
1203        }
1204        (RuntimeValue::Float(a), RuntimeValue::BigInt(b)) => {
1205            Ok(RuntimeValue::Float(a / b.to_f64()))
1206        }
1207        // Exact division on Rational operands: the quotient is exact (downsized to an
1208        // Int when it reduces to a whole number). A Float operand makes it Float.
1209        (RuntimeValue::Rational(_), RuntimeValue::Rational(_))
1210        | (RuntimeValue::Rational(_), RuntimeValue::Int(_))
1211        | (RuntimeValue::Int(_), RuntimeValue::Rational(_))
1212        | (RuntimeValue::Rational(_), RuntimeValue::BigInt(_))
1213        | (RuntimeValue::BigInt(_), RuntimeValue::Rational(_)) => rat_of(&left)
1214            .unwrap()
1215            .div(&rat_of(&right).unwrap())
1216            .map(RuntimeValue::from_rational)
1217            .ok_or_else(|| logicaffeine_data::failure::DIVISION_BY_ZERO.to_string()),
1218        (RuntimeValue::Rational(r), RuntimeValue::Float(b)) => {
1219            if *b == 0.0 {
1220                return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1221            }
1222            Ok(RuntimeValue::Float(r.to_f64() / b))
1223        }
1224        (RuntimeValue::Float(a), RuntimeValue::Rational(r)) => {
1225            Ok(RuntimeValue::Float(a / r.to_f64()))
1226        }
1227        _ => Err(format!(
1228            "Cannot divide {} by {}",
1229            left.type_name(),
1230            right.type_name()
1231        )),
1232    }
1233}
1234
1235/// Exact integer division of two `i64`s as a BigInt `(quotient, remainder)` — used on
1236/// the one overflowing case, `i64::MIN / -1`.
1237fn int_div(a: i64, b: i64) -> (BigInt, BigInt) {
1238    BigInt::from_i64(a)
1239        .div_rem(&BigInt::from_i64(b))
1240        .expect("nonzero divisor")
1241}
1242
1243/// FLOOR division — the runtime of [`BinaryOpKind::FloorDivide`] (`a // b`), the quotient
1244/// rounded toward NEGATIVE INFINITY. On exact operands (Int/BigInt/Rational/Decimal) the
1245/// result is the exact quotient's floor as an integer (`-7 // 2 → -4`, `10^30 // 7` exact);
1246/// a Float operand floors the float quotient but stays Float (`7.5 // 2 → 3.0`, Python
1247/// semantics). Distinct from [`divide`], which truncates toward zero. Zero divisor is loud.
1248pub fn floor_divide(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
1249    if let Some(r) = exact::arith(exact::Op::FloorDiv, &left, &right, &exact_recurse) {
1250        return r;
1251    }
1252    // Float domain: floor the float quotient, staying inexact.
1253    if matches!(left, RuntimeValue::Float(_)) || matches!(right, RuntimeValue::Float(_)) {
1254        if let (Some(a), Some(b)) = (num_f64(&left), num_f64(&right)) {
1255            if b == 0.0 {
1256                return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1257            }
1258            return Ok(RuntimeValue::Float((a / b).floor()));
1259        }
1260    }
1261    // Exact domain: the exact rational quotient, floored to an integer (BigInt-promoting,
1262    // downsized to Int when it fits). `rat_of` covers Int/BigInt/Rational/Decimal.
1263    if let (Some(a), Some(b)) = (rat_of(&left), rat_of(&right)) {
1264        return a
1265            .div(&b)
1266            .map(|q| RuntimeValue::from_bigint(q.floor()))
1267            .ok_or_else(|| logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1268    }
1269    Err(format!(
1270        "Cannot floor-divide {} by {}",
1271        left.type_name(),
1272        right.type_name()
1273    ))
1274}
1275
1276/// EXACT division — the runtime of [`BinaryOpKind::ExactDivide`], the type-directed
1277/// sibling of [`divide`]. An evenly-dividing integer pair stays an `Int`/`BigInt`;
1278/// otherwise the quotient is an exact `Rational` (`7 / 2 → 7/2`) — it NEVER truncates.
1279/// A `Float` operand divides as `Float` (floats are inexact by choice). This only ever
1280/// runs where the type says the result is a `Rational`, so floor code is untouched.
1281pub fn exact_divide(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
1282    if let Some(r) = exact::arith(exact::Op::ExactDiv, &left, &right, &exact_recurse) {
1283        return r;
1284    }
1285    match (&left, &right) {
1286        // Every Int/BigInt/Rational combination divides to an EXACT value — downsized to
1287        // an Int/BigInt when it reduces to a whole number, else an exact Rational.
1288        (a, b) if rat_of(a).is_some() && rat_of(b).is_some() => rat_of(&left)
1289            .unwrap()
1290            .div(&rat_of(&right).unwrap())
1291            .map(RuntimeValue::from_rational)
1292            .ok_or_else(|| logicaffeine_data::failure::DIVISION_BY_ZERO.to_string()),
1293        // A Float operand makes it Float — defer to the Float-aware `divide` (whose Float
1294        // arms don't truncate anyway).
1295        (RuntimeValue::Float(_), _) | (_, RuntimeValue::Float(_)) => divide(left, right),
1296        _ => Err(format!(
1297            "Cannot divide {} by {}",
1298            left.type_name(),
1299            right.type_name()
1300        )),
1301    }
1302}
1303
1304pub fn modulo(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
1305    if let Some(r) = exact::arith(exact::Op::Mod, &left, &right, &exact_recurse) {
1306        return r;
1307    }
1308    if let (RuntimeValue::Word(a), RuntimeValue::Word(b)) = (&left, &right) {
1309        if a.width() != b.width() {
1310            return Err(word_width_err(*a, *b));
1311        }
1312        if b.to_u64() == 0 {
1313            return Err(logicaffeine_data::failure::MODULO_BY_ZERO.to_string());
1314        }
1315        return Ok(RuntimeValue::Word(a.rem(*b).expect("width checked above")));
1316    }
1317    match (&left, &right) {
1318        (RuntimeValue::Int(a), RuntimeValue::Int(b)) => {
1319            if *b == 0 {
1320                return Err(logicaffeine_data::failure::MODULO_BY_ZERO.to_string());
1321            }
1322            // checked_rem is None only for i64::MIN % -1, whose true remainder is 0.
1323            Ok(RuntimeValue::Int(a.checked_rem(*b).unwrap_or(0)))
1324        }
1325        (RuntimeValue::BigInt(a), RuntimeValue::BigInt(b)) => Ok(RuntimeValue::from_bigint(
1326            a.div_rem(b).expect("BigInt divisor is never zero").1,
1327        )),
1328        (RuntimeValue::BigInt(a), RuntimeValue::Int(b)) => {
1329            if *b == 0 {
1330                return Err(logicaffeine_data::failure::MODULO_BY_ZERO.to_string());
1331            }
1332            Ok(RuntimeValue::from_bigint(
1333                a.div_rem(&BigInt::from_i64(*b)).unwrap().1,
1334            ))
1335        }
1336        (RuntimeValue::Int(a), RuntimeValue::BigInt(b)) => Ok(RuntimeValue::from_bigint(
1337            BigInt::from_i64(*a).div_rem(b).unwrap().1,
1338        )),
1339        _ => Err(format!(
1340            "Cannot compute modulo of {} and {}",
1341            left.type_name(),
1342            right.type_name()
1343        )),
1344    }
1345}
1346
1347/// One CRDT counter step: `current + amount`. A CRDT grow-counter is intentionally
1348/// `wrapping` (modular) — convergence is defined over the cyclic group, so overflow
1349/// is a feature here, NOT the silent-corruption footgun that ordinary integer math
1350/// now promotes away. An absent or Nothing field starts from zero.
1351pub fn crdt_counter_bump(
1352    current: RuntimeValue,
1353    amount: i64,
1354    field_name: &str,
1355) -> Result<RuntimeValue, String> {
1356    match current {
1357        // A live per-replica counter (`ConvergentCount`/`Tally`): bump THIS replica's slot, returning
1358        // a fresh replica so the field never aliases. The per-replica accounting is what makes a
1359        // later merge idempotent — the same remote state re-merged never double-counts.
1360        RuntimeValue::Crdt(rc) => {
1361            let mut cv = rc.borrow().clone();
1362            cv.bump(amount)?;
1363            Ok(RuntimeValue::Crdt(std::rc::Rc::new(
1364                std::cell::RefCell::new(cv),
1365            )))
1366        }
1367        RuntimeValue::Int(n) => Ok(RuntimeValue::Int(n.wrapping_add(amount))),
1368        RuntimeValue::Nothing => Ok(RuntimeValue::Int(amount)),
1369        _ => Err(format!("Field '{}' is not a counter", field_name)),
1370    }
1371}
1372
1373/// Merge one CRDT field by its convergence rule:
1374/// - `Int` + `Int` — a grow-counter, so add (intentionally `wrapping`/modular);
1375/// - `Set` + `Set` — a grow-set, so union (dedup by value);
1376/// - anything else (LWW register: Bool/Text/Float/…) — last writer wins ⇒ take
1377///   the incoming value.
1378/// The struct type tag the interpreter uses for a state-based, gossip-safe G-Counter: a
1379/// map of `replica id → that replica's monotonic count`. Distinct from a plain counter
1380/// (a bare `Int` whose op-based `add` merge is NOT idempotent under redelivery).
1381pub const GCOUNTER_TAG: &str = "__GCounter";
1382
1383/// The total of a [`GCOUNTER_TAG`] counter — the sum of every replica's count. `None` for
1384/// a value that is not a G-Counter.
1385pub fn gcounter_value(v: &RuntimeValue) -> Option<i64> {
1386    match v {
1387        RuntimeValue::Struct(s) if s.type_name == GCOUNTER_TAG => Some(
1388            s.fields
1389                .values()
1390                .map(|c| if let RuntimeValue::Int(n) = c { *n } else { 0 })
1391                .fold(0i64, i64::wrapping_add),
1392        ),
1393        _ => None,
1394    }
1395}
1396
1397pub fn crdt_merge_field(current: &RuntimeValue, incoming: RuntimeValue) -> RuntimeValue {
1398    match (current, &incoming) {
1399        // A state-based G-Counter: per-replica MAX. Unlike the bare-Int `add` below, MAX is
1400        // IDEMPOTENT (max of a value with itself is itself), so a redelivered or duplicated
1401        // counter state never double-counts — gossip/lossy-network safe. Commutative and
1402        // associative too, so all replicas converge to the same total.
1403        (RuntimeValue::Struct(a), RuntimeValue::Struct(b))
1404            if a.type_name == GCOUNTER_TAG && b.type_name == GCOUNTER_TAG =>
1405        {
1406            let mut fields = a.fields.clone();
1407            for (replica, count) in &b.fields {
1408                let next = match (fields.get(replica), count) {
1409                    (Some(RuntimeValue::Int(x)), RuntimeValue::Int(y)) => {
1410                        RuntimeValue::Int((*x).max(*y))
1411                    }
1412                    _ => count.clone(),
1413                };
1414                fields.insert(replica.clone(), next);
1415            }
1416            RuntimeValue::Struct(Box::new(crate::interpreter::StructValue {
1417                type_name: GCOUNTER_TAG.to_string(),
1418                fields,
1419            }))
1420        }
1421        (RuntimeValue::Int(a), RuntimeValue::Int(b)) => RuntimeValue::Int(a.wrapping_add(*b)),
1422        (RuntimeValue::Set(_), RuntimeValue::Set(_)) => {
1423            crate::semantics::collections::union(current, &incoming).unwrap_or(incoming)
1424        }
1425        // A CRDT MAP — "shared memory" over the network: the union of keys, each shared
1426        // key's values merged RECURSIVELY through this same join. The merge inherits the
1427        // value type's laws: a map of sets (or of nested maps) is commutative, associative,
1428        // AND idempotent, so replicas converge no matter the order or duplication of merges.
1429        (RuntimeValue::Map(a), RuntimeValue::Map(b)) => {
1430            let mut out = a.borrow().clone();
1431            for (k, v) in b.borrow().iter() {
1432                let merged = match out.get(k) {
1433                    Some(cur) => crdt_merge_field(cur, v.clone()),
1434                    None => v.clone(),
1435                };
1436                out.insert(k.clone(), merged);
1437            }
1438            RuntimeValue::Map(std::rc::Rc::new(std::cell::RefCell::new(out)))
1439        }
1440        // A live CRDT (OR-Set / RGA / MV-register) converges through its own state-based
1441        // join. The result is a FRESH replica (the current state deep-copied, then the
1442        // incoming state merged into it), so neither operand is aliased into the result —
1443        // the join inherits the data-crate type's commutativity/associativity/idempotence.
1444        (RuntimeValue::Crdt(a), RuntimeValue::Crdt(b)) => {
1445            let mut merged = a.borrow().clone();
1446            let _ = merged.merge(&b.borrow());
1447            RuntimeValue::Crdt(std::rc::Rc::new(std::cell::RefCell::new(merged)))
1448        }
1449        // A live COUNTER CRDT receiving an incoming Int-projected total from the readable relay wire
1450        // (`{"points":3}`): a state-based counter cannot reconstruct a peer's per-replica breakdown
1451        // from a scalar total, so the local per-replica counter is authoritative and STANDS — folding a
1452        // bare total would be non-idempotent (double-count on redelivery) and would clobber the live
1453        // CRDT. Cross-replica counter convergence uses the in-process `Merge` (real per-replica MAX);
1454        // the Int wire form is the READABLE projection, not the merge channel.
1455        (RuntimeValue::Crdt(a), _) if a.borrow().counter_value().is_some() => {
1456            RuntimeValue::Crdt(a.clone())
1457        }
1458        _ => incoming,
1459    }
1460}
1461
1462/// The state-based CRDT LATTICE JOIN of one struct field — the IDEMPOTENT sibling of `crdt_merge_field`:
1463/// identical EXCEPT a bare-`Int` field takes per-field MAX (not ADD), so applying a redelivered state twice
1464/// never double-counts. Counter/other fields defer to `crdt_merge_field` (already idempotent / LWW).
1465pub fn crdt_join_field(current: &RuntimeValue, incoming: RuntimeValue) -> RuntimeValue {
1466    match (current, &incoming) {
1467        (RuntimeValue::Int(a), RuntimeValue::Int(b)) => RuntimeValue::Int((*a).max(*b)),
1468        _ => crdt_merge_field(current, incoming),
1469    }
1470}
1471
1472/// One CRDT field value → its JSON wire form. Scalars map directly; a `Set`
1473/// becomes a JSON array of its (scalar) members. Returns `None` for values that
1474/// are not CRDT-syncable.
1475fn field_to_json(value: &RuntimeValue) -> Option<serde_json::Value> {
1476    use serde_json::{json, Value};
1477    Some(match value {
1478        RuntimeValue::Int(n) => json!(n),
1479        RuntimeValue::Bool(b) => json!(b),
1480        RuntimeValue::Float(f) => json!(f),
1481        RuntimeValue::Text(s) => json!(s.as_str()),
1482        RuntimeValue::Nothing => Value::Null,
1483        RuntimeValue::Set(items) => {
1484            Value::Array(items.borrow().iter().filter_map(field_to_json).collect())
1485        }
1486        // A map ships as a TAGGED array of [key, value] pairs so it is unambiguous from a
1487        // plain Set array, and any key type (not just strings) round-trips.
1488        RuntimeValue::Map(m) => {
1489            let pairs: Vec<Value> = m
1490                .borrow()
1491                .iter()
1492                .filter_map(|(k, v)| Some(Value::Array(vec![field_to_json(k)?, field_to_json(v)?])))
1493                .collect();
1494            json!({ "__map": pairs })
1495        }
1496        // A live COUNTER CRDT (`ConvergentCount`/`Tally`) projects to its Int TOTAL — the readable
1497        // relay wire form `{"points":3}` (Spec A: a counter reads/serializes as its scalar total). A
1498        // non-counter CRDT (OR-Set / RGA / MV-register) has no scalar projection and ships its full
1499        // state through the δ-state `Sync` path instead, so it is `None` here.
1500        RuntimeValue::Crdt(rc) => match rc.borrow().counter_value() {
1501            Some(n) => json!(n),
1502            None => return None,
1503        },
1504        _ => return None,
1505    })
1506}
1507
1508/// A JSON wire value → a CRDT field value. The inverse of [`field_to_json`]; a
1509/// JSON array reconstructs a `Set`.
1510fn field_from_json(value: &serde_json::Value) -> RuntimeValue {
1511    use serde_json::Value;
1512    match value {
1513        Value::Bool(b) => RuntimeValue::Bool(*b),
1514        Value::String(s) => RuntimeValue::Text(std::rc::Rc::new(s.clone())),
1515        Value::Number(n) => match n.as_i64() {
1516            Some(i) => RuntimeValue::Int(i),
1517            None => RuntimeValue::Float(n.as_f64().unwrap_or(0.0)),
1518        },
1519        Value::Array(items) => RuntimeValue::Set(std::rc::Rc::new(std::cell::RefCell::new(
1520            items.iter().map(field_from_json).collect(),
1521        ))),
1522        // A tagged `{"__map": [[k,v],…]}` reconstructs a map (the inverse of `field_to_json`).
1523        Value::Object(o) if o.contains_key("__map") => {
1524            let mut map = crate::interpreter::MapStorage::default();
1525            if let Some(Value::Array(pairs)) = o.get("__map") {
1526                for p in pairs {
1527                    if let Value::Array(kv) = p {
1528                        if kv.len() == 2 {
1529                            map.insert(field_from_json(&kv[0]), field_from_json(&kv[1]));
1530                        }
1531                    }
1532                }
1533            }
1534            RuntimeValue::Map(std::rc::Rc::new(std::cell::RefCell::new(map)))
1535        }
1536        _ => RuntimeValue::Nothing,
1537    }
1538}
1539
1540/// Encode a CRDT value for the relay wire: a JSON object mapping each Int field
1541/// to its value. A bare `Int` counter uses the empty field name. `Nothing` (and
1542/// any non-counter value) has nothing to publish. The format is browser-friendly
1543/// and field-addressable, so structs merge field-by-field on the other side.
1544pub fn crdt_to_wire(value: &RuntimeValue) -> Option<Vec<u8>> {
1545    use serde_json::{Map, Value};
1546    let mut map = Map::new();
1547    match value {
1548        RuntimeValue::Nothing => return None,
1549        RuntimeValue::Struct(s) => {
1550            for (k, v) in &s.fields {
1551                if let Some(j) = field_to_json(v) {
1552                    map.insert(k.clone(), j);
1553                }
1554            }
1555        }
1556        // A bare counter / register / set uses the unnamed field.
1557        other => match field_to_json(other) {
1558            Some(j) => {
1559                map.insert(String::new(), j);
1560            }
1561            None => return None,
1562        },
1563    }
1564    serde_json::to_vec(&Value::Object(map)).ok()
1565}
1566
1567/// Merge a wire-encoded CRDT value (from [`crdt_to_wire`]) into `local`, field by
1568/// field through [`crdt_merge_field`] — counters add, sets union, registers take
1569/// the latest. A struct merges each named field; a bare value the unnamed field.
1570/// Malformed bytes leave `local` unchanged.
1571pub fn crdt_merge_wire(local: RuntimeValue, bytes: &[u8]) -> RuntimeValue {
1572    let Ok(serde_json::Value::Object(map)) = serde_json::from_slice::<serde_json::Value>(bytes)
1573    else {
1574        return local;
1575    };
1576    match local {
1577        RuntimeValue::Struct(mut s) => {
1578            for (k, v) in map {
1579                let incoming = field_from_json(&v);
1580                let current = s.fields.get(&k).cloned().unwrap_or(RuntimeValue::Nothing);
1581                s.fields.insert(k, crdt_merge_field(&current, incoming));
1582            }
1583            RuntimeValue::Struct(s)
1584        }
1585        other => match map.get("") {
1586            Some(v) => crdt_merge_field(&other, field_from_json(v)),
1587            None => other,
1588        },
1589    }
1590}
1591
1592/// `not x` — logical negation of truthiness (Bool out). The bitwise complement is `~`.
1593pub fn not_value(val: RuntimeValue) -> Result<RuntimeValue, String> {
1594    if let Some(r) = exact::not(&val, &not_value) {
1595        return r;
1596    }
1597    Ok(RuntimeValue::Bool(!val.is_truthy()))
1598}
1599
1600#[cfg(test)]
1601#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/semantics/arith/tests.rs"]
1602mod tests;
1603
1604#[cfg(test)]
1605#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/semantics/arith/bigint_exact_arithmetic.rs"]
1606mod bigint_exact_arithmetic;
1607
1608#[cfg(test)]
1609#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/semantics/arith/rational_exact_arithmetic.rs"]
1610mod rational_exact_arithmetic;
1611
1612#[cfg(test)]
1613#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/semantics/arith/word_tests.rs"]
1614mod word_tests;