Skip to main content

logicaffeine_base/
arena.rs

1//! Arena allocation for stable AST references.
2//!
3//! This module provides owning allocation for AST nodes, ensuring references
4//! remain valid throughout parsing and semantic analysis. The arena pattern
5//! eliminates reference counting overhead and enables zero-copy parsing.
6//!
7//! ## Example
8//!
9//! ```
10//! use logicaffeine_base::Arena;
11//!
12//! let arena: Arena<String> = Arena::new();
13//! let s1 = arena.alloc("hello".to_string());
14//! let s2 = arena.alloc("world".to_string());
15//!
16//! // Both references remain valid as long as arena is alive
17//! assert_eq!(s1, "hello");
18//! assert_eq!(s2, "world");
19//! ```
20//!
21//! ## REPL Reuse
22//!
23//! For interactive use, call [`Arena::reset`] between evaluations to
24//! reclaim memory while keeping allocated capacity.
25
26use std::cell::RefCell;
27
28/// An owning arena for stable references.
29///
30/// Values stay at their allocated addresses until the arena is dropped or reset.
31/// Their destructors run at that boundary, including destructors of owned AST
32/// vectors and strings.
33pub struct Arena<T> {
34    chunks: RefCell<Chunks<T>>,
35}
36
37// Owning Vec<T>s give both ordinary drop glue and Rust's drop checking access to T.
38// Moving a Vec header never moves its elements; a published chunk never reallocates.
39struct Chunks<T> {
40    values: Vec<Vec<T>>,
41    active: usize,
42}
43
44impl<T> Arena<T> {
45    /// Creates an empty arena.
46    pub fn new() -> Self {
47        Self {
48            chunks: RefCell::new(Chunks {
49                values: Vec::new(),
50                active: 0,
51            }),
52        }
53    }
54
55    /// Allocates a value and returns a reference valid for the arena's lifetime.
56    pub fn alloc(&self, value: T) -> &T {
57        let mut chunks = self.chunks.borrow_mut();
58        let has_room = chunks.active > 0 && {
59            let current = &chunks.values[chunks.active - 1];
60            current.len() < current.capacity()
61        };
62        if !has_room {
63            let next = chunks.active;
64            if next == chunks.values.len() {
65                let initial = (4096 / std::mem::size_of::<T>().max(1)).max(1);
66                let previous = chunks.values.last().map_or(0, Vec::capacity);
67                let capacity = previous.saturating_mul(2).max(initial);
68                chunks.values.push(Vec::with_capacity(capacity));
69            }
70            debug_assert!(chunks.values[next].is_empty());
71            chunks.active += 1;
72        }
73        let current = chunks.active - 1;
74        let chunk = &mut chunks.values[current];
75        let index = chunk.len();
76        debug_assert!(index < chunk.capacity());
77        chunk.push(value);
78        // SAFETY: push stayed within the existing capacity. This and every later
79        // allocation leave previously published elements at their addresses. The
80        // buffer is owned by self; reset needs exclusive access and drop ends the
81        // borrow. Do not index through a mutable slice spanning earlier values.
82        unsafe { &*chunk.as_ptr().add(index) }
83    }
84
85    /// Allocates a contiguous slice from an iterator.
86    ///
87    /// The iterator must implement ExactSizeIterator so its allocation can be
88    /// reserved up front. It may itself allocate from this arena.
89    pub fn alloc_slice<I>(&self, items: I) -> &[T]
90    where
91        I: IntoIterator<Item = T>,
92        I::IntoIter: ExactSizeIterator,
93    {
94        let iter = items.into_iter();
95        let length = iter.len();
96        // Take an unused buffer without holding the RefCell borrow while user
97        // iterator code runs. Its Vec owns partial initialization if that code
98        // panics; no initialized element can be forgotten.
99        let mut buffer = {
100            let mut chunks = self.chunks.borrow_mut();
101            let spare = (chunks.active..chunks.values.len())
102                .find(|&i| chunks.values[i].capacity() >= length);
103            match spare {
104                Some(i) => chunks.values.swap_remove(i),
105                None => Vec::with_capacity(length),
106            }
107        };
108        debug_assert!(buffer.is_empty());
109        buffer.extend(iter);
110        if buffer.is_empty() {
111            return &[];
112        }
113        let pointer = buffer.as_ptr();
114        let length = buffer.len();
115        let mut chunks = self.chunks.borrow_mut();
116        let next = chunks.active;
117        chunks.values.insert(next, buffer);
118        chunks.active += 1;
119        // SAFETY: moving the Vec into the arena preserves its buffer address.
120        // Future scalar allocations check its capacity before pushing, and slice
121        // allocations use separate unused buffers. The shared arena borrow keeps
122        // reset and drop from running while the returned slice is live.
123        unsafe { std::slice::from_raw_parts(pointer, length) }
124    }
125
126    /// Drops every value, invalidating references while retaining reusable storage.
127    ///
128    /// Repeated evaluations can reuse the arena without retaining AST-owned data.
129    pub fn reset(&mut self) {
130        let chunks = self.chunks.get_mut();
131        for chunk in &mut chunks.values {
132            chunk.clear();
133        }
134        chunks.active = 0;
135    }
136}
137
138impl<T> Default for Arena<T> {
139    fn default() -> Self {
140        Self::new()
141    }
142}
143
144#[cfg(test)]
145#[path = "../../logicaffeine_tests/unit/logicaffeine_base/arena/tests.rs"]
146mod tests;