Skip to main content

eventql_parser/
arena.rs

1use crate::typing::{ArgsRef, Record, Type, TypeRef};
2use crate::{Attrs, ExprKey, ExprPtr, ExprRef, Field, RecRef, StrRef, Value, VecRef};
3use rustc_hash::{FxBuildHasher, FxHashMap};
4use serde::Serialize;
5use std::collections::hash_map::Entry;
6use std::hash::BuildHasher;
7use std::ops::Range;
8use unicase::Ascii;
9
10/// An arena-based allocator for interning strings.
11///
12/// Deduplicates strings by hash and returns lightweight [`StrRef`] handles for O(1) lookups.
13#[derive(Default, Serialize)]
14pub(crate) struct StringArena {
15    #[serde(skip_serializing)]
16    hasher: FxBuildHasher,
17
18    cache: FxHashMap<u64, StrRef>,
19    slots: Vec<String>,
20}
21
22impl StringArena {
23    /// Interns a string and returns its [`StrRef`]. Returns the existing reference if already interned.
24    pub fn alloc(&mut self, value: &str) -> StrRef {
25        match self.cache.entry(self.hasher.hash_one(value)) {
26            Entry::Occupied(entry) => *entry.get(),
27            Entry::Vacant(entry) => {
28                let key = StrRef(self.slots.len());
29                entry.insert(key);
30                self.slots.push(value.to_owned());
31
32                key
33            }
34        }
35    }
36
37    /// If that value has already been interned, it returns the string pointer in the arena.
38    pub fn str_ref(&self, value: &str) -> Option<StrRef> {
39        self.cache.get(&self.hasher.hash_one(value)).copied()
40    }
41
42    /// Interns a string using case-insensitive hashing.
43    ///
44    /// Two strings that differ only in ASCII case will resolve to the same [`StrRef`].
45    /// The original casing of the first insertion is preserved.
46    pub fn alloc_no_case(&mut self, value: &str) -> StrRef {
47        match self.cache.entry(self.hasher.hash_one(Ascii::new(value))) {
48            Entry::Occupied(entry) => *entry.get(),
49            Entry::Vacant(entry) => {
50                let key = StrRef(self.slots.len());
51                entry.insert(key);
52                self.slots.push(value.to_owned());
53
54                key
55            }
56        }
57    }
58
59    /// Retrieves the string associated with the given [`StrRef`].
60    pub fn get(&self, key: StrRef) -> &str {
61        &self.slots[key.0]
62    }
63}
64
65/// An expression node stored in the [`ExprArena`].
66///
67/// Combines the expression's metadata ([`Attrs`]) with its actual content ([`Value`]).
68#[derive(Debug, Clone, Copy, Serialize)]
69pub struct Expr {
70    /// Metadata including source position.
71    pub attrs: Attrs,
72    /// The kind and content of this expression.
73    pub value: Value,
74}
75
76/// An arena-based allocator for EventQL expressions.
77///
78/// The `ExprArena` provides a memory-efficient way to store and manage AST nodes
79/// by using a flat vector and returning lightweight [`ExprRef`] handles.
80#[derive(Default, Serialize)]
81pub(crate) struct ExprArena {
82    #[serde(skip_serializing)]
83    hasher: FxBuildHasher,
84    exprs: Vec<Expr>,
85    vecs: Vec<Vec<ExprRef>>,
86    recs: Vec<Vec<Field>>,
87}
88
89impl ExprArena {
90    /// Allocates a new expression in the arena.
91    ///
92    /// This method takes an expression's attributes and value, hashes the value
93    /// to create a stable [`ExprKey`], and stores it in the arena. It returns
94    /// an [`ExprRef`] which can be used to retrieve the expression later.
95    pub fn alloc(&mut self, attrs: Attrs, value: Value) -> ExprRef {
96        let key = ExprKey(self.hasher.hash_one(value));
97
98        let ptr = ExprPtr(self.exprs.len());
99        self.exprs.push(Expr { attrs, value });
100
101        ExprRef { key, ptr }
102    }
103
104    /// Retrieves a node from the arena using an [`ExprRef`].
105    ///
106    /// # Panics
107    ///
108    /// Panics if the [`ExprRef`] contains an invalid pointer that is out of bounds
109    /// of the arena's internal storage.
110    pub fn get(&self, node_ref: ExprRef) -> Expr {
111        self.exprs[node_ref.ptr.0]
112    }
113
114    /// Allocates a vector of expression references and returns a [`VecRef`] handle.
115    pub fn alloc_vec(&mut self, values: Vec<ExprRef>) -> VecRef {
116        let key = VecRef(self.vecs.len());
117        self.vecs.push(values);
118
119        key
120    }
121
122    /// Allocates a vector of record fields and returns a [`RecRef`] handle.
123    pub fn alloc_rec(&mut self, values: Vec<Field>) -> RecRef {
124        let key = RecRef(self.recs.len());
125        self.recs.push(values);
126
127        key
128    }
129
130    /// Returns the slice of expression references for the given [`VecRef`].
131    pub fn vec(&self, ptr: VecRef) -> &[ExprRef] {
132        &self.vecs[ptr.0]
133    }
134
135    /// Returns the expression reference at index `idx` within the given [`VecRef`].
136    pub fn vec_get(&self, ptr: VecRef, idx: usize) -> ExprRef {
137        self.vecs[ptr.0][idx]
138    }
139
140    /// Returns an iterator over valid indices for the given [`VecRef`].
141    pub fn vec_idxes(&self, ptr: VecRef) -> Range<usize> {
142        0..self.vec(ptr).len()
143    }
144
145    /// Returns the vector of fields for the given [`RecRef`].
146    pub fn rec(&self, ptr: RecRef) -> &[Field] {
147        self.recs[ptr.0].as_slice()
148    }
149
150    /// Returns the field at index `idx` within the given [`RecRef`].
151    pub fn rec_get(&self, ptr: RecRef, idx: usize) -> Field {
152        self.recs[ptr.0][idx]
153    }
154
155    /// Returns an iterator over valid indices for the given [`RecRef`].
156    pub fn rec_idxes(&self, ptr: RecRef) -> Range<usize> {
157        0..self.rec(ptr).len()
158    }
159}
160
161/// An arena-based allocator for type information.
162///
163/// Stores and deduplicates types, record definitions, and function argument lists.
164/// Supports freezing to mark a baseline and freeing types allocated after the baseline.
165#[derive(Default, Serialize)]
166pub(crate) struct TypeArena {
167    #[serde(skip_serializing)]
168    args_hasher: FxBuildHasher,
169
170    type_offset: usize,
171    rec_offset: usize,
172
173    dedup_types: FxHashMap<Type, TypeRef>,
174    dedup_args: FxHashMap<u64, ArgsRef>,
175    types: Vec<Type>,
176    pub(crate) records: Vec<FxHashMap<StrRef, Type>>,
177    pub(crate) args: Vec<Vec<Type>>,
178}
179
180impl TypeArena {
181    /// Marks the current allocation state as the baseline.
182    ///
183    /// Subsequent calls to [`free_space`](TypeArena::free_space) will deallocate
184    /// only types and records allocated after this point.
185    pub fn freeze(&mut self) {
186        self.rec_offset = self.records.len();
187        self.type_offset = self.types.len();
188    }
189
190    /// Frees types and records allocated after the last [`freeze`](TypeArena::freeze) call.
191    pub fn free_space(&mut self) {
192        for tpe in self.types.drain(self.type_offset..) {
193            self.dedup_types.remove(&tpe);
194        }
195
196        for _ in self.records.drain(self.rec_offset..) {}
197    }
198
199    /// Registers a type and returns a deduplicated [`TypeRef`]. Returns the existing reference if already registered.
200    pub fn register_type(&mut self, tpe: Type) -> TypeRef {
201        match self.dedup_types.entry(tpe) {
202            Entry::Occupied(entry) => *entry.get(),
203            Entry::Vacant(entry) => {
204                let key = TypeRef(self.types.len());
205                self.types.push(tpe);
206                entry.insert(key);
207
208                key
209            }
210        }
211    }
212
213    /// Allocates a fresh copy of a type. For records, this clones the record definition.
214    pub fn alloc_type(&mut self, tpe: Type) -> Type {
215        if let Type::Record(rec) = tpe {
216            let key = Record {
217                id: self.records.len(),
218                open: rec.open,
219            };
220            // TODO: technically, a deep-clone is needed here, where properties that point to
221            // records should also be allocated as well.
222            self.records.push(self.records[rec.id].clone());
223
224            return Type::Record(key);
225        }
226
227        tpe
228    }
229
230    /// Creates an array type containing elements of the given type.
231    pub fn alloc_array_of(&mut self, tpe: Type) -> Type {
232        Type::Array(self.register_type(tpe))
233    }
234
235    /// Allocates a new record type from a map of field names to types.
236    pub fn alloc_record(&mut self, record: FxHashMap<StrRef, Type>) -> Record {
237        let key = Record {
238            id: self.records.len(),
239            open: false,
240        };
241        self.records.push(record);
242        key
243    }
244
245    /// Allocates a new open record type from a map of field names to types. An open record type is
246    /// a record type that doesn't fail typechecking if we try to access a field that isn't defined yet.
247    pub fn alloc_open_record(&mut self, record: FxHashMap<StrRef, Type>) -> Record {
248        let key = Record {
249            id: self.records.len(),
250            open: true,
251        };
252        self.records.push(record);
253        key
254    }
255
256    /// Allocates a deduplicated list of function argument types and returns an [`ArgsRef`].
257    pub fn alloc_args(&mut self, args: &[Type]) -> ArgsRef {
258        let hash = self.args_hasher.hash_one(args);
259
260        match self.dedup_args.entry(hash) {
261            Entry::Occupied(entry) => *entry.get(),
262            Entry::Vacant(entry) => {
263                let key = ArgsRef(self.args.len());
264                entry.insert(key);
265                self.args.push(args.to_vec());
266
267                key
268            }
269        }
270    }
271
272    /// Retrieves the type for the given [`TypeRef`].
273    pub fn get_type(&self, key: TypeRef) -> Type {
274        self.types[key.0]
275    }
276
277    /// Returns the field map for the given record.
278    pub fn get_record(&self, key: Record) -> &FxHashMap<StrRef, Type> {
279        &self.records[key.id]
280    }
281
282    /// Returns the argument type slice for the given [`ArgsRef`].
283    pub fn get_args(&self, key: ArgsRef) -> &[Type] {
284        self.args[key.0].as_slice()
285    }
286
287    /// Returns an iterator over valid indices for the given [`ArgsRef`].
288    pub fn args_idxes(&self, key: ArgsRef) -> impl Iterator<Item = usize> + use<> {
289        0..self.get_args(key).len()
290    }
291
292    /// Returns the argument type at index `idx` for the given [`ArgsRef`].
293    pub fn args_get(&self, key: ArgsRef, idx: usize) -> Type {
294        self.get_args(key)[idx]
295    }
296
297    /// Returns the type of a field in the given record, or `None` if the field doesn't exist.
298    pub fn record_get(&self, record: Record, field: StrRef) -> Option<Type> {
299        self.records[record.id].get(&field).copied()
300    }
301
302    /// Checks whether two records have the exact same set of field names.
303    pub fn records_have_same_keys(&self, rec_a: Record, rec_b: Record) -> bool {
304        let rec_a = self.get_record(rec_a);
305        let rec_b = self.get_record(rec_b);
306
307        if rec_a.is_empty() && rec_b.is_empty() {
308            return true;
309        }
310
311        if rec_a.len() != rec_b.len() {
312            return false;
313        }
314
315        for bk in rec_b.keys() {
316            if !rec_a.contains_key(bk) {
317                return false;
318            }
319        }
320
321        true
322    }
323
324    /// Creates an empty open record type.
325    pub fn instantiate_open_record(&mut self) -> Record {
326        self.alloc_open_record(FxHashMap::default())
327    }
328
329    /// Sets the type of a field in the given record, inserting or updating as needed.
330    pub fn record_set(&mut self, record: Record, field: StrRef, value: Type) {
331        self.records[record.id].insert(field, value);
332    }
333
334    /// Returns the number of fields in the given record.
335    pub fn record_len(&self, record: Record) -> usize {
336        self.records[record.id].len()
337    }
338}
339
340/// Top-level arena that holds all memory pools for expressions, strings, and types.
341#[derive(Default, Serialize)]
342pub struct Arena {
343    pub(crate) exprs: ExprArena,
344    pub(crate) strings: StringArena,
345    pub(crate) types: TypeArena,
346}
347
348impl Arena {
349    /// Freezes the type arena to mark the current state as baseline.
350    pub fn freeze(&mut self) {
351        self.types.freeze();
352    }
353
354    /// Frees types allocated after the last freeze, reclaiming memory for reuse.
355    pub fn free_space(&mut self) {
356        self.types.free_space();
357    }
358
359    /// Retrieves the interned string associated with the given [`StrRef`].
360    pub fn get_str(&self, key: StrRef) -> &str {
361        self.strings.get(key)
362    }
363
364    /// If that value has already been interned, it returns the string pointer in the arena.
365    pub fn str_ref(&self, key: &str) -> Option<StrRef> {
366        self.strings.str_ref(key)
367    }
368
369    /// Retrieves the expression node associated with the given [`ExprRef`].
370    pub fn get_expr(&self, key: ExprRef) -> Expr {
371        self.exprs.get(key)
372    }
373
374    /// Retrieves the type associated with the given [`TypeRef`].
375    pub fn get_type(&self, key: TypeRef) -> Type {
376        self.types.get_type(key)
377    }
378
379    /// Returns the slice of expression references for the given [`VecRef`].
380    pub fn get_vec(&self, key: VecRef) -> &[ExprRef] {
381        self.exprs.vec(key)
382    }
383
384    /// Returns the slice of record fields for the given [`RecRef`].
385    pub fn get_rec(&self, key: RecRef) -> &[Field] {
386        self.exprs.rec(key)
387    }
388
389    /// Returns the map of type record fields for the given type [`Record`]
390    pub fn get_type_rec(&self, key: Record) -> &FxHashMap<StrRef, Type> {
391        self.types.get_record(key)
392    }
393
394    /// Returns the function argument types for the given [`ArgsRef`].
395    pub fn get_args(&self, key: ArgsRef) -> &[Type] {
396        self.types.get_args(key)
397    }
398}