beamr 0.6.4

A Rust runtime with the BEAM's execution model, targeting Gleam
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
//! Call stack frames.
//!
//! The stack holds return addresses and Y-register slots. `allocate` pushes a
//! frame with N Y-register slots; `deallocate` pops it. Tail calls
//! (`call_last`, `call_ext_last`) deallocate before jumping, preventing stack
//! growth in recursive functions.

use std::fmt;
use std::sync::Arc;

use crate::atom::Atom;
use crate::module::Module;
use crate::term::Term;

/// Default maximum call-stack depth in frames.
pub const DEFAULT_STACK_FRAME_LIMIT: usize = 10_000;

/// Saved return location for a stack frame.
#[derive(Clone, Debug)]
pub struct ReturnPoint {
    /// Module to return to.
    pub module: Atom,
    /// Instruction pointer to resume at in `module`.
    pub ip: usize,
    /// Pinned module version to resume after returning.
    pub module_version: Arc<Module>,
}

impl PartialEq for ReturnPoint {
    fn eq(&self, other: &Self) -> bool {
        self.module == other.module
            && self.ip == other.ip
            && Arc::ptr_eq(&self.module_version, &other.module_version)
    }
}

impl Eq for ReturnPoint {}

/// One call-stack frame with its own Y-register slots.
#[derive(Clone, Debug)]
pub struct StackFrame {
    return_module: Atom,
    return_ip: usize,
    pinned_module: Arc<Module>,
    y_slots: u16,
    y_regs: Vec<Term>,
}

impl StackFrame {
    fn new(
        return_module: Atom,
        return_ip: usize,
        pinned_module: Arc<Module>,
        y_slots: u16,
    ) -> Self {
        Self {
            return_module,
            return_ip,
            pinned_module,
            y_slots,
            y_regs: vec![Term::NIL; usize::from(y_slots)],
        }
    }

    /// Return module saved by this frame.
    #[must_use]
    pub const fn return_module(&self) -> Atom {
        self.return_module
    }

    /// Return instruction pointer saved by this frame.
    #[must_use]
    pub const fn return_ip(&self) -> usize {
        self.return_ip
    }

    /// Pinned module version saved by this frame.
    #[must_use]
    pub const fn pinned_module(&self) -> &Arc<Module> {
        &self.pinned_module
    }

    /// Number of Y-register slots owned by this frame.
    #[must_use]
    pub const fn y_slots(&self) -> u16 {
        self.y_slots
    }

    /// Iterator over all Y-register slots in this frame.
    pub(crate) fn y_regs(&self) -> impl Iterator<Item = &Term> {
        self.y_regs.iter()
    }

    /// Mutable iterator over all Y-register slots in this frame.
    pub(crate) fn y_regs_mut(&mut self) -> impl Iterator<Item = &mut Term> {
        self.y_regs.iter_mut()
    }

    /// Read a Y-register in this frame.
    pub fn y_reg(&self, n: u16) -> Result<Term, StackError> {
        self.y_regs
            .get(usize::from(n))
            .copied()
            .ok_or(StackError::YRegisterOutOfBounds {
                index: n,
                slots: self.y_slots,
            })
    }

    /// Write a Y-register in this frame.
    pub fn set_y_reg(&mut self, n: u16, value: Term) -> Result<(), StackError> {
        let slots = self.y_slots;
        let Some(slot) = self.y_regs.get_mut(usize::from(n)) else {
            return Err(StackError::YRegisterOutOfBounds { index: n, slots });
        };
        *slot = value;
        Ok(())
    }

    /// Shrink this frame to `remaining` Y-register slots.
    ///
    /// BEAM `trim N, Remaining` discards the N lowest-numbered Y registers
    /// and renumbers the survivors down: the old `y(N+k)` becomes `y(k)`.
    pub fn trim_y_regs(&mut self, remaining: u16) -> Result<(), StackError> {
        if remaining > self.y_slots {
            return Err(StackError::YRegisterOutOfBounds {
                index: remaining,
                slots: self.y_slots,
            });
        }

        let discard = usize::from(self.y_slots - remaining);
        self.y_regs.drain(..discard);
        self.y_slots = remaining;
        Ok(())
    }
}

impl PartialEq for StackFrame {
    fn eq(&self, other: &Self) -> bool {
        self.return_module == other.return_module
            && self.return_ip == other.return_ip
            && Arc::ptr_eq(&self.pinned_module, &other.pinned_module)
            && self.y_slots == other.y_slots
            && self.y_regs == other.y_regs
    }
}

impl Eq for StackFrame {}

