Skip to main content

logicaffeine_compile/vm/
value.rs

1//! The VM value type.
2//!
3//! `Value` is the register-file cell. It has two representations, selected at
4//! compile time:
5//!
6//! * **default** — `Value(RuntimeValue)`, a newtype over the tree-walker's fat
7//!   16-byte enum. Every operation delegates to the shared semantics kernel
8//!   (`crate::semantics`) — the same functions the tree-walker calls — so the
9//!   two engines cannot diverge on value semantics.
10//! * **`feature = "narrow-value"`** — `Value(Narrow)`, the 8-byte NaN-boxed
11//!   value from [`super::nanbox`]. Inline scalars (`Int` in ±2^47, `Float`,
12//!   `Bool`, `Nothing`) live in one machine word; everything else (large ints,
13//!   collections, strings, structs, temporals) boxes behind a heap tag. The
14//!   register file (`Vec<Value>`) is then half the width, and every Move/clone
15//!   in the dispatch loop copies 8 bytes instead of 16.
16//!
17//! Both representations expose the SAME public API and route non-inline operands
18//! through `crate::semantics` exactly the same way, so the VM↔tree-walker
19//! differential gate holds under either build. This is the seam the VM's design calls
20//! for: the representation swap touches only this file (plus the `as_runtime`
21//! borrow sites in `machine.rs`, which use [`RuntimeRef`] uniformly).
22
23use std::cell::RefCell;
24use std::rc::Rc;
25
26use crate::ast::stmt::BinaryOpKind;
27use crate::interpreter::RuntimeValue;
28use crate::semantics::{arith, collections, compare};
29
30/// A borrow of a [`Value`] as a `RuntimeValue`, usable identically under both
31/// representations.
32///
33/// * default: `RuntimeRef<'a>` borrows the `Value`'s own `RuntimeValue` — zero
34///   cost, exactly the old `&RuntimeValue` return.
35/// * narrow: a heap `Value` borrows the boxed pointee directly; an inline scalar
36///   materialises a fresh `RuntimeValue` that the `RuntimeRef` owns.
37///
38/// `Deref<Target = RuntimeValue>` makes `r.method()`, `&*r`, and `(*r).clone()`
39/// behave the same in either build. Match scrutinees do not auto-deref, so the
40/// `machine.rs` sites match on `&*value.as_runtime()`.
41pub struct RuntimeRef<'a>(RuntimeRefInner<'a>);
42
43enum RuntimeRefInner<'a> {
44    Borrowed(&'a RuntimeValue),
45    #[cfg(feature = "narrow-value")]
46    Owned(RuntimeValue),
47}
48
49impl std::ops::Deref for RuntimeRef<'_> {
50    type Target = RuntimeValue;
51    #[inline]
52    fn deref(&self) -> &RuntimeValue {
53        match &self.0 {
54            RuntimeRefInner::Borrowed(r) => r,
55            #[cfg(feature = "narrow-value")]
56            RuntimeRefInner::Owned(v) => v,
57        }
58    }
59}
60
61impl AsRef<RuntimeValue> for RuntimeRef<'_> {
62    #[inline]
63    fn as_ref(&self) -> &RuntimeValue {
64        self
65    }
66}
67
68impl std::fmt::Debug for RuntimeRef<'_> {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        (**self).fmt(f)
71    }
72}
73
74// ===========================================================================
75// Default representation: Value(RuntimeValue)
76// ===========================================================================
77
78#[cfg(not(feature = "narrow-value"))]
79mod repr {
80    use super::*;
81
82    /// A VM value (fat 16-byte representation).
83    #[derive(Clone, Debug)]
84    pub struct Value(pub(super) RuntimeValue);
85
86    impl Value {
87        #[inline]
88        pub fn int(n: i64) -> Self {
89            Value(RuntimeValue::Int(n))
90        }
91        #[inline]
92        pub fn float(f: f64) -> Self {
93            Value(RuntimeValue::Float(f))
94        }
95        #[inline]
96        pub fn bool(b: bool) -> Self {
97            Value(RuntimeValue::Bool(b))
98        }
99        #[inline]
100        pub fn nothing() -> Self {
101            Value(RuntimeValue::Nothing)
102        }
103        /// Whether this is the default/absent value — a register's pristine initial state. A write
104        /// that overwrites `Nothing` destroys no information (the default is known), so it costs zero
105        /// Landauer bits (see `HistoryTape::landauer_bytes`).
106        #[inline]
107        pub fn is_nothing(&self) -> bool {
108            matches!(&*self.as_runtime(), RuntimeValue::Nothing)
109        }
110
111        #[inline]
112        pub fn from_runtime(rv: RuntimeValue) -> Self {
113            Value(rv)
114        }
115        #[inline]
116        pub fn into_runtime(self) -> RuntimeValue {
117            self.0
118        }
119
120        /// Borrow as a `RuntimeValue`. Zero cost: the `Value` IS a
121        /// `RuntimeValue`.
122        #[inline]
123        pub fn as_runtime(&self) -> RuntimeRef<'_> {
124            RuntimeRef(RuntimeRefInner::Borrowed(&self.0))
125        }
126
127        /// Borrow the `RuntimeValue` DIRECTLY (lifetime tied to `&self`, no
128        /// `RuntimeRef` temporary) when one already exists in place. Default:
129        /// always `Some`. The seam for the `machine.rs` sites that destructure a
130        /// heap arm and hold a borrow (an `Rc`/`RefMut`) across statements — see
131        /// the narrow impl, where an inline scalar returns `None`.
132        #[inline]
133        pub fn as_runtime_ref(&self) -> Option<&RuntimeValue> {
134            Some(&self.0)
135        }
136
137        /// Mutably borrow as a `RuntimeValue`.
138        #[inline]
139        pub fn as_runtime_mut(&mut self) -> &mut RuntimeValue {
140            &mut self.0
141        }
142
143        #[inline]
144        pub fn as_int(&self) -> Option<i64> {
145            match &self.0 {
146                RuntimeValue::Int(n) => Some(*n),
147                _ => None,
148            }
149        }
150        #[inline]
151        pub fn as_bool(&self) -> Option<bool> {
152            match &self.0 {
153                RuntimeValue::Bool(b) => Some(*b),
154                _ => None,
155            }
156        }
157        #[inline]
158        pub fn as_float(&self) -> Option<f64> {
159            match &self.0 {
160                RuntimeValue::Float(f) => Some(*f),
161                _ => None,
162            }
163        }
164        #[inline]
165        pub fn is_int(&self) -> bool {
166            matches!(self.0, RuntimeValue::Int(_))
167        }
168
169        // ---- Arithmetic (Int×Int inlined; EXACT — overflow promotes to BigInt) ---
170        //
171        // The fast path uses `checked_*` and, only on i64 overflow, falls through to
172        // the shared `arith` operators (which promote to BigInt). This keeps the VM
173        // byte-identical to the tree-walker at the overflow boundary — integer math
174        // is exact on every tier, never silently wrapping.
175
176        #[inline]
177        pub fn add(&self, rhs: &Value) -> Result<Value, String> {
178            if let (RuntimeValue::Int(a), RuntimeValue::Int(b)) = (&self.0, &rhs.0) {
179                if let Some(s) = a.checked_add(*b) {
180                    return Ok(Value::int(s));
181                }
182            }
183            arith::add(self.0.clone(), rhs.0.clone()).map(Value)
184        }
185        #[inline]
186        pub fn sub(&self, rhs: &Value) -> Result<Value, String> {
187            if let (RuntimeValue::Int(a), RuntimeValue::Int(b)) = (&self.0, &rhs.0) {
188                if let Some(s) = a.checked_sub(*b) {
189                    return Ok(Value::int(s));
190                }
191            }
192            arith::subtract(self.0.clone(), rhs.0.clone()).map(Value)
193        }
194        #[inline]
195        pub fn mul(&self, rhs: &Value) -> Result<Value, String> {
196            if let (RuntimeValue::Int(a), RuntimeValue::Int(b)) = (&self.0, &rhs.0) {
197                if let Some(p) = a.checked_mul(*b) {
198                    return Ok(Value::int(p));
199                }
200            }
201            arith::multiply(self.0.clone(), rhs.0.clone()).map(Value)
202        }
203
204        // ---- Comparison (Int×Int inlined — same proof) -----------------------
205
206        #[inline]
207        pub fn lt(&self, rhs: &Value) -> Result<Value, String> {
208            if let (RuntimeValue::Int(a), RuntimeValue::Int(b)) = (&self.0, &rhs.0) {
209                return Ok(Value::bool(a < b));
210            }
211            compare::compare(BinaryOpKind::Lt, &self.0, &rhs.0).map(Value)
212        }
213        #[inline]
214        pub fn gt(&self, rhs: &Value) -> Result<Value, String> {
215            if let (RuntimeValue::Int(a), RuntimeValue::Int(b)) = (&self.0, &rhs.0) {
216                return Ok(Value::bool(a > b));
217            }
218            compare::compare(BinaryOpKind::Gt, &self.0, &rhs.0).map(Value)
219        }
220        #[inline]
221        pub fn lte(&self, rhs: &Value) -> Result<Value, String> {
222            if let (RuntimeValue::Int(a), RuntimeValue::Int(b)) = (&self.0, &rhs.0) {
223                return Ok(Value::bool(a <= b));
224            }
225            compare::compare(BinaryOpKind::LtEq, &self.0, &rhs.0).map(Value)
226        }
227        #[inline]
228        pub fn gte(&self, rhs: &Value) -> Result<Value, String> {
229            if let (RuntimeValue::Int(a), RuntimeValue::Int(b)) = (&self.0, &rhs.0) {
230                return Ok(Value::bool(a >= b));
231            }
232            compare::compare(BinaryOpKind::GtEq, &self.0, &rhs.0).map(Value)
233        }
234        #[inline]
235        pub fn eq_op(&self, rhs: &Value) -> Result<Value, String> {
236            if let (RuntimeValue::Int(a), RuntimeValue::Int(b)) = (&self.0, &rhs.0) {
237                return Ok(Value::bool(a == b));
238            }
239            compare::equality(&self.0, &rhs.0, false).map(Value)
240        }
241        #[inline]
242        pub fn neq_op(&self, rhs: &Value) -> Result<Value, String> {
243            if let (RuntimeValue::Int(a), RuntimeValue::Int(b)) = (&self.0, &rhs.0) {
244                return Ok(Value::bool(a != b));
245            }
246            compare::equality(&self.0, &rhs.0, true).map(Value)
247        }
248    }
249}
250
251// ===========================================================================
252// Narrow representation: Value(Narrow)
253// ===========================================================================
254
255#[cfg(feature = "narrow-value")]
256mod repr {
257    use super::*;
258    use crate::vm::nanbox::Narrow;
259
260    /// A VM value (8-byte NaN-boxed representation).
261    #[derive(Clone, Debug)]
262    pub struct Value(pub(super) Narrow);
263
264    impl Value {
265        #[inline]
266        pub fn int(n: i64) -> Self {
267            Value(Narrow::int(n))
268        }
269        #[inline]
270        pub fn float(f: f64) -> Self {
271            Value(Narrow::float(f))
272        }
273        #[inline]
274        pub fn bool(b: bool) -> Self {
275            Value(Narrow::bool(b))
276        }
277        #[inline]
278        pub fn nothing() -> Self {
279            Value(Narrow::nothing())
280        }
281        /// Whether this is the default/absent value — a register's pristine initial state. A write
282        /// that overwrites `Nothing` destroys no information (the default is known), so it costs zero
283        /// Landauer bits (see `HistoryTape::landauer_bytes`).
284        #[inline]
285        pub fn is_nothing(&self) -> bool {
286            matches!(&*self.as_runtime(), RuntimeValue::Nothing)
287        }
288
289        #[inline]
290        pub fn from_runtime(rv: RuntimeValue) -> Self {
291            Value(Narrow::from_runtime(rv))
292        }
293        #[inline]
294        pub fn into_runtime(self) -> RuntimeValue {
295            self.0.into_runtime()
296        }
297
298        /// Borrow as a `RuntimeValue`. A heap value borrows the boxed pointee
299        /// directly (zero copy); an inline scalar materialises a fresh
300        /// `RuntimeValue` the [`RuntimeRef`] owns. Both deref to `&RuntimeValue`.
301        #[inline]
302        pub fn as_runtime(&self) -> RuntimeRef<'_> {
303            match self.0.as_heap() {
304                Some(rv) => RuntimeRef(RuntimeRefInner::Borrowed(rv)),
305                None => RuntimeRef(RuntimeRefInner::Owned(self.0.to_runtime())),
306            }
307        }
308
309        /// Borrow the boxed `RuntimeValue` DIRECTLY (lifetime tied to `&self`)
310        /// for the heap arms; `None` for an inline scalar (which is never a List,
311        /// Map, Struct, or Text — the only shapes the borrow-holding `machine.rs`
312        /// sites destructure, so a `None` falls into their `else`/error arm
313        /// exactly as a non-matching variant would). This is the seam that keeps
314        /// an `Rc`/`RefMut` borrow alive across statements without a `RuntimeRef`
315        /// temporary in the way.
316        #[inline]
317        pub fn as_runtime_ref(&self) -> Option<&RuntimeValue> {
318            self.0.as_heap()
319        }
320
321        /// Mutably borrow as a `RuntimeValue`. Promotes an inline scalar to the
322        /// heap form first so a stable `&mut RuntimeValue` always exists (the VM
323        /// only mutates heap arms — Struct/Text — through this; a scalar
324        /// promotion is lossless and the mutation, if any, lands in the box).
325        #[inline]
326        pub fn as_runtime_mut(&mut self) -> &mut RuntimeValue {
327            self.0.make_heap_mut()
328        }
329
330        #[inline]
331        pub fn as_int(&self) -> Option<i64> {
332            self.0.as_int()
333        }
334        #[inline]
335        pub fn as_bool(&self) -> Option<bool> {
336            self.0.as_bool()
337        }
338        #[inline]
339        pub fn as_float(&self) -> Option<f64> {
340            self.0.as_float()
341        }
342        #[inline]
343        pub fn is_int(&self) -> bool {
344            self.0.as_int().is_some()
345        }
346
347        // ---- Arithmetic --------------------------------------------------------
348        // Inline Int×Int rides the nanbox fast path (bit-identical to the kernel,
349        // proven by nanbox's arith-parity test); every other shape (floats, large
350        // boxed ints, mixed operands) routes through `crate::semantics` exactly as
351        // the default representation does, via a single materialised round-trip.
352
353        #[inline]
354        pub fn add(&self, rhs: &Value) -> Result<Value, String> {
355            if let Some(n) = self.0.int_add(&rhs.0) {
356                return Ok(Value(n));
357            }
358            arith::add(self.0.to_runtime(), rhs.0.to_runtime()).map(Value::from_runtime)
359        }
360        #[inline]
361        pub fn sub(&self, rhs: &Value) -> Result<Value, String> {
362            if let Some(n) = self.0.int_sub(&rhs.0) {
363                return Ok(Value(n));
364            }
365            arith::subtract(self.0.to_runtime(), rhs.0.to_runtime()).map(Value::from_runtime)
366        }
367        #[inline]
368        pub fn mul(&self, rhs: &Value) -> Result<Value, String> {
369            if let Some(n) = self.0.int_mul(&rhs.0) {
370                return Ok(Value(n));
371            }
372            arith::multiply(self.0.to_runtime(), rhs.0.to_runtime()).map(Value::from_runtime)
373        }
374
375        // ---- Comparison --------------------------------------------------------
376
377        #[inline]
378        pub fn lt(&self, rhs: &Value) -> Result<Value, String> {
379            if let Some(b) = self.0.int_lt(&rhs.0) {
380                return Ok(Value::bool(b));
381            }
382            compare::compare(BinaryOpKind::Lt, &self.0.to_runtime(), &rhs.0.to_runtime())
383                .map(Value::from_runtime)
384        }
385        #[inline]
386        pub fn gt(&self, rhs: &Value) -> Result<Value, String> {
387            if let (Some(a), Some(b)) = (self.0.as_inline_int(), rhs.0.as_inline_int()) {
388                return Ok(Value::bool(a > b));
389            }
390            compare::compare(BinaryOpKind::Gt, &self.0.to_runtime(), &rhs.0.to_runtime())
391                .map(Value::from_runtime)
392        }
393        #[inline]
394        pub fn lte(&self, rhs: &Value) -> Result<Value, String> {
395            if let (Some(a), Some(b)) = (self.0.as_inline_int(), rhs.0.as_inline_int()) {
396                return Ok(Value::bool(a <= b));
397            }
398            compare::compare(
399                BinaryOpKind::LtEq,
400                &self.0.to_runtime(),
401                &rhs.0.to_runtime(),
402            )
403            .map(Value::from_runtime)
404        }
405        #[inline]
406        pub fn gte(&self, rhs: &Value) -> Result<Value, String> {
407            if let (Some(a), Some(b)) = (self.0.as_inline_int(), rhs.0.as_inline_int()) {
408                return Ok(Value::bool(a >= b));
409            }
410            compare::compare(
411                BinaryOpKind::GtEq,
412                &self.0.to_runtime(),
413                &rhs.0.to_runtime(),
414            )
415            .map(Value::from_runtime)
416        }
417        #[inline]
418        pub fn eq_op(&self, rhs: &Value) -> Result<Value, String> {
419            if let Some(b) = self.0.int_eq(&rhs.0) {
420                return Ok(Value::bool(b));
421            }
422            compare::equality(&self.0.to_runtime(), &rhs.0.to_runtime(), false)
423                .map(Value::from_runtime)
424        }
425        #[inline]
426        pub fn neq_op(&self, rhs: &Value) -> Result<Value, String> {
427            if let Some(b) = self.0.int_eq(&rhs.0) {
428                return Ok(Value::bool(!b));
429            }
430            compare::equality(&self.0.to_runtime(), &rhs.0.to_runtime(), true)
431                .map(Value::from_runtime)
432        }
433    }
434}
435
436pub use repr::Value;
437
438// ===========================================================================
439// Representation-independent API (delegates through the kernel)
440// ===========================================================================
441
442impl Value {
443    #[inline]
444    pub fn text(s: String) -> Self {
445        Value::from_runtime(RuntimeValue::Text(Rc::new(s)))
446    }
447
448    /// The truth of a value that decides a branch — [`RuntimeValue::decided_truth`].
449    #[inline]
450    pub fn decided_truth(&self) -> Result<bool, String> {
451        if let Some(b) = self.as_bool() {
452            return Ok(b);
453        }
454        if let Some(n) = self.as_int() {
455            return Ok(n != 0);
456        }
457        self.as_runtime().decided_truth()
458    }
459
460    #[inline]
461    pub fn is_truthy(&self) -> bool {
462        // Inline scalar fast paths avoid materialising; heap arms defer to the
463        // kernel's truthiness (which only the boxed types reach).
464        if let Some(b) = self.as_bool() {
465            return b;
466        }
467        if let Some(n) = self.as_int() {
468            return n != 0;
469        }
470        self.as_runtime().is_truthy()
471    }
472    #[inline]
473    pub fn to_display_string(&self) -> String {
474        self.as_runtime().to_display_string()
475    }
476    /// The value's type name. Borrows `&self` (Struct/Inductive names live in the
477    /// value; the scalar names are `'static` literals) — never a temporary, so it
478    /// is valid under the narrow representation where `as_runtime()` would
479    /// materialise an inline scalar into a short-lived `RuntimeValue`.
480    #[inline]
481    pub fn type_name(&self) -> &str {
482        // Inline scalars have `'static` names; the rest borrow the in-place
483        // (heap, under narrow) `RuntimeValue` directly.
484        if self.as_bool().is_some() {
485            return "Bool";
486        }
487        if self.as_int().is_some() {
488            return "Int";
489        }
490        if self.as_float().is_some() {
491            return "Float";
492        }
493        match self.as_runtime_ref() {
494            Some(rv) => rv.type_name(),
495            None => "Nothing",
496        }
497    }
498
499    /// Value equality for the `equals`/`==` operator and for set/list
500    /// membership (epsilon floats, structural inductives — the kernel's rules).
501    #[inline]
502    pub fn values_equal(&self, other: &Value) -> bool {
503        compare::values_equal(&self.as_runtime(), &other.as_runtime())
504    }
505
506    // ---- Collections (shared kernel) ------------------------------------------
507
508    pub fn list(items: Vec<Value>) -> Self {
509        let values: Vec<RuntimeValue> = items.into_iter().map(Value::into_runtime).collect();
510        Value::from_runtime(RuntimeValue::List(Rc::new(RefCell::new(
511            crate::interpreter::ListRepr::from_values(values),
512        ))))
513    }
514    /// Wrap a raw Int vector as a list value (the native tier's fresh
515    /// allocations re-box through here).
516    pub fn int_list(items: Vec<i64>) -> Self {
517        Value::from_runtime(RuntimeValue::List(Rc::new(RefCell::new(
518            crate::interpreter::ListRepr::Ints(items),
519        ))))
520    }
521
522    /// A `Seq of Word32` holding these masked words, in the representation the VM gives one: packed words once it
523    /// holds any (the VM retags its empty list on the first word pushed), an empty list of Ints before that.
524    pub fn word32_list(items: Vec<i64>) -> Self {
525        if items.is_empty() {
526            return Value::empty_list();
527        }
528        Value::from_runtime(RuntimeValue::List(Rc::new(RefCell::new(
529            crate::interpreter::ListRepr::Words32(items),
530        ))))
531    }
532
533    pub fn empty_list() -> Self {
534        Value::from_runtime(RuntimeValue::List(Rc::new(RefCell::new(
535            crate::interpreter::ListRepr::Ints(Vec::new()),
536        ))))
537    }
538    /// A fresh empty Int sequence whose statically-proven maximum length is
539    /// reserved once. The logical value remains the same as `empty_list`.
540    pub fn empty_list_with_capacity(capacity: usize) -> Self {
541        Value::from_runtime(RuntimeValue::List(Rc::new(RefCell::new(
542            crate::interpreter::ListRepr::Ints(Vec::with_capacity(capacity)),
543        ))))
544    }
545    /// A fresh empty half-width Int sequence (`ListRepr::IntsI32`), backing a
546    /// narrowing-proven `new Seq of Int` under `LOGOS_NARROW_VM`.
547    pub fn empty_list_i32() -> Self {
548        Value::from_runtime(RuntimeValue::List(Rc::new(RefCell::new(
549            crate::interpreter::ListRepr::IntsI32(Vec::new()),
550        ))))
551    }
552    pub fn empty_set() -> Self {
553        Value::from_runtime(RuntimeValue::Set(Rc::new(RefCell::new(Vec::new()))))
554    }
555    pub fn empty_map() -> Self {
556        Value::from_runtime(RuntimeValue::Map(Rc::new(RefCell::new(
557            crate::interpreter::MapStorage::default(),
558        ))))
559    }
560    /// A fresh empty map with storage reserved for a runtime capacity hint.
561    /// A hint must never make an otherwise-valid program fail, so allocation
562    /// refusal degrades to the ordinary growable empty representation.
563    pub fn empty_map_with_capacity(capacity: usize) -> Self {
564        let mut map = crate::interpreter::MapStorage::default();
565        let _ = map.try_reserve(capacity);
566        Value::from_runtime(RuntimeValue::Map(Rc::new(RefCell::new(map))))
567    }
568    pub fn int_range(lo: i64, hi: i64) -> Self {
569        Value::from_runtime(RuntimeValue::List(Rc::new(RefCell::new(
570            crate::interpreter::ListRepr::Ints((lo..=hi).collect()),
571        ))))
572    }
573
574    pub fn list_push(&self, value: Value) -> Result<(), String> {
575        collections::list_push(&self.as_runtime(), value.into_runtime())
576    }
577
578    pub fn len(&self) -> Result<i64, String> {
579        match collections::length_of(&self.as_runtime())? {
580            RuntimeValue::Int(n) => Ok(n),
581            _ => unreachable!("length_of always returns Int"),
582        }
583    }
584
585    pub fn index_get(&self, idx: &Value) -> Result<Value, String> {
586        collections::index_get(&self.as_runtime(), &idx.as_runtime()).map(Value::from_runtime)
587    }
588
589    pub fn set_add(&self, value: Value) -> Result<(), String> {
590        collections::set_add(&self.as_runtime(), value.into_runtime())
591    }
592
593    pub fn remove_from(&self, value: &Value) -> Result<(), String> {
594        collections::remove_from(&self.as_runtime(), &value.as_runtime())
595    }
596
597    pub fn index_set(&self, idx: &Value, value: Value) -> Result<(), String> {
598        collections::index_set(&self.as_runtime(), &idx.as_runtime(), value.into_runtime())
599    }
600
601    pub fn contains(&self, value: &Value) -> Result<bool, String> {
602        match collections::contains(&self.as_runtime(), &value.as_runtime())? {
603            RuntimeValue::Bool(b) => Ok(b),
604            _ => unreachable!("contains always returns Bool"),
605        }
606    }
607
608    // ---- General arithmetic (always through the kernel; no inline fast path) ---
609
610    pub fn div(&self, rhs: &Value) -> Result<Value, String> {
611        arith::divide(self.runtime_owned(), rhs.runtime_owned()).map(Value::from_runtime)
612    }
613
614    /// EXACT division (`Op::ExactDiv`) — the type-directed sibling of [`Value::div`]:
615    /// `7 / 2 → 7/2` (a Rational), never the floored `3`. Routes through the shared
616    /// kernel exactly like `div`, so the VM stays bit-identical to the tree-walker.
617    pub fn exact_div(&self, rhs: &Value) -> Result<Value, String> {
618        arith::exact_divide(self.runtime_owned(), rhs.runtime_owned()).map(Value::from_runtime)
619    }
620
621    /// FLOOR division (`Op::FloorDiv`, `a // b`) — the quotient rounded toward negative
622    /// infinity (`-7 // 2 → -4`), distinct from the truncating [`Value::div`]. Routes
623    /// through the shared kernel, so the VM stays bit-identical to the tree-walker.
624    pub fn floor_div(&self, rhs: &Value) -> Result<Value, String> {
625        arith::floor_divide(self.runtime_owned(), rhs.runtime_owned()).map(Value::from_runtime)
626    }
627
628    pub fn modulo(&self, rhs: &Value) -> Result<Value, String> {
629        arith::modulo(self.runtime_owned(), rhs.runtime_owned()).map(Value::from_runtime)
630    }
631
632    pub fn concat(&self, rhs: &Value) -> Result<Value, String> {
633        arith::concat(self.runtime_owned(), rhs.runtime_owned()).map(Value::from_runtime)
634    }
635
636    /// `a followed by b` — merge two sequences into one (reuses the tree-walker semantics).
637    pub fn seq_concat(&self, rhs: &Value) -> Result<Value, String> {
638        arith::seq_concat(self.runtime_owned(), rhs.runtime_owned()).map(Value::from_runtime)
639    }
640
641    pub fn pow(&self, rhs: &Value) -> Result<Value, String> {
642        arith::binary_op(BinaryOpKind::Pow, self.runtime_owned(), rhs.runtime_owned())
643            .map(Value::from_runtime)
644    }
645
646    pub fn bitxor(&self, rhs: &Value) -> Result<Value, String> {
647        arith::binary_op(
648            BinaryOpKind::BitXor,
649            self.runtime_owned(),
650            rhs.runtime_owned(),
651        )
652        .map(Value::from_runtime)
653    }
654
655    pub fn bitand(&self, rhs: &Value) -> Result<Value, String> {
656        arith::binary_op(
657            BinaryOpKind::BitAnd,
658            self.runtime_owned(),
659            rhs.runtime_owned(),
660        )
661        .map(Value::from_runtime)
662    }
663
664    pub fn bitor(&self, rhs: &Value) -> Result<Value, String> {
665        arith::binary_op(
666            BinaryOpKind::BitOr,
667            self.runtime_owned(),
668            rhs.runtime_owned(),
669        )
670        .map(Value::from_runtime)
671    }
672
673    pub fn shl(&self, rhs: &Value) -> Result<Value, String> {
674        arith::binary_op(BinaryOpKind::Shl, self.runtime_owned(), rhs.runtime_owned())
675            .map(Value::from_runtime)
676    }
677
678    pub fn shr(&self, rhs: &Value) -> Result<Value, String> {
679        arith::binary_op(BinaryOpKind::Shr, self.runtime_owned(), rhs.runtime_owned())
680            .map(Value::from_runtime)
681    }
682
683    /// `not x` — logical for Bool, bitwise for Int, error otherwise.
684    pub fn not_op(&self) -> Result<Value, String> {
685        arith::not_value(self.runtime_owned()).map(Value::from_runtime)
686    }
687
688    /// Materialise an owned `RuntimeValue` (a clone in the default repr; a
689    /// decode in the narrow repr). The kernel's `arith`/`binary_op` entry points
690    /// take owned operands, so the general (non-inlined) ops funnel through here.
691    #[inline]
692    fn runtime_owned(&self) -> RuntimeValue {
693        self.as_runtime().clone()
694    }
695}
696
697#[cfg(test)]
698#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/vm/value/fast_path_kernel_differential.rs"]
699mod fast_path_kernel_differential;
700
701#[cfg(test)]
702#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/vm/value/value_comparison_tests.rs"]
703mod value_comparison_tests;