Skip to main content

aver/nan_value/
arena.rs

1use super::*;
2
3impl Arena {
4    pub fn new() -> Self {
5        Arena {
6            young_entries: Vec::with_capacity(256),
7            yard_entries: Vec::with_capacity(64),
8            handoff_entries: Vec::with_capacity(64),
9            stable_entries: Vec::with_capacity(64),
10            scratch_young: Vec::new(),
11            scratch_yard: Vec::new(),
12            scratch_handoff: Vec::new(),
13            scratch_stable: Vec::new(),
14            peak_usage: ArenaUsage::default(),
15            alloc_space: AllocSpace::Young,
16            type_names: Vec::new(),
17            type_field_names: Vec::new(),
18            type_variant_names: Vec::new(),
19            type_variant_ctor_ids: Vec::new(),
20            ctor_to_type_variant: Vec::new(),
21            symbol_entries: Vec::new(),
22        }
23    }
24
25    /// Create a fresh Arena with only the static context (symbols, type metadata,
26    /// stable constants) from this Arena. Dynamic runtime entries are empty.
27    /// Used for independent product threads: each gets a clean Arena with just the
28    /// compile-time context needed to execute functions and builtins.
29    pub fn clone_static(&self) -> Self {
30        Arena {
31            young_entries: Vec::with_capacity(64),
32            yard_entries: Vec::new(),
33            handoff_entries: Vec::new(),
34            stable_entries: self.stable_entries.clone(),
35            scratch_young: Vec::new(),
36            scratch_yard: Vec::new(),
37            scratch_handoff: Vec::new(),
38            scratch_stable: Vec::new(),
39            peak_usage: ArenaUsage::default(),
40            alloc_space: AllocSpace::Young,
41            type_names: self.type_names.clone(),
42            type_field_names: self.type_field_names.clone(),
43            type_variant_names: self.type_variant_names.clone(),
44            type_variant_ctor_ids: self.type_variant_ctor_ids.clone(),
45            ctor_to_type_variant: self.ctor_to_type_variant.clone(),
46            symbol_entries: self.symbol_entries.clone(),
47        }
48    }
49
50    /// Deep-import a NanValue from `source` arena into `self`.
51    /// Inline values (int, float, bool, unit, none, empty containers) are returned as-is.
52    /// Heap-referenced values are recursively copied into `self` with new indices.
53    pub fn deep_import(&mut self, value: NanValue, source: &Arena) -> NanValue {
54        // Not NaN-boxed = plain float, return as-is
55        if !value.is_nan_boxed() {
56            return value;
57        }
58        // Check if it has a heap index — if not, it's inline
59        let heap_idx = match value.heap_index() {
60            Some(idx) => idx,
61            None => return value, // inline int, bool, unit, none, empty list/map/etc
62        };
63
64        let entry = source.get(heap_idx).clone();
65        match entry {
66            ArenaEntry::Int(i) => NanValue::new_int(i, self),
67            ArenaEntry::String(s) => {
68                let idx = self.push(ArenaEntry::String(s));
69                NanValue::new_string(idx)
70            }
71            ArenaEntry::Tuple(items) => {
72                let imported: Vec<NanValue> =
73                    items.iter().map(|v| self.deep_import(*v, source)).collect();
74                let idx = self.push_tuple(imported);
75                NanValue::new_tuple(idx)
76            }
77            ArenaEntry::List(_) => {
78                // Flatten list and re-import as a fresh flat list
79                let flat = source.list_to_vec_value(value);
80                let imported: Vec<NanValue> =
81                    flat.iter().map(|v| self.deep_import(*v, source)).collect();
82                if imported.is_empty() {
83                    NanValue::EMPTY_LIST
84                } else {
85                    let rc_items = Rc::new(imported);
86                    let idx = self.push(ArenaEntry::List(ArenaList::Flat {
87                        items: rc_items,
88                        start: 0,
89                    }));
90                    NanValue::new_list(idx)
91                }
92            }
93            ArenaEntry::Map(map) => {
94                let new_map = super::PersistentMap::new();
95                for (hash, (k, v)) in map.iter() {
96                    let ik = self.deep_import(*k, source);
97                    let iv = self.deep_import(*v, source);
98                    new_map.insert(*hash, (ik, iv));
99                }
100                let idx = self.push(ArenaEntry::Map(new_map));
101                NanValue::new_map(idx)
102            }
103            ArenaEntry::Vector(items) => {
104                let imported: Vec<NanValue> =
105                    items.iter().map(|v| self.deep_import(*v, source)).collect();
106                let idx = self.push(ArenaEntry::Vector(imported));
107                NanValue::new_vector(idx)
108            }
109            ArenaEntry::Record { type_id, fields } => {
110                let imported: Vec<NanValue> = fields
111                    .iter()
112                    .map(|v| self.deep_import(*v, source))
113                    .collect();
114                let idx = self.push(ArenaEntry::Record {
115                    type_id,
116                    fields: imported,
117                });
118                NanValue::new_record(idx)
119            }
120            ArenaEntry::Variant {
121                type_id,
122                variant_id,
123                fields,
124            } => {
125                let imported: Vec<NanValue> = fields
126                    .iter()
127                    .map(|v| self.deep_import(*v, source))
128                    .collect();
129                let idx = self.push(ArenaEntry::Variant {
130                    type_id,
131                    variant_id,
132                    fields: imported,
133                });
134                NanValue::new_variant(idx)
135            }
136            ArenaEntry::Boxed(inner) => {
137                let imported = self.deep_import(inner, source);
138                let idx = self.push(ArenaEntry::Boxed(imported));
139                NanValue::encode(value.tag(), ARENA_REF_BIT | (idx as u64))
140            }
141            // Fn/Builtin/Namespace — should not appear in independent product results
142            ArenaEntry::Fn(_) | ArenaEntry::Builtin(_) | ArenaEntry::Namespace { .. } => value,
143        }
144    }
145
146    #[inline]
147    pub fn push(&mut self, entry: ArenaEntry) -> u32 {
148        match &entry {
149            ArenaEntry::Fn(_) | ArenaEntry::Builtin(_) | ArenaEntry::Namespace { .. } => {}
150            _ => {
151                return match self.alloc_space {
152                    AllocSpace::Young => {
153                        let idx = self.young_entries.len() as u32;
154                        self.young_entries.push(entry);
155                        self.note_peak_usage();
156                        Self::encode_index(HeapSpace::Young, idx)
157                    }
158                    AllocSpace::Yard => {
159                        let idx = self.yard_entries.len() as u32;
160                        self.yard_entries.push(entry);
161                        self.note_peak_usage();
162                        Self::encode_index(HeapSpace::Yard, idx)
163                    }
164                    AllocSpace::Handoff => {
165                        let idx = self.handoff_entries.len() as u32;
166                        self.handoff_entries.push(entry);
167                        self.note_peak_usage();
168                        Self::encode_index(HeapSpace::Handoff, idx)
169                    }
170                };
171            }
172        }
173        match entry {
174            ArenaEntry::Fn(f) => self.push_symbol(ArenaSymbol::Fn(f)),
175            ArenaEntry::Builtin(name) => self.push_symbol(ArenaSymbol::Builtin(name)),
176            ArenaEntry::Namespace { name, members } => {
177                self.push_symbol(ArenaSymbol::Namespace { name, members })
178            }
179            _ => unreachable!("non-symbol entry already returned above"),
180        }
181    }
182
183    #[inline]
184    pub fn push_symbol(&mut self, symbol: ArenaSymbol) -> u32 {
185        let idx = self.symbol_entries.len() as u32;
186        self.symbol_entries.push(symbol);
187        idx
188    }
189
190    #[inline]
191    pub fn get(&self, index: u32) -> &ArenaEntry {
192        let (space, raw_index) = Self::decode_index(index);
193        match space {
194            HeapSpace::Young => &self.young_entries[raw_index as usize],
195            HeapSpace::Yard => &self.yard_entries[raw_index as usize],
196            HeapSpace::Handoff => &self.handoff_entries[raw_index as usize],
197            HeapSpace::Stable => &self.stable_entries[raw_index as usize],
198        }
199    }
200
201    #[inline]
202    pub(super) fn encode_index(space: HeapSpace, index: u32) -> u32 {
203        ((space as u32) << HEAP_SPACE_SHIFT) | index
204    }
205
206    #[inline]
207    pub(super) fn encode_yard_index(index: u32) -> u32 {
208        Self::encode_index(HeapSpace::Yard, index)
209    }
210
211    #[inline]
212    pub(super) fn encode_stable_index(index: u32) -> u32 {
213        Self::encode_index(HeapSpace::Stable, index)
214    }
215
216    #[inline]
217    pub(super) fn encode_handoff_index(index: u32) -> u32 {
218        Self::encode_index(HeapSpace::Handoff, index)
219    }
220
221    #[inline]
222    pub(super) fn decode_index(index: u32) -> (HeapSpace, u32) {
223        let space = match (index & HEAP_SPACE_MASK_U32) >> HEAP_SPACE_SHIFT {
224            0 => HeapSpace::Young,
225            1 => HeapSpace::Yard,
226            2 => HeapSpace::Handoff,
227            3 => HeapSpace::Stable,
228            _ => unreachable!("invalid heap space bits"),
229        };
230        (space, index & HEAP_INDEX_MASK_U32)
231    }
232
233    #[inline]
234    pub fn is_stable_index(index: u32) -> bool {
235        matches!(Self::decode_index(index).0, HeapSpace::Stable)
236    }
237
238    #[inline]
239    pub fn is_yard_index_in_region(&self, index: u32, mark: u32) -> bool {
240        let (space, raw_index) = Self::decode_index(index);
241        matches!(space, HeapSpace::Yard)
242            && raw_index >= mark
243            && raw_index < self.yard_entries.len() as u32
244    }
245
246    #[inline]
247    pub fn is_handoff_index_in_region(&self, index: u32, mark: u32) -> bool {
248        let (space, raw_index) = Self::decode_index(index);
249        matches!(space, HeapSpace::Handoff)
250            && raw_index >= mark
251            && raw_index < self.handoff_entries.len() as u32
252    }
253
254    #[inline]
255    pub fn is_young_index_in_region(&self, index: u32, mark: u32) -> bool {
256        let (space, raw_index) = Self::decode_index(index);
257        matches!(space, HeapSpace::Young)
258            && raw_index >= mark
259            && raw_index < self.young_entries.len() as u32
260    }
261
262    #[inline]
263    pub fn young_len(&self) -> usize {
264        self.young_entries.len()
265    }
266
267    #[inline]
268    pub fn yard_len(&self) -> usize {
269        self.yard_entries.len()
270    }
271
272    #[inline]
273    pub fn handoff_len(&self) -> usize {
274        self.handoff_entries.len()
275    }
276
277    #[inline]
278    pub fn stable_len(&self) -> usize {
279        self.stable_entries.len()
280    }
281
282    #[inline]
283    pub fn usage(&self) -> ArenaUsage {
284        ArenaUsage {
285            young: self.young_entries.len(),
286            yard: self.yard_entries.len(),
287            handoff: self.handoff_entries.len(),
288            stable: self.stable_entries.len(),
289        }
290    }
291
292    #[inline]
293    pub fn peak_usage(&self) -> ArenaUsage {
294        self.peak_usage
295    }
296
297    #[inline]
298    pub(super) fn note_peak_usage(&mut self) {
299        let usage = self.usage();
300        self.peak_usage.young = self.peak_usage.young.max(usage.young);
301        self.peak_usage.yard = self.peak_usage.yard.max(usage.yard);
302        self.peak_usage.handoff = self.peak_usage.handoff.max(usage.handoff);
303        self.peak_usage.stable = self.peak_usage.stable.max(usage.stable);
304    }
305
306    #[inline]
307    pub(super) fn take_u32_scratch(slot: &mut Vec<u32>, len: usize) -> Vec<u32> {
308        let mut scratch = std::mem::take(slot);
309        scratch.clear();
310        scratch.resize(len, u32::MAX);
311        scratch
312    }
313
314    #[inline]
315    pub(super) fn recycle_u32_scratch(slot: &mut Vec<u32>, mut scratch: Vec<u32>) {
316        scratch.clear();
317        *slot = scratch;
318    }
319
320    #[inline]
321    pub fn is_frame_local_index(
322        &self,
323        index: u32,
324        arena_mark: u32,
325        yard_mark: u32,
326        handoff_mark: u32,
327    ) -> bool {
328        self.is_young_index_in_region(index, arena_mark)
329            || self.is_yard_index_in_region(index, yard_mark)
330            || self.is_handoff_index_in_region(index, handoff_mark)
331    }
332
333    pub fn with_alloc_space<T>(&mut self, space: AllocSpace, f: impl FnOnce(&mut Arena) -> T) -> T {
334        let prev = self.alloc_space;
335        self.alloc_space = space;
336        let out = f(self);
337        self.alloc_space = prev;
338        out
339    }
340
341    // -- Typed push helpers ------------------------------------------------
342
343    pub fn push_i64(&mut self, val: i64) -> u32 {
344        self.push(ArenaEntry::Int(val))
345    }
346    pub fn push_string(&mut self, s: &str) -> u32 {
347        self.push(ArenaEntry::String(Rc::from(s)))
348    }
349    pub fn push_boxed(&mut self, val: NanValue) -> u32 {
350        self.push(ArenaEntry::Boxed(val))
351    }
352    pub fn push_record(&mut self, type_id: u32, fields: Vec<NanValue>) -> u32 {
353        self.push(ArenaEntry::Record { type_id, fields })
354    }
355    pub fn push_variant(&mut self, type_id: u32, variant_id: u16, fields: Vec<NanValue>) -> u32 {
356        self.push(ArenaEntry::Variant {
357            type_id,
358            variant_id,
359            fields,
360        })
361    }
362    pub fn push_list(&mut self, items: Vec<NanValue>) -> u32 {
363        self.push(ArenaEntry::List(ArenaList::Flat {
364            items: Rc::new(items),
365            start: 0,
366        }))
367    }
368    pub fn push_map(&mut self, map: PersistentMap) -> u32 {
369        self.push(ArenaEntry::Map(map))
370    }
371    pub fn push_tuple(&mut self, items: Vec<NanValue>) -> u32 {
372        self.push(ArenaEntry::Tuple(items))
373    }
374    pub fn push_vector(&mut self, items: Vec<NanValue>) -> u32 {
375        self.push(ArenaEntry::Vector(items))
376    }
377    pub fn push_fn(&mut self, f: Rc<FunctionValue>) -> u32 {
378        self.push_symbol(ArenaSymbol::Fn(f))
379    }
380    pub fn push_builtin(&mut self, name: &str) -> u32 {
381        self.push_symbol(ArenaSymbol::Builtin(Rc::from(name)))
382    }
383    pub fn push_nullary_variant_symbol(&mut self, ctor_id: u32) -> u32 {
384        self.push_symbol(ArenaSymbol::NullaryVariant { ctor_id })
385    }
386
387    // -- Typed getters -----------------------------------------------------
388
389    pub fn get_i64(&self, index: u32) -> i64 {
390        match self.get(index) {
391            ArenaEntry::Int(i) => *i,
392            _ => panic!("Arena: expected Int at {}", index),
393        }
394    }
395    pub fn get_string(&self, index: u32) -> &str {
396        match self.get(index) {
397            ArenaEntry::String(s) => s,
398            other => panic!("Arena: expected String at {} but found {:?}", index, other),
399        }
400    }
401    pub fn get_string_value(&self, value: NanValue) -> NanString<'_> {
402        if let Some(s) = value.small_string() {
403            s
404        } else {
405            NanString::Borrowed(self.get_string(value.arena_index()))
406        }
407    }
408    pub fn get_boxed(&self, index: u32) -> NanValue {
409        match self.get(index) {
410            ArenaEntry::Boxed(v) => *v,
411            _ => panic!("Arena: expected Boxed at {}", index),
412        }
413    }
414    pub fn get_record(&self, index: u32) -> (u32, &[NanValue]) {
415        match self.get(index) {
416            ArenaEntry::Record { type_id, fields } => (*type_id, fields),
417            _ => panic!("Arena: expected Record at {}", index),
418        }
419    }
420    pub fn get_variant(&self, index: u32) -> (u32, u16, &[NanValue]) {
421        match self.get(index) {
422            ArenaEntry::Variant {
423                type_id,
424                variant_id,
425                fields,
426            } => (*type_id, *variant_id, fields),
427            other => panic!("Arena: expected Variant at {} but found {:?}", index, other),
428        }
429    }
430    pub fn get_list(&self, index: u32) -> &ArenaList {
431        match self.get(index) {
432            ArenaEntry::List(items) => items,
433            _ => panic!("Arena: expected List at {}", index),
434        }
435    }
436    pub fn get_tuple(&self, index: u32) -> &[NanValue] {
437        match self.get(index) {
438            ArenaEntry::Tuple(items) => items,
439            _ => panic!("Arena: expected Tuple at {}", index),
440        }
441    }
442    pub fn get_vector(&self, index: u32) -> &[NanValue] {
443        match self.get(index) {
444            ArenaEntry::Vector(items) => items,
445            _ => panic!("Arena: expected Vector at {}", index),
446        }
447    }
448    pub fn vector_ref_value(&self, value: NanValue) -> &[NanValue] {
449        if value.is_empty_vector_immediate() {
450            return &[];
451        }
452        self.get_vector(value.arena_index())
453    }
454    pub fn clone_vector_value(&self, value: NanValue) -> Vec<NanValue> {
455        if value.is_empty_vector_immediate() {
456            Vec::new()
457        } else {
458            self.get_vector(value.arena_index()).to_vec()
459        }
460    }
461    pub fn get_map(&self, index: u32) -> &PersistentMap {
462        match self.get(index) {
463            ArenaEntry::Map(map) => map,
464            _ => panic!("Arena: expected Map at {}", index),
465        }
466    }
467    pub fn map_ref_value(&self, map: NanValue) -> &PersistentMap {
468        thread_local! {
469            static EMPTY_MAP: PersistentMap = PersistentMap::new();
470        }
471        if map.is_empty_map_immediate() {
472            // SAFETY: thread_local guarantees single-thread; reference is valid
473            // for the lifetime of the thread (longer than any Arena borrow).
474            return EMPTY_MAP.with(|m| unsafe { &*(m as *const PersistentMap) });
475        }
476        self.get_map(map.arena_index())
477    }
478    pub fn clone_map_value(&self, map: NanValue) -> PersistentMap {
479        if map.is_empty_map_immediate() {
480            PersistentMap::new()
481        } else {
482            self.get_map(map.arena_index()).clone()
483        }
484    }
485    pub fn get_fn(&self, index: u32) -> &FunctionValue {
486        match &self.symbol_entries[index as usize] {
487            ArenaSymbol::Fn(f) => f,
488            _ => panic!("Arena: expected Fn symbol at {}", index),
489        }
490    }
491    pub fn get_fn_rc(&self, index: u32) -> &Rc<FunctionValue> {
492        match &self.symbol_entries[index as usize] {
493            ArenaSymbol::Fn(f) => f,
494            _ => panic!("Arena: expected Fn symbol at {}", index),
495        }
496    }
497    pub fn get_builtin(&self, index: u32) -> &str {
498        match &self.symbol_entries[index as usize] {
499            ArenaSymbol::Builtin(s) => s,
500            _ => panic!("Arena: expected Builtin symbol at {}", index),
501        }
502    }
503    pub fn get_namespace(&self, index: u32) -> (&str, &[(Rc<str>, NanValue)]) {
504        match &self.symbol_entries[index as usize] {
505            ArenaSymbol::Namespace { name, members } => (name, members),
506            _ => panic!("Arena: expected Namespace symbol at {}", index),
507        }
508    }
509    pub fn get_nullary_variant_ctor(&self, index: u32) -> u32 {
510        match &self.symbol_entries[index as usize] {
511            ArenaSymbol::NullaryVariant { ctor_id } => *ctor_id,
512            _ => panic!("Arena: expected NullaryVariant symbol at {}", index),
513        }
514    }
515
516    // -- Type registry -----------------------------------------------------
517
518    pub fn register_record_type(&mut self, name: &str, field_names: Vec<String>) -> u32 {
519        let id = self.type_names.len() as u32;
520        self.type_names.push(name.to_string());
521        self.type_field_names.push(field_names);
522        self.type_variant_names.push(Vec::new());
523        self.type_variant_ctor_ids.push(Vec::new());
524        id
525    }
526
527    pub fn register_sum_type(&mut self, name: &str, variant_names: Vec<String>) -> u32 {
528        let id = self.type_names.len() as u32;
529        self.type_names.push(name.to_string());
530        self.type_field_names.push(Vec::new());
531        let ctor_ids: Vec<u32> = (0..variant_names.len())
532            .map(|variant_idx| {
533                let ctor_id = self.ctor_to_type_variant.len() as u32;
534                self.ctor_to_type_variant.push((id, variant_idx as u16));
535                ctor_id
536            })
537            .collect();
538        self.type_variant_names.push(variant_names);
539        self.type_variant_ctor_ids.push(ctor_ids);
540        id
541    }
542
543    pub fn register_variant_name(&mut self, type_id: u32, variant_name: String) -> u16 {
544        let variants = &mut self.type_variant_names[type_id as usize];
545        let variant_id = variants.len() as u16;
546        variants.push(variant_name);
547
548        let ctor_id = self.ctor_to_type_variant.len() as u32;
549        self.ctor_to_type_variant.push((type_id, variant_id));
550        self.type_variant_ctor_ids[type_id as usize].push(ctor_id);
551
552        variant_id
553    }
554
555    pub fn get_type_name(&self, type_id: u32) -> &str {
556        &self.type_names[type_id as usize]
557    }
558    pub fn type_count(&self) -> u32 {
559        self.type_names.len() as u32
560    }
561    pub fn get_field_names(&self, type_id: u32) -> &[String] {
562        &self.type_field_names[type_id as usize]
563    }
564    pub fn get_variant_name(&self, type_id: u32, variant_id: u16) -> &str {
565        &self.type_variant_names[type_id as usize][variant_id as usize]
566    }
567    pub fn find_type_id(&self, name: &str) -> Option<u32> {
568        self.type_names
569            .iter()
570            .position(|n| n == name)
571            .map(|i| i as u32)
572    }
573    pub fn find_variant_id(&self, type_id: u32, variant_name: &str) -> Option<u16> {
574        self.type_variant_names
575            .get(type_id as usize)?
576            .iter()
577            .position(|n| n == variant_name)
578            .map(|i| i as u16)
579    }
580
581    pub fn find_ctor_id(&self, type_id: u32, variant_id: u16) -> Option<u32> {
582        self.type_variant_ctor_ids
583            .get(type_id as usize)?
584            .get(variant_id as usize)
585            .copied()
586    }
587
588    pub fn get_ctor_parts(&self, ctor_id: u32) -> (u32, u16) {
589        self.ctor_to_type_variant
590            .get(ctor_id as usize)
591            .copied()
592            .unwrap_or_else(|| panic!("Arena: expected ctor id {} to be registered", ctor_id))
593    }
594
595    pub fn len(&self) -> usize {
596        self.young_entries.len()
597            + self.yard_entries.len()
598            + self.handoff_entries.len()
599            + self.stable_entries.len()
600    }
601    pub fn is_empty(&self) -> bool {
602        self.young_entries.is_empty()
603            && self.yard_entries.is_empty()
604            && self.handoff_entries.is_empty()
605            && self.stable_entries.is_empty()
606    }
607}
608
609impl Default for Arena {
610    fn default() -> Self {
611        Self::new()
612    }
613}