/// Stack operation errors.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum StackError {
    /// Pushing another frame would exceed the configured frame limit.
    StackOverflow { limit: usize },
    /// A pop or Y-register access was attempted with no current frame.
    StackUnderflow,
    /// A Y-register index exceeded the current frame's slot count.
    YRegisterOutOfBounds { index: u16, slots: u16 },
}

impl fmt::Display for StackError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::StackOverflow { limit } => {
                write!(f, "stack overflow: frame limit {limit} reached")
            }
            Self::StackUnderflow => f.write_str("stack underflow"),
            Self::YRegisterOutOfBounds { index, slots } => {
                write!(f, "Y register {index} out of bounds for {slots} slots")
            }
        }
    }
}

impl std::error::Error for StackError {}

/// Per-process call stack.
#[derive(Clone, Debug)]
pub struct Stack {
    frames: Vec<StackFrame>,
    frame_limit: usize,
}

impl Stack {
    /// Create an empty stack with the default frame limit.
    #[must_use]
    pub fn new() -> Self {
        Self::with_frame_limit(DEFAULT_STACK_FRAME_LIMIT)
    }

    /// Create an empty stack with a custom frame limit.
    #[must_use]
    pub const fn with_frame_limit(frame_limit: usize) -> Self {
        Self {
            frames: Vec::new(),
            frame_limit,
        }
    }

    /// Push a frame saving `module:ip`, pinning the caller module version, and allocating `y_slots` Y-registers.
    pub fn push_frame(
        &mut self,
        module: Atom,
        ip: usize,
        pinned_module: Arc<Module>,
        y_slots: u16,
    ) -> Result<(), StackError> {
        if self.frames.len() >= self.frame_limit {
            return Err(StackError::StackOverflow {
                limit: self.frame_limit,
            });
        }

        self.frames
            .push(StackFrame::new(module, ip, pinned_module, y_slots));
        Ok(())
    }

    /// Pop the current frame and return its saved return point.
    pub fn pop_frame(&mut self) -> Result<ReturnPoint, StackError> {
        let Some(frame) = self.frames.pop() else {
            return Err(StackError::StackUnderflow);
        };

        Ok(ReturnPoint {
            module: frame.return_module,
            ip: frame.return_ip,
            module_version: frame.pinned_module,
        })
    }

    /// Return the current frame.
    pub fn current_frame(&self) -> Result<&StackFrame, StackError> {
        self.frames.last().ok_or(StackError::StackUnderflow)
    }

    /// Return the current frame mutably.
    pub fn current_frame_mut(&mut self) -> Result<&mut StackFrame, StackError> {
        self.frames.last_mut().ok_or(StackError::StackUnderflow)
    }

    /// Read a Y-register from the current frame.
    pub fn y_reg(&self, n: u16) -> Result<Term, StackError> {
        self.current_frame()?.y_reg(n)
    }

    /// Write a Y-register in the current frame.
    pub fn set_y_reg(&mut self, n: u16, value: Term) -> Result<(), StackError> {
        self.current_frame_mut()?.set_y_reg(n, value)
    }

    /// Shrink the current frame to `remaining` lowest-numbered Y-register slots.
    pub fn trim_y_regs(&mut self, remaining: u16) -> Result<(), StackError> {
        self.current_frame_mut()?.trim_y_regs(remaining)
    }

    /// Number of frames on the stack.
    #[must_use]
    pub fn len(&self) -> usize {
        self.frames.len()
    }

    /// Drop frames above `len`, preserving all lower frames.
    pub fn truncate(&mut self, len: usize) {
        self.frames.truncate(len);
    }

    /// Returns true when the stack has no frames.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.frames.is_empty()
    }

    /// Configured maximum frame count.
    #[must_use]
    pub const fn frame_limit(&self) -> usize {
        self.frame_limit
    }

    /// Iterator over every module version pinned by stack frames.
    pub fn pinned_modules(&self) -> impl Iterator<Item = &Arc<Module>> {
        self.frames.iter().map(StackFrame::pinned_module)
    }

    /// Iterator over call frames from newest to oldest.
    pub fn frames_from_top(&self) -> impl Iterator<Item = &StackFrame> {
        self.frames.iter().rev()
    }

    /// Iterator over every Y-register in every stack frame.
    pub(crate) fn y_regs(&self) -> impl Iterator<Item = &Term> {
        self.frames.iter().flat_map(StackFrame::y_regs)
    }

    /// Mutable iterator over every Y-register in every stack frame.
    pub(crate) fn y_regs_mut(&mut self) -> impl Iterator<Item = &mut Term> {
        self.frames.iter_mut().flat_map(StackFrame::y_regs_mut)
    }
}

