Alpha Chen 2 years ago
parent da8c978c11
commit cc6d837f49
Signed by: alpha
SSH Key Fingerprint: SHA256:3fOT8fiYQG/aK9ntivV3Bqtg8AYQ7q4nV6ZgihOA20g

@ -5,6 +5,7 @@ use crate::value::Value;
#[derive(Debug)] #[derive(Debug)]
pub enum OpCode { pub enum OpCode {
Constant(usize), Constant(usize),
Negate,
Return, Return,
} }
@ -62,13 +63,13 @@ impl fmt::Display for DisassembledInstruction<'_> {
write!(f, "{:>4} ", line)?; write!(f, "{:>4} ", line)?;
} }
match self.chunk.code[self.i] { match self.chunk.code[self.i] {
OpCode::Constant(constant) => { OpCode::Constant(constant) => write!(
let value = self.chunk.constants[constant]; f,
write!(f, "{:<16} {:4} '{}'", "OP_CONSTANT", constant, value)?; "{:<16} {:4} '{}'",
} "OP_CONSTANT", constant, self.chunk.constants[constant]
OpCode::Return => { )?,
write!(f, "OP_RETURN")?; OpCode::Negate => write!(f, "OP_NEGATE")?,
} OpCode::Return => write!(f, "OP_RETURN")?,
} }
Ok(()) Ok(())

@ -19,6 +19,7 @@ fn main() -> Result<()> {
let mut chunk = Chunk::default(); let mut chunk = Chunk::default();
chunk.push_constant(1.2, 123); chunk.push_constant(1.2, 123);
chunk.push(OpCode::Negate, 123);
chunk.push(OpCode::Return, 123); chunk.push(OpCode::Return, 123);
chunk.disassemble("test chunk"); chunk.disassemble("test chunk");

@ -42,6 +42,10 @@ impl VM {
let value = self.chunk.constants[*constant]; let value = self.chunk.constants[*constant];
self.push(value); self.push(value);
} }
OpCode::Negate => {
let value = self.pop();
self.push(-value);
}
OpCode::Return => { OpCode::Return => {
println!("{}", self.pop()); println!("{}", self.pop());
return Ok(()); return Ok(());

Loading…
Cancel
Save