blob: e35cd99b1e3d3f5607f863ee50ceda6d2aac1592 (
plain) (
blame)
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
|
//! This module implements the virtual (or abstract) machine that runs
//! Tvix bytecode.
use crate::{chunk::Chunk, errors::EvalResult, opcode::OpCode, value::Value};
pub struct VM {
ip: usize,
chunk: Chunk,
stack: Vec<Value>,
}
impl VM {
fn push(&mut self, value: Value) {
self.stack.push(value)
}
fn pop(&mut self) -> Value {
self.stack.pop().expect("TODO")
}
fn inc_ip(&mut self) -> OpCode {
let op = self.chunk.code[self.ip];
self.ip += 1;
op
}
fn run(&mut self) -> EvalResult<Value> {
loop {
match self.inc_ip() {
OpCode::OpConstant(idx) => {
let c = self.chunk.constant(idx).clone();
self.push(c);
}
OpCode::OpNull => todo!(),
OpCode::OpTrue => todo!(),
OpCode::OpFalse => todo!(),
}
if self.ip == self.chunk.code.len() {
return Ok(self.pop());
}
}
}
}
pub fn run_chunk(chunk: Chunk) -> EvalResult<Value> {
let mut vm = VM {
chunk,
ip: 0,
stack: vec![],
};
vm.run()
}
|