impl Default for Stack {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::{ReturnPoint, Stack, StackError, StackFrame};
    use std::collections::HashMap;
    use std::sync::Arc;

    use crate::atom::Atom;
    use crate::loader::Instruction;
    use crate::module::{Module, ModuleOrigin, ModuleRegistry, PurgeError};
    use crate::term::Term;

    fn test_module(name: Atom) -> Module {
        Module {
            name,
            generation: 0,
            origin: ModuleOrigin::Preloaded,
            exports: HashMap::new(),
            label_index: HashMap::from([(1, 0)]),
            code: vec![Instruction::Label { label: 1 }],
            literals: Vec::new(),
            constant_pool: Default::default(),
            resolved_imports: Vec::new(),
            lambdas: Vec::new(),
            string_table: Vec::new(),
            function_table: Vec::new(),
            line_table: Vec::new(),
            line_info: Vec::new(),
        }
    }

    fn module_arc(name: Atom) -> Arc<Module> {
        Arc::new(test_module(name))
    }

    #[test]
    fn new_stack_is_empty() {
        let stack = Stack::new();

        assert!(stack.is_empty());
        assert_eq!(stack.len(), 0);
    }

    #[test]
    fn push_and_pop_round_trips_return_point() {
        let mut stack = Stack::new();
        let module_version = module_arc(Atom::OK);

        stack
            .push_frame(Atom::OK, 42, Arc::clone(&module_version), 2)
            .expect("frame should fit on empty stack");
        let return_point = stack.pop_frame().expect("frame should pop");

        assert_eq!(
            return_point,
            ReturnPoint {
                module: Atom::OK,
                ip: 42,
                module_version,
            }
        );
        assert!(stack.is_empty());
    }

    #[test]
    fn y_registers_start_as_nil() {
        let mut stack = Stack::new();

        stack
            .push_frame(Atom::OK, 0, module_arc(Atom::OK), 2)
            .expect("frame should fit on empty stack");

        assert_eq!(stack.y_reg(0), Ok(Term::NIL));
        assert_eq!(stack.y_reg(1), Ok(Term::NIL));
    }

    #[test]
    fn y_registers_are_isolated_by_frame() {
        let mut stack = Stack::new();

        stack
            .push_frame(Atom::OK, 0, module_arc(Atom::OK), 1)
            .expect("first frame should fit");
        stack
            .set_y_reg(0, Term::small_int(10))
            .expect("Y0 exists in first frame");
        stack
            .push_frame(Atom::ERROR, 1, module_arc(Atom::ERROR), 1)
            .expect("second frame should fit");
        stack
            .set_y_reg(0, Term::small_int(20))
            .expect("Y0 exists in second frame");

        assert_eq!(stack.y_reg(0), Ok(Term::small_int(20)));
        let _ = stack.pop_frame().expect("second frame should pop");
        assert_eq!(stack.y_reg(0), Ok(Term::small_int(10)));
    }

    #[test]
    fn truncate_drops_frames_above_depth() {
        let mut stack = Stack::new();

        stack
            .push_frame(Atom::OK, 0, module_arc(Atom::OK), 1)
            .expect("first frame should fit");
        stack
            .set_y_reg(0, Term::small_int(10))
            .expect("Y0 exists in first frame");
        stack
            .push_frame(Atom::ERROR, 1, module_arc(Atom::ERROR), 1)
            .expect("second frame should fit");
        stack
            .set_y_reg(0, Term::small_int(20))
            .expect("Y0 exists in second frame");

        stack.truncate(1);

        assert_eq!(stack.len(), 1);
        assert_eq!(stack.y_reg(0), Ok(Term::small_int(10)));

        stack.truncate(0);

        assert!(stack.is_empty());
        assert_eq!(stack.y_reg(0), Err(StackError::StackUnderflow));
    }

    #[test]
    fn pushing_beyond_frame_limit_returns_overflow() {
        let mut stack = Stack::with_frame_limit(1);

        stack
            .push_frame(Atom::OK, 0, module_arc(Atom::OK), 0)
            .expect("first frame should fit");
        let error = stack
            .push_frame(Atom::OK, 1, module_arc(Atom::OK), 0)
            .expect_err("second frame should exceed custom limit");

        assert_eq!(error, StackError::StackOverflow { limit: 1 });
    }

    #[test]
    fn pop_on_empty_stack_returns_underflow() {
        let mut stack = Stack::new();

        assert_eq!(stack.pop_frame(), Err(StackError::StackUnderflow));
    }

