[rlox] Add dedicated instruction for Nil

This commit is contained in:
ctsk
2023-10-08 20:30:43 +02:00
parent 68b165bebe
commit ef7c53a55c
3 changed files with 8 additions and 6 deletions

View File

@@ -6,6 +6,7 @@ use std::fmt;
pub enum Op { pub enum Op {
Return, Return,
Constant { offset: usize }, Constant { offset: usize },
Nil,
Negate, Negate,
Add, Add,
Subtract, Subtract,
@@ -133,7 +134,7 @@ impl fmt::Debug for TraceInfo<'_> {
}?; }?;
match op { match op {
Op::Return | Op::Negate | Op::Add | Op::Subtract | Op::Multiply | Op::Divide => { Op::Return | Op::Nil | Op::Negate | Op::Add | Op::Subtract | Op::Multiply | Op::Divide => {
write!(f, "{:?}", op) write!(f, "{:?}", op)
} }
Op::Constant { offset } => { Op::Constant { offset } => {

View File

@@ -352,7 +352,7 @@ impl<'src> Parser<'src> {
ttype: TokenType::Nil, ttype: TokenType::Nil,
span: _, span: _,
} => { } => {
chunk.add_constant(Value::Nil, 0); chunk.add_op(Op::Nil, 0);
} }
Token { Token {
ttype: TokenType::LeftParen, ttype: TokenType::LeftParen,
@@ -497,9 +497,9 @@ mod tests {
use crate::bc::Op::*; use crate::bc::Op::*;
let expected = Chunk::new_with( let expected = Chunk::new_with(
vec![Constant { offset: 0 }, Constant { offset: 1 }, Add], vec![Nil, Nil, Add],
vec![],
vec![], vec![],
vec![Value::Nil, Value::Nil],
); );
assert!(chunk.instr_eq(&expected)); assert!(chunk.instr_eq(&expected));

View File

@@ -76,6 +76,7 @@ impl VM {
match instr { match instr {
Op::Return => print!("{:?}", self.pop()?), Op::Return => print!("{:?}", self.pop()?),
Op::Constant { offset } => self.push(chunk.constants[offset]), Op::Constant { offset } => self.push(chunk.constants[offset]),
Op::Nil => self.push(Value::Nil),
Op::Negate => { Op::Negate => {
let new_val = -self.pop_num()?; let new_val = -self.pop_num()?;
self.push(new_val.into()); self.push(new_val.into());
@@ -144,9 +145,9 @@ mod tests {
#[test] #[test]
fn runtime_type_error() { fn runtime_type_error() {
let chunk = Chunk::new_with( let chunk = Chunk::new_with(
vec![Op::Constant { offset: 0 }, Op::Negate], vec![Op::Nil, Op::Negate],
vec![],
vec![], vec![],
vec![Value::Nil],
); );
let mut vm = VM::new(); let mut vm = VM::new();