[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 {
Return,
Constant { offset: usize },
Nil,
Negate,
Add,
Subtract,
@@ -133,7 +134,7 @@ impl fmt::Debug for TraceInfo<'_> {
}?;
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)
}
Op::Constant { offset } => {

View File

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

View File

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