Skip to main content

logicaffeine_data/
types.rs

1//! Core runtime type definitions.
2//!
3//! This module defines the primitive types used by LOGOS programs at runtime.
4//! These are type aliases that map LOGOS types to their Rust equivalents.
5//!
6//! ## Type Mappings
7//!
8//! | LOGOS Type | Rust Type | Description |
9//! |------------|-----------|-------------|
10//! | `Nat` | `u64` | Natural numbers (non-negative) |
11//! | `Int` | `i64` | Signed integers |
12//! | `Real` | `f64` | Floating-point numbers |
13//! | `Text` | `String` | UTF-8 strings |
14//! | `Bool` | `bool` | Boolean values |
15//! | `Unit` | `()` | The unit type |
16//! | `Char` | `char` | Unicode scalar values |
17//! | `Byte` | `u8` | Raw bytes |
18//! | `Seq<T>` | `LogosSeq<T>` | Ordered sequences (reference semantics) |
19//! | `Set<T>` | `HashSet<T>` | Unordered unique elements |
20//! | `Map<K,V>` | `LogosMap<K,V>` | Key-value mappings (reference semantics) |
21
22use std::cell::RefCell;
23use std::hash::Hash;
24use std::rc::Rc;
25
26/// Non-negative integers. Maps to Peano `Nat` in the kernel.
27pub type Nat = u64;
28/// Signed integers.
29pub type Int = i64;
30/// IEEE 754 floating-point numbers.
31pub type Real = f64;
32/// UTF-8 encoded text strings.
33pub type Text = String;
34/// Boolean truth values.
35pub type Bool = bool;
36/// The unit type (single value).
37pub type Unit = ();
38/// Unicode scalar values.
39pub type Char = char;
40/// Raw bytes (0-255).
41pub type Byte = u8;
42
43/// Ordered sequence with reference semantics.
44///
45/// `LogosSeq<T>` wraps `Rc<RefCell<Vec<T>>>` to provide shared mutable access.
46/// Cloning a `LogosSeq` produces a shallow copy (shared reference), not a deep copy.
47/// Use `.deep_clone()` for an independent copy (LOGOS `copy of`).
48#[derive(Debug)]
49pub struct LogosSeq<T>(pub Rc<RefCell<Vec<T>>>);
50
51impl<T> LogosSeq<T> {
52    pub fn new() -> Self {
53        Self(Rc::new(RefCell::new(Vec::new())))
54    }
55
56    pub fn from_vec(v: Vec<T>) -> Self {
57        Self(Rc::new(RefCell::new(v)))
58    }
59
60    pub fn with_capacity(cap: usize) -> Self {
61        Self(Rc::new(RefCell::new(Vec::with_capacity(cap))))
62    }
63
64    pub fn push(&self, value: T) {
65        self.0.borrow_mut().push(value);
66    }
67
68    pub fn pop(&self) -> Option<T> {
69        self.0.borrow_mut().pop()
70    }
71
72    pub fn len(&self) -> usize {
73        self.0.borrow().len()
74    }
75
76    pub fn is_empty(&self) -> bool {
77        self.0.borrow().is_empty()
78    }
79
80    pub fn remove(&self, index: usize) -> T {
81        self.0.borrow_mut().remove(index)
82    }
83
84    pub fn borrow(&self) -> std::cell::Ref<'_, Vec<T>> {
85        self.0.borrow()
86    }
87
88    pub fn borrow_mut(&self) -> std::cell::RefMut<'_, Vec<T>> {
89        self.0.borrow_mut()
90    }
91}
92
93/// A FILL-SLOT copy: collections copy DEEP, so every slot of a fill
94/// (`n copies of x`, `[x] * n`) is an independent row — never `n` aliases of
95/// one row (the classic `[[0]] * 3` footgun is designed out). Scalars copy
96/// plain. Mirrors the tree-walker's recursive `RuntimeValue::deep_clone`.
97pub trait FillClone {
98    fn fill_clone(&self) -> Self;
99}
100
101macro_rules! fill_by_clone {
102    ($($t:ty),* $(,)?) => {
103        $(impl FillClone for $t {
104            #[inline]
105            fn fill_clone(&self) -> Self {
106                self.clone()
107            }
108        })*
109    };
110}
111
112fill_by_clone!(i8, i16, i32, i64, i128, u8, u16, u32, u64, usize, f32, f64, bool, char, String);
113
114impl<T: FillClone> FillClone for LogosSeq<T> {
115    fn fill_clone(&self) -> Self {
116        Self(Rc::new(RefCell::new(
117            self.0.borrow().iter().map(|e| e.fill_clone()).collect(),
118        )))
119    }
120}
121
122impl<K: Clone + Eq + Hash, V: FillClone> FillClone for LogosMap<K, V> {
123    fn fill_clone(&self) -> Self {
124        Self(Rc::new(RefCell::new(
125            self.0
126                .borrow()
127                .iter()
128                .map(|(k, v)| (k.clone(), v.fill_clone()))
129                .collect(),
130        )))
131    }
132}
133
134impl<T: Clone> LogosSeq<T> {
135    pub fn deep_clone(&self) -> Self {
136        Self(Rc::new(RefCell::new(self.0.borrow().clone())))
137    }
138
139    pub fn to_vec(&self) -> Vec<T> {
140        self.0.borrow().clone()
141    }
142
143    pub fn extend_from_slice(&self, other: &[T]) {
144        self.0.borrow_mut().extend_from_slice(other);
145    }
146
147    pub fn iter(&self) -> LogosSeqIter<T> {
148        LogosSeqIter {
149            data: self.to_vec(),
150            pos: 0,
151        }
152    }
153}
154
155pub struct LogosSeqIter<T> {
156    data: Vec<T>,
157    pos: usize,
158}
159
160impl<T: Clone> Iterator for LogosSeqIter<T> {
161    type Item = T;
162    fn next(&mut self) -> Option<T> {
163        if self.pos < self.data.len() {
164            let val = self.data[self.pos].clone();
165            self.pos += 1;
166            Some(val)
167        } else {
168            None
169        }
170    }
171}
172
173impl<T: Ord> LogosSeq<T> {
174    pub fn sort(&self) {
175        self.0.borrow_mut().sort();
176    }
177}
178
179impl<T> LogosSeq<T> {
180    pub fn reverse(&self) {
181        self.0.borrow_mut().reverse();
182    }
183}
184
185/// Whether Mutable Value Semantics is enabled for compiled (AOT) programs. The
186/// AOT binary is a separate process from the interpreter, so it reads the
187/// `LOGOS_VALUE_SEMANTICS` env var itself (inherited from the parent process),
188/// cached once. When on, collection `Clone` deep-copies (value semantics); when
189/// off it shares the `Rc` (the historical reference semantics — unchanged).
190pub fn value_semantics_enabled() -> bool {
191    use std::sync::OnceLock;
192    static ON: OnceLock<bool> = OnceLock::new();
193    // Value semantics is the DEFAULT; `LOGOS_VALUE_SEMANTICS=0` restores the
194    // historical reference semantics. Matches the compile-crate gate.
195    *ON.get_or_init(|| std::env::var("LOGOS_VALUE_SEMANTICS").as_deref() != Ok("0"))
196}
197
198impl<T: Clone> Clone for LogosSeq<T> {
199    fn clone(&self) -> Self {
200        // Both semantics now SHARE the allocation on `Clone` — a cheap `Rc`
201        // bump. Under value semantics, isolation is preserved LAZILY by `cow()`
202        // (below), which codegen/the engines call before an in-place mutation:
203        // clone-on-write instead of the historical clone-on-copy. Reference
204        // semantics never calls `cow()`, so the share is permanent (its
205        // historical behavior). This is the "best of all worlds" model: aliases
206        // share until one of them diverges via mutation.
207        Self(Rc::clone(&self.0))
208    }
209}
210
211impl<T: Clone> LogosSeq<T> {
212    /// Copy-on-write: make this handle uniquely own its buffer before an
213    /// in-place mutation, so the mutation cannot leak into a value-semantics
214    /// sibling that shares the same allocation. A no-op when already unique
215    /// (`strong_count == 1`), so the common case pays only a count read.
216    /// Mirrors the tree-walker's `ensure_collection_owned` and the VM's
217    /// `ensure_reg_owned`.
218    #[inline]
219    pub fn cow(&mut self) {
220        if Rc::strong_count(&self.0) > 1 {
221            // Bind the clone first so the `borrow()` temporary is released before the reassignment
222            // (edition-2024 extends the temporary's lifetime to the end of the statement otherwise).
223            let cloned = self.0.borrow().clone();
224            self.0 = Rc::new(RefCell::new(cloned));
225        }
226    }
227}
228
229/// A no-op `cow()` for an OWNED `Vec` — a scalarized (non-shared) sequence never aliases, so the
230/// copy-on-write barrier the codegen emits before an in-place mutation is unnecessary. This keeps the
231/// codegen's `cow()` emission TOTAL: whether a `Seq` lowered to a shared `LogosSeq` (real copy-on-write)
232/// or a scalarized owned `Vec<T>` (a proven-non-aliased buffer — e.g. a `Seq of Real` → `Vec<f64>`),
233/// `<seq>.cow()` always type-checks. Without this, a scalarized float/int vector whose `variable_types`
234/// entry still read `LogosSeq` made the emitter write `vec.cow()` on a `Vec`, which has no such method
235/// (`error[E0599]: no method named `cow``), breaking every float-sequence program on the compiled tiers.
236/// `LogosSeq`'s inherent `cow()` shadows this trait method, so shared handles keep the real barrier.
237pub trait VecCowNoop {
238    #[inline]
239    fn cow(&mut self) {}
240}
241impl<T> VecCowNoop for Vec<T> {}
242
243impl<T: Clone> LogosSeq<LogosSeq<T>> {
244    /// Value-semantic nested write `Set item i of item k of grid to v` (the through-write fast path):
245    /// copy-on-write the ROW `k` names (deep-copy only if its buffer is shared with a value-semantics
246    /// sibling), then set the item `i` names in that row in place. Both are 1-based LOGOS indices under
247    /// [`crate::resolve_logos_index`], the row's first. The compiled mirror of the parser's
248    /// clone-modify-writeback place desugar, but O(1) when the row is uniquely owned — no full-row clone.
249    /// The caller `cow()`s the OUTER handle first (as the codegen emits), so a shared `grid` is never
250    /// mutated in place.
251    #[inline]
252    pub fn set_nested(&self, k: i64, i: i64, v: T) {
253        use crate::LogosItems;
254        let mut outer = self.borrow_mut();
255        let row = outer.logos_item_mut(k);
256        row.cow();
257        *row.borrow_mut().logos_item_mut(i) = v;
258    }
259}
260
261impl<T> Default for LogosSeq<T> {
262    fn default() -> Self {
263        Self::new()
264    }
265}
266
267impl<T: PartialEq> PartialEq for LogosSeq<T> {
268    fn eq(&self, other: &Self) -> bool {
269        *self.0.borrow() == *other.0.borrow()
270    }
271}
272
273impl<T: std::fmt::Display> std::fmt::Display for LogosSeq<T> {
274    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
275        let inner = self.0.borrow();
276        write!(f, "[")?;
277        for (i, item) in inner.iter().enumerate() {
278            if i > 0 {
279                write!(f, ", ")?;
280            }
281            write!(f, "{}", item)?;
282        }
283        write!(f, "]")
284    }
285}
286
287impl<T> From<Vec<T>> for LogosSeq<T> {
288    fn from(v: Vec<T>) -> Self {
289        Self::from_vec(v)
290    }
291}
292
293impl<T: serde::Serialize> serde::Serialize for LogosSeq<T> {
294    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
295        self.0.borrow().serialize(serializer)
296    }
297}
298
299impl<'de, T: serde::Deserialize<'de>> serde::Deserialize<'de> for LogosSeq<T> {
300    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
301        let vec = Vec::<T>::deserialize(deserializer)?;
302        Ok(Self::from_vec(vec))
303    }
304}
305
306impl<T: PartialEq> LogosContains<T> for LogosSeq<T> {
307    #[inline(always)]
308    fn logos_contains(&self, value: &T) -> bool {
309        self.0.borrow().contains(value)
310    }
311}
312
313impl<T: Clone> IntoIterator for LogosSeq<T> {
314    type Item = T;
315    type IntoIter = std::vec::IntoIter<T>;
316
317    fn into_iter(self) -> Self::IntoIter {
318        self.to_vec().into_iter()
319    }
320}
321
322/// The insertion-ordered map behind every LOGOS `Map`: `IndexMap` for the
323/// order contract (iteration, display, and serialization follow insertion,
324/// like a Python dict), Fx hashing for speed on the small keys LOGOS programs
325/// use (no DoS-resistance requirement).
326pub type FxIndexMap<K, V> =
327    indexmap::IndexMap<K, V, std::hash::BuildHasherDefault<rustc_hash::FxHasher>>;
328
329/// Key-value mapping with reference semantics.
330///
331/// `LogosMap<K, V>` wraps `Rc<RefCell<FxIndexMap<K, V>>>` to provide shared mutable access.
332/// Cloning a `LogosMap` produces a shallow copy (shared reference), not a deep copy.
333/// Use `.deep_clone()` for an independent copy (LOGOS `copy of`).
334#[derive(Debug)]
335pub struct LogosMap<K, V>(pub Rc<RefCell<FxIndexMap<K, V>>>);
336
337impl<K: Eq + Hash, V> LogosMap<K, V> {
338    pub fn new() -> Self {
339        Self(Rc::new(RefCell::new(FxIndexMap::default())))
340    }
341
342    pub fn with_capacity(cap: usize) -> Self {
343        Self(Rc::new(RefCell::new(FxIndexMap::with_capacity_and_hasher(
344            cap,
345            Default::default(),
346        ))))
347    }
348
349    pub fn from_map(m: FxIndexMap<K, V>) -> Self {
350        Self(Rc::new(RefCell::new(m)))
351    }
352
353    pub fn insert(&self, key: K, value: V) -> Option<V> {
354        self.0.borrow_mut().insert(key, value)
355    }
356
357    /// Removes a key while PRESERVING the insertion order of the remaining
358    /// entries (`shift_remove` — Python `del` semantics, O(n)).
359    pub fn remove(&self, key: &K) -> Option<V> {
360        self.0.borrow_mut().shift_remove(key)
361    }
362
363    pub fn len(&self) -> usize {
364        self.0.borrow().len()
365    }
366
367    pub fn is_empty(&self) -> bool {
368        self.0.borrow().is_empty()
369    }
370
371    pub fn contains_key(&self, key: &K) -> bool {
372        self.0.borrow().contains_key(key)
373    }
374
375    pub fn borrow(&self) -> std::cell::Ref<'_, FxIndexMap<K, V>> {
376        self.0.borrow()
377    }
378
379    pub fn borrow_mut(&self) -> std::cell::RefMut<'_, FxIndexMap<K, V>> {
380        self.0.borrow_mut()
381    }
382}
383
384impl<K: Eq + Hash + Clone, V: Clone> LogosMap<K, V> {
385    pub fn deep_clone(&self) -> Self {
386        Self(Rc::new(RefCell::new(self.0.borrow().clone())))
387    }
388
389    pub fn get(&self, key: &K) -> Option<V> {
390        self.0.borrow().get(key).cloned()
391    }
392
393    pub fn values(&self) -> Vec<V> {
394        self.0.borrow().values().cloned().collect()
395    }
396
397    pub fn keys(&self) -> Vec<K> {
398        self.0.borrow().keys().cloned().collect()
399    }
400}
401
402impl<K: Clone, V: Clone> Clone for LogosMap<K, V> {
403    fn clone(&self) -> Self {
404        // Share on `Clone` under both semantics; value-semantics isolation is
405        // preserved lazily by `cow()` before an in-place mutation. See
406        // `LogosSeq::clone`/`cow` for the full rationale.
407        Self(Rc::clone(&self.0))
408    }
409}
410
411impl<K: Clone, V: Clone> LogosMap<K, V> {
412    /// Copy-on-write: make this handle uniquely own its map before an in-place
413    /// mutation. See [`LogosSeq::cow`].
414    #[inline]
415    pub fn cow(&mut self) {
416        if Rc::strong_count(&self.0) > 1 {
417            // Bind the clone first so the `borrow()` temporary is released before the reassignment
418            // (edition-2024 extends the temporary's lifetime to the end of the statement otherwise).
419            let cloned = self.0.borrow().clone();
420            self.0 = Rc::new(RefCell::new(cloned));
421        }
422    }
423}
424
425impl<K: Eq + Hash, V> Default for LogosMap<K, V> {
426    fn default() -> Self {
427        Self::new()
428    }
429}
430
431impl<K: PartialEq + Eq + Hash, V: PartialEq> PartialEq for LogosMap<K, V> {
432    fn eq(&self, other: &Self) -> bool {
433        *self.0.borrow() == *other.0.borrow()
434    }
435}
436
437impl<K: std::fmt::Display + Eq + Hash, V: std::fmt::Display> std::fmt::Display for LogosMap<K, V> {
438    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
439        let inner = self.0.borrow();
440        write!(f, "{{")?;
441        for (i, (k, v)) in inner.iter().enumerate() {
442            if i > 0 {
443                write!(f, ", ")?;
444            }
445            write!(f, "{}: {}", k, v)?;
446        }
447        write!(f, "}}")
448    }
449}
450
451impl<K: serde::Serialize + Eq + Hash, V: serde::Serialize> serde::Serialize for LogosMap<K, V> {
452    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
453        self.0.borrow().serialize(serializer)
454    }
455}
456
457impl<'de, K: serde::Deserialize<'de> + Eq + Hash, V: serde::Deserialize<'de>>
458    serde::Deserialize<'de> for LogosMap<K, V>
459{
460    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
461        let map = FxIndexMap::<K, V>::deserialize(deserializer)?;
462        Ok(Self::from_map(map))
463    }
464}
465
466/// Iterating a map yields `(key, value)` pairs in INSERTION order — the same
467/// order the tree-walker and VM iterate. Snapshot semantics (like
468/// [`LogosSeq`]'s `IntoIterator`): the entries are collected up front, so
469/// mutating the map inside the loop never invalidates the iteration.
470impl<K: Clone, V: Clone> IntoIterator for LogosMap<K, V> {
471    type Item = (K, V);
472    type IntoIter = std::vec::IntoIter<(K, V)>;
473
474    fn into_iter(self) -> Self::IntoIter {
475        let entries: Vec<(K, V)> = self
476            .0
477            .borrow()
478            .iter()
479            .map(|(k, v)| (k.clone(), v.clone()))
480            .collect();
481        entries.into_iter()
482    }
483}
484
485impl<K: Eq + Hash, V> LogosContains<K> for LogosMap<K, V> {
486    #[inline(always)]
487    fn logos_contains(&self, key: &K) -> bool {
488        self.0.borrow().contains_key(key)
489    }
490}
491
492/// The most an open-addressed Int table ([`LogosI64Map`], [`LogosI64Set`], [`LogosI32Map`], [`LogosI32Set`]) is filled:
493/// half. A linear-probing miss walks (1 + 1/(1 - α)²) / 2 slots on average, 1.6 at a load of 0.3 and 3.6 at 0.6, and
494/// in a table larger than the cache every slot walked is a cache miss: two_sum's set spent a fifth fewer cycles at half
495/// full than at three-quarters.
496const INT_TABLE_MAX_LOAD: (usize, usize) = (1, 2);
497
498/// The power-of-two slot count (at least 8) that holds `cap` entries within [`INT_TABLE_MAX_LOAD`].
499fn int_table_slots(cap: usize) -> usize {
500    let (num, den) = INT_TABLE_MAX_LOAD;
501    (cap.saturating_mul(den) / num + 1).next_power_of_two().max(8)
502}
503
504/// The slot of an Int key in an open-addressed table of `2^(64 - shift)` slots: Fibonacci hashing, the TOP bits of the
505/// key times `2^64/φ` (Knuth). The top bits are the ones the multiply mixes from every bit of the key, so keys that
506/// differ only high (multiples of `2^32`) spread as sequential ones do, in two instructions, the table C hand-rolls.
507#[inline(always)]
508fn fib_slot(key: u64, shift: u32) -> usize {
509    (key.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> shift) as usize
510}
511
512/// Whether a table of `slots` holding `len` probed entries must grow before it takes another.
513fn int_table_full(len: usize, slots: usize) -> bool {
514    let (num, den) = INT_TABLE_MAX_LOAD;
515    (len + 1) * den > slots * num
516}
517
518/// A specialized open-addressing `i64 → i64` map with VALUE semantics and no
519/// `Rc<RefCell>` indirection.
520///
521/// The code generator emits this in place of `LogosMap<i64, i64>` for
522/// non-aliased local `Map of Int to Int` variables (see `codegen::i64_map`):
523/// linear probing over two flat `Vec`s with `Copy` keys and values — no
524/// per-operation `RefCell` borrow, no key/value clone, `&mut self` mutation
525/// that LLVM can keep in registers. This is the C open-addressing shape, and it
526/// is only selected where the alias analysis proves the map never escapes or is
527/// shared, so the loss of reference semantics is invisible to the program.
528///
529/// `0` is the empty-slot sentinel; the real key `0` is tracked separately so the
530/// map is correct for the entire `i64` key space. The sentinel is `0`, not
531/// `i64::MIN`, so the probe table allocates via `vec![[0, 0]; slots]` — the bit
532/// pattern Rust's `IsZero` specialization lowers to `alloc_zeroed` (calloc):
533/// lazily-zeroed pages, no eager memset/page-fault storm up front.
534#[derive(Debug, Clone)]
535pub struct LogosI64Map {
536    /// AoS probe table of `[key, value]` slots; `key == EMPTY` marks empty.
537    /// Interleaving key and value keeps both on the SAME cache line, so a lookup
538    /// hit reads ONE line, not two (the SoA tax) — matching C's `struct Entry`.
539    /// `[i64; 2]` (not a tuple) so the zero fill hits `alloc_zeroed`.
540    entries: Vec<[i64; 2]>,
541    mask: usize,
542    /// `64 - log2(slots)`: a key's slot is the top bits of its Fibonacci product ([`fib_slot`]).
543    shift: u32,
544    len: usize,
545    has_zero_key: bool,
546    zero_key_val: i64,
547}
548
549impl LogosI64Map {
550    const EMPTY: i64 = 0;
551
552    pub fn new() -> Self {
553        Self {
554            entries: Vec::new(),
555            mask: 0,
556            shift: 64,
557            len: 0,
558            has_zero_key: false,
559            zero_key_val: 0,
560        }
561    }
562
563    pub fn with_capacity(cap: usize) -> Self {
564        let mut m = Self::new();
565        if cap > 0 {
566            // Within the most a table is filled, rounded up to a power of two
567            // (so the probe mask is `slots - 1`), with a floor of 8 slots.
568            let slots = int_table_slots(cap);
569            // `[Self::EMPTY, 0] == [0, 0]` → `alloc_zeroed` (calloc): lazily
570            // zeroed, no eager memset of the whole table.
571            m.entries = vec![[Self::EMPTY, 0]; slots];
572            m.mask = slots - 1;
573            m.shift = 64 - slots.trailing_zeros();
574        }
575        m
576    }
577
578    /// Live entries stored in the probe table (excludes the zero key, which
579    /// lives outside the table).
580    #[inline]
581    fn table_len(&self) -> usize {
582        self.len - self.has_zero_key as usize
583    }
584
585    /// See [`LogosI64Set::assume_table_invariant`]: `entries.len() == mask + 1`
586    /// once `mask != 0`, so masked probe indices need no bounds check.
587    #[inline(always)]
588    fn assume_table_invariant(&self) {
589        unsafe {
590            std::hint::assert_unchecked(self.mask + 1 == self.entries.len());
591        }
592    }
593
594    #[inline]
595    fn slot(&self, key: i64) -> usize {
596        fib_slot(key as u64, self.shift)
597    }
598
599    #[inline]
600    pub fn insert(&mut self, key: i64, value: i64) {
601        if key == Self::EMPTY {
602            if !self.has_zero_key {
603                self.has_zero_key = true;
604                self.len += 1;
605            }
606            self.zero_key_val = value;
607            return;
608        }
609        if self.mask == 0 || int_table_full(self.table_len(), self.mask + 1) {
610            self.grow();
611        }
612        self.assume_table_invariant();
613        let mut i = self.slot(key);
614        loop {
615            let k = self.entries[i][0];
616            if k == Self::EMPTY {
617                self.entries[i] = [key, value];
618                self.len += 1;
619                return;
620            }
621            if k == key {
622                self.entries[i][1] = value;
623                return;
624            }
625            i = (i + 1) & self.mask;
626        }
627    }
628
629    #[cold]
630    #[inline(never)]
631    fn grow(&mut self) {
632        let new_slots = if self.mask == 0 {
633            8
634        } else {
635            (self.mask + 1) * 2
636        };
637        let old = std::mem::replace(&mut self.entries, vec![[Self::EMPTY, 0]; new_slots]);
638        self.mask = new_slots - 1;
639        self.shift = 64 - new_slots.trailing_zeros();
640        self.assume_table_invariant();
641        for &[k, v] in old.iter() {
642            if k != Self::EMPTY {
643                let mut i = self.slot(k);
644                while self.entries[i][0] != Self::EMPTY {
645                    i = (i + 1) & self.mask;
646                }
647                self.entries[i] = [k, v];
648            }
649        }
650    }
651
652    #[inline]
653    pub fn get(&self, key: &i64) -> Option<i64> {
654        let key = *key;
655        if key == Self::EMPTY {
656            return if self.has_zero_key {
657                Some(self.zero_key_val)
658            } else {
659                None
660            };
661        }
662        if self.mask == 0 {
663            return None;
664        }
665        self.assume_table_invariant();
666        let mut i = self.slot(key);
667        loop {
668            let [k, v] = self.entries[i];
669            if k == key {
670                return Some(v);
671            }
672            if k == Self::EMPTY {
673                return None;
674            }
675            i = (i + 1) & self.mask;
676        }
677    }
678
679    #[inline]
680    pub fn contains_key(&self, key: &i64) -> bool {
681        self.get(key).is_some()
682    }
683
684    pub fn len(&self) -> usize {
685        self.len
686    }
687
688    pub fn is_empty(&self) -> bool {
689        self.len == 0
690    }
691}
692
693impl Default for LogosI64Map {
694    fn default() -> Self {
695        Self::new()
696    }
697}
698
699impl LogosContains<i64> for LogosI64Map {
700    #[inline(always)]
701    fn logos_contains(&self, key: &i64) -> bool {
702        self.get(key).is_some()
703    }
704}
705
706/// A `Seq of Bool` held one bit per item: the representation a local sequence of truth values takes when every use
707/// of it is an item read, an item store, a push or its length. A table of `n` flags takes `n / 8` bytes where a
708/// `Vec<bool>` takes `n`, so a sieve over 10^8 numbers fits in the cache it used to stream past.
709///
710/// Items are counted from 1 as in every sequence, through [`crate::resolve_logos_index`]: an index counted from the
711/// back reaches the same item, and one that names no item fails with the sentence every tier reports. The unchecked
712/// accessors take a 0-based offset the caller has proven below [`LogosBits::len`].
713#[derive(Debug, Clone, Default)]
714pub struct LogosBits {
715    /// Item `k` (0-based) is bit `k % 64` of word `k / 64`; bits past `len` are zero.
716    words: Vec<u64>,
717    len: usize,
718}
719
720impl LogosBits {
721    pub fn new() -> Self {
722        Self::default()
723    }
724
725    /// An empty sequence with room for `items` items before it grows.
726    pub fn with_capacity(items: usize) -> Self {
727        LogosBits {
728            words: Vec::with_capacity(items.div_ceil(64)),
729            len: 0,
730        }
731    }
732
733    /// `len` items, each `value`.
734    pub fn filled(len: usize, value: bool) -> Self {
735        let mut words = vec![if value { u64::MAX } else { 0 }; len.div_ceil(64)];
736        if value && len % 64 != 0 {
737            if let Some(last) = words.last_mut() {
738                *last = (1u64 << (len % 64)) - 1;
739            }
740        }
741        LogosBits { words, len }
742    }
743
744    #[inline(always)]
745    pub fn len(&self) -> usize {
746        self.len
747    }
748
749    #[inline(always)]
750    pub fn is_empty(&self) -> bool {
751        self.len == 0
752    }
753
754    #[inline]
755    pub fn push(&mut self, value: bool) {
756        if self.len % 64 == 0 {
757            self.words.push(0);
758        }
759        let at = self.len;
760        self.len += 1;
761        // SAFETY: `at` is below the new `len`, and its word exists.
762        unsafe { self.set_unchecked(at, value) }
763    }
764
765    /// The item `index` names (counted from 1, or from the back when negative).
766    #[inline]
767    pub fn item(&self, index: i64) -> bool {
768        let at = crate::resolve_logos_index(index, self.len);
769        // SAFETY: `resolve_logos_index` returns an offset below `len` or does not return.
770        unsafe { self.get_unchecked(at) }
771    }
772
773    /// Store `value` as the item `index` names.
774    #[inline]
775    pub fn set_item(&mut self, index: i64, value: bool) {
776        let at = crate::resolve_logos_index(index, self.len);
777        // SAFETY: as in `item`.
778        unsafe { self.set_unchecked(at, value) }
779    }
780
781    /// The item at 0-based `offset`.
782    ///
783    /// # Safety
784    /// `offset` is below [`LogosBits::len`].
785    #[inline(always)]
786    pub unsafe fn get_unchecked(&self, offset: usize) -> bool {
787        debug_assert!(offset < self.len);
788        (*self.words.get_unchecked(offset / 64) >> (offset % 64)) & 1 == 1
789    }
790
791    /// Store `value` at 0-based `offset`.
792    ///
793    /// # Safety
794    /// `offset` is below [`LogosBits::len`].
795    #[inline(always)]
796    pub unsafe fn set_unchecked(&mut self, offset: usize, value: bool) {
797        debug_assert!(offset < self.len);
798        let word = self.words.get_unchecked_mut(offset / 64);
799        let bit = 1u64 << (offset % 64);
800        *word = (*word & !bit) | ((value as u64) << (offset % 64));
801    }
802
803    /// Store `true` at 0-based `offset`: one `or` into its word.
804    ///
805    /// # Safety
806    /// `offset` is below [`LogosBits::len`].
807    #[inline(always)]
808    pub unsafe fn set_true_unchecked(&mut self, offset: usize) {
809        debug_assert!(offset < self.len);
810        *self.words.get_unchecked_mut(offset / 64) |= 1u64 << (offset % 64);
811    }
812
813    /// Store `value` at the `count` offsets `first`, `first + step`, `first + 2 * step`, ….
814    ///
815    /// A step of a word or more puts each offset in a word of its own, and a handful of offsets cost no more one at a
816    /// time; both store in place. Otherwise `Self::fill_stride_words` writes each word the progression crosses once,
817    /// out of line, so a loop that fills now and then keeps none of the walk's state in its own registers.
818    ///
819    /// # Safety
820    /// `step` is at least 1 and, when `count` is not 0, `first + (count - 1) * step` is below [`LogosBits::len`].
821    #[inline]
822    pub unsafe fn fill_stride_unchecked(&mut self, first: usize, count: usize, step: usize, value: bool) {
823        debug_assert!(step >= 1);
824        debug_assert!(count == 0 || first + (count - 1) * step < self.len);
825        if step >= 64 || count < 8 {
826            let mut at = first;
827            for _ in 0..count {
828                let word = self.words.get_unchecked_mut(at / 64);
829                let bit = 1u64 << (at % 64);
830                *word = if value { *word | bit } else { *word & !bit };
831                at += step;
832            }
833        } else {
834            self.fill_stride_words(first, count, step, value);
835        }
836    }
837
838    /// Store `value` at `first`, `first + step`, … up to `through`, and return how many steps past `first` that took:
839    /// a loop's stores from its counter's value on entry to its bound, the bound given as the offset it would store at.
840    /// Out of line, so the loop that calls it keeps no arithmetic of the progression in its own registers: what it
841    /// computes from its counter is the counter.
842    ///
843    /// # Safety
844    /// `step` is at least 1, `first <= through`, and `first + (through - first) / step * step` is below
845    /// [`LogosBits::len`].
846    #[inline(never)]
847    pub unsafe fn fill_stride_through_unchecked(
848        &mut self,
849        first: usize,
850        through: usize,
851        step: usize,
852        value: bool,
853    ) -> usize {
854        debug_assert!(step >= 1 && first <= through);
855        let more = (through - first) / step;
856        self.fill_stride_unchecked(first, more + 1, step, value);
857        more
858    }
859
860    /// [`Self::fill_stride_unchecked`] for a step shorter than a word: the offsets in one word are a fixed pattern,
861    /// the multiples of `step` below 64, shifted to where the progression enters the word, so each word is written
862    /// once. The progression enters the next word `64 % step` bits earlier in the pattern, wrapping by `step`.
863    ///
864    /// # Safety
865    /// As [`Self::fill_stride_unchecked`], with `1 <= step < 64` and `count >= 1`.
866    #[inline(never)]
867    unsafe fn fill_stride_words(&mut self, first: usize, count: usize, step: usize, value: bool) {
868        let last = first + (count - 1) * step;
869        let words = self.words.as_mut_ptr();
870        let store = |w: usize, mask: u64| {
871            let word = words.add(w);
872            *word = if value { *word | mask } else { *word & !mask };
873        };
874        let mut pattern = 0u64;
875        let mut k = 0;
876        while k < 64 {
877            pattern |= 1u64 << k;
878            k += step;
879        }
880        let back = 64 % step;
881        let (first_word, last_word) = (first / 64, last / 64);
882        let through_last = u64::MAX >> (63 - last % 64);
883        let mut phase = first % 64;
884        if first_word == last_word {
885            store(first_word, (pattern << phase) & through_last);
886            return;
887        }
888        store(first_word, pattern << phase);
889        phase = (phase + step - back) % step;
890        for w in first_word + 1..last_word {
891            store(w, pattern << phase);
892            phase = if phase >= back { phase - back } else { phase + step - back };
893        }
894        store(last_word, (pattern << phase) & through_last);
895    }
896
897    /// The items, first to last.
898    pub fn iter(&self) -> impl Iterator<Item = bool> + '_ {
899        // SAFETY: every offset below `len`.
900        (0..self.len).map(move |k| unsafe { self.get_unchecked(k) })
901    }
902}
903
904impl PartialEq for LogosBits {
905    fn eq(&self, other: &Self) -> bool {
906        self.len == other.len && self.words == other.words
907    }
908}
909
910impl Eq for LogosBits {}
911
912/// Open-addressing `i64` SET — the keys-only sibling of [`LogosI64Map`], emitted
913/// for a `Map of Int to Int` the alias analysis proves is used ONLY as a set
914/// (insert + contains; the value is never read — two_sum's `seen`). ONE flat
915/// `Vec<i64>` with linear probing and a `0` empty-slot sentinel (the real key
916/// `0` tracked separately for full key-space correctness). With no value array
917/// it has HALF the store traffic and footprint of the map — 8 bytes/slot,
918/// smaller than C's `struct Entry { long key; int occupied; }`.
919///
920/// The sentinel is `0`, not `i64::MIN`, on purpose: `vec![0; slots]` is the bit
921/// pattern Rust's `IsZero` specialization lowers to `alloc_zeroed` (calloc), so
922/// the table comes from the OS lazily-zeroed — no eager 1 GiB memset/page-fault
923/// storm up front (the kernel-time gap that made two_sum lose to C's `calloc`).
924#[derive(Debug, Clone)]
925pub struct LogosI64Set {
926    keys: Vec<i64>,
927    mask: usize,
928    /// `64 - log2(slots)`: a key's slot is the top bits of its Fibonacci product ([`fib_slot`]).
929    shift: u32,
930    len: usize,
931    has_zero_key: bool,
932}
933
934impl LogosI64Set {
935    const EMPTY: i64 = 0;
936
937    pub fn new() -> Self {
938        Self {
939            keys: Vec::new(),
940            mask: 0,
941            shift: 64,
942            len: 0,
943            has_zero_key: false,
944        }
945    }
946
947    pub fn with_capacity(cap: usize) -> Self {
948        let mut s = Self::new();
949        if cap > 0 {
950            let slots = int_table_slots(cap);
951            // `Self::EMPTY == 0` → `alloc_zeroed` (calloc): lazily-zeroed pages,
952            // no eager memset/fault of the whole table.
953            s.keys = vec![Self::EMPTY; slots];
954            s.mask = slots - 1;
955            s.shift = 64 - slots.trailing_zeros();
956        }
957        s
958    }
959
960    #[inline]
961    fn table_len(&self) -> usize {
962        self.len - self.has_zero_key as usize
963    }
964
965    /// The probe table is a power-of-two `Vec` whose length is exactly
966    /// `mask + 1` (maintained by `with_capacity`/`grow`); every probe index is
967    /// `… & mask`, so once `mask != 0` every `self.keys[i]` is in bounds. Telling
968    /// LLVM the invariant lets it drop the per-probe bounds check (matching C's
969    /// raw indexed loads). Caller must have established `mask != 0`.
970    #[inline(always)]
971    fn assume_table_invariant(&self) {
972        unsafe {
973            std::hint::assert_unchecked(self.mask + 1 == self.keys.len());
974        }
975    }
976
977    #[inline]
978    fn slot(&self, key: i64) -> usize {
979        fib_slot(key as u64, self.shift)
980    }
981
982    /// Insert a key. The `_value` parameter mirrors [`LogosI64Map::insert`]'s
983    /// call shape so codegen needs no special-casing at the insert site — by the
984    /// set-usage proof the value is never read.
985    #[inline]
986    pub fn insert(&mut self, key: i64, _value: i64) {
987        if key == Self::EMPTY {
988            if !self.has_zero_key {
989                self.has_zero_key = true;
990                self.len += 1;
991            }
992            return;
993        }
994        if self.mask == 0 || int_table_full(self.table_len(), self.mask + 1) {
995            self.grow();
996        }
997        self.assume_table_invariant();
998        let mut i = self.slot(key);
999        loop {
1000            let k = self.keys[i];
1001            if k == Self::EMPTY {
1002                self.keys[i] = key;
1003                self.len += 1;
1004                return;
1005            }
1006            if k == key {
1007                return;
1008            }
1009            i = (i + 1) & self.mask;
1010        }
1011    }
1012
1013    #[cold]
1014    #[inline(never)]
1015    fn grow(&mut self) {
1016        let new_slots = if self.mask == 0 {
1017            8
1018        } else {
1019            (self.mask + 1) * 2
1020        };
1021        let old_keys = std::mem::replace(&mut self.keys, vec![Self::EMPTY; new_slots]);
1022        self.mask = new_slots - 1;
1023        self.shift = 64 - new_slots.trailing_zeros();
1024        self.assume_table_invariant();
1025        for &k in old_keys.iter() {
1026            if k != Self::EMPTY {
1027                let mut i = self.slot(k);
1028                while self.keys[i] != Self::EMPTY {
1029                    i = (i + 1) & self.mask;
1030                }
1031                self.keys[i] = k;
1032            }
1033        }
1034    }
1035
1036    #[inline]
1037    pub fn contains_key(&self, key: &i64) -> bool {
1038        let key = *key;
1039        if key == Self::EMPTY {
1040            return self.has_zero_key;
1041        }
1042        if self.mask == 0 {
1043            return false;
1044        }
1045        self.assume_table_invariant();
1046        let mut i = self.slot(key);
1047        loop {
1048            let k = self.keys[i];
1049            if k == key {
1050                return true;
1051            }
1052            if k == Self::EMPTY {
1053                return false;
1054            }
1055            i = (i + 1) & self.mask;
1056        }
1057    }
1058
1059    pub fn len(&self) -> usize {
1060        self.len
1061    }
1062
1063    pub fn is_empty(&self) -> bool {
1064        self.len == 0
1065    }
1066}
1067
1068impl Default for LogosI64Set {
1069    fn default() -> Self {
1070        Self::new()
1071    }
1072}
1073
1074impl LogosContains<i64> for LogosI64Set {
1075    #[inline(always)]
1076    fn logos_contains(&self, key: &i64) -> bool {
1077        self.contains_key(key)
1078    }
1079}
1080
1081/// i32-narrowed open-addressing `i64 → i64` map — the same probe-table shape as
1082/// [`LogosI64Map`] but with 8-byte `(i32, i32)` slots, emitted when the compiler
1083/// PROVES every key AND value stays in `i32` range. Halving the slot width halves
1084/// the table's memory traffic — the dominant cost of this random-access workload —
1085/// for maps the dense gate cannot capture (no proven contiguous key window). The
1086/// call surface is `i64` (keys/values widen at the boundary; the proof makes the
1087/// narrowing cast lossless), so codegen emits it identically to `LogosI64Map`.
1088#[derive(Debug, Clone)]
1089pub struct LogosI32Map {
1090    entries: Vec<[i32; 2]>,
1091    mask: usize,
1092    /// `64 - log2(slots)`: a key's slot is the top bits of its Fibonacci product ([`fib_slot`]).
1093    shift: u32,
1094    len: usize,
1095    has_zero_key: bool,
1096    zero_key_val: i32,
1097}
1098
1099impl LogosI32Map {
1100    const EMPTY: i32 = 0;
1101
1102    pub fn new() -> Self {
1103        Self {
1104            entries: Vec::new(),
1105            mask: 0,
1106            shift: 64,
1107            len: 0,
1108            has_zero_key: false,
1109            zero_key_val: 0,
1110        }
1111    }
1112
1113    pub fn with_capacity(cap: usize) -> Self {
1114        let mut m = Self::new();
1115        if cap > 0 {
1116            let slots = int_table_slots(cap);
1117            // `[0, 0]` → `alloc_zeroed` (calloc): lazily zeroed, no eager memset.
1118            m.entries = vec![[Self::EMPTY, 0]; slots];
1119            m.mask = slots - 1;
1120            m.shift = 64 - slots.trailing_zeros();
1121        }
1122        m
1123    }
1124
1125    #[inline]
1126    fn table_len(&self) -> usize {
1127        self.len - self.has_zero_key as usize
1128    }
1129
1130    /// See [`LogosI64Set::assume_table_invariant`]: `entries.len() == mask + 1`
1131    /// once `mask != 0`, so masked probe indices need no bounds check.
1132    #[inline(always)]
1133    fn assume_table_invariant(&self) {
1134        unsafe {
1135            std::hint::assert_unchecked(self.mask + 1 == self.entries.len());
1136        }
1137    }
1138
1139    #[inline]
1140    fn slot(&self, key: i32) -> usize {
1141        fib_slot(key as u32 as u64, self.shift)
1142    }
1143
1144    #[inline]
1145    pub fn insert(&mut self, key: i64, value: i64) {
1146        let key = key as i32;
1147        let value = value as i32;
1148        if key == Self::EMPTY {
1149            if !self.has_zero_key {
1150                self.has_zero_key = true;
1151                self.len += 1;
1152            }
1153            self.zero_key_val = value;
1154            return;
1155        }
1156        if self.mask == 0 || int_table_full(self.table_len(), self.mask + 1) {
1157            self.grow();
1158        }
1159        self.assume_table_invariant();
1160        let mut i = self.slot(key);
1161        loop {
1162            let k = self.entries[i][0];
1163            if k == Self::EMPTY {
1164                self.entries[i] = [key, value];
1165                self.len += 1;
1166                return;
1167            }
1168            if k == key {
1169                self.entries[i][1] = value;
1170                return;
1171            }
1172            i = (i + 1) & self.mask;
1173        }
1174    }
1175
1176    #[cold]
1177    #[inline(never)]
1178    fn grow(&mut self) {
1179        let new_slots = if self.mask == 0 {
1180            8
1181        } else {
1182            (self.mask + 1) * 2
1183        };
1184        let old = std::mem::replace(&mut self.entries, vec![[Self::EMPTY, 0]; new_slots]);
1185        self.mask = new_slots - 1;
1186        self.shift = 64 - new_slots.trailing_zeros();
1187        self.assume_table_invariant();
1188        for &[k, v] in old.iter() {
1189            if k != Self::EMPTY {
1190                let mut i = self.slot(k);
1191                while self.entries[i][0] != Self::EMPTY {
1192                    i = (i + 1) & self.mask;
1193                }
1194                self.entries[i] = [k, v];
1195            }
1196        }
1197    }
1198
1199    #[inline]
1200    pub fn get(&self, key: &i64) -> Option<i64> {
1201        let key = *key as i32;
1202        if key == Self::EMPTY {
1203            return if self.has_zero_key {
1204                Some(self.zero_key_val as i64)
1205            } else {
1206                None
1207            };
1208        }
1209        if self.mask == 0 {
1210            return None;
1211        }
1212        self.assume_table_invariant();
1213        let mut i = self.slot(key);
1214        loop {
1215            let [k, v] = self.entries[i];
1216            if k == key {
1217                return Some(v as i64);
1218            }
1219            if k == Self::EMPTY {
1220                return None;
1221            }
1222            i = (i + 1) & self.mask;
1223        }
1224    }
1225
1226    #[inline]
1227    pub fn contains_key(&self, key: &i64) -> bool {
1228        self.get(key).is_some()
1229    }
1230
1231    pub fn len(&self) -> usize {
1232        self.len
1233    }
1234
1235    pub fn is_empty(&self) -> bool {
1236        self.len == 0
1237    }
1238}
1239
1240impl Default for LogosI32Map {
1241    fn default() -> Self {
1242        Self::new()
1243    }
1244}
1245
1246impl LogosContains<i64> for LogosI32Map {
1247    #[inline(always)]
1248    fn logos_contains(&self, key: &i64) -> bool {
1249        self.get(key).is_some()
1250    }
1251}
1252
1253/// i32-narrowed open-addressing set — the keys-only sibling of [`LogosI32Map`]
1254/// (the i32 analogue of [`LogosI64Set`]). One flat `Vec<i32>`: 4 bytes per slot,
1255/// a quarter of `LogosI64Map`'s footprint. Emitted for a set-usage `Int → Int`
1256/// map whose keys are all proven to fit `i32`. The empty-slot sentinel is `0`
1257/// (the real key `0` tracked separately) so `vec![0; slots]` allocates via
1258/// `alloc_zeroed` — lazily-zeroed, no eager memset of the table.
1259#[derive(Debug, Clone)]
1260pub struct LogosI32Set {
1261    keys: Vec<i32>,
1262    mask: usize,
1263    /// `64 - log2(slots)`: a key's slot is the top bits of its Fibonacci product ([`fib_slot`]).
1264    shift: u32,
1265    len: usize,
1266    has_zero_key: bool,
1267}
1268
1269impl LogosI32Set {
1270    const EMPTY: i32 = 0;
1271
1272    pub fn new() -> Self {
1273        Self {
1274            keys: Vec::new(),
1275            mask: 0,
1276            shift: 64,
1277            len: 0,
1278            has_zero_key: false,
1279        }
1280    }
1281
1282    pub fn with_capacity(cap: usize) -> Self {
1283        let mut s = Self::new();
1284        if cap > 0 {
1285            let slots = int_table_slots(cap);
1286            s.keys = vec![Self::EMPTY; slots];
1287            s.mask = slots - 1;
1288            s.shift = 64 - slots.trailing_zeros();
1289        }
1290        s
1291    }
1292
1293    #[inline]
1294    fn table_len(&self) -> usize {
1295        self.len - self.has_zero_key as usize
1296    }
1297
1298    /// See [`LogosI64Set::assume_table_invariant`]: `keys.len() == mask + 1` once
1299    /// `mask != 0`, so masked probe indices need no bounds check.
1300    #[inline(always)]
1301    fn assume_table_invariant(&self) {
1302        unsafe {
1303            std::hint::assert_unchecked(self.mask + 1 == self.keys.len());
1304        }
1305    }
1306
1307    #[inline]
1308    fn slot(&self, key: i32) -> usize {
1309        fib_slot(key as u32 as u64, self.shift)
1310    }
1311
1312    #[inline]
1313    pub fn insert(&mut self, key: i64, _value: i64) {
1314        let key = key as i32;
1315        if key == Self::EMPTY {
1316            if !self.has_zero_key {
1317                self.has_zero_key = true;
1318                self.len += 1;
1319            }
1320            return;
1321        }
1322        if self.mask == 0 || int_table_full(self.table_len(), self.mask + 1) {
1323            self.grow();
1324        }
1325        self.assume_table_invariant();
1326        let mut i = self.slot(key);
1327        loop {
1328            let k = self.keys[i];
1329            if k == Self::EMPTY {
1330                self.keys[i] = key;
1331                self.len += 1;
1332                return;
1333            }
1334            if k == key {
1335                return;
1336            }
1337            i = (i + 1) & self.mask;
1338        }
1339    }
1340
1341    #[cold]
1342    #[inline(never)]
1343    fn grow(&mut self) {
1344        let new_slots = if self.mask == 0 {
1345            8
1346        } else {
1347            (self.mask + 1) * 2
1348        };
1349        let old_keys = std::mem::replace(&mut self.keys, vec![Self::EMPTY; new_slots]);
1350        self.mask = new_slots - 1;
1351        self.shift = 64 - new_slots.trailing_zeros();
1352        self.assume_table_invariant();
1353        for &k in old_keys.iter() {
1354            if k != Self::EMPTY {
1355                let mut i = self.slot(k);
1356                while self.keys[i] != Self::EMPTY {
1357                    i = (i + 1) & self.mask;
1358                }
1359                self.keys[i] = k;
1360            }
1361        }
1362    }
1363
1364    #[inline]
1365    pub fn contains_key(&self, key: &i64) -> bool {
1366        let key = *key as i32;
1367        if key == Self::EMPTY {
1368            return self.has_zero_key;
1369        }
1370        if self.mask == 0 {
1371            return false;
1372        }
1373        self.assume_table_invariant();
1374        let mut i = self.slot(key);
1375        loop {
1376            let k = self.keys[i];
1377            if k == key {
1378                return true;
1379            }
1380            if k == Self::EMPTY {
1381                return false;
1382            }
1383            i = (i + 1) & self.mask;
1384        }
1385    }
1386
1387    pub fn len(&self) -> usize {
1388        self.len
1389    }
1390
1391    pub fn is_empty(&self) -> bool {
1392        self.len == 0
1393    }
1394}
1395
1396impl Default for LogosI32Set {
1397    fn default() -> Self {
1398        Self::new()
1399    }
1400}
1401
1402impl LogosContains<i64> for LogosI32Set {
1403    #[inline(always)]
1404    fn logos_contains(&self, key: &i64) -> bool {
1405        self.contains_key(key)
1406    }
1407}
1408
1409/// Direct-addressed `i64 → i64` map — the densest representation of a
1410/// `Map of Int to Int`, emitted when the compiler PROVES every key ever inserted
1411/// or queried lands in a statically bounded window `[lo, lo + slots)` whose width
1412/// is ≤ the map's own `with capacity` hint. Keys index a flat value array
1413/// (`data[key - lo]`); a parallel presence bitset distinguishes a stored value
1414/// from an absent slot, so `get` returns `None` for an in-range key that was
1415/// never inserted. No hashing, no probing, no sparse table — both build and scan
1416/// phases are sequential array accesses, which the backend vectorizes and the
1417/// prefetcher loves. This is perfect hashing for dense integer keys: it removes
1418/// the random-access hash table that costs `LogosI64Map` its cache locality.
1419#[derive(Debug, Clone)]
1420pub struct LogosDenseI64Map {
1421    /// Value slots, indexed by `key - lo`. Zero-initialized; a zero is only a
1422    /// real value when its presence bit is set.
1423    data: Vec<i64>,
1424    /// One bit per slot: set ⇔ the slot holds an inserted value.
1425    present: Vec<u64>,
1426    /// The window's lower bound; `data[key - lo]` rebases the key space (so a
1427    /// 1-based or negative key domain maps onto `[0, slots)`).
1428    lo: i64,
1429    len: usize,
1430}
1431
1432impl LogosDenseI64Map {
1433    pub fn new() -> Self {
1434        Self {
1435            data: Vec::new(),
1436            present: Vec::new(),
1437            lo: 0,
1438            len: 0,
1439        }
1440    }
1441
1442    /// A window `[0, cap)` — the offset-free form. Mirrors the `LogosI64Map`
1443    /// constructor name so a non-offset dense map reuses the same emission.
1444    pub fn with_capacity(cap: usize) -> Self {
1445        Self::with_bounds(0, cap)
1446    }
1447
1448    /// A window `[lo, lo + slots)`. `slots` is sized to the proven capacity hint;
1449    /// the soundness gate guarantees every key falls inside, so `key - lo` is a
1450    /// valid index for every insert and get the program performs.
1451    pub fn with_bounds(lo: i64, slots: usize) -> Self {
1452        Self {
1453            data: vec![0; slots],
1454            present: vec![0; slots.div_ceil(64)],
1455            lo,
1456            len: 0,
1457        }
1458    }
1459
1460    #[inline]
1461    pub fn insert(&mut self, key: i64, value: i64) {
1462        let idx = (key - self.lo) as usize;
1463        debug_assert!(
1464            key >= self.lo && idx < self.data.len(),
1465            "dense map key {key} outside proven window [{}, {})",
1466            self.lo,
1467            self.lo + self.data.len() as i64
1468        );
1469        let bit = 1u64 << (idx & 63);
1470        let word = &mut self.present[idx >> 6];
1471        if *word & bit == 0 {
1472            *word |= bit;
1473            self.len += 1;
1474        }
1475        self.data[idx] = value;
1476    }
1477
1478    #[inline]
1479    pub fn get(&self, key: &i64) -> Option<i64> {
1480        let idx = (*key - self.lo) as usize;
1481        debug_assert!(
1482            *key >= self.lo && idx < self.data.len(),
1483            "dense map key {key} outside proven window [{}, {})",
1484            self.lo,
1485            self.lo + self.data.len() as i64
1486        );
1487        if self.present[idx >> 6] & (1u64 << (idx & 63)) != 0 {
1488            Some(self.data[idx])
1489        } else {
1490            None
1491        }
1492    }
1493
1494    #[inline]
1495    pub fn contains_key(&self, key: &i64) -> bool {
1496        let idx = (*key - self.lo) as usize;
1497        debug_assert!(*key >= self.lo && idx < self.data.len());
1498        self.present[idx >> 6] & (1u64 << (idx & 63)) != 0
1499    }
1500
1501    pub fn len(&self) -> usize {
1502        self.len
1503    }
1504
1505    pub fn is_empty(&self) -> bool {
1506        self.len == 0
1507    }
1508}
1509
1510impl Default for LogosDenseI64Map {
1511    fn default() -> Self {
1512        Self::new()
1513    }
1514}
1515
1516impl LogosContains<i64> for LogosDenseI64Map {
1517    #[inline(always)]
1518    fn logos_contains(&self, key: &i64) -> bool {
1519        self.contains_key(key)
1520    }
1521}
1522
1523/// The presence-elided sibling of [`LogosDenseI64Map`], emitted ONLY when the
1524/// compiler additionally proves the get/contains key domain is a subset of a
1525/// CONTIGUOUSLY FULLY-COVERED insert range — i.e. every key the program reads was
1526/// definitely written first. With that proof the presence bit is invariably set,
1527/// so it is dropped: `get` is a bare `Some(data[key - lo])` load, byte-identical
1528/// to a C array read, and no presence bitset is allocated. The gate forbids this
1529/// type for any map with a `contains` use (there is no way to answer membership
1530/// without presence), so `contains_key`/`LogosContains` are intentionally absent
1531/// — a generated `contains` on this type would fail to compile, surfacing a gate
1532/// bug loudly rather than silently miscompiling.
1533#[derive(Debug, Clone)]
1534pub struct LogosDenseI64MapNoPresence {
1535    data: Vec<i64>,
1536    lo: i64,
1537    /// Insert count. Exact under the proven regime (each covered key written
1538    /// once); never emitted (a `length of m` use disqualifies the map upstream).
1539    len: usize,
1540}
1541
1542impl LogosDenseI64MapNoPresence {
1543    pub fn new() -> Self {
1544        Self {
1545            data: Vec::new(),
1546            lo: 0,
1547            len: 0,
1548        }
1549    }
1550
1551    pub fn with_capacity(cap: usize) -> Self {
1552        Self::with_bounds(0, cap)
1553    }
1554
1555    pub fn with_bounds(lo: i64, slots: usize) -> Self {
1556        Self {
1557            data: vec![0; slots],
1558            lo,
1559            len: 0,
1560        }
1561    }
1562
1563    #[inline]
1564    pub fn insert(&mut self, key: i64, value: i64) {
1565        let idx = (key - self.lo) as usize;
1566        debug_assert!(
1567            key >= self.lo && idx < self.data.len(),
1568            "dense map key {key} outside proven window [{}, {})",
1569            self.lo,
1570            self.lo + self.data.len() as i64
1571        );
1572        self.data[idx] = value;
1573        self.len += 1;
1574    }
1575
1576    #[inline]
1577    pub fn get(&self, key: &i64) -> Option<i64> {
1578        let idx = (*key - self.lo) as usize;
1579        debug_assert!(
1580            *key >= self.lo && idx < self.data.len(),
1581            "dense map key {key} outside proven window [{}, {})",
1582            self.lo,
1583            self.lo + self.data.len() as i64
1584        );
1585        Some(self.data[idx])
1586    }
1587
1588    pub fn len(&self) -> usize {
1589        self.len
1590    }
1591
1592    pub fn is_empty(&self) -> bool {
1593        self.len == 0
1594    }
1595}
1596
1597impl Default for LogosDenseI64MapNoPresence {
1598    fn default() -> Self {
1599        Self::new()
1600    }
1601}
1602
1603/// Direct-addressed `i64` SET — the keys-only, value-free sibling of
1604/// [`LogosDenseI64Map`] (the dense analogue of [`LogosI64Set`]). Membership lives
1605/// in a presence bitset over the proven window `[lo, lo + slots)`; `insert` sets
1606/// a bit, `contains` tests one. No value array → 1 bit per key, the smallest
1607/// footprint of any map/set representation.
1608#[derive(Debug, Clone)]
1609pub struct LogosDenseI64Set {
1610    present: Vec<u64>,
1611    lo: i64,
1612    len: usize,
1613}
1614
1615impl LogosDenseI64Set {
1616    pub fn new() -> Self {
1617        Self {
1618            present: Vec::new(),
1619            lo: 0,
1620            len: 0,
1621        }
1622    }
1623
1624    pub fn with_capacity(cap: usize) -> Self {
1625        Self::with_bounds(0, cap)
1626    }
1627
1628    pub fn with_bounds(lo: i64, slots: usize) -> Self {
1629        Self {
1630            present: vec![0; slots.div_ceil(64)],
1631            lo,
1632            len: 0,
1633        }
1634    }
1635
1636    /// Insert a key. The `_value` mirrors [`LogosDenseI64Map::insert`]'s call
1637    /// shape so codegen needs no special-casing at the insert site.
1638    #[inline]
1639    pub fn insert(&mut self, key: i64, _value: i64) {
1640        let idx = (key - self.lo) as usize;
1641        debug_assert!(
1642            key >= self.lo && idx < self.present.len() * 64,
1643            "dense set key {key} outside proven window starting at {}",
1644            self.lo
1645        );
1646        let bit = 1u64 << (idx & 63);
1647        let word = &mut self.present[idx >> 6];
1648        if *word & bit == 0 {
1649            *word |= bit;
1650            self.len += 1;
1651        }
1652    }
1653
1654    #[inline]
1655    pub fn contains_key(&self, key: &i64) -> bool {
1656        let idx = (*key - self.lo) as usize;
1657        debug_assert!(*key >= self.lo && idx < self.present.len() * 64);
1658        self.present[idx >> 6] & (1u64 << (idx & 63)) != 0
1659    }
1660
1661    pub fn len(&self) -> usize {
1662        self.len
1663    }
1664
1665    pub fn is_empty(&self) -> bool {
1666        self.len == 0
1667    }
1668}
1669
1670impl Default for LogosDenseI64Set {
1671    fn default() -> Self {
1672        Self::new()
1673    }
1674}
1675
1676impl LogosContains<i64> for LogosDenseI64Set {
1677    #[inline(always)]
1678    fn logos_contains(&self, key: &i64) -> bool {
1679        self.contains_key(key)
1680    }
1681}
1682
1683/// Precomputed unsigned division by a **loop-invariant runtime divisor** — the
1684/// magic-multiply that replaces a hardware `div`/`idiv` once the divisor is
1685/// pinned. Codegen emits `LogosDivU64::new(n)` in a loop's preheader (computed
1686/// ONCE) and rewrites each in-loop `x % n` / `x / n` to `.rem(x)` / `.div(x)`,
1687/// turning a ~20–40-cycle division into a multiply-high plus a shift. gcc and
1688/// rustc both leave a runtime-invariant divisor as a real `div` (neither
1689/// synthesizes this), so it is a strict win over the C baseline on division-hot
1690/// loops (graph_bfs's `% n` adjacency build).
1691///
1692/// The construction is the standard Granlund–Montgomery / libdivide unsigned
1693/// algorithm, exact for every divisor in `1..=u64::MAX` (power-of-two fast path,
1694/// the 64-bit-magic path, and the 65-bit "add marker" path). Codegen only emits
1695/// it where the dividend is proven non-negative and `n > 0` (the existing
1696/// positivity guard), so the `i64`→`u64` reinterpretation is value-preserving.
1697#[derive(Debug, Clone, Copy)]
1698pub struct LogosDivU64 {
1699    magic: u64,
1700    /// Low 6 bits: shift amount. `ADD_MARKER` (0x40): the 65-bit-magic path.
1701    /// `SHIFT_PATH` (0x80): the divisor is a power of two (pure shift).
1702    more: u8,
1703    d: u64,
1704}
1705
1706impl LogosDivU64 {
1707    const SHIFT_MASK: u8 = 0x3F;
1708    const ADD_MARKER: u8 = 0x40;
1709    const SHIFT_PATH: u8 = 0x80;
1710
1711    /// Build the magic numbers for divisor `d` (must be non-zero). Runs once per
1712    /// loop in the preheader, so its cost (a single 128/64 division) amortizes
1713    /// over the whole loop.
1714    #[inline]
1715    pub fn new(d: u64) -> Self {
1716        debug_assert!(d != 0, "LogosDivU64: divisor must be non-zero");
1717        if d & (d - 1) == 0 {
1718            // Power of two (including d == 1, shift 0): the division is a shift.
1719            return Self {
1720                magic: 0,
1721                more: (d.trailing_zeros() as u8) | Self::SHIFT_PATH,
1722                d,
1723            };
1724        }
1725        let floor_log_2_d = 63 - d.leading_zeros();
1726        // proposed_m = floor(2^(64 + floor_log_2_d) / d); rem the remainder.
1727        let numer = 1u128 << (64 + floor_log_2_d);
1728        let proposed_m = (numer / d as u128) as u64;
1729        let rem = (numer % d as u128) as u64;
1730        let e = d - rem;
1731        let (magic, more) = if e < (1u64 << floor_log_2_d) {
1732            // The 64-bit magic suffices.
1733            (proposed_m + 1, floor_log_2_d as u8)
1734        } else {
1735            // Need the 65th bit — fold it into an extra add at division time.
1736            let twice_rem = rem.wrapping_mul(2);
1737            let bump = (twice_rem >= d || twice_rem < rem) as u64;
1738            (
1739                proposed_m.wrapping_mul(2).wrapping_add(bump) + 1,
1740                (floor_log_2_d as u8) | Self::ADD_MARKER,
1741            )
1742        };
1743        Self { magic, more, d }
1744    }
1745
1746    #[inline(always)]
1747    pub fn div(&self, numer: u64) -> u64 {
1748        if self.more & Self::SHIFT_PATH != 0 {
1749            return numer >> (self.more & Self::SHIFT_MASK);
1750        }
1751        let q = (((self.magic as u128) * (numer as u128)) >> 64) as u64;
1752        if self.more & Self::ADD_MARKER != 0 {
1753            let t = ((numer - q) >> 1).wrapping_add(q);
1754            t >> (self.more & Self::SHIFT_MASK)
1755        } else {
1756            q >> self.more
1757        }
1758    }
1759
1760    #[inline(always)]
1761    pub fn rem(&self, numer: u64) -> u64 {
1762        numer - self.div(numer).wrapping_mul(self.d)
1763    }
1764
1765    /// The raw `(magic, more)` pair, for backends (the VM / JIT interpreter
1766    /// tiers) that bake the precomputed constants into a single fused op instead
1767    /// of holding a `LogosDivU64` struct. The encoding of `more` is exactly the
1768    /// one `div`/`rem` consume (low 6 bits = shift; `0x40` = the 65-bit
1769    /// add-marker path; `0x80` = the pure-shift power-of-two path).
1770    #[inline]
1771    pub fn parts(&self) -> (u64, u8) {
1772        (self.magic, self.more)
1773    }
1774}
1775
1776/// Ordered sequences with reference semantics.
1777pub type Seq<T> = LogosSeq<T>;
1778
1779/// Key-value mappings with reference semantics.
1780pub type Map<K, V> = LogosMap<K, V>;
1781
1782/// Unordered collections of unique elements with FxHash.
1783/// The insertion-ordered set behind every LOGOS `Set`: display and iteration
1784/// follow first-insertion order, identical to the tree-walker's Vec-backed
1785/// sets and the direct-WASM linear sets. Fx hashing for speed. NOTE: removal
1786/// must go through `shift_remove` (order-preserving), never `swap_remove`.
1787pub type FxIndexSet<T> = indexmap::IndexSet<T, std::hash::BuildHasherDefault<rustc_hash::FxHasher>>;
1788pub type Set<T> = FxIndexSet<T>;
1789
1790/// Unified containment testing for all collection types.
1791///
1792/// This trait provides a consistent `logos_contains` method across Logos's
1793/// collection types, abstracting over the different containment semantics
1794/// of vectors (by value), sets (by membership), maps (by key), and
1795/// strings (by substring or character).
1796///
1797/// # Implementations
1798///
1799/// - [`Vec<T>`]: Tests if the vector contains an element equal to the value
1800/// - `HashSet<T>`: Tests if the element is a member of the set
1801/// - `HashMap<K, V>`: Tests if a key exists in the map
1802/// - [`String`]: Tests for substring (`&str`) or character (`char`) presence
1803/// - `ORSet<T, B>`: Tests if the element is in the CRDT set
1804///
1805/// # Examples
1806///
1807/// ```
1808/// use logicaffeine_data::LogosContains;
1809///
1810/// // Vector: contains by value equality
1811/// let v = vec![1, 2, 3];
1812/// assert!(v.logos_contains(&2));
1813/// assert!(!v.logos_contains(&5));
1814///
1815/// // String: contains by substring
1816/// let s = String::from("hello world");
1817/// assert!(s.logos_contains(&"world"));
1818///
1819/// // String: contains by character
1820/// assert!(s.logos_contains(&'o'));
1821/// ```
1822pub trait LogosContains<T> {
1823    /// Check if this collection contains the given value.
1824    fn logos_contains(&self, value: &T) -> bool;
1825}
1826
1827impl<T: PartialEq> LogosContains<T> for Vec<T> {
1828    #[inline(always)]
1829    fn logos_contains(&self, value: &T) -> bool {
1830        self.contains(value)
1831    }
1832}
1833
1834impl<T: PartialEq> LogosContains<T> for [T] {
1835    #[inline(always)]
1836    fn logos_contains(&self, value: &T) -> bool {
1837        self.contains(value)
1838    }
1839}
1840
1841impl<T: Eq + Hash, S: std::hash::BuildHasher> LogosContains<T> for indexmap::IndexSet<T, S> {
1842    #[inline(always)]
1843    fn logos_contains(&self, value: &T) -> bool {
1844        self.contains(value)
1845    }
1846}
1847
1848impl<T: Eq + Hash> LogosContains<T> for rustc_hash::FxHashSet<T> {
1849    #[inline(always)]
1850    fn logos_contains(&self, value: &T) -> bool {
1851        self.contains(value)
1852    }
1853}
1854
1855impl<K: Eq + Hash, V> LogosContains<K> for rustc_hash::FxHashMap<K, V> {
1856    #[inline(always)]
1857    fn logos_contains(&self, key: &K) -> bool {
1858        self.contains_key(key)
1859    }
1860}
1861
1862impl LogosContains<&str> for String {
1863    #[inline(always)]
1864    fn logos_contains(&self, value: &&str) -> bool {
1865        self.contains(*value)
1866    }
1867}
1868
1869impl LogosContains<String> for String {
1870    #[inline(always)]
1871    fn logos_contains(&self, value: &String) -> bool {
1872        self.contains(value.as_str())
1873    }
1874}
1875
1876impl LogosContains<char> for String {
1877    #[inline(always)]
1878    fn logos_contains(&self, value: &char) -> bool {
1879        self.contains(*value)
1880    }
1881}
1882
1883impl<T: Eq + Hash + Clone, B: crate::crdt::SetBias> LogosContains<T> for crate::crdt::ORSet<T, B> {
1884    #[inline(always)]
1885    fn logos_contains(&self, value: &T) -> bool {
1886        self.contains(value)
1887    }
1888}
1889
1890/// Dynamic value type for heterogeneous collections.
1891///
1892/// `Value` enables tuples and other heterogeneous data structures in Logos.
1893/// It supports basic arithmetic between compatible types and provides
1894/// runtime type coercion where sensible.
1895///
1896/// # Variants
1897///
1898/// - `Int(i64)` - Integer values
1899/// - `Float(f64)` - Floating-point values
1900/// - `Bool(bool)` - Boolean values
1901/// - `Text(String)` - String values
1902/// - `Char(char)` - Single character values
1903/// - `Nothing` - Unit/null value
1904///
1905/// # Arithmetic
1906///
1907/// Arithmetic operations are supported between numeric types:
1908/// - `Int op Int` → `Int`
1909/// - `Float op Float` → `Float`
1910/// - `Int op Float` or `Float op Int` → `Float` (promotion)
1911/// - `Text + Text` → `Text` (concatenation)
1912///
1913/// # Panics
1914///
1915/// Arithmetic on incompatible variants panics at runtime.
1916///
1917/// # Examples
1918///
1919/// ```
1920/// use logicaffeine_data::Value;
1921///
1922/// let a = Value::Int(10);
1923/// let b = Value::Int(3);
1924/// assert_eq!(a + b, Value::Int(13));
1925///
1926/// let x = Value::Float(2.5);
1927/// let y = Value::Int(2);
1928/// assert_eq!(x * y, Value::Float(5.0));
1929/// ```
1930#[derive(Clone, Debug, PartialEq)]
1931pub enum Value {
1932    /// Integer values.
1933    Int(i64),
1934    /// Floating-point values.
1935    Float(f64),
1936    /// Boolean values.
1937    Bool(bool),
1938    /// String values.
1939    Text(String),
1940    /// Single character values.
1941    Char(char),
1942    /// A boxed homogeneous sequence — the carrier that lets a `LogosTuple` hold a COLLECTION element
1943    /// (`(Seq of Text, Seq of Int)`), not just a scalar. The elements are themselves boxed `Value`s, so
1944    /// a `Seq of Seq of _` nests naturally. Constructed by the `From<LogosSeq<T>>` impls and read back by
1945    /// the `logos_seq_*` unboxers, exactly as the scalar variants pair with `From`/`logos_*`.
1946    Seq(LogosSeq<Value>),
1947    /// A value of a type the program declares (a record, a variant), boxed so it rides a tuple element
1948    /// beside scalars and lists. Built by the `From<T: Boxable>` impl, read back by
1949    /// [`Value::logos_boxed`], rendered by the type's own `Show`.
1950    Boxed(LogosBoxed),
1951    /// Unit/null value.
1952    Nothing,
1953}
1954
1955impl std::fmt::Display for Value {
1956    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1957        match self {
1958            Value::Int(n) => write!(f, "{}", n),
1959            Value::Float(n) => write!(f, "{}", n),
1960            Value::Bool(b) => write!(f, "{}", b),
1961            Value::Text(s) => write!(f, "{}", s),
1962            Value::Char(c) => write!(f, "{}", c),
1963            Value::Seq(xs) => write!(f, "{}", xs),
1964            Value::Boxed(b) => write!(f, "{}", b),
1965            Value::Nothing => write!(f, "nothing"),
1966        }
1967    }
1968}
1969
1970/// A type a compiled program declares that can ride a tuple element as a [`Value::Boxed`]. The
1971/// program implements it for each record and variant it declares; `render` is the type's own `Show`
1972/// (this crate has no IO, so the rendering is supplied by the implementor).
1973pub trait Boxable: std::any::Any + Clone + PartialEq + std::fmt::Debug {
1974    fn render(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
1975}
1976
1977/// The object-safe face of a [`Boxable`]: what a [`LogosBoxed`] needs from the value it holds.
1978trait BoxedValue: std::any::Any {
1979    fn render(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
1980    fn debug(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
1981    fn equals(&self, other: &dyn BoxedValue) -> bool;
1982    fn as_any(&self) -> &dyn std::any::Any;
1983}
1984
1985impl<T: Boxable> BoxedValue for T {
1986    fn render(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1987        Boxable::render(self, f)
1988    }
1989    fn debug(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1990        std::fmt::Debug::fmt(self, f)
1991    }
1992    fn equals(&self, other: &dyn BoxedValue) -> bool {
1993        other
1994            .as_any()
1995            .downcast_ref::<T>()
1996            .is_some_and(|other| self == other)
1997    }
1998    fn as_any(&self) -> &dyn std::any::Any {
1999        self
2000    }
2001}
2002
2003/// A [`Boxable`] value behind a shared, immutable pointer. Reading it back clones the value out, so
2004/// sharing the allocation between clones of a tuple never lets one copy observe another's writes.
2005/// Two boxes are equal when they hold the same type and equal values.
2006#[derive(Clone)]
2007pub struct LogosBoxed(Rc<dyn BoxedValue>);
2008
2009impl LogosBoxed {
2010    #[inline]
2011    pub fn new<T: Boxable>(value: T) -> Self {
2012        LogosBoxed(Rc::new(value))
2013    }
2014
2015    /// The held value as a `T`. Holding any other type is a program-type error, and panics like the
2016    /// scalar unboxers.
2017    #[inline]
2018    pub fn get<T: Boxable>(&self) -> T {
2019        match self.0.as_any().downcast_ref::<T>() {
2020            Some(value) => value.clone(),
2021            None => panic!(
2022                "expected a {} tuple/record element, found {}",
2023                std::any::type_name::<T>(),
2024                self
2025            ),
2026        }
2027    }
2028}
2029
2030impl PartialEq for LogosBoxed {
2031    fn eq(&self, other: &Self) -> bool {
2032        self.0.equals(&*other.0)
2033    }
2034}
2035
2036impl std::fmt::Debug for LogosBoxed {
2037    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2038        self.0.debug(f)
2039    }
2040}
2041
2042impl std::fmt::Display for LogosBoxed {
2043    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2044        self.0.render(f)
2045    }
2046}
2047
2048impl<T: Boxable> From<T> for Value {
2049    #[inline]
2050    fn from(value: T) -> Self {
2051        Value::Boxed(LogosBoxed::new(value))
2052    }
2053}
2054
2055/// A LOGOS tuple `(a, b, …)` — a positional, heterogeneous value. A newtype over `Vec<Value>` that
2056/// `Deref`s to it, so every existing indexing / destructuring / iteration / return path keeps working
2057/// unchanged; it exists ONLY to carry a distinct display: a tuple renders with PARENS `(a, b)` and — the
2058/// whole point — stays distinguishable from a `Seq` even when nested (`[(1, 2), (3, 4)]`), which a bare
2059/// `Vec<Value>` (shown as `[…]`, identical to a Seq) could not.
2060#[derive(Clone, Debug, PartialEq, Default)]
2061pub struct LogosTuple(pub Vec<Value>);
2062
2063impl std::ops::Deref for LogosTuple {
2064    type Target = Vec<Value>;
2065    fn deref(&self) -> &Vec<Value> {
2066        &self.0
2067    }
2068}
2069
2070impl std::ops::DerefMut for LogosTuple {
2071    fn deref_mut(&mut self) -> &mut Vec<Value> {
2072        &mut self.0
2073    }
2074}
2075
2076impl From<Vec<Value>> for LogosTuple {
2077    fn from(v: Vec<Value>) -> Self {
2078        LogosTuple(v)
2079    }
2080}
2081
2082impl std::fmt::Display for LogosTuple {
2083    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2084        write!(f, "(")?;
2085        for (i, v) in self.0.iter().enumerate() {
2086            if i > 0 {
2087                write!(f, ", ")?;
2088            }
2089            write!(f, "{}", v)?;
2090        }
2091        write!(f, ")")
2092    }
2093}
2094
2095// Conversion traits for Value
2096impl From<i64> for Value {
2097    fn from(n: i64) -> Self {
2098        Value::Int(n)
2099    }
2100}
2101
2102impl From<f64> for Value {
2103    fn from(n: f64) -> Self {
2104        Value::Float(n)
2105    }
2106}
2107
2108impl From<bool> for Value {
2109    fn from(b: bool) -> Self {
2110        Value::Bool(b)
2111    }
2112}
2113
2114impl From<String> for Value {
2115    fn from(s: String) -> Self {
2116        Value::Text(s)
2117    }
2118}
2119
2120impl From<&str> for Value {
2121    fn from(s: &str) -> Self {
2122        Value::Text(s.to_string())
2123    }
2124}
2125
2126impl From<char> for Value {
2127    fn from(c: char) -> Self {
2128        Value::Char(c)
2129    }
2130}
2131
2132/// BOX a homogeneous sequence into a `Value` so it can ride as a tuple element. Each element is boxed
2133/// via its own `Into<Value>` (so `LogosSeq<i64>` → `Value::Seq` of `Value::Int`, and a `LogosSeq<LogosSeq<_>>`
2134/// nests by boxing each inner seq the same way; a `LogosSeq<Value>` uses the reflexive `Value: Into<Value>`).
2135/// Pairs with the `logos_seq_*` unboxers.
2136impl<T: Into<Value> + Clone> From<LogosSeq<T>> for Value {
2137    fn from(xs: LogosSeq<T>) -> Self {
2138        Value::Seq(LogosSeq::from_vec(
2139            xs.0.borrow().iter().cloned().map(Into::into).collect(),
2140        ))
2141    }
2142}
2143
2144/// Tuple type: Vec of heterogeneous Values (uses LogosIndex from indexing module)
2145pub type Tuple = Vec<Value>;
2146
2147impl Value {
2148    /// UNBOX a heterogeneous-tuple / named-record element (a boxed `Value` read out of the positional
2149    /// `Vec<Value>`) back to its concrete scalar so it can be USED in a typed position — `upper(item 2 of
2150    /// t)` where element 2 is a `Text`, or `r's ratio * 2.0` where `ratio` is a `Real`. Extraction alone
2151    /// yields a `Value` (fine for `Show`, which takes any `Display`); these turn it back into the exact
2152    /// scalar the AOT-Rust code's type context demands. A wrong-variant unbox is a genuine program-type
2153    /// error, so it panics loudly (mirrors the interpreter/VM, which would surface the same mismatch).
2154    #[inline]
2155    pub fn logos_i64(self) -> i64 {
2156        match self {
2157            Value::Int(n) => n,
2158            other => panic!("expected an Int tuple/record element, found {other}"),
2159        }
2160    }
2161    #[inline]
2162    pub fn logos_f64(self) -> f64 {
2163        match self {
2164            Value::Float(x) => x,
2165            Value::Int(n) => n as f64,
2166            other => panic!("expected a Real tuple/record element, found {other}"),
2167        }
2168    }
2169    #[inline]
2170    pub fn logos_bool(self) -> bool {
2171        match self {
2172            Value::Bool(b) => b,
2173            other => panic!("expected a Bool tuple/record element, found {other}"),
2174        }
2175    }
2176    #[inline]
2177    pub fn logos_string(self) -> String {
2178        match self {
2179            Value::Text(s) => s,
2180            Value::Char(c) => c.to_string(),
2181            other => panic!("expected a Text tuple/record element, found {other}"),
2182        }
2183    }
2184    #[inline]
2185    pub fn logos_char(self) -> char {
2186        match self {
2187            Value::Char(c) => c,
2188            other => panic!("expected a Char tuple/record element, found {other}"),
2189        }
2190    }
2191    /// UNBOX a [`Value::Boxed`] element back to the record or variant it holds.
2192    #[inline]
2193    pub fn logos_boxed<T: Boxable>(self) -> T {
2194        match self {
2195            Value::Boxed(b) => b.get(),
2196            other => panic!(
2197                "expected a {} tuple/record element, found {other}",
2198                std::any::type_name::<T>()
2199            ),
2200        }
2201    }
2202
2203    /// UNBOX the [`Value::Seq`] carrier back to a typed `LogosSeq<T>`, unboxing each element with `f`
2204    /// (`Value::logos_i64` for a `Seq of Int`, `Value::logos_seq_string` for a `Seq of Seq of Text`, …).
2205    /// The scalar-per-type wrappers below name the common element unboxers; nesting composes them. A
2206    /// non-`Seq` value is a genuine program-type error, so it panics loudly like the scalar unboxers.
2207    #[inline]
2208    pub fn logos_seq<T>(self, f: impl Fn(Value) -> T) -> LogosSeq<T> {
2209        match self {
2210            Value::Seq(xs) => LogosSeq::from_vec(xs.0.borrow().iter().cloned().map(f).collect()),
2211            other => panic!("expected a Seq tuple/record element, found {other}"),
2212        }
2213    }
2214    #[inline]
2215    pub fn logos_seq_i64(self) -> LogosSeq<i64> {
2216        self.logos_seq(Value::logos_i64)
2217    }
2218    #[inline]
2219    pub fn logos_seq_f64(self) -> LogosSeq<f64> {
2220        self.logos_seq(Value::logos_f64)
2221    }
2222    #[inline]
2223    pub fn logos_seq_bool(self) -> LogosSeq<bool> {
2224        self.logos_seq(Value::logos_bool)
2225    }
2226    #[inline]
2227    pub fn logos_seq_string(self) -> LogosSeq<String> {
2228        self.logos_seq(Value::logos_string)
2229    }
2230    #[inline]
2231    pub fn logos_seq_seq_i64(self) -> LogosSeq<LogosSeq<i64>> {
2232        self.logos_seq(Value::logos_seq_i64)
2233    }
2234    #[inline]
2235    pub fn logos_seq_seq_f64(self) -> LogosSeq<LogosSeq<f64>> {
2236        self.logos_seq(Value::logos_seq_f64)
2237    }
2238    #[inline]
2239    pub fn logos_seq_seq_bool(self) -> LogosSeq<LogosSeq<bool>> {
2240        self.logos_seq(Value::logos_seq_bool)
2241    }
2242    #[inline]
2243    pub fn logos_seq_seq_string(self) -> LogosSeq<LogosSeq<String>> {
2244        self.logos_seq(Value::logos_seq_string)
2245    }
2246}
2247
2248// NOTE: Showable impl for Value is in logicaffeine_system (io module)
2249// This crate (logicaffeine_data) has NO IO dependencies.
2250
2251// Arithmetic operations for Value
2252impl std::ops::Add for Value {
2253    type Output = Value;
2254
2255    #[inline]
2256    fn add(self, other: Value) -> Value {
2257        match (self, other) {
2258            (Value::Int(a), Value::Int(b)) => Value::Int(a + b),
2259            (Value::Float(a), Value::Float(b)) => Value::Float(a + b),
2260            (Value::Int(a), Value::Float(b)) => Value::Float(a as f64 + b),
2261            (Value::Float(a), Value::Int(b)) => Value::Float(a + b as f64),
2262            (Value::Text(a), Value::Text(b)) => Value::Text(format!("{}{}", a, b)),
2263            _ => panic!("Cannot add these value types"),
2264        }
2265    }
2266}
2267
2268impl std::ops::Sub for Value {
2269    type Output = Value;
2270
2271    #[inline]
2272    fn sub(self, other: Value) -> Value {
2273        match (self, other) {
2274            (Value::Int(a), Value::Int(b)) => Value::Int(a - b),
2275            (Value::Float(a), Value::Float(b)) => Value::Float(a - b),
2276            (Value::Int(a), Value::Float(b)) => Value::Float(a as f64 - b),
2277            (Value::Float(a), Value::Int(b)) => Value::Float(a - b as f64),
2278            _ => panic!("Cannot subtract these value types"),
2279        }
2280    }
2281}
2282
2283impl std::ops::Mul for Value {
2284    type Output = Value;
2285
2286    #[inline]
2287    fn mul(self, other: Value) -> Value {
2288        match (self, other) {
2289            (Value::Int(a), Value::Int(b)) => Value::Int(a * b),
2290            (Value::Float(a), Value::Float(b)) => Value::Float(a * b),
2291            (Value::Int(a), Value::Float(b)) => Value::Float(a as f64 * b),
2292            (Value::Float(a), Value::Int(b)) => Value::Float(a * b as f64),
2293            _ => panic!("Cannot multiply these value types"),
2294        }
2295    }
2296}
2297
2298impl std::ops::Div for Value {
2299    type Output = Value;
2300
2301    #[inline]
2302    fn div(self, other: Value) -> Value {
2303        match (self, other) {
2304            (Value::Int(a), Value::Int(b)) => Value::Int(a / b),
2305            (Value::Float(a), Value::Float(b)) => Value::Float(a / b),
2306            (Value::Int(a), Value::Float(b)) => Value::Float(a as f64 / b),
2307            (Value::Float(a), Value::Int(b)) => Value::Float(a / b as f64),
2308            _ => panic!("Cannot divide these value types"),
2309        }
2310    }
2311}
2312
2313/// Exact rational number for compiled LOGOS programs — the AOT counterpart of the
2314/// interpreter's `RuntimeValue::Rational`.
2315///
2316/// Wraps the always-reduced [`logicaffeine_base::Rational`] (a `BigInt` numerator over a
2317/// positive `BigInt` denominator) so a `Let x: Rational be 7 / 2` compiles to an exact
2318/// `7/2` instead of flooring to `3`. The type-directed `resolve_divisions` pass only ever
2319/// produces these in a `Rational`-typed context, so the integer floor default is untouched.
2320/// `Display` reduces a whole value to a bare integer (`6 / 2 → "3"`), matching the interpreter.
2321#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
2322pub struct LogosRational(pub logicaffeine_base::Rational);
2323
2324impl LogosRational {
2325    /// A whole integer as an exact rational (`5 → 5/1`, shown `5`).
2326    #[inline]
2327    pub fn from_i64(n: i64) -> Self {
2328        LogosRational(logicaffeine_base::Rational::from_i64(n))
2329    }
2330
2331    /// The exact quotient `n / d`. Panics on a zero denominator, mirroring integer `/ 0`.
2332    #[inline]
2333    pub fn from_ratio(n: i64, d: i64) -> Self {
2334        LogosRational(
2335            logicaffeine_base::Rational::from_ratio_i64(n, d)
2336                .expect(crate::failure::DIVISION_BY_ZERO),
2337        )
2338    }
2339
2340    #[inline]
2341    pub fn add(&self, other: &LogosRational) -> LogosRational {
2342        LogosRational(self.0.add(&other.0))
2343    }
2344
2345    #[inline]
2346    pub fn sub(&self, other: &LogosRational) -> LogosRational {
2347        LogosRational(self.0.sub(&other.0))
2348    }
2349
2350    #[inline]
2351    pub fn mul(&self, other: &LogosRational) -> LogosRational {
2352        LogosRational(self.0.mul(&other.0))
2353    }
2354
2355    /// Exact division. Panics on a zero divisor, mirroring integer `/ 0`.
2356    #[inline]
2357    pub fn div_exact(&self, other: &LogosRational) -> LogosRational {
2358        LogosRational(
2359            self.0
2360                .div(&other.0)
2361                .expect(crate::failure::DIVISION_BY_ZERO),
2362        )
2363    }
2364
2365    /// The exact absolute value (a rational stays a rational: `|-7/2| = 7/2`).
2366    #[inline]
2367    pub fn abs(&self) -> LogosRational {
2368        LogosRational(self.0.abs())
2369    }
2370
2371    /// The greatest integer ≤ this rational (toward −∞), computed EXACTLY on the
2372    /// BigInt numerator/denominator — never through a lossy `f64`.
2373    #[inline]
2374    pub fn floor(&self) -> i64 {
2375        self.0
2376            .floor()
2377            .to_i64()
2378            .expect("LOGOS runtime error: floor exceeds i64")
2379    }
2380
2381    /// The least integer ≥ this rational (toward +∞), computed exactly.
2382    #[inline]
2383    pub fn ceil(&self) -> i64 {
2384        self.0
2385            .ceil()
2386            .to_i64()
2387            .expect("LOGOS runtime error: ceiling exceeds i64")
2388    }
2389
2390    /// The nearest integer, ties away from zero (matching `f64::round`), computed exactly.
2391    #[inline]
2392    pub fn round(&self) -> i64 {
2393        self.0
2394            .round()
2395            .to_i64()
2396            .expect("LOGOS runtime error: round exceeds i64")
2397    }
2398
2399    /// The exact number the language holds this as: the integer it equals when it is whole, so every
2400    /// operator below takes the rule the interpreter takes for the value (a whole value the integer's).
2401    fn exact(&self) -> crate::LogosValue {
2402        crate::LogosValue::from_rational(self.0.clone())
2403    }
2404
2405    /// The rational an operator over two exact numbers answers.
2406    fn of_exact(v: crate::LogosValue) -> LogosRational {
2407        match v {
2408            crate::LogosValue::Int(n) => LogosRational::from_i64(n),
2409            crate::LogosValue::BigInt(b) => LogosRational(logicaffeine_base::Rational::from_bigint((*b).clone())),
2410            crate::LogosValue::Rational(r) => LogosRational((*r).clone()),
2411            other => unreachable!("an operator over exact numbers answered a {}", other.type_name()),
2412        }
2413    }
2414
2415    fn exact_op(
2416        &self,
2417        other: &LogosRational,
2418        op: fn(&crate::LogosValue, &crate::LogosValue) -> Result<crate::LogosValue, String>,
2419    ) -> LogosRational {
2420        LogosRational::of_exact(crate::failure::answered(op(&self.exact(), &other.exact())))
2421    }
2422
2423    fn integer_op(
2424        &self,
2425        other: &LogosRational,
2426        op: fn(&crate::LogosValue, &crate::LogosValue) -> Result<crate::LogosValue, String>,
2427    ) -> i64 {
2428        match crate::failure::answered(op(&self.exact(), &other.exact())) {
2429            crate::LogosValue::Int(n) => n,
2430            other => unreachable!("an integer operator answered a {}", other.type_name()),
2431        }
2432    }
2433
2434    /// `self / other`: two whole values truncate as integers do, and otherwise the quotient is exact.
2435    pub fn quotient(&self, other: &LogosRational) -> LogosRational {
2436        self.exact_op(other, crate::LogosValue::div)
2437    }
2438
2439    /// `self % other`: the remainder of two whole values, its sign the dividend's; a fraction has none.
2440    pub fn remainder(&self, other: &LogosRational) -> LogosRational {
2441        self.exact_op(other, crate::LogosValue::rem)
2442    }
2443
2444    /// `self // other`: the floor of the exact quotient.
2445    pub fn floor_quotient(&self, other: &LogosRational) -> LogosRational {
2446        self.exact_op(other, crate::LogosValue::floor_div)
2447    }
2448
2449    /// `self ** other`: a whole base takes an integer's power, a fraction a rational's.
2450    pub fn power(&self, other: &LogosRational) -> LogosRational {
2451        self.exact_op(other, crate::LogosValue::pow)
2452    }
2453
2454    /// `self & other` of two whole values.
2455    pub fn bit_and(&self, other: &LogosRational) -> i64 {
2456        self.integer_op(other, crate::LogosValue::bit_and)
2457    }
2458
2459    /// `self | other` of two whole values.
2460    pub fn bit_or(&self, other: &LogosRational) -> i64 {
2461        self.integer_op(other, crate::LogosValue::bit_or)
2462    }
2463
2464    /// `self ^ other` of two whole values.
2465    pub fn bit_xor(&self, other: &LogosRational) -> i64 {
2466        self.integer_op(other, crate::LogosValue::bit_xor)
2467    }
2468
2469    /// `self << other` of two whole values.
2470    pub fn shl(&self, other: &LogosRational) -> i64 {
2471        self.integer_op(other, crate::LogosValue::shl)
2472    }
2473
2474    /// `self >> other` of two whole values.
2475    pub fn shr(&self, other: &LogosRational) -> i64 {
2476        self.integer_op(other, crate::LogosValue::shr)
2477    }
2478
2479    /// The real the language computes with where this meets one.
2480    #[inline]
2481    pub fn to_f64(&self) -> f64 {
2482        self.0.to_f64()
2483    }
2484
2485    /// How this compares with the real `other`, by that real's exact value; `None` against NaN.
2486    #[inline]
2487    pub fn order_real(&self, other: f64) -> Option<std::cmp::Ordering> {
2488        logicaffeine_base::numeric::cmp_rational_f64_exact(&self.0, other)
2489    }
2490
2491    /// The machine integer this is where the language takes one (an index, a bound): stopped with
2492    /// `past_word` when it is whole but outside `i64`, and with `fraction` when it is not whole.
2493    pub fn integer(&self, past_word: &str, fraction: &str) -> i64 {
2494        if !self.0.is_integer() {
2495            return crate::failure::answered(Err(fraction.to_string()));
2496        }
2497        match self.0.to_bigint().and_then(|b| b.to_i64()) {
2498            Some(n) => n,
2499            None => crate::failure::answered(Err(past_word.to_string())),
2500        }
2501    }
2502}
2503
2504impl std::fmt::Display for LogosRational {
2505    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2506        std::fmt::Display::fmt(&self.0, f)
2507    }
2508}
2509
2510impl From<i64> for LogosRational {
2511    #[inline]
2512    fn from(n: i64) -> Self {
2513        LogosRational::from_i64(n)
2514    }
2515}
2516
2517/// The placeholder `#[derive(Default)]` on a record needs. The language holds nothing in a rational field a record is
2518/// built without, which a `LogosRational` cannot hold, so a compiled construction that leaves one unset is refused
2519/// and this value is never observed.
2520impl Default for LogosRational {
2521    fn default() -> Self {
2522        LogosRational::from_i64(0)
2523    }
2524}
2525
2526impl From<LogosInt> for LogosRational {
2527    #[inline]
2528    fn from(n: LogosInt) -> Self {
2529        match n {
2530            LogosInt::Small(n) => LogosRational::from_i64(n),
2531            LogosInt::Big(b) => LogosRational(logicaffeine_base::Rational::from_bigint(*b)),
2532        }
2533    }
2534}
2535
2536/// A value of integers held where the language holds rationals: an integer as the rational it equals, a list item
2537/// by item, at any depth.
2538pub trait ToRationals {
2539    /// The same value with each integer a rational.
2540    type Rationals;
2541    fn to_rationals(&self) -> Self::Rationals;
2542}
2543
2544impl ToRationals for i64 {
2545    type Rationals = LogosRational;
2546    #[inline]
2547    fn to_rationals(&self) -> LogosRational {
2548        LogosRational::from_i64(*self)
2549    }
2550}
2551
2552impl ToRationals for LogosRational {
2553    type Rationals = LogosRational;
2554    #[inline]
2555    fn to_rationals(&self) -> LogosRational {
2556        self.clone()
2557    }
2558}
2559
2560impl<T: ToRationals> ToRationals for [T] {
2561    type Rationals = LogosSeq<T::Rationals>;
2562    fn to_rationals(&self) -> LogosSeq<T::Rationals> {
2563        LogosSeq::from_vec(self.iter().map(ToRationals::to_rationals).collect())
2564    }
2565}
2566
2567impl<T: ToRationals> ToRationals for Vec<T> {
2568    type Rationals = LogosSeq<T::Rationals>;
2569    fn to_rationals(&self) -> LogosSeq<T::Rationals> {
2570        self.as_slice().to_rationals()
2571    }
2572}
2573
2574impl<T: ToRationals> ToRationals for LogosSeq<T> {
2575    type Rationals = LogosSeq<T::Rationals>;
2576    fn to_rationals(&self) -> LogosSeq<T::Rationals> {
2577        self.0.borrow().as_slice().to_rationals()
2578    }
2579}
2580
2581// Arithmetic OPERATORS so codegen can emit `a + b` for rationals (a `decimal ÷` widens to
2582// `LogosRational`, and a following `+`/`−`/`×` composed raw would otherwise be E0369). They delegate
2583// to the wrapped exact `Rational`, so they stay byte-identical to `.add()`/`.sub()`/`.mul()`. `/`
2584// panics on a zero divisor, mirroring integer `/ 0`.
2585impl std::ops::Add for LogosRational {
2586    type Output = LogosRational;
2587    #[inline]
2588    fn add(self, other: LogosRational) -> LogosRational {
2589        LogosRational(self.0.add(&other.0))
2590    }
2591}
2592impl std::ops::Sub for LogosRational {
2593    type Output = LogosRational;
2594    #[inline]
2595    fn sub(self, other: LogosRational) -> LogosRational {
2596        LogosRational(self.0.sub(&other.0))
2597    }
2598}
2599impl std::ops::Mul for LogosRational {
2600    type Output = LogosRational;
2601    #[inline]
2602    fn mul(self, other: LogosRational) -> LogosRational {
2603        LogosRational(self.0.mul(&other.0))
2604    }
2605}
2606impl std::ops::Div for LogosRational {
2607    type Output = LogosRational;
2608    #[inline]
2609    fn div(self, other: LogosRational) -> LogosRational {
2610        LogosRational(
2611            self.0
2612                .div(&other.0)
2613                .expect(crate::failure::DIVISION_BY_ZERO),
2614        )
2615    }
2616}
2617
2618/// An exact base-10 fixed-point number — money's runtime type on the compiled-to-Rust
2619/// path, the AOT mirror of the interpreter's `Decimal`. `decimal("19.99")` compiles to
2620/// `LogosDecimal::parse("19.99")`; `+ − ×` stay exact `Decimal` (scale preserved), and `÷`
2621/// widens to the exact `LogosRational` (base-10 division need not terminate). `Display`
2622/// shows the scale faithfully (`19.99`, `20.00`), matching the interpreter.
2623#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
2624pub struct LogosDecimal(pub logicaffeine_base::Decimal);
2625
2626/// A value `decimal(…)` takes: Text is read as a base-10 number, an Int widens exactly, a Decimal is
2627/// itself, and any other kind stops the program with [`crate::failure::decimal_needs_text_or_int`],
2628/// naming it as the engines do.
2629pub trait DecimalArg {
2630    fn into_decimal(self) -> LogosDecimal;
2631}
2632
2633impl DecimalArg for &str {
2634    fn into_decimal(self) -> LogosDecimal {
2635        LogosDecimal::parse(self)
2636    }
2637}
2638
2639impl DecimalArg for String {
2640    fn into_decimal(self) -> LogosDecimal {
2641        LogosDecimal::parse(&self)
2642    }
2643}
2644
2645impl DecimalArg for &String {
2646    fn into_decimal(self) -> LogosDecimal {
2647        LogosDecimal::parse(self)
2648    }
2649}
2650
2651impl DecimalArg for i64 {
2652    fn into_decimal(self) -> LogosDecimal {
2653        LogosDecimal::from_i64(self)
2654    }
2655}
2656
2657impl DecimalArg for LogosInt {
2658    fn into_decimal(self) -> LogosDecimal {
2659        match self {
2660            LogosInt::Small(n) => LogosDecimal::from_i64(n),
2661            LogosInt::Big(b) => LogosDecimal::parse(&b.to_string()),
2662        }
2663    }
2664}
2665
2666impl DecimalArg for LogosDecimal {
2667    fn into_decimal(self) -> LogosDecimal {
2668        self
2669    }
2670}
2671
2672impl DecimalArg for &LogosDecimal {
2673    fn into_decimal(self) -> LogosDecimal {
2674        self.clone()
2675    }
2676}
2677
2678impl DecimalArg for f64 {
2679    fn into_decimal(self) -> LogosDecimal {
2680        panic!("{}", crate::failure::decimal_needs_text_or_int("Float"))
2681    }
2682}
2683
2684impl DecimalArg for bool {
2685    fn into_decimal(self) -> LogosDecimal {
2686        panic!("{}", crate::failure::decimal_needs_text_or_int("Bool"))
2687    }
2688}
2689
2690impl DecimalArg for char {
2691    fn into_decimal(self) -> LogosDecimal {
2692        panic!("{}", crate::failure::decimal_needs_text_or_int("Char"))
2693    }
2694}
2695
2696/// `decimal(v)`: see [`DecimalArg`].
2697pub fn decimal_of(v: impl DecimalArg) -> LogosDecimal {
2698    v.into_decimal()
2699}
2700
2701impl LogosDecimal {
2702    /// A whole integer as a scale-0 decimal (`5 → "5"`).
2703    #[inline]
2704    pub fn from_i64(n: i64) -> Self {
2705        LogosDecimal(logicaffeine_base::Decimal::from_i64(n))
2706    }
2707
2708    /// The exact value `decimal(text)` names: the text, surrounding whitespace aside, read as a
2709    /// base-10 number (`"19.99"`; [`logicaffeine_base::Decimal::parse`] owns the rule). Any other text
2710    /// stops the program with [`crate::failure::not_a_decimal`], as on every tier.
2711    #[inline]
2712    pub fn parse(s: &str) -> Self {
2713        match logicaffeine_base::Decimal::parse(s) {
2714            Some(d) => LogosDecimal(d),
2715            None => panic!("{}", crate::failure::not_a_decimal(s)),
2716        }
2717    }
2718
2719    #[inline]
2720    pub fn add(&self, other: &LogosDecimal) -> LogosDecimal {
2721        LogosDecimal(self.0.add(&other.0))
2722    }
2723
2724    #[inline]
2725    pub fn sub(&self, other: &LogosDecimal) -> LogosDecimal {
2726        LogosDecimal(self.0.sub(&other.0))
2727    }
2728
2729    #[inline]
2730    pub fn mul(&self, other: &LogosDecimal) -> LogosDecimal {
2731        LogosDecimal(self.0.mul(&other.0))
2732    }
2733
2734    /// The exact rational view (`coeff / 10^scale`) — the bridge `÷` widens through.
2735    #[inline]
2736    pub fn to_rational(&self) -> LogosRational {
2737        LogosRational(self.0.to_rational())
2738    }
2739
2740    /// Exact division, widening to a `LogosRational` (base-10 division need not terminate).
2741    /// Panics on a zero divisor, mirroring integer `/ 0`.
2742    #[inline]
2743    pub fn div_exact(&self, other: &LogosDecimal) -> LogosRational {
2744        self.to_rational().div_exact(&other.to_rational())
2745    }
2746
2747    /// The exact absolute value (scale preserved).
2748    #[inline]
2749    pub fn abs(&self) -> LogosDecimal {
2750        LogosDecimal(self.0.abs())
2751    }
2752}
2753
2754impl std::fmt::Display for LogosDecimal {
2755    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2756        std::fmt::Display::fmt(&self.0, f)
2757    }
2758}
2759
2760impl From<i64> for LogosDecimal {
2761    #[inline]
2762    fn from(n: i64) -> Self {
2763        LogosDecimal::from_i64(n)
2764    }
2765}
2766
2767/// An exact complex number `re + im·i` — the AOT mirror of the interpreter's `Complex`.
2768/// `complex(0, 1)` compiles to `LogosComplex::new(..)`; `+ − × ÷` stay exact and closed
2769/// (`i·i = −1`). NOT ordered. `Display` shows `3+4i` / `i` / `-2i`, matching the interpreter.
2770#[derive(Clone, Debug, PartialEq, Eq, Hash)]
2771pub struct LogosComplex(pub logicaffeine_base::Complex);
2772
2773impl LogosComplex {
2774    /// A real integer as `re + 0i`.
2775    #[inline]
2776    pub fn from_i64(n: i64) -> Self {
2777        LogosComplex(logicaffeine_base::Complex::from_i64(n))
2778    }
2779
2780    /// `re + im·i` from two exact rationals.
2781    #[inline]
2782    pub fn new(re: LogosRational, im: LogosRational) -> Self {
2783        LogosComplex(logicaffeine_base::Complex::new(re.0, im.0))
2784    }
2785
2786    #[inline]
2787    pub fn add(&self, other: &LogosComplex) -> LogosComplex {
2788        LogosComplex(self.0.add(&other.0))
2789    }
2790
2791    #[inline]
2792    pub fn sub(&self, other: &LogosComplex) -> LogosComplex {
2793        LogosComplex(self.0.sub(&other.0))
2794    }
2795
2796    #[inline]
2797    pub fn mul(&self, other: &LogosComplex) -> LogosComplex {
2798        LogosComplex(self.0.mul(&other.0))
2799    }
2800
2801    /// Exact division (the complex field is closed). Panics on a zero divisor, mirroring `/ 0`.
2802    #[inline]
2803    pub fn div_exact(&self, other: &LogosComplex) -> LogosComplex {
2804        LogosComplex(
2805            self.0
2806                .div(&other.0)
2807                .expect(crate::failure::DIVISION_BY_ZERO),
2808        )
2809    }
2810
2811    /// The complex conjugate `re − im·i` — stays exact. The Hermitian-transpose primitive.
2812    #[inline]
2813    pub fn conjugate(&self) -> LogosComplex {
2814        LogosComplex(self.0.conjugate())
2815    }
2816    /// The real part as an `f64` (`re(z)`).
2817    #[inline]
2818    pub fn re(&self) -> f64 {
2819        self.0.re().to_f64()
2820    }
2821    /// The imaginary part as an `f64` (`im(z)`).
2822    #[inline]
2823    pub fn im(&self) -> f64 {
2824        self.0.im().to_f64()
2825    }
2826    /// The modulus `|z| = √(re² + im²)` as an `f64` — delegates to the wrapped `Complex`, so it is
2827    /// byte-identical to the interpreter's `abs(Complex)` (`RuntimeValue::Float(c.abs_f64())`).
2828    #[inline]
2829    pub fn abs_f64(&self) -> f64 {
2830        self.0.abs_f64()
2831    }
2832}
2833
2834impl std::fmt::Display for LogosComplex {
2835    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2836        std::fmt::Display::fmt(&self.0, f)
2837    }
2838}
2839
2840impl From<i64> for LogosComplex {
2841    #[inline]
2842    fn from(n: i64) -> Self {
2843        LogosComplex::from_i64(n)
2844    }
2845}
2846
2847/// A floating-point complex `re + im·i` (each part `f64`) — the AOT mirror of the interpreter's
2848/// `ComplexF` (LAPACK `Z`). `complex(3.0, 4.0)` compiles to `LogosComplexF::new(..)`; `+ − × ÷` and
2849/// `sqrt` are inexact `f64` (the reason it exists over the exact `LogosComplex`). NOT ordered.
2850/// `Display` matches the interpreter (`2+i`, `4+6i`) via `fmt_f64`.
2851#[derive(Clone, Copy, Debug, PartialEq)]
2852pub struct LogosComplexF(pub logicaffeine_base::ComplexF);
2853
2854impl LogosComplexF {
2855    /// A real `f64` as `re + 0i`.
2856    #[inline]
2857    pub fn from_f64(re: f64) -> Self {
2858        LogosComplexF(logicaffeine_base::ComplexF::from_f64(re))
2859    }
2860    /// `re + im·i` from two `f64`s.
2861    #[inline]
2862    pub fn new(re: f64, im: f64) -> Self {
2863        LogosComplexF(logicaffeine_base::ComplexF::new(re, im))
2864    }
2865    #[inline]
2866    pub fn add(&self, other: &LogosComplexF) -> LogosComplexF {
2867        LogosComplexF(self.0.add(&other.0))
2868    }
2869    #[inline]
2870    pub fn sub(&self, other: &LogosComplexF) -> LogosComplexF {
2871        LogosComplexF(self.0.sub(&other.0))
2872    }
2873    #[inline]
2874    pub fn mul(&self, other: &LogosComplexF) -> LogosComplexF {
2875        LogosComplexF(self.0.mul(&other.0))
2876    }
2877    /// Division; panics on a zero divisor, mirroring `/ 0`.
2878    #[inline]
2879    pub fn div_exact(&self, other: &LogosComplexF) -> LogosComplexF {
2880        LogosComplexF(
2881            self.0
2882                .div(&other.0)
2883                .expect(crate::failure::DIVISION_BY_ZERO),
2884        )
2885    }
2886    /// The principal square root (via the real `sqrt`) — the operation the exact `LogosComplex` lacks.
2887    #[inline]
2888    pub fn sqrt(&self) -> LogosComplexF {
2889        LogosComplexF(self.0.sqrt())
2890    }
2891    #[inline]
2892    pub fn conjugate(&self) -> LogosComplexF {
2893        LogosComplexF(self.0.conjugate())
2894    }
2895    #[inline]
2896    pub fn abs(&self) -> f64 {
2897        self.0.abs()
2898    }
2899    /// The real part as an `f64` (`re(z)`).
2900    #[inline]
2901    pub fn re(&self) -> f64 {
2902        self.0.re()
2903    }
2904    /// The imaginary part as an `f64` (`im(z)`).
2905    #[inline]
2906    pub fn im(&self) -> f64 {
2907        self.0.im()
2908    }
2909}
2910
2911impl std::fmt::Display for LogosComplexF {
2912    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2913        // Match the interpreter's `ComplexF` display: `fmt_f64` parts with the unit coefficient omitted.
2914        let (re, im) = (self.0.re(), self.0.im());
2915        let g = crate::fmt::fmt_f64;
2916        if im == 0.0 {
2917            return write!(f, "{}", g(re));
2918        }
2919        let mag = im.abs();
2920        let icoef = if mag == 1.0 { String::new() } else { g(mag) };
2921        if re == 0.0 {
2922            write!(f, "{}{}i", if im < 0.0 { "-" } else { "" }, icoef)
2923        } else {
2924            write!(f, "{}{}{}i", g(re), if im < 0.0 { "-" } else { "+" }, icoef)
2925        }
2926    }
2927}
2928
2929impl From<f64> for LogosComplexF {
2930    #[inline]
2931    fn from(re: f64) -> Self {
2932        LogosComplexF::from_f64(re)
2933    }
2934}
2935
2936/// An element of the ring ℤ/nℤ — the AOT mirror of the interpreter's `Modular`.
2937/// `modular(value, modulus)` compiles to `LogosModular::new(..)`; `+ − ×` wrap in the ring,
2938/// `pow` is fast modular exponentiation, and `÷` multiplies by the modular inverse. NOT ordered.
2939#[derive(Clone, Debug, PartialEq, Eq, Hash)]
2940pub struct LogosModular(pub logicaffeine_base::Modular);
2941
2942impl LogosModular {
2943    /// `value mod modulus`. Panics on a non-positive modulus (a LOGOS runtime error).
2944    #[inline]
2945    pub fn new(value: i64, modulus: i64) -> Self {
2946        LogosModular(
2947            logicaffeine_base::Modular::from_i64(value, modulus)
2948                .unwrap_or_else(|| panic!("{}", crate::failure::MODULUS_NOT_POSITIVE)),
2949        )
2950    }
2951
2952    #[inline]
2953    pub fn add(&self, other: &LogosModular) -> LogosModular {
2954        LogosModular(
2955            self.0
2956                .add(&other.0)
2957                .unwrap_or_else(|| panic!("{}", crate::failure::modular_rings_differ("add"))),
2958        )
2959    }
2960
2961    #[inline]
2962    pub fn sub(&self, other: &LogosModular) -> LogosModular {
2963        LogosModular(
2964            self.0
2965                .sub(&other.0)
2966                .unwrap_or_else(|| panic!("{}", crate::failure::modular_rings_differ("subtract"))),
2967        )
2968    }
2969
2970    #[inline]
2971    pub fn mul(&self, other: &LogosModular) -> LogosModular {
2972        LogosModular(
2973            self.0
2974                .mul(&other.0)
2975                .unwrap_or_else(|| panic!("{}", crate::failure::modular_rings_differ("multiply"))),
2976        )
2977    }
2978
2979    /// Division by the modular inverse. Stops the program when the moduli differ or the divisor is not
2980    /// coprime to the modulus.
2981    #[inline]
2982    pub fn div_exact(&self, other: &LogosModular) -> LogosModular {
2983        if self.0.modulus() != other.0.modulus() {
2984            panic!("{}", crate::failure::modular_rings_differ("divide"));
2985        }
2986        LogosModular(
2987            self.0
2988                .div(&other.0)
2989                .unwrap_or_else(|| panic!("{}", crate::failure::NO_MODULAR_INVERSE)),
2990        )
2991    }
2992
2993    /// Fast modular exponentiation `self^exp`.
2994    #[inline]
2995    pub fn pow(&self, exp: u64) -> LogosModular {
2996        LogosModular(self.0.pow(exp))
2997    }
2998}
2999
3000impl std::fmt::Display for LogosModular {
3001    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3002        std::fmt::Display::fmt(&self.0, f)
3003    }
3004}
3005
3006/// A physical quantity on the compiled-to-Rust path — the AOT mirror of the interpreter's
3007/// `Quantity` value. The magnitude rides the exact rational tower (no float drift) and the display
3008/// unit travels with it so `Show` renders faithfully (`42/127 ft`). `+ −` require the same
3009/// dimension — the front-end's type checker proves this, so a mismatch is a *compile* error, not a
3010/// runtime one; the runtime check here is a defensive backstop. `× ÷` combine dimensions, and a
3011/// quantity may be scaled by a dimensionless number (unit preserved).
3012#[derive(Clone, Debug)]
3013pub struct LogosQuantity {
3014    pub q: logicaffeine_base::Quantity,
3015    pub unit: logicaffeine_base::Unit,
3016}
3017
3018impl LogosQuantity {
3019    /// `value` of the named unit (`LogosQuantity::of(2, "inch")`).
3020    #[inline]
3021    pub fn of(value: i64, unit_name: &str) -> Self {
3022        Self::from_rational(LogosRational::from_i64(value), unit_name)
3023    }
3024
3025    /// An exact-rational magnitude of the named unit. Panics on an unknown unit, which the
3026    /// front-end has already rejected before codegen.
3027    pub fn from_rational(value: LogosRational, unit_name: &str) -> Self {
3028        let unit = logicaffeine_base::quantity::units::by_name(unit_name)
3029            .unwrap_or_else(|| panic!("{}", crate::failure::unknown_unit(unit_name)));
3030        LogosQuantity {
3031            q: logicaffeine_base::Quantity::of(value.0, &unit),
3032            unit,
3033        }
3034    }
3035
3036    #[inline]
3037    pub fn add(&self, other: &LogosQuantity) -> LogosQuantity {
3038        let q = self.q.add(&other.q).unwrap_or_else(|| {
3039            panic!(
3040                "{}",
3041                crate::failure::quantities_differ("add", self.q.dimension(), other.q.dimension())
3042            )
3043        });
3044        LogosQuantity {
3045            q,
3046            unit: self.unit.clone(),
3047        }
3048    }
3049
3050    #[inline]
3051    pub fn sub(&self, other: &LogosQuantity) -> LogosQuantity {
3052        let q = self.q.sub(&other.q).unwrap_or_else(|| {
3053            panic!(
3054                "{}",
3055                crate::failure::quantities_differ(
3056                    "subtract",
3057                    self.q.dimension(),
3058                    other.q.dimension()
3059                )
3060            )
3061        });
3062        LogosQuantity {
3063            q,
3064            unit: self.unit.clone(),
3065        }
3066    }
3067
3068    /// `× ÷` combine dimensions; the result is shown in SI/dimension form (empty display unit).
3069    #[inline]
3070    pub fn mul(&self, other: &LogosQuantity) -> LogosQuantity {
3071        let q = self.q.mul(&other.q);
3072        let unit = Self::si_unit(&q);
3073        LogosQuantity { q, unit }
3074    }
3075
3076    #[inline]
3077    pub fn div_exact(&self, other: &LogosQuantity) -> LogosQuantity {
3078        let q = self
3079            .q
3080            .div(&other.q)
3081            .unwrap_or_else(|| panic!("{}", crate::failure::DIVIDE_BY_ZERO_QUANTITY));
3082        let unit = Self::si_unit(&q);
3083        LogosQuantity { q, unit }
3084    }
3085
3086    /// Scale by a dimensionless number (unit preserved): `q * k`.
3087    #[inline]
3088    pub fn scale(&self, k: &LogosRational) -> LogosQuantity {
3089        let mag = self.q.magnitude_si().mul(&k.0);
3090        LogosQuantity {
3091            q: logicaffeine_base::Quantity::si(mag, self.q.dimension()),
3092            unit: self.unit.clone(),
3093        }
3094    }
3095
3096    /// Scale by a dimensionless integer (unit preserved) — the common `q * 3` case from codegen.
3097    #[inline]
3098    pub fn scale_int(&self, k: i64) -> LogosQuantity {
3099        self.scale(&LogosRational::from_i64(k))
3100    }
3101
3102    /// Divide by a dimensionless integer (unit preserved) — the common `q / 2` case from codegen.
3103    #[inline]
3104    pub fn div_int(&self, k: i64) -> LogosQuantity {
3105        self.div_scalar(&LogosRational::from_i64(k))
3106    }
3107
3108    /// Divide by a dimensionless number (unit preserved): `q / k`.
3109    #[inline]
3110    pub fn div_scalar(&self, k: &LogosRational) -> LogosQuantity {
3111        let mag = self
3112            .q
3113            .magnitude_si()
3114            .div(&k.0)
3115            .unwrap_or_else(|| panic!("{}", crate::failure::DIVIDE_QUANTITY_BY_ZERO));
3116        LogosQuantity {
3117            q: logicaffeine_base::Quantity::si(mag, self.q.dimension()),
3118            unit: self.unit.clone(),
3119        }
3120    }
3121
3122    /// Re-express in another unit of the SAME dimension. A different dimension is the forbidden
3123    /// cast — the type checker rejects it, so this panic is a defensive backstop.
3124    pub fn convert(&self, unit_name: &str) -> LogosQuantity {
3125        let unit = logicaffeine_base::quantity::units::by_name(unit_name)
3126            .unwrap_or_else(|| panic!("{}", crate::failure::unknown_unit(unit_name)));
3127        if self.q.dimension() != unit.dimension {
3128            panic!(
3129                "{}",
3130                crate::failure::cannot_convert(&self.unit.symbol, &unit.symbol)
3131            );
3132        }
3133        LogosQuantity {
3134            q: self.q.clone(),
3135            unit,
3136        }
3137    }
3138
3139    /// A synthetic SI-base unit (empty symbol) for a combined dimension.
3140    fn si_unit(q: &logicaffeine_base::Quantity) -> logicaffeine_base::Unit {
3141        logicaffeine_base::Unit::linear("", q.dimension(), logicaffeine_base::Rational::one())
3142    }
3143}
3144
3145// Equality is PHYSICAL (SI magnitude + dimension); the display unit is presentation only, so
3146// `100 cm` equals `1 m`. Ordering is by magnitude within a shared dimension (the type checker
3147// guarantees comparisons are same-dimension).
3148impl PartialEq for LogosQuantity {
3149    fn eq(&self, other: &Self) -> bool {
3150        self.q == other.q
3151    }
3152}
3153impl Eq for LogosQuantity {}
3154
3155impl PartialOrd for LogosQuantity {
3156    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
3157        if self.q.dimension() != other.q.dimension() {
3158            return None;
3159        }
3160        self.q.magnitude_si().partial_cmp(other.q.magnitude_si())
3161    }
3162}
3163
3164impl std::fmt::Display for LogosQuantity {
3165    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3166        let magnitude = self
3167            .q
3168            .in_unit(&self.unit)
3169            .expect("a Quantity's display unit always shares its dimension");
3170        if self.unit.symbol.is_empty() {
3171            write!(f, "{} {}", magnitude, self.q.dimension())
3172        } else {
3173            write!(f, "{} {}", magnitude, self.unit.symbol)
3174        }
3175    }
3176}
3177
3178/// Money for the compiled tier — an exact amount in a currency, mirroring `base::Money`. `+ −`
3179/// require the SAME currency (a runtime-panic backstop; the type checker rejects mismatches first),
3180/// `× ÷` scale by an exact number, and a same-currency `÷` is the dimensionless ratio.
3181#[derive(Clone, Debug)]
3182pub struct LogosMoney(pub logicaffeine_base::Money);
3183
3184// `Default` for the exact value types — required so a user struct with a value-type field can
3185// `#[derive(Default)]` (the AOT-Rust struct codegen always derives Default and constructs via
3186// `Struct { field: v, ..Default::default() }`, which needs Default even when every field is given).
3187// These are zero/nil/dimensionless placeholders, only ever materialized for an UNINITIALIZED field
3188// (which the construction immediately overwrites), so the degenerate currency/modulus/unit is never observed.
3189impl Default for LogosDecimal {
3190    fn default() -> Self {
3191        LogosDecimal(logicaffeine_base::Decimal::zero())
3192    }
3193}
3194impl Default for LogosComplex {
3195    fn default() -> Self {
3196        LogosComplex(logicaffeine_base::Complex::zero())
3197    }
3198}
3199impl Default for LogosModular {
3200    fn default() -> Self {
3201        LogosModular(
3202            logicaffeine_base::Modular::from_i64(0, 1).expect("0 mod 1 is a valid modular value"),
3203        )
3204    }
3205}
3206impl Default for LogosUuid {
3207    fn default() -> Self {
3208        LogosUuid(logicaffeine_base::Uuid::NIL)
3209    }
3210}
3211impl Default for LogosMoney {
3212    fn default() -> Self {
3213        LogosMoney::from_i64(0, "USD")
3214    }
3215}
3216impl Default for LogosQuantity {
3217    fn default() -> Self {
3218        LogosQuantity {
3219            q: logicaffeine_base::Quantity::scalar(logicaffeine_base::Rational::zero()),
3220            unit: logicaffeine_base::Unit::linear(
3221                "",
3222                logicaffeine_base::Dimension::DIMENSIONLESS,
3223                logicaffeine_base::Rational::one(),
3224            ),
3225        }
3226    }
3227}
3228
3229impl LogosMoney {
3230    /// Money of a `Decimal` amount in the named currency. Panics on an unknown currency, which the
3231    /// front-end has already rejected before codegen.
3232    pub fn of(amount: LogosDecimal, code: &str) -> Self {
3233        let currency = logicaffeine_base::money::currency::by_code(code)
3234            .unwrap_or_else(|| panic!("{}", crate::failure::unknown_currency(code)));
3235        LogosMoney(logicaffeine_base::Money::of(amount.0, currency))
3236    }
3237
3238    /// Money of an integer amount — the `5 USD` case (codegen passes the literal directly).
3239    pub fn from_i64(amount: i64, code: &str) -> Self {
3240        Self::of(
3241            LogosDecimal(logicaffeine_base::Decimal::from_i64(amount)),
3242            code,
3243        )
3244    }
3245
3246    #[inline]
3247    pub fn add(&self, other: &LogosMoney) -> LogosMoney {
3248        LogosMoney(self.0.add(&other.0).unwrap_or_else(|| {
3249            panic!(
3250                "{}",
3251                crate::failure::currencies_differ(
3252                    "add",
3253                    self.0.currency.code,
3254                    other.0.currency.code
3255                )
3256            )
3257        }))
3258    }
3259
3260    #[inline]
3261    pub fn sub(&self, other: &LogosMoney) -> LogosMoney {
3262        LogosMoney(self.0.sub(&other.0).unwrap_or_else(|| {
3263            panic!(
3264                "{}",
3265                crate::failure::currencies_differ(
3266                    "subtract",
3267                    self.0.currency.code,
3268                    other.0.currency.code
3269                )
3270            )
3271        }))
3272    }
3273
3274    /// Scale by an integer (`19.99 USD × 3`), re-quantised to the currency.
3275    #[inline]
3276    pub fn scale_int(&self, k: i64) -> LogosMoney {
3277        LogosMoney(self.0.scale_int(k))
3278    }
3279
3280    /// Scale by an exact decimal (`price × 1.5`), re-quantised to the currency.
3281    #[inline]
3282    pub fn scale_decimal(&self, k: &LogosDecimal) -> LogosMoney {
3283        LogosMoney(logicaffeine_base::Money::of(
3284            self.0.amount.mul(&k.0),
3285            self.0.currency,
3286        ))
3287    }
3288
3289    /// Divide by an integer (split a bill), re-quantised to the currency.
3290    #[inline]
3291    pub fn div_int(&self, k: i64) -> LogosMoney {
3292        let d = self
3293            .0
3294            .amount
3295            .div(
3296                &logicaffeine_base::Decimal::from_i64(k),
3297                self.0.currency.scale,
3298                logicaffeine_base::RoundingMode::HalfEven,
3299            )
3300            .unwrap_or_else(|| panic!("{}", crate::failure::DIVIDE_MONEY_BY_ZERO));
3301        LogosMoney(logicaffeine_base::Money::of(d, self.0.currency))
3302    }
3303
3304    /// The exact dimensionless ratio of two same-currency amounts.
3305    #[inline]
3306    pub fn ratio(&self, other: &LogosMoney) -> LogosRational {
3307        match self.0.ratio(&other.0) {
3308            Some(r) => LogosRational(r),
3309            None if self.0.currency != other.0.currency => panic!(
3310                "{}",
3311                crate::failure::currencies_differ(
3312                    "compare",
3313                    self.0.currency.code,
3314                    other.0.currency.code
3315                )
3316            ),
3317            None => panic!("{}", crate::failure::DIVIDE_MONEY_BY_ZERO_AMOUNT),
3318        }
3319    }
3320}
3321
3322impl PartialEq for LogosMoney {
3323    fn eq(&self, other: &Self) -> bool {
3324        self.0 == other.0
3325    }
3326}
3327impl Eq for LogosMoney {}
3328
3329impl PartialOrd for LogosMoney {
3330    /// Ordered by amount within a currency; across currencies it is incomparable (`None`).
3331    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
3332        if self.0.currency != other.0.currency {
3333            return None;
3334        }
3335        self.0
3336            .amount
3337            .to_rational()
3338            .partial_cmp(&other.0.amount.to_rational())
3339    }
3340}
3341
3342impl std::fmt::Display for LogosMoney {
3343    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3344        write!(f, "{}", self.0)
3345    }
3346}
3347
3348/// A 128-bit UUID for the compiled tier (RFC 9562), mirroring `logicaffeine_base::Uuid`. A `Copy` newtype over
3349/// `[u8; 16]` — no allocation, byte-ordered comparison (so v6/v7 sort by time), canonical text form.
3350#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
3351pub struct LogosUuid(pub logicaffeine_base::Uuid);
3352
3353impl LogosUuid {
3354    /// Parse from canonical/simple/braced/urn text. Panics on a malformed id (the front-end has
3355    /// already validated literal forms; a runtime parse of bad data is a clean program error).
3356    pub fn parse(s: &str) -> Self {
3357        LogosUuid(
3358            logicaffeine_base::Uuid::parse(s)
3359                .unwrap_or_else(|| panic!("{}", crate::failure::invalid_uuid(s))),
3360        )
3361    }
3362    /// The nil (all-zero) UUID.
3363    pub fn nil() -> Self {
3364        LogosUuid(logicaffeine_base::Uuid::NIL)
3365    }
3366    /// The max (all-one) UUID.
3367    pub fn max() -> Self {
3368        LogosUuid(logicaffeine_base::Uuid::MAX)
3369    }
3370    /// The version nibble (0 for nil, 1–8 for the defined versions, 15 for max).
3371    pub fn version(&self) -> i64 {
3372        self.0.version() as i64
3373    }
3374    /// The well-known DNS / URL / OID / X.500 namespaces.
3375    pub fn namespace_dns() -> Self {
3376        LogosUuid(logicaffeine_base::Uuid::NAMESPACE_DNS)
3377    }
3378    pub fn namespace_url() -> Self {
3379        LogosUuid(logicaffeine_base::Uuid::NAMESPACE_URL)
3380    }
3381    pub fn namespace_oid() -> Self {
3382        LogosUuid(logicaffeine_base::Uuid::NAMESPACE_OID)
3383    }
3384    pub fn namespace_x500() -> Self {
3385        LogosUuid(logicaffeine_base::Uuid::NAMESPACE_X500)
3386    }
3387}
3388
3389impl LogosUuid {
3390    /// The UUID's 16 bytes as a `Seq of Int` — the byte view the Logos-written version constructors
3391    /// (uuid.lg) prepend as the namespace.
3392    pub fn byte_seq(&self) -> LogosSeq<i64> {
3393        LogosSeq::from_vec(self.0.as_bytes().iter().map(|&b| b as i64).collect())
3394    }
3395    /// Build a UUID from the first 16 bytes of a `Seq of Int` (the compiled mirror of the
3396    /// `uuid_from_bytes` builtin). Panics on fewer than 16 bytes — the front-end feeds a digest.
3397    pub fn from_byte_seq(seq: &LogosSeq<i64>) -> LogosUuid {
3398        let v = seq.0.borrow();
3399        if v.len() < 16 {
3400            panic!("{}", crate::failure::uuid_needs_16_bytes(v.len()));
3401        }
3402        let mut b = [0u8; 16];
3403        for (i, slot) in b.iter_mut().enumerate() {
3404            *slot = (v[i] & 0xff) as u8;
3405        }
3406        LogosUuid(logicaffeine_base::Uuid::from_bytes(b))
3407    }
3408}
3409
3410/// A Text's UTF-8 bytes as a `Seq of Int` (the `text_bytes` builtin, AOT).
3411pub fn text_bytes(s: &str) -> LogosSeq<i64> {
3412    LogosSeq::from_vec(s.as_bytes().iter().map(|&b| b as i64).collect())
3413}
3414
3415/// Rebuild a Text from a `Seq of Int` of UTF-8 bytes (the `text_from_bytes` builtin, AOT —
3416/// the exact inverse of [`text_bytes`]).
3417///
3418/// ★ INVALID BYTES ARE A FAILURE, NOT A SUBSTITUTION. This used to fall back to
3419/// `from_utf8_lossy`, justified by a premise written in this very comment: *"inputs originate
3420/// from `text_bytes`, so the bytes are always valid UTF-8"*. **Our own stdlib falsifies it** —
3421/// `fromHex` (encoding.lg) decodes arbitrary hex and hands the result straight in, so
3422/// `fromHex("ff")` arrives here with byte 255.
3423///
3424/// The consequence was three answers to one question: the tree-walker and the VM raised
3425/// `text_from_bytes(): invalid UTF-8`, this returned `U+FFFD`, and the wasm lowering checked
3426/// nothing at all. A panic is what the AOT tier means by "the reference tier errored" —
3427/// `readBytes` already answers that way — so the tiers now agree.
3428///
3429/// A premise asserted in a doc comment is enforced by nothing, and the caller that violates it
3430/// is usually in a different file from the one that states it.
3431pub fn text_from_bytes(bytes: &LogosSeq<i64>) -> String {
3432    let b: Vec<u8> = bytes.iter().map(|v| v as u8).collect();
3433    match String::from_utf8(b) {
3434        Ok(s) => s,
3435        Err(e) => panic!("{}", crate::failure::invalid_utf8(e)),
3436    }
3437}
3438
3439impl std::fmt::Display for LogosUuid {
3440    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3441        write!(f, "{}", self.0)
3442    }
3443}
3444
3445/// An exchange rate accepted by [`set_rate`] — a plain integer (`1`), an exact `LogosDecimal`
3446/// (`1.10`), or a `LogosRational`. All widen losslessly onto the Rational tower so normalisation
3447/// stays exact, matching the interpreter's `set_rate` builtin.
3448pub trait IntoRate {
3449    fn into_rate(self) -> logicaffeine_base::Rational;
3450}
3451impl IntoRate for i64 {
3452    fn into_rate(self) -> logicaffeine_base::Rational {
3453        logicaffeine_base::Rational::from_i64(self)
3454    }
3455}
3456impl IntoRate for LogosDecimal {
3457    fn into_rate(self) -> logicaffeine_base::Rational {
3458        self.0.to_rational()
3459    }
3460}
3461impl IntoRate for LogosRational {
3462    fn into_rate(self) -> logicaffeine_base::Rational {
3463        self.0
3464    }
3465}
3466
3467/// Install (or replace) one exchange rate in the ambient rate context — `1 <code> = rate` reference
3468/// units. The compiled-tier mirror of the `set_rate` builtin; a fresh process starts with no rates,
3469/// so a program installs them before any `<money> in <currency>` conversion.
3470pub fn set_rate<R: IntoRate>(code: String, rate: R) {
3471    logicaffeine_base::money::set_ambient_rate(&code, rate.into_rate());
3472}
3473
3474/// Bulk-install a whole exchange-rate table from a `Map of Text to <number>` (currency code → rate
3475/// vs the reference) into the ambient rate context. The compiled-tier mirror of the `set_rates`
3476/// builtin and the bridge a literal, network-synced, or fetched table feeds. Order-independent.
3477pub fn set_rates<V: IntoRate + Clone>(map: LogosMap<String, V>) {
3478    for (code, rate) in map.0.borrow().iter() {
3479        logicaffeine_base::money::set_ambient_rate(code, rate.clone().into_rate());
3480    }
3481}
3482
3483/// Convert money to another currency via the ambient rate context — the `<money> in <currency>`
3484/// surface. Panics (the typed-error backstop, like a currency-mismatch `+`) when no rates are in
3485/// scope or the currency lacks a rate; the front-end / interpreter surface these as clean errors.
3486pub fn to_currency(money: LogosMoney, code: String) -> LogosMoney {
3487    let to = logicaffeine_base::money::currency::by_code(&code)
3488        .unwrap_or_else(|| panic!("{}", crate::failure::unknown_currency(&code)));
3489    let converted = logicaffeine_base::money::ambient_convert(&money.0, to).unwrap_or_else(|| {
3490        if logicaffeine_base::money::has_ambient_rates() {
3491            panic!(
3492                "{}",
3493                crate::failure::no_exchange_rate(money.0.currency.code, to.code)
3494            )
3495        } else {
3496            panic!("{}", crate::failure::NO_EXCHANGE_RATES)
3497        }
3498    });
3499    LogosMoney(converted)
3500}
3501
3502#[cfg(test)]
3503#[path = "../../logicaffeine_tests/unit/logicaffeine_data/types/logos_money_tests.rs"]
3504mod logos_money_tests;
3505
3506#[cfg(test)]
3507#[path = "../../logicaffeine_tests/unit/logicaffeine_data/types/logos_quantity_tests.rs"]
3508mod logos_quantity_tests;
3509
3510#[cfg(test)]
3511#[path = "../../logicaffeine_tests/unit/logicaffeine_data/types/logos_rational_tests.rs"]
3512mod logos_rational_tests;
3513
3514#[cfg(test)]
3515#[path = "../../logicaffeine_tests/unit/logicaffeine_data/types/tests.rs"]
3516mod tests;
3517
3518#[cfg(test)]
3519#[path = "../../logicaffeine_tests/unit/logicaffeine_data/types/logos_bits_tests.rs"]
3520mod logos_bits_tests;
3521
3522// ===========================================================================
3523// LogosInt — the EXACT compiled integer (overflow ruling v2, stage 2)
3524// ===========================================================================
3525
3526/// The exact integer for GENERATED code: `i64` on the fast path, spilling to a
3527/// heap [`logicaffeine_base::BigInt`] the moment a value escapes 64 bits — the
3528/// AOT's mirror of the interpreter's Int→BigInt promotion (and of the JIT's
3529/// overflow side-exit). Every operation NORMALIZES: a big result that fits
3530/// `i64` downsizes to `Small`, so representation never leaks into `==`/`Ord`.
3531#[derive(Clone, Debug)]
3532pub enum LogosInt {
3533    Small(i64),
3534    Big(Box<logicaffeine_base::BigInt>),
3535}
3536
3537/// Zero, so a struct holding a promoted `Int` can still `#[derive(Default)]` — the AOT-Rust
3538/// struct codegen always derives it and constructs with `..Default::default()`.
3539impl Default for LogosInt {
3540    fn default() -> Self {
3541        LogosInt::Small(0)
3542    }
3543}
3544
3545impl LogosInt {
3546    #[inline]
3547    pub fn from_i64(x: i64) -> Self {
3548        LogosInt::Small(x)
3549    }
3550
3551    pub fn from_big(b: logicaffeine_base::BigInt) -> Self {
3552        match b.to_i64() {
3553            Some(x) => LogosInt::Small(x),
3554            None => LogosInt::Big(Box::new(b)),
3555        }
3556    }
3557
3558    /// Parse a (possibly > 64-bit) decimal literal the codegen emitted.
3559    pub fn from_literal(s: &str) -> Self {
3560        if let Ok(x) = s.parse::<i64>() {
3561            return LogosInt::Small(x);
3562        }
3563        let (neg, digits) = match s.strip_prefix('-') {
3564            Some(d) => (true, d),
3565            None => (false, s),
3566        };
3567        let ten = logicaffeine_base::BigInt::from_i64(10);
3568        let mut acc = logicaffeine_base::BigInt::from_i64(0);
3569        for ch in digits.bytes() {
3570            debug_assert!(ch.is_ascii_digit(), "LogosInt literal digit");
3571            acc = acc
3572                .mul(&ten)
3573                .add(&logicaffeine_base::BigInt::from_i64((ch - b'0') as i64));
3574        }
3575        if neg {
3576            acc = acc.negated();
3577        }
3578        LogosInt::from_big(acc)
3579    }
3580
3581    fn to_bigint(&self) -> logicaffeine_base::BigInt {
3582        match self {
3583            LogosInt::Small(x) => logicaffeine_base::BigInt::from_i64(*x),
3584            LogosInt::Big(b) => (**b).clone(),
3585        }
3586    }
3587
3588    /// Borrow the value as a `&BigInt` WITHOUT cloning a heap `Big`. A `Small`
3589    /// materializes a cheap single-limb `BigInt` (no heap); a `Big` borrows its box.
3590    /// This is the allocation-avoiding counterpart to [`to_bigint`] for the by-ref
3591    /// `BigInt` arithmetic below — a growing accumulator (`factorial`, `pow_exact`)
3592    /// was being cloned once per operation purely to pass it by reference.
3593    #[inline]
3594    fn as_bigint(&self) -> std::borrow::Cow<'_, logicaffeine_base::BigInt> {
3595        match self {
3596            LogosInt::Small(x) => std::borrow::Cow::Owned(logicaffeine_base::BigInt::from_i64(*x)),
3597            LogosInt::Big(b) => std::borrow::Cow::Borrowed(&**b),
3598        }
3599    }
3600
3601    /// The value as `i64` when it fits.
3602    pub fn to_i64(&self) -> Option<i64> {
3603        match self {
3604            LogosInt::Small(x) => Some(*x),
3605            LogosInt::Big(b) => b.to_i64(),
3606        }
3607    }
3608
3609    /// The low 64 bits of this integer, reduced modulo 2^64.
3610    #[inline]
3611    pub fn wrapping_u64(&self) -> u64 {
3612        match self {
3613            Self::Small(value) => *value as u64,
3614            Self::Big(value) => value.wrapping_u64(),
3615        }
3616    }
3617
3618    /// The value as `i64`, or a LOUD canonical error — for sinks that are
3619    /// structurally 64-bit (indices, sizes, native call arguments).
3620    #[inline]
3621    pub fn expect_i64(&self, what: &str) -> i64 {
3622        match self.to_i64() {
3623            Some(x) => x,
3624            None => panic!("Integer overflow: {self} does not fit a 64-bit {what}"),
3625        }
3626    }
3627
3628    #[inline]
3629    pub fn add(&self, rhs: &LogosInt) -> LogosInt {
3630        if let (LogosInt::Small(a), LogosInt::Small(b)) = (self, rhs) {
3631            if let Some(s) = a.checked_add(*b) {
3632                return LogosInt::Small(s);
3633            }
3634        }
3635        let (a, b) = (self.as_bigint(), rhs.as_bigint());
3636        LogosInt::from_big(a.add(&b))
3637    }
3638
3639    #[inline]
3640    pub fn sub(&self, rhs: &LogosInt) -> LogosInt {
3641        if let (LogosInt::Small(a), LogosInt::Small(b)) = (self, rhs) {
3642            if let Some(s) = a.checked_sub(*b) {
3643                return LogosInt::Small(s);
3644            }
3645        }
3646        let (a, b) = (self.as_bigint(), rhs.as_bigint());
3647        LogosInt::from_big(a.sub(&b))
3648    }
3649
3650    #[inline]
3651    pub fn mul(&self, rhs: &LogosInt) -> LogosInt {
3652        if let (LogosInt::Small(a), LogosInt::Small(b)) = (self, rhs) {
3653            if let Some(p) = a.checked_mul(*b) {
3654                return LogosInt::Small(p);
3655            }
3656        }
3657        let (a, b) = (self.as_bigint(), rhs.as_bigint());
3658        LogosInt::from_big(a.mul(&b))
3659    }
3660
3661    /// In-place multiply by a machine-integer scalar — the exact-value equivalent of
3662    /// `*self = self.mul(&LogosInt::from(rhs))`, but a `Big` accumulator mutates its heap
3663    /// buffer in place instead of allocating a fresh product each call (the `Set p to p * i`
3664    /// factorial hot loop). A `Small` stays on the checked fast path, promoting to `Big` only
3665    /// on overflow. A `Big` never shrinks below the i64 range under a nonzero scalar, so it
3666    /// stays a canonical `Big`; a zero scalar collapses to `Small(0)`.
3667    #[inline]
3668    pub fn mul_assign_i64(&mut self, rhs: i64) {
3669        match self {
3670            LogosInt::Small(a) => match a.checked_mul(rhs) {
3671                Some(p) => *a = p,
3672                None => {
3673                    let big = logicaffeine_base::BigInt::from_i64(*a)
3674                        .mul(&logicaffeine_base::BigInt::from_i64(rhs));
3675                    *self = LogosInt::from_big(big);
3676                }
3677            },
3678            LogosInt::Big(b) => {
3679                if rhs == 0 {
3680                    *self = LogosInt::Small(0);
3681                } else {
3682                    b.mul_assign_i64(rhs);
3683                }
3684            }
3685        }
3686    }
3687
3688    /// Truncating division; `Err` on a zero divisor (the interp's catchable
3689    /// "Division by zero"). `i64::MIN / -1` promotes exactly.
3690    #[inline]
3691    pub fn div(&self, rhs: &LogosInt) -> Result<LogosInt, String> {
3692        if let (LogosInt::Small(a), LogosInt::Small(b)) = (self, rhs) {
3693            if *b == 0 {
3694                return Err(crate::failure::DIVISION_BY_ZERO.to_string());
3695            }
3696            if let Some(q) = a.checked_div(*b) {
3697                return Ok(LogosInt::Small(q));
3698            }
3699        }
3700        match self.to_bigint().div_rem(&rhs.to_bigint()) {
3701            Some((q, _)) => Ok(LogosInt::from_big(q)),
3702            None => Err(crate::failure::DIVISION_BY_ZERO.to_string()),
3703        }
3704    }
3705
3706    /// Floor division — the quotient rounded toward NEGATIVE INFINITY (`-7 // 2 → -4`),
3707    /// the semantics of the `//` operator. Distinct from [`div`](Self::div), which
3708    /// truncates toward zero (`-7 / 2 → -3`); the two agree when the operands share a
3709    /// sign. Exact (promotes to `BigInt`); a zero divisor is a loud error.
3710    pub fn div_floor(&self, rhs: &LogosInt) -> Result<LogosInt, String> {
3711        if let (LogosInt::Small(a), LogosInt::Small(b)) = (self, rhs) {
3712            if *b == 0 {
3713                return Err(crate::failure::DIVISION_BY_ZERO.to_string());
3714            }
3715            // `i64::MIN / -1` overflows the Small path → fall through to the exact BigInt
3716            // branch. Otherwise floor = truncate, minus one when a nonzero remainder means
3717            // the true quotient sits below the truncated one (operands of opposite sign).
3718            if let (Some(q), Some(r)) = (a.checked_div(*b), a.checked_rem(*b)) {
3719                let floored = if r != 0 && (r < 0) != (*b < 0) {
3720                    q - 1
3721                } else {
3722                    q
3723                };
3724                return Ok(LogosInt::Small(floored));
3725            }
3726        }
3727        match self.to_bigint().div_rem(&rhs.to_bigint()) {
3728            Some((q, r)) => {
3729                let floored = if !r.is_zero() && r.is_negative() != rhs.to_bigint().is_negative() {
3730                    q.sub(&logicaffeine_base::BigInt::from_i64(1))
3731                } else {
3732                    q
3733                };
3734                Ok(LogosInt::from_big(floored))
3735            }
3736            None => Err(crate::failure::DIVISION_BY_ZERO.to_string()),
3737        }
3738    }
3739
3740    /// Truncating remainder (sign of the dividend); `i64::MIN % -1` is 0.
3741    #[inline]
3742    pub fn rem(&self, rhs: &LogosInt) -> Result<LogosInt, String> {
3743        if let (LogosInt::Small(a), LogosInt::Small(b)) = (self, rhs) {
3744            if *b == 0 {
3745                return Err(crate::failure::MODULO_BY_ZERO.to_string());
3746            }
3747            if let Some(r) = a.checked_rem(*b) {
3748                return Ok(LogosInt::Small(r));
3749            }
3750            return Ok(LogosInt::Small(0)); // MIN % -1
3751        }
3752        match self.to_bigint().div_rem(&rhs.to_bigint()) {
3753            Some((_, r)) => Ok(LogosInt::from_big(r)),
3754            None => Err(crate::failure::MODULO_BY_ZERO.to_string()),
3755        }
3756    }
3757
3758    /// Exponentiation with an integer exponent. `Err` on a negative exponent
3759    /// (an Int can't hold the fractional result) or one too large to be a
3760    /// `u32` power; overflow of the i64 fast path promotes to `BigInt`
3761    /// exactly. Mirrors the interpreter's `int_power`.
3762    pub fn pow(&self, exp: &LogosInt) -> Result<LogosInt, String> {
3763        let e = match exp.to_i64() {
3764            Some(e) if e < 0 => {
3765                return Err("negative exponent on an integer (an Int can't hold a fraction — use a Float base)".to_string());
3766            }
3767            Some(e) => e,
3768            None => return Err("exponent too large".to_string()),
3769        };
3770        let e = u32::try_from(e).map_err(|_| "exponent too large".to_string())?;
3771        if let LogosInt::Small(b) = self {
3772            if let Some(r) = b.checked_pow(e) {
3773                return Ok(LogosInt::Small(r));
3774            }
3775        }
3776        Ok(LogosInt::from_big(self.to_bigint().pow(e)))
3777    }
3778
3779    pub fn neg(&self) -> LogosInt {
3780        match self {
3781            LogosInt::Small(x) => match x.checked_neg() {
3782                Some(n) => LogosInt::Small(n),
3783                None => LogosInt::from_big(self.to_bigint().negated()),
3784            },
3785            LogosInt::Big(b) => LogosInt::from_big(b.negated()),
3786        }
3787    }
3788}
3789
3790impl From<i64> for LogosInt {
3791    #[inline]
3792    fn from(x: i64) -> Self {
3793        LogosInt::Small(x)
3794    }
3795}
3796
3797impl PartialEq for LogosInt {
3798    fn eq(&self, other: &Self) -> bool {
3799        match (self, other) {
3800            // Normalization invariant: a Big never holds an i64-fitting value.
3801            (LogosInt::Small(a), LogosInt::Small(b)) => a == b,
3802            (LogosInt::Big(a), LogosInt::Big(b)) => **a == **b,
3803            _ => false,
3804        }
3805    }
3806}
3807impl Eq for LogosInt {}
3808
3809impl PartialEq<i64> for LogosInt {
3810    fn eq(&self, other: &i64) -> bool {
3811        matches!(self, LogosInt::Small(a) if a == other)
3812    }
3813}
3814impl PartialEq<LogosInt> for i64 {
3815    fn eq(&self, other: &LogosInt) -> bool {
3816        other == self
3817    }
3818}
3819
3820impl Ord for LogosInt {
3821    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
3822        match (self, other) {
3823            (LogosInt::Small(a), LogosInt::Small(b)) => a.cmp(b),
3824            _ => self.to_bigint().cmp(&other.to_bigint()),
3825        }
3826    }
3827}
3828impl PartialOrd for LogosInt {
3829    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
3830        Some(self.cmp(other))
3831    }
3832}
3833impl PartialOrd<i64> for LogosInt {
3834    fn partial_cmp(&self, other: &i64) -> Option<core::cmp::Ordering> {
3835        self.partial_cmp(&LogosInt::Small(*other))
3836    }
3837}
3838impl PartialOrd<LogosInt> for i64 {
3839    fn partial_cmp(&self, other: &LogosInt) -> Option<core::cmp::Ordering> {
3840        LogosInt::Small(*self).partial_cmp(other)
3841    }
3842}
3843
3844impl core::hash::Hash for LogosInt {
3845    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
3846        // The unified numeric hash (mod 2^61−1) — coherent with equal i64s.
3847        match self {
3848            LogosInt::Small(x) => logicaffeine_base::numeric::numeric_hash_i64(*x).hash(state),
3849            LogosInt::Big(b) => logicaffeine_base::numeric::numeric_hash_bigint(b).hash(state),
3850        }
3851    }
3852}
3853
3854impl core::fmt::Display for LogosInt {
3855    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
3856        match self {
3857            LogosInt::Small(x) => write!(f, "{x}"),
3858            LogosInt::Big(b) => write!(f, "{b}"),
3859        }
3860    }
3861}
3862
3863#[cfg(test)]
3864#[path = "../../logicaffeine_tests/unit/logicaffeine_data/types/logos_int_spec.rs"]
3865mod logos_int_spec;