diff options
| author | Edvard Thörnros <edvard.thornros@gmail.com> | 2021-01-09 16:03:41 +0100 |
|---|---|---|
| committer | Edvard Thörnros <edvard.thornros@gmail.com> | 2021-01-09 16:03:41 +0100 |
| commit | 3b480795fd82b5fd66b2b6263a2cac3335717202 (patch) | |
| tree | d161ef210b0d22962b3613876666df45b58ffaf1 /src/vm.rs | |
| parent | fccbcffcc8b1707760445d9f18f1bbdebbb4b69c (diff) | |
| download | sylt-3b480795fd82b5fd66b2b6263a2cac3335717202.tar.gz | |
Super simple VM
Diffstat (limited to 'src/vm.rs')
| -rw-r--r-- | src/vm.rs | 102 |
1 files changed, 102 insertions, 0 deletions
diff --git a/src/vm.rs b/src/vm.rs new file mode 100644 index 0000000..6b26b65 --- /dev/null +++ b/src/vm.rs @@ -0,0 +1,102 @@ + +#[derive(Debug, Clone, Copy)] +pub enum Value { + Float(f64), + Int(i64), + Bool(bool), +} + +#[derive(Debug)] +pub enum Op { + Pop, + Constant(Value), + Print, + Return, +} + +#[derive(Debug)] +pub struct Block { + name: String, + ops: Vec<Op>, +} + +impl Block { + pub fn new(name: &str) -> Self { + Self { + name: String::from(name), + ops: Vec::new(), + } + } + + pub fn add(&mut self, op: Op) -> usize { + self.ops.push(op); + self.ops.len() + } +} + +#[derive(Debug)] +pub struct VM { + stack: Vec<Value>, + + block: Block, + ip: usize, +} + +pub fn run_block(block: Block) { + let mut vm = VM { + stack: Vec::new(), + + block, + ip: 0, + }; + + vm.run(); +} + +impl VM { + pub fn run(&mut self) { + const PRINT_WHILE_RUNNING: bool = true; + const PRINT_BLOCK: bool = true; + + if PRINT_BLOCK { + println!(" === {} ===", self.block.name); + for s in self.block.ops.iter() { + println!("| {:?}", s); + } + println!(""); + } + + loop { + + if PRINT_WHILE_RUNNING { + print!(" ["); + for s in self.stack.iter() { + print!("{:?} ", s); + } + println!("]"); + + println!("{:?}", self.block.ops[self.ip]); + } + + match self.block.ops[self.ip] { + Op::Pop => { + self.stack.pop(); + } + + Op::Constant(value) => { + self.stack.push(value); + } + + Op::Print => { + println!("PRINT: {:?}", self.stack[0]); + } + + Op::Return => { + return; + } + } + + self.ip += 1; + } + } +} |
