Skip to main content

logicaffeine_data/
indexing.rs

1//! Polymorphic indexing traits for Logos collections.
2//!
3//! Logos uses **1-based indexing** to match natural language conventions.
4//! These traits provide get/set operations that automatically convert
5//! 1-based indices to 0-based for underlying Rust collections.
6//!
7//! # Supported Collections
8//!
9//! - [`Vec<T>`]: Indexed by `i64` (1-based, converted to 0-based internally)
10//! - `HashMap<K, V>`: Indexed by key `K` (pass-through semantics)
11//! - `HashMap<String, V>`: Also supports `&str` keys for convenience
12//!
13//! # Panics
14//!
15//! Vector indexing operations panic if the index is out of bounds
16//! (less than 1 or greater than collection length). Map operations
17//! panic if the key is not found.
18
19use rustc_hash::FxHashMap;
20use std::hash::Hash;
21
22/// Immutable element access by index.
23///
24/// Provides 1-based indexing for Logos collections. Index `1` refers
25/// to the first element, index `2` to the second, and so on.
26///
27/// # Examples
28///
29/// ```
30/// use logicaffeine_data::LogosIndex;
31///
32/// let v = vec!["a", "b", "c"];
33/// assert_eq!(v.logos_get(1i64), "a");  // 1-based!
34/// assert_eq!(v.logos_get(3i64), "c");
35/// ```
36///
37/// # Panics
38///
39/// Panics if the index is less than 1 or greater than the collection length.
40pub trait LogosIndex<I> {
41    /// The type of element returned by indexing.
42    type Output;
43    /// Get the element at the given index.
44    fn logos_get(&self, index: I) -> Self::Output;
45}
46
47/// Mutable element access by index.
48///
49/// Provides 1-based mutable indexing for Logos collections.
50///
51/// # Examples
52///
53/// ```
54/// use logicaffeine_data::LogosIndexMut;
55///
56/// let mut v = vec![1, 2, 3];
57/// v.logos_set(2i64, 20);
58/// assert_eq!(v, vec![1, 20, 3]);
59/// ```
60///
61/// # Panics
62///
63/// Panics if the index is less than 1 or greater than the collection length.
64pub trait LogosIndexMut<I>: LogosIndex<I> {
65    /// Set the element at the given index.
66    fn logos_set(&mut self, index: I, value: Self::Output);
67}
68
69/// The 0-based offset of the item a 1-based LOGOS index names in a sequence of `len` items, or `None` when it
70/// names none. Index 1 is the first item and a negative index counts from the back (-1 is the last); 0 and
71/// anything past either end name nothing. ONE definition: every engine, every generated program and every
72/// fast path indexes through this rule. The arithmetic is 64-bit on every target, so a wasm32 build reads
73/// the same item a native one does.
74#[inline(always)]
75pub fn logos_offset(index: i64, len: usize) -> Option<usize> {
76    let offset = index.wrapping_sub(1) as u64;
77    if offset < len as u64 {
78        Some(offset as usize)
79    } else {
80        logos_offset_from_the_back(index, len)
81    }
82}
83
84/// The rest of [`logos_offset`], off the hot path: an index counted from the back, or none.
85#[cold]
86#[inline(never)]
87fn logos_offset_from_the_back(index: i64, len: usize) -> Option<usize> {
88    let back = index.unsigned_abs();
89    (index <= -1 && back <= len as u64).then(|| len - back as usize)
90}
91
92/// [`logos_offset`], failing with the one sentence every tier reports when the index names no item.
93#[inline(always)]
94pub fn resolve_logos_index(index: i64, len: usize) -> usize {
95    match logos_offset(index, len) {
96        Some(offset) => offset,
97        None => no_item_at(index),
98    }
99}
100
101#[cold]
102#[inline(never)]
103fn no_item_at(index: i64) -> ! {
104    panic!("{}", crate::failure::index_out_of_bounds(index))
105}
106
107/// The 0-based range `items start through end` names in a sequence of `len` items, or an empty range when
108/// the slice reaches outside it (or runs backwards). ONE definition, like [`logos_offset`], and 64-bit on
109/// every target.
110#[inline]
111pub fn logos_slice_range(start: i64, end: i64, len: usize) -> core::ops::Range<usize> {
112    let from = (start as u64).saturating_sub(1);
113    let to = end as u64;
114    if from < to && to <= len as u64 {
115        from as usize..to as usize
116    } else {
117        0..0
118    }
119}
120
121/// The items a counted loop over the indices `first` through `last` reads from a sequence of `len` items, in
122/// order, as the 0-based range they occupy: empty when `first` is past `last`, and otherwise the stop
123/// [`resolve_logos_index`] makes at the first index in the loop's order that names no item. A backend that
124/// copies such a loop in one step copies this range, so it reads what the loop reads and stops where the loop
125/// stops. (A run that crosses 0 always stops at 0; one wholly below 0 counts from the back.)
126#[inline]
127pub fn logos_run_through(first: i64, last: i64, len: usize) -> core::ops::Range<usize> {
128    if first > last {
129        return 0..0;
130    }
131    let len64 = len as u64;
132    if first >= 1 {
133        if last as u64 <= len64 {
134            return (first - 1) as usize..last as usize;
135        }
136        return no_item_at(first.max(len as i64 + 1));
137    }
138    if first.unsigned_abs() > len64 {
139        return no_item_at(first);
140    }
141    if last <= -1 {
142        return len - first.unsigned_abs() as usize..len - last.unsigned_abs() as usize + 1;
143    }
144    no_item_at(0)
145}
146
147/// [`logos_run_through`] for a loop that stops before `stop` (`while i < stop`).
148#[inline]
149pub fn logos_run_before(first: i64, stop: i64, len: usize) -> core::ops::Range<usize> {
150    match stop.checked_sub(1) {
151        Some(last) => logos_run_through(first, last, len),
152        None => 0..0,
153    }
154}
155
156/// The text a counted loop produces when it copies bytes `first` through `last` of `s` into a sequence and
157/// reads them back with `text_from_bytes`: the bytes under [`logos_run_through`], and the stop
158/// `text_from_bytes` makes when they do not form UTF-8. A slice of text is text exactly when both of its
159/// ends fall between characters, so the common case costs two boundary checks.
160pub fn logos_text_run_through(s: &str, first: i64, last: i64) -> &str {
161    text_bytes_as_text(s, logos_run_through(first, last, s.len()))
162}
163
164/// [`logos_text_run_through`] for a loop that stops before `stop`.
165pub fn logos_text_run_before(s: &str, first: i64, stop: i64) -> &str {
166    text_bytes_as_text(s, logos_run_before(first, stop, s.len()))
167}
168
169fn text_bytes_as_text(s: &str, range: core::ops::Range<usize>) -> &str {
170    if s.is_char_boundary(range.start) && s.is_char_boundary(range.end) {
171        return &s[range];
172    }
173    match core::str::from_utf8(&s.as_bytes()[range]) {
174        Ok(text) => text,
175        Err(e) => panic!("{}", crate::failure::invalid_utf8(e)),
176    }
177}
178
179/// Borrowing access to the item a 1-based LOGOS index names, under [`resolve_logos_index`]. A generated
180/// program reads and writes a sequence's items through this, so its fast path costs one compare and every
181/// other index means what it means on the interpreter.
182pub trait LogosItems<T> {
183    /// The item `index` names.
184    fn logos_item(&self, index: i64) -> &T;
185    /// The item `index` names, to write.
186    fn logos_item_mut(&mut self, index: i64) -> &mut T;
187    /// [`logos_item`](Self::logos_item) for an `index` the caller has proven is at least 1: the item, counted
188    /// from the front, or the failure past the end. With no index from the back to resolve, a miss only fails,
189    /// and a loop whose indices are proven in range compiles to plain loads.
190    fn logos_item_front(&self, index: i64) -> &T;
191    /// [`logos_item_front`](Self::logos_item_front), to write.
192    fn logos_item_front_mut(&mut self, index: i64) -> &mut T;
193    /// Items `start` through `end`, under [`logos_slice_range`].
194    fn logos_slice(&self, start: i64, end: i64) -> &[T];
195    /// The items a counted loop from `first` through `last` reads, under [`logos_run_through`].
196    fn logos_run_through(&self, first: i64, last: i64) -> &[T];
197    /// The items a counted loop from `first` up to, not including, `stop` reads, under [`logos_run_before`].
198    fn logos_run_before(&self, first: i64, stop: i64) -> &[T];
199    /// `While lo < hi: swap items lo and hi, then step lo up and hi down`, under the one index rule: the
200    /// slice's own (vectorized) reversal when both ends count from the front and name items, and the loop
201    /// itself, index by index, otherwise.
202    fn logos_reverse_between(&mut self, lo: i64, hi: i64);
203}
204
205impl<T> LogosItems<T> for [T] {
206    #[inline(always)]
207    fn logos_item(&self, index: i64) -> &T {
208        let offset = resolve_logos_index(index, self.len());
209        // SAFETY: `resolve_logos_index` returns an offset below `len` or does not return.
210        unsafe { self.get_unchecked(offset) }
211    }
212
213    #[inline(always)]
214    fn logos_item_mut(&mut self, index: i64) -> &mut T {
215        let offset = resolve_logos_index(index, self.len());
216        // SAFETY: as in `logos_item`.
217        unsafe { self.get_unchecked_mut(offset) }
218    }
219
220    #[inline(always)]
221    fn logos_item_front(&self, index: i64) -> &T {
222        debug_assert!(index >= 1, "a front index is at least 1, not {index}");
223        let offset = index.wrapping_sub(1) as u64;
224        if offset < self.len() as u64 {
225            // SAFETY: `offset` is below `len`.
226            unsafe { self.get_unchecked(offset as usize) }
227        } else {
228            no_item_at(index)
229        }
230    }
231
232    #[inline(always)]
233    fn logos_item_front_mut(&mut self, index: i64) -> &mut T {
234        debug_assert!(index >= 1, "a front index is at least 1, not {index}");
235        let offset = index.wrapping_sub(1) as u64;
236        if offset < self.len() as u64 {
237            // SAFETY: `offset` is below `len`.
238            unsafe { self.get_unchecked_mut(offset as usize) }
239        } else {
240            no_item_at(index)
241        }
242    }
243
244    #[inline]
245    fn logos_slice(&self, start: i64, end: i64) -> &[T] {
246        &self[logos_slice_range(start, end, self.len())]
247    }
248
249    #[inline]
250    fn logos_run_through(&self, first: i64, last: i64) -> &[T] {
251        &self[logos_run_through(first, last, self.len())]
252    }
253
254    #[inline]
255    fn logos_run_before(&self, first: i64, stop: i64) -> &[T] {
256        &self[logos_run_before(first, stop, self.len())]
257    }
258
259    fn logos_reverse_between(&mut self, lo: i64, hi: i64) {
260        if lo >= 1 && lo < hi && hi as u64 <= self.len() as u64 {
261            self[(lo - 1) as usize..hi as usize].reverse();
262            return;
263        }
264        let (mut lo, mut hi) = (lo, hi);
265        while lo < hi {
266            let a = resolve_logos_index(lo, self.len());
267            let b = resolve_logos_index(hi, self.len());
268            self.swap(a, b);
269            lo += 1;
270            hi -= 1;
271        }
272    }
273}
274
275// === Vec<T> with i64 (1-based indexing) ===
276
277impl<T: Clone> LogosIndex<i64> for Vec<T> {
278    type Output = T;
279
280    #[inline(always)]
281    fn logos_get(&self, index: i64) -> T {
282        let idx = resolve_logos_index(index, self.len());
283        unsafe { self.get_unchecked(idx).clone() }
284    }
285}
286
287impl<T: Clone> LogosIndexMut<i64> for Vec<T> {
288    #[inline(always)]
289    fn logos_set(&mut self, index: i64, value: T) {
290        let idx = resolve_logos_index(index, self.len());
291        unsafe {
292            *self.get_unchecked_mut(idx) = value;
293        }
294    }
295}
296
297// === LogosTuple (a newtype over Vec<Value>) with i64 (1-based indexing) ===
298// UFCS `LogosIndex::logos_get(&t, n)` does NOT deref-coerce, so the tuple newtype needs its own impl
299// (delegating to the inner Vec) for `item N of t` / `t[n]`.
300impl LogosIndex<i64> for crate::types::LogosTuple {
301    type Output = crate::types::Value;
302
303    #[inline(always)]
304    fn logos_get(&self, index: i64) -> crate::types::Value {
305        let idx = resolve_logos_index(index, self.0.len());
306        unsafe { self.0.get_unchecked(idx).clone() }
307    }
308}
309
310impl LogosIndexMut<i64> for crate::types::LogosTuple {
311    #[inline(always)]
312    fn logos_set(&mut self, index: i64, value: crate::types::Value) {
313        let idx = resolve_logos_index(index, self.0.len());
314        unsafe {
315            *self.0.get_unchecked_mut(idx) = value;
316        }
317    }
318}
319
320// === [T] slice with i64 (1-based indexing, used by &mut [T] borrow params) ===
321
322impl<T: Clone> LogosIndex<i64> for [T] {
323    type Output = T;
324
325    #[inline(always)]
326    fn logos_get(&self, index: i64) -> T {
327        let idx = resolve_logos_index(index, self.len());
328        unsafe { self.get_unchecked(idx).clone() }
329    }
330}
331
332impl<T: Clone> LogosIndexMut<i64> for [T] {
333    #[inline(always)]
334    fn logos_set(&mut self, index: i64, value: T) {
335        let idx = resolve_logos_index(index, self.len());
336        unsafe {
337            *self.get_unchecked_mut(idx) = value;
338        }
339    }
340}
341
342// === &mut [T] and &[T] with i64 (thin wrappers for UFCS compatibility) ===
343//
344// When the codegen emits `LogosIndex::logos_get(&arr, i)` where `arr: &mut [T]`,
345// the first argument is `&&mut [T]` (or `&&[T]` for a borrowed slice). Rust doesn't auto-coerce
346// these to `&[T]` in UFCS, so each has an explicit impl that delegates to the `[T]` impl.
347
348impl<T: Clone> LogosIndex<i64> for &mut [T] {
349    type Output = T;
350
351    #[inline(always)]
352    fn logos_get(&self, index: i64) -> T {
353        <[T] as LogosIndex<i64>>::logos_get(self, index)
354    }
355}
356
357impl<T: Clone> LogosIndex<i64> for &[T] {
358    type Output = T;
359
360    #[inline(always)]
361    fn logos_get(&self, index: i64) -> T {
362        <[T] as LogosIndex<i64>>::logos_get(self, index)
363    }
364}
365
366impl<T: Clone> LogosIndexMut<i64> for &mut [T] {
367    #[inline(always)]
368    fn logos_set(&mut self, index: i64, value: T) {
369        <[T] as LogosIndexMut<i64>>::logos_set(self, index, value)
370    }
371}
372
373// === String with i64 (1-based character indexing) ===
374
375impl LogosIndex<i64> for String {
376    type Output = String;
377
378    #[inline(always)]
379    fn logos_get(&self, index: i64) -> String {
380        // Positive indexes keep the count-free ASCII fast path; only an
381        // end-relative (or zero) index pays the char count.
382        let idx = if index >= 1 {
383            (index - 1) as usize
384        } else {
385            resolve_logos_index(index, self.chars().count())
386        };
387        match self.as_bytes().get(idx) {
388            Some(&b) if b.is_ascii() => {
389                // Fast path: ASCII byte
390                String::from(b as char)
391            }
392            _ => {
393                // Slow path: Unicode or out of bounds
394                self.chars()
395                    .nth(idx)
396                    .map(|c| c.to_string())
397                    .unwrap_or_else(|| panic!("{}", crate::failure::index_out_of_bounds(index)))
398            }
399        }
400    }
401}
402
403// === String with i64 (1-based character indexing, char return) ===
404
405/// Zero-allocation character access for string comparisons.
406///
407/// Unlike [`LogosIndex`] for `String` which returns a `String`,
408/// this trait returns a `char` — avoiding heap allocation entirely.
409/// Used by the codegen optimizer for string-index-vs-string-index comparisons.
410pub trait LogosGetChar {
411    fn logos_get_char(&self, index: i64) -> char;
412}
413
414impl LogosGetChar for String {
415    #[inline(always)]
416    fn logos_get_char(&self, index: i64) -> char {
417        let idx = if index >= 1 {
418            (index - 1) as usize
419        } else {
420            resolve_logos_index(index, self.chars().count())
421        };
422        match self.as_bytes().get(idx) {
423            Some(&b) if b.is_ascii() => b as char,
424            _ => self
425                .chars()
426                .nth(idx)
427                .unwrap_or_else(|| panic!("{}", crate::failure::index_out_of_bounds(index))),
428        }
429    }
430}
431
432// === LogosSeq<T> with i64 (1-based indexing, reference semantics) ===
433
434impl<T: Clone> LogosIndex<i64> for crate::types::LogosSeq<T> {
435    type Output = T;
436
437    #[inline(always)]
438    fn logos_get(&self, index: i64) -> T {
439        let inner = self.borrow();
440        <Vec<T> as LogosIndex<i64>>::logos_get(&*inner, index)
441    }
442}
443
444impl<T: Clone> LogosIndexMut<i64> for crate::types::LogosSeq<T> {
445    #[inline(always)]
446    fn logos_set(&mut self, index: i64, value: T) {
447        let mut inner = self.borrow_mut();
448        <Vec<T> as LogosIndexMut<i64>>::logos_set(&mut *inner, index, value)
449    }
450}
451
452// === LogosMap<K, V> with K (key-based indexing, reference semantics) ===
453
454impl<K: Eq + Hash + crate::failure::FailureText, V: Clone> LogosIndex<K>
455    for crate::types::LogosMap<K, V>
456{
457    type Output = V;
458
459    #[inline(always)]
460    fn logos_get(&self, key: K) -> V {
461        let inner = self.borrow();
462        inner
463            .get(&key)
464            .cloned()
465            .unwrap_or_else(|| panic!("{}", crate::failure::key_not_found(&key)))
466    }
467}
468
469impl<K: Eq + Hash + crate::failure::FailureText, V: Clone> LogosIndexMut<K>
470    for crate::types::LogosMap<K, V>
471{
472    #[inline(always)]
473    fn logos_set(&mut self, key: K, value: V) {
474        self.insert(key, value);
475    }
476}
477
478// === &str convenience for LogosMap<String, V> ===
479
480impl<V: Clone> LogosIndex<&str> for crate::types::LogosMap<String, V> {
481    type Output = V;
482
483    #[inline(always)]
484    fn logos_get(&self, key: &str) -> V {
485        let inner = self.borrow();
486        inner
487            .get(key)
488            .cloned()
489            .unwrap_or_else(|| panic!("{}", crate::failure::key_not_found(key)))
490    }
491}
492
493impl<V: Clone> LogosIndexMut<&str> for crate::types::LogosMap<String, V> {
494    #[inline(always)]
495    fn logos_set(&mut self, key: &str, value: V) {
496        self.insert(key.to_string(), value);
497    }
498}
499
500// === HashMap<K, V> with K (key-based indexing) ===
501
502impl<K: Eq + Hash + crate::failure::FailureText, V: Clone> LogosIndex<K> for FxHashMap<K, V> {
503    type Output = V;
504
505    #[inline(always)]
506    fn logos_get(&self, key: K) -> V {
507        self.get(&key)
508            .cloned()
509            .unwrap_or_else(|| panic!("{}", crate::failure::key_not_found(&key)))
510    }
511}
512
513impl<K: Eq + Hash + crate::failure::FailureText, V: Clone> LogosIndexMut<K> for FxHashMap<K, V> {
514    #[inline(always)]
515    fn logos_set(&mut self, key: K, value: V) {
516        self.insert(key, value);
517    }
518}
519
520// === &str convenience for HashMap<String, V> ===
521
522impl<V: Clone> LogosIndex<&str> for FxHashMap<String, V> {
523    type Output = V;
524
525    #[inline(always)]
526    fn logos_get(&self, key: &str) -> V {
527        self.get(key)
528            .cloned()
529            .unwrap_or_else(|| panic!("{}", crate::failure::key_not_found(key)))
530    }
531}
532
533impl<V: Clone> LogosIndexMut<&str> for FxHashMap<String, V> {
534    #[inline(always)]
535    fn logos_set(&mut self, key: &str, value: V) {
536        self.insert(key.to_string(), value);
537    }
538}
539
540#[cfg(test)]
541#[path = "../../logicaffeine_tests/unit/logicaffeine_data/indexing/tests.rs"]
542mod tests;