Skip to main content

logicaffeine_compile/semantics/
collections.rs

1//! Collection operations: indexing, length, membership, mutation, set algebra.
2
3use std::cell::RefCell;
4use std::rc::Rc;
5
6use crate::interpreter::RuntimeValue;
7
8use super::compare::values_equal;
9
10/// The interned single-character `Text` for an ASCII byte. `item k of text`
11/// on an ASCII string is the hot path of every character-scanning loop
12/// (string search, parsing); allocating a fresh one-char `Rc<String>` per
13/// access dominated those loops. The 128 ASCII single-char strings are
14/// immutable and shared per thread, so indexing collapses to a refcount
15/// bump. (Texts are never mutated in place, so sharing the `Rc` is safe.)
16fn ascii_char_text(b: u8) -> Rc<String> {
17    debug_assert!(b < 128, "caller guarantees an ASCII byte");
18    thread_local! {
19        static CACHE: RefCell<[Option<Rc<String>>; 128]> =
20            RefCell::new(std::array::from_fn(|_| None));
21    }
22    CACHE.with(|c| {
23        c.borrow_mut()[b as usize]
24            .get_or_insert_with(|| Rc::new((b as char).to_string()))
25            .clone()
26    })
27}
28
29/// Cached `(is_ascii, char_len)` for a `Text`, keyed by Rc identity AND byte
30/// length. A character-scanning loop (`item i of text` for i = 1..n) otherwise
31/// re-runs the O(n) `is_ascii()` / `chars().count()` on EVERY access — turning
32/// the scan O(n²). The only in-place Text mutation is append (`add_assign`),
33/// which grows the byte length, so a length mismatch detects staleness and
34/// recomputes; holding the Rc clone keeps the pointer from being reused while
35/// cached. (`index_set` has no Text arm — no same-length mutation exists — so
36/// the metadata cannot silently change.)
37fn text_metrics(s: &Rc<String>) -> (bool, usize) {
38    thread_local! {
39        static CACHE: RefCell<Vec<(Rc<String>, usize, bool, usize)>> =
40            const { RefCell::new(Vec::new()) };
41    }
42    CACHE.with(|c| {
43        let mut c = c.borrow_mut();
44        let len = s.len();
45        if let Some(e) = c
46            .iter()
47            .find(|(rc, l, _, _)| *l == len && Rc::ptr_eq(rc, s))
48        {
49            return (e.2, e.3);
50        }
51        let ascii = s.is_ascii();
52        let char_len = if ascii { len } else { s.chars().count() };
53        if c.len() >= 8 {
54            c.remove(0);
55        }
56        c.push((s.clone(), len, ascii, char_len));
57        (ascii, char_len)
58    })
59}
60
61/// Whether a `Text` is pure ASCII, answered in O(1) per call via the same
62/// `(is_ascii, char_len)` cache the indexing hot path uses (the first call for
63/// a given `Rc`/length pays the vectorized `is_ascii()` scan, every later one is
64/// a cache hit). The VM's tier-up seam asks this on every hot back-edge crossing
65/// and again at every region entry: a Text-as-bytes pin is sound ONLY for ASCII
66/// (char index == byte index, char count == byte length), so a non-ASCII Text
67/// must never pin.
68pub fn text_is_ascii(s: &Rc<String>) -> bool {
69    text_metrics(s).0
70}
71
72/// [`logicaffeine_data::logos_offset`] with the failure as a catchable error rather than a panic.
73fn resolve_index(i: i64, len: usize) -> Result<usize, String> {
74    logicaffeine_data::logos_offset(i, len).ok_or_else(|| {
75        crate::semantics::failcode::message(
76            crate::semantics::failcode::FailCode::IndexOutOfBounds.code(),
77            i,
78        )
79    })
80}
81
82/// 1-based index for List/Tuple/Text; key lookup for Map; Text-keyed field
83/// read for Struct.
84pub fn index_get(coll: &RuntimeValue, idx: &RuntimeValue) -> Result<RuntimeValue, String> {
85    match (coll, idx) {
86        (RuntimeValue::List(items), RuntimeValue::Int(i)) => {
87            let items = items.borrow();
88            let idx = resolve_index(*i, items.len())?;
89            Ok(items.get(idx).expect("bounds checked above"))
90        }
91        (RuntimeValue::Tuple(items), RuntimeValue::Int(i)) => {
92            let idx = resolve_index(*i, items.len())?;
93            Ok(items[idx].clone())
94        }
95        (RuntimeValue::Text(s), RuntimeValue::Int(i)) => {
96            let i = *i;
97            // ASCII fast path: byte position == char position and the
98            // in-bounds check over bytes equals the check over chars. The
99            // `is_ascii` scan is vectorized — far cheaper than the per-char
100            // decode of `chars().nth` that the general path needs.
101            let bytes = s.as_bytes();
102            // Cached metrics: ASCII-ness and char length are O(1) per access
103            // (recomputed only when the string's byte length changes), so a
104            // scan loop stays O(n) instead of O(n²).
105            let (ascii, char_len) = text_metrics(s);
106            if i >= 1 && (i as usize) <= bytes.len() && ascii {
107                return Ok(RuntimeValue::Text(ascii_char_text(bytes[i as usize - 1])));
108            }
109            let idx = resolve_index(i, char_len)?;
110            Ok(RuntimeValue::Text(Rc::new(
111                s.chars().nth(idx).unwrap().to_string(),
112            )))
113        }
114        (RuntimeValue::Map(map), key) => {
115            let map = map.borrow();
116            match map.get(key) {
117                Some(val) => Ok(val.clone()),
118                None => Err(logicaffeine_data::failure::key_not_found(
119                    key.to_display_string().as_str(),
120                )),
121            }
122        }
123        // A `SharedMap` reads its register under a present key (a missing key traps like a Map's).
124        (RuntimeValue::Crdt(c), key)
125            if matches!(&*c.borrow(), crate::semantics::crdt::CrdtValue::Map(_)) =>
126        {
127            c.borrow().map_get(key)
128        }
129        // Struct field read via index syntax (`item "field" of struct`).
130        (RuntimeValue::Struct(s), RuntimeValue::Text(field)) => {
131            match s.fields.get(field.as_str()) {
132                Some(val) => Ok(val.clone()),
133                None => Err(format!("Struct has no field '{}'", field)),
134            }
135        }
136        _ => Err(format!(
137            "Cannot index {} with {}",
138            coll.type_name(),
139            idx.type_name()
140        )),
141    }
142}
143
144/// `Set item idx of collection to value` — 1-based list set, or map insert.
145/// (Struct field set needs an environment reassign and stays engine-side.)
146pub fn index_set(
147    coll: &RuntimeValue,
148    idx: &RuntimeValue,
149    value: RuntimeValue,
150) -> Result<(), String> {
151    match (coll, idx) {
152        (RuntimeValue::List(items), RuntimeValue::Int(n)) => {
153            let mut items = items.borrow_mut();
154            let idx = resolve_index(*n, items.len())?;
155            items.set(idx, value);
156            Ok(())
157        }
158        (RuntimeValue::Map(map), key) => {
159            assert_hashable_key(key)?;
160            map.borrow_mut().insert(key.clone(), value);
161            Ok(())
162        }
163        // A `SharedMap` write stamps the key's register (the CRDT is shared in place, like a Map).
164        (RuntimeValue::Crdt(c), key)
165            if matches!(&*c.borrow(), crate::semantics::crdt::CrdtValue::Map(_)) =>
166        {
167            c.borrow_mut().map_put(key, &value)
168        }
169        (RuntimeValue::List(_), _) => Err("List index must be an integer".to_string()),
170        _ => Err(format!("Cannot index into {}", coll.type_name())),
171    }
172}
173
174/// A Map key must be TRANSITIVELY immutable: a List/Set/Map key (even one
175/// buried inside a tuple or struct) is a shared handle whose later mutation
176/// would silently corrupt the map, so the insert refuses it outright with a
177/// catchable error. Tuples and structs of immutable parts are VALUE keys.
178pub fn assert_hashable_key(key: &RuntimeValue) -> Result<(), String> {
179    match key {
180        RuntimeValue::List(_) | RuntimeValue::Set(_) | RuntimeValue::Map(_) => Err(format!(
181            "a {} cannot be a Map key — it is mutable, and mutating a live key \
182             would corrupt the map (use a Tuple of its values instead)",
183            key.type_name()
184        )),
185        RuntimeValue::Tuple(items) => {
186            for item in items.iter() {
187                assert_hashable_key(item)?;
188            }
189            Ok(())
190        }
191        RuntimeValue::Struct(s) => {
192            for value in s.fields.values() {
193                assert_hashable_key(value)?;
194            }
195            Ok(())
196        }
197        _ => Ok(()),
198    }
199}
200
201/// 1-indexed, inclusive-end slice of a List, under [`logicaffeine_data::logos_slice_range`]: one that reaches
202/// outside the list is empty.
203pub fn slice(
204    coll: &RuntimeValue,
205    start: &RuntimeValue,
206    end: &RuntimeValue,
207) -> Result<RuntimeValue, String> {
208    match (coll, start, end) {
209        (RuntimeValue::List(items), RuntimeValue::Int(s), RuntimeValue::Int(e)) => {
210            let items = items.borrow();
211            let range = logicaffeine_data::logos_slice_range(*s, *e, items.len());
212            let payload = if range.is_empty() {
213                crate::interpreter::ListRepr::Boxed(Vec::new())
214            } else {
215                items.slice(range.start, range.end - 1)
216            };
217            Ok(RuntimeValue::List(Rc::new(RefCell::new(payload))))
218        }
219        _ => Err("Slice requires List and Int indices".to_string()),
220    }
221}
222
223/// `length of x`. NOTE: Text length is BYTES (while Text indexing is chars) —
224/// a pinned tree-walker behavior.
225pub fn length_of(coll: &RuntimeValue) -> Result<RuntimeValue, String> {
226    match coll {
227        RuntimeValue::List(items) => Ok(RuntimeValue::Int(items.borrow().len() as i64)),
228        RuntimeValue::Tuple(items) => Ok(RuntimeValue::Int(items.len() as i64)),
229        RuntimeValue::Set(items) => Ok(RuntimeValue::Int(items.borrow().len() as i64)),
230        RuntimeValue::Text(s) => Ok(RuntimeValue::Int(s.len() as i64)),
231        RuntimeValue::Map(map) => Ok(RuntimeValue::Int(map.borrow().len() as i64)),
232        RuntimeValue::Crdt(c) => Ok(RuntimeValue::Int(c.borrow().len() as i64)),
233        _ => Err(format!("Cannot get length of {}", coll.type_name())),
234    }
235}
236
237/// Membership: `values_equal` scan for Set/List, key lookup for Map,
238/// substring/char for Text.
239pub fn contains(coll: &RuntimeValue, val: &RuntimeValue) -> Result<RuntimeValue, String> {
240    match coll {
241        RuntimeValue::List(items) => Ok(RuntimeValue::Bool(items.borrow().contains(val))),
242        RuntimeValue::Set(items) => {
243            let items = items.borrow();
244            let found = items.iter().any(|item| values_equal(item, val));
245            Ok(RuntimeValue::Bool(found))
246        }
247        RuntimeValue::Map(entries) => Ok(RuntimeValue::Bool(entries.borrow().contains_key(val))),
248        RuntimeValue::Text(s) => {
249            if let RuntimeValue::Text(needle) = val {
250                Ok(RuntimeValue::Bool(s.contains(needle.as_str())))
251            } else if let RuntimeValue::Char(c) = val {
252                Ok(RuntimeValue::Bool(s.contains(*c)))
253            } else {
254                Err(format!("Cannot check if Text contains {}", val.type_name()))
255            }
256        }
257        RuntimeValue::Crdt(c) => Ok(RuntimeValue::Bool(c.borrow().contains(val)?)),
258        _ => Err(format!("Cannot check contains on {}", coll.type_name())),
259    }
260}
261
262/// Set union — left's elements, then right's not already present.
263pub fn union(left: &RuntimeValue, right: &RuntimeValue) -> Result<RuntimeValue, String> {
264    match (left, right) {
265        (RuntimeValue::Set(a), RuntimeValue::Set(b)) => {
266            let a = a.borrow();
267            let b = b.borrow();
268            let mut result = a.clone();
269            for item in b.iter() {
270                if !result.iter().any(|x| values_equal(x, item)) {
271                    result.push(item.clone());
272                }
273            }
274            Ok(RuntimeValue::Set(Rc::new(RefCell::new(result))))
275        }
276        _ => Err(format!(
277            "Cannot union {} and {}",
278            left.type_name(),
279            right.type_name()
280        )),
281    }
282}
283
284/// Set intersection — left's elements present in right, in left's order.
285pub fn intersection(left: &RuntimeValue, right: &RuntimeValue) -> Result<RuntimeValue, String> {
286    match (left, right) {
287        (RuntimeValue::Set(a), RuntimeValue::Set(b)) => {
288            let a = a.borrow();
289            let b = b.borrow();
290            let result: Vec<RuntimeValue> = a
291                .iter()
292                .filter(|item| b.iter().any(|x| values_equal(x, item)))
293                .cloned()
294                .collect();
295            Ok(RuntimeValue::Set(Rc::new(RefCell::new(result))))
296        }
297        _ => Err(format!(
298            "Cannot intersect {} and {}",
299            left.type_name(),
300            right.type_name()
301        )),
302    }
303}
304
305/// `a to b` — inclusive integer range as a List.
306pub fn range(start: &RuntimeValue, end: &RuntimeValue) -> Result<RuntimeValue, String> {
307    match (start, end) {
308        (RuntimeValue::Int(s), RuntimeValue::Int(e)) => {
309            let range: Vec<i64> = (*s..=*e).collect();
310            Ok(RuntimeValue::List(Rc::new(RefCell::new(
311                crate::interpreter::ListRepr::Ints(range),
312            ))))
313        }
314        _ => Err("Range requires Int bounds".to_string()),
315    }
316}
317
318/// The `Repeat` iteration snapshot: the collection is materialized ONCE before
319/// the loop, so mutation inside the body cannot extend or shrink the
320/// iteration. Text iterates per char (as 1-char Texts); a Map yields (key,
321/// value) Tuples in insertion order. A shared collection yields what every
322/// replica holding its state agrees on: a sequence in its convergent order, a
323/// set sorted, a map's (key, value) Tuples by key.
324pub fn iteration_snapshot(v: &RuntimeValue) -> Result<Vec<RuntimeValue>, String> {
325    match v {
326        RuntimeValue::List(list) => Ok(list.borrow().to_values()),
327        RuntimeValue::Set(set) => Ok(set.borrow().clone()),
328        RuntimeValue::Text(s) => Ok(s
329            .chars()
330            .map(|c| RuntimeValue::Text(Rc::new(c.to_string())))
331            .collect()),
332        RuntimeValue::Map(map) => Ok(map
333            .borrow()
334            .iter()
335            .map(|(k, v)| RuntimeValue::Tuple(Rc::new(vec![k.clone(), v.clone()])))
336            .collect()),
337        RuntimeValue::Crdt(c) => {
338            use crate::semantics::crdt::CrdtKind;
339            let c = c.borrow();
340            match c.crdt_kind() {
341                CrdtKind::Set | CrdtKind::SetRemoveWins | CrdtKind::Seq | CrdtKind::Map => {
342                    Ok(c.to_runtime_vec())
343                }
344                CrdtKind::Register | CrdtKind::Counter | CrdtKind::PnCounter => {
345                    Err(format!("Cannot iterate over {}", v.type_name()))
346                }
347            }
348        }
349        _ => Err(format!("Cannot iterate over {}", v.type_name())),
350    }
351}
352
353/// `Push value to obj's field` — pushes into a struct's List field through
354/// the shared allocation. Every error string is the spec.
355pub fn push_to_struct_field(
356    obj: &RuntimeValue,
357    field_name: &str,
358    val: RuntimeValue,
359) -> Result<(), String> {
360    if let RuntimeValue::Struct(s) = obj {
361        if let Some(RuntimeValue::List(items)) = s.fields.get(field_name) {
362            items.borrow_mut().push(val);
363            Ok(())
364        } else {
365            Err(format!("Field '{}' is not a List", field_name))
366        }
367    } else {
368        Err("Cannot push to field of non-struct".to_string())
369    }
370}
371
372thread_local! {
373    /// When > 0, the current thread runs collections under REFERENCE semantics
374    /// regardless of the global default. This is the bootstrap-scope: the
375    /// compile-time partial evaluator and self-interpreter (`pe_source.logos`,
376    /// `pe_mini_source.logos`, the core interpreter) are SELF-APPLICABLE — a
377    /// Futamura projection specializes them, and that only works when their
378    /// threaded state is mutated IN PLACE (a stable binding), which is exactly
379    /// reference semantics. They are compiler infrastructure, authored in
380    /// reference-semantics Logos; user programs (the residuals they emit) still
381    /// run under value semantics, which is the default everywhere else.
382    static FORCE_REFERENCE: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
383}
384
385/// RAII guard: run the closure / dynamic extent under reference semantics on this
386/// thread. Re-entrant (nested PE calls compose). See `FORCE_REFERENCE`.
387pub struct ReferenceScope;
388
389impl ReferenceScope {
390    pub fn enter() -> Self {
391        FORCE_REFERENCE.with(|c| c.set(c.get() + 1));
392        ReferenceScope
393    }
394}
395
396impl Drop for ReferenceScope {
397    fn drop(&mut self) {
398        FORCE_REFERENCE.with(|c| c.set(c.get().saturating_sub(1)));
399    }
400}
401
402/// Run `f` with reference semantics forced on this thread (the bootstrap scope).
403pub fn with_reference_semantics<T>(f: impl FnOnce() -> T) -> T {
404    let _g = ReferenceScope::enter();
405    f()
406}
407
408/// Whether the current thread is inside a [`ReferenceScope`]. Consulted by the
409/// AOT runner so a child process compiled from PE source inherits reference
410/// semantics (`LOGOS_VALUE_SEMANTICS=0`).
411pub fn reference_scope_active() -> bool {
412    FORCE_REFERENCE.with(|c| c.get() > 0)
413}
414
415/// Whether Mutable Value Semantics (copy-on-write for collections) is enabled.
416/// Value semantics is the DEFAULT (all four tiers — tree-walker, VM, AOT, JIT —
417/// implement it). `LOGOS_VALUE_SEMANTICS=0` restores the historical reference
418/// semantics (escape hatch). A thread-local [`ReferenceScope`] also forces
419/// reference semantics for the duration of compile-time PE / self-interpreter
420/// execution (bootstrap-scope). The env var is read once and cached; the
421/// thread-local check is a single `Cell` read, so the hot path stays cheap.
422pub fn value_semantics_enabled() -> bool {
423    use std::sync::OnceLock;
424    static ON: OnceLock<bool> = OnceLock::new();
425    if reference_scope_active() {
426        return false;
427    }
428    *ON.get_or_init(|| std::env::var("LOGOS_VALUE_SEMANTICS").as_deref() != Ok("0"))
429}
430
431/// `Push value to list` — mutates the shared allocation in place.
432pub fn list_push(coll: &RuntimeValue, value: RuntimeValue) -> Result<(), String> {
433    match coll {
434        RuntimeValue::List(items) => {
435            items.borrow_mut().push(value);
436            Ok(())
437        }
438        _ => Err("Can only push to a List".to_string()),
439    }
440}
441
442/// `Pop from list` — removes and returns the last element, or Nothing when
443/// the list is empty (popping an empty list is NOT an error).
444pub fn list_pop(coll: &RuntimeValue) -> Result<RuntimeValue, String> {
445    match coll {
446        RuntimeValue::List(items) => Ok(items.borrow_mut().pop().unwrap_or(RuntimeValue::Nothing)),
447        _ => Err("Can only pop from a List".to_string()),
448    }
449}
450
451/// `Add value to set` — dedups via `values_equal`.
452pub fn set_add(coll: &RuntimeValue, value: RuntimeValue) -> Result<(), String> {
453    match coll {
454        RuntimeValue::Set(items) => {
455            let already_present = items.borrow().iter().any(|x| values_equal(x, &value));
456            if !already_present {
457                items.borrow_mut().push(value);
458            }
459            Ok(())
460        }
461        RuntimeValue::Crdt(c) => c.borrow_mut().insert(&value),
462        _ => Err("Can only add to a Set".to_string()),
463    }
464}
465
466/// `Remove value from set/map`.
467pub fn remove_from(coll: &RuntimeValue, value: &RuntimeValue) -> Result<(), String> {
468    match coll {
469        RuntimeValue::Set(items) => {
470            items.borrow_mut().retain(|x| !values_equal(x, value));
471            Ok(())
472        }
473        RuntimeValue::Map(map) => {
474            map.borrow_mut().shift_remove(value);
475            Ok(())
476        }
477        RuntimeValue::Crdt(c) => c.borrow_mut().remove(value),
478        _ => Err("Can only remove from a Set or Map".to_string()),
479    }
480}
481
482#[cfg(test)]
483#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/semantics/collections/tests.rs"]
484mod tests;
485
486/// A place the VM takes a machine integer: a list's index read (`ListRead`), a list's index stored to (`ListStore`),
487/// a text's index (`Text`), a tuple's position (`Tuple`), a range bound (`Range`), a slice bound (`Slice`).
488#[derive(Debug, Clone, Copy, PartialEq, Eq)]
489pub enum IntegerPlace {
490    ListRead,
491    ListStore,
492    Text,
493    Tuple,
494    Range,
495    Slice,
496}
497
498impl IntegerPlace {
499    /// Every place, in the order its code names it.
500    pub const ALL: [IntegerPlace; 6] = [
501        IntegerPlace::ListRead,
502        IntegerPlace::ListStore,
503        IntegerPlace::Text,
504        IntegerPlace::Tuple,
505        IntegerPlace::Range,
506        IntegerPlace::Slice,
507    ];
508
509    /// The code a compiled program hands its runtime for this place: its position in [`IntegerPlace::ALL`].
510    pub fn code(self) -> i32 {
511        IntegerPlace::ALL.iter().position(|p| *p == self).expect("every place is listed") as i32
512    }
513
514    /// The place `code` names.
515    pub fn of_code(code: i32) -> Option<IntegerPlace> {
516        usize::try_from(code).ok().and_then(|i| IntegerPlace::ALL.get(i).copied())
517    }
518}
519
520/// What the VM says at `place` when it gets a whole number past i64, and when it gets a fraction: the sentences a
521/// compiled program that holds an exact number where the VM takes a machine integer refuses it with.
522pub fn integer_place_refusals(place: IntegerPlace) -> (String, String) {
523    use crate::semantics::failcode::{message, FailCode};
524    let list = || RuntimeValue::List(Rc::new(RefCell::new(crate::interpreter::ListRepr::from_values(Vec::new()))));
525    let pair = || RuntimeValue::Tuple(Rc::new(vec![RuntimeValue::Int(1), RuntimeValue::Int(2)]));
526    let fraction = || {
527        RuntimeValue::from_rational(logicaffeine_base::Rational::from_ratio_i64(1, 2).expect("a nonzero denominator"))
528    };
529    let past_word = || RuntimeValue::from_bigint(logicaffeine_base::BigInt::from_i64(2).pow(70));
530    let refused = |r: Result<RuntimeValue, String>| r.expect_err("the VM refuses it");
531    let past = |code: FailCode| message(code.code(), 0);
532    match place {
533        IntegerPlace::ListRead => (past(FailCode::ListIndexTooWide), refused(index_get(&list(), &fraction()))),
534        IntegerPlace::ListStore => (
535            past(FailCode::ListStoreIndexTooWide),
536            index_set(&list(), &fraction(), RuntimeValue::Int(0)).expect_err("the VM refuses it"),
537        ),
538        IntegerPlace::Text => (
539            past(FailCode::TextIndexTooWide),
540            refused(index_get(&RuntimeValue::Text(Rc::new("abc".to_string())), &fraction())),
541        ),
542        IntegerPlace::Tuple => (refused(index_get(&pair(), &past_word())), refused(index_get(&pair(), &fraction()))),
543        IntegerPlace::Range => (
544            refused(range(&RuntimeValue::Int(1), &past_word())),
545            refused(range(&RuntimeValue::Int(1), &fraction())),
546        ),
547        IntegerPlace::Slice => (
548            refused(slice(&list(), &past_word(), &RuntimeValue::Int(1))),
549            refused(slice(&list(), &fraction(), &RuntimeValue::Int(1))),
550        ),
551    }
552}