    #[test]
    fn y_register_bounds_are_checked() {
        let mut stack = Stack::new();

        stack
            .push_frame(Atom::OK, 0, module_arc(Atom::OK), 1)
            .expect("frame should fit on empty stack");

        assert_eq!(
            stack.y_reg(1),
            Err(StackError::YRegisterOutOfBounds { index: 1, slots: 1 })
        );
    }

    #[test]
    fn stack_frame_trim_y_registers_keeps_high_slots_and_updates_slot_count() {
        let mut frame = StackFrame::new(Atom::OK, 7, module_arc(Atom::OK), 5);
        for (index, value) in (0_u16..).zip([10, 20, 30, 40, 50]) {
            frame
                .set_y_reg(index, Term::small_int(value))
                .expect("allocated Y register should exist");
        }

        frame.trim_y_regs(3).expect("trim within frame slots");

        assert_eq!(frame.y_slots(), 3);
        assert_eq!(frame.y_reg(0), Ok(Term::small_int(30)));
        assert_eq!(frame.y_reg(1), Ok(Term::small_int(40)));
        assert_eq!(frame.y_reg(2), Ok(Term::small_int(50)));
        assert_eq!(
            frame.y_reg(3),
            Err(StackError::YRegisterOutOfBounds { index: 3, slots: 3 })
        );
    }

    #[test]
    fn stack_trim_y_registers_keeps_high_slots_and_preserves_return_metadata() {
        let mut stack = Stack::new();
        let module_version = module_arc(Atom::OK);

        stack
            .push_frame(Atom::OK, 7, Arc::clone(&module_version), 5)
            .expect("frame should fit on empty stack");
        for (index, value) in (0_u16..).zip([10, 20, 30, 40, 50]) {
            stack
                .set_y_reg(index, Term::small_int(value))
                .expect("allocated Y register should exist");
        }

        stack.trim_y_regs(3).expect("trim within frame slots");

        let growth_error = stack
            .trim_y_regs(4)
            .expect_err("trim must not grow current frame");
        assert_eq!(
            growth_error,
            StackError::YRegisterOutOfBounds { index: 4, slots: 3 }
        );

        let frame = stack.current_frame().expect("trim must not pop frame");
        assert_eq!(frame.y_slots(), 3);
        assert_eq!(frame.return_module(), Atom::OK);
        assert_eq!(frame.return_ip(), 7);
        assert!(Arc::ptr_eq(frame.pinned_module(), &module_version));
        assert_eq!(stack.y_reg(0), Ok(Term::small_int(30)));
        assert_eq!(stack.y_reg(1), Ok(Term::small_int(40)));
        assert_eq!(stack.y_reg(2), Ok(Term::small_int(50)));
        assert_eq!(
            stack.y_reg(3),
            Err(StackError::YRegisterOutOfBounds { index: 3, slots: 3 })
        );
    }

    #[test]
    fn frames_pin_old_module_versions_across_reload_and_purge() {
        let registry = ModuleRegistry::new();
        let a_v1 = registry.insert(test_module(Atom::OK));
        let b_v1 = registry.insert(test_module(Atom::ERROR));
        let c_v1 = registry.insert(test_module(Atom::UNDEFINED));
        let mut stack = Stack::new();

        stack
            .push_frame(Atom::OK, 10, Arc::clone(&a_v1), 0)
            .expect("A frame should fit");
        stack
            .push_frame(Atom::ERROR, 20, Arc::clone(&b_v1), 0)
            .expect("B frame should fit");
        stack
            .push_frame(Atom::UNDEFINED, 30, Arc::clone(&c_v1), 0)
            .expect("C frame should fit");

        let _a_v2 = registry.insert(test_module(Atom::OK));
        let _b_v2 = registry.insert(test_module(Atom::ERROR));

        assert!(matches!(
            registry.purge_old(Atom::OK),
            Err(PurgeError::StillReferenced {
                module: Atom::OK,
                ..
            })
        ));
        assert!(matches!(
            registry.purge_old(Atom::ERROR),
            Err(PurgeError::StillReferenced {
                module: Atom::ERROR,
                ..
            })
        ));

        let c_return = stack.pop_frame().expect("C frame should pop");
        assert_eq!(c_return.module, Atom::UNDEFINED);
        assert!(Arc::ptr_eq(&c_return.module_version, &c_v1));

        let b_return = stack.pop_frame().expect("B frame should pop");
        assert_eq!(b_return.module, Atom::ERROR);
        assert!(Arc::ptr_eq(&b_return.module_version, &b_v1));

        let a_return = stack.pop_frame().expect("A frame should pop");
        assert_eq!(a_return.module, Atom::OK);
        assert!(Arc::ptr_eq(&a_return.module_version, &a_v1));
    }
}