stack_vm/
frame.rs

1//! A call frame.
2//!
3//! Used internally by the `Machine` to keep track of call scope.
4
5use crate::write_many_table::WriteManyTable;
6use crate::table::Table;
7
8/// A call frame.
9///
10/// Contains:
11/// * A `WriteManyTable` for storage of local variables.
12/// * A return address - the instruction pointer for the machine to return to
13///   when returning from this call.
14#[derive(Debug)]
15pub struct Frame<T> {
16    locals: WriteManyTable<T>,
17    pub return_address: usize
18}
19
20impl<T> Frame<T> {
21    /// Creates a new call frame with the specified return address.
22    pub fn new(return_address: usize) -> Frame<T> {
23        Frame {
24            locals: WriteManyTable::new(),
25            return_address
26        }
27    }
28
29    /// Return a reference to the specified local variable.
30    pub fn get_local(&self, name: &str) -> Option<&T> {
31        self.locals.get(name)
32    }
33
34    /// Set the value of a local variable.
35    pub fn set_local(&mut self, name: &str, value: T) {
36        self.locals.insert(name, value);
37    }
38}
39
40#[cfg(test)]
41mod test {
42    use super::*;
43
44    #[test]
45    fn new_has_locals() {
46        let frame: Frame<usize> = Frame::new(0);
47        assert!(frame.locals.is_empty())
48    }
49}