You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.1 KiB

2 years ago
use std::fmt;
2 years ago
2 years ago
use crate::value::Value;
2 years ago
2 years ago
#[derive(Debug)]
2 years ago
pub enum OpCode {
2 years ago
Constant(usize),
2 years ago
Add,
Subtract,
Multiply,
Divide,
2 years ago
Negate,
2 years ago
Return,
}
2 years ago
#[derive(Debug, Default)]
2 years ago
pub struct Chunk {
pub code: Vec<OpCode>,
pub lines: Vec<usize>,
2 years ago
pub constants: Vec<Value>,
2 years ago
}
2 years ago
impl Chunk {
2 years ago
pub fn push(&mut self, op_code: OpCode, line: usize) {
self.code.push(op_code);
self.lines.push(line);
2 years ago
}
2 years ago
2 years ago
pub fn push_constant(&mut self, value: Value, line: usize) {
2 years ago
self.constants.push(value);
2 years ago
self.push(OpCode::Constant(self.constants.len() - 1), line)
2 years ago
}
2 years ago
pub fn disassemble(&self, name: &str) {
2 years ago
println!("== {} ==\n{}", name, self);
2 years ago
}
2 years ago
}
2 years ago
impl fmt::Display for Chunk {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2 years ago
for i in 0..self.code.len() {
writeln!(f, "{}", DisassembledInstruction { i, chunk: self })?;
}
Ok(())
}
}
pub struct DisassembledInstruction<'a> {
i: usize,
chunk: &'a Chunk,
}
impl<'a> DisassembledInstruction<'a> {
pub fn new(i: usize, chunk: &'a Chunk) -> Self {
Self { i, chunk }
}
}
impl fmt::Display for DisassembledInstruction<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:04} ", self.i)?;
let line = self.chunk.lines[self.i];
if self.i > 0 && line != self.chunk.lines[self.i - 1] {
write!(f, " | ")?;
} else {
write!(f, "{:>4} ", line)?;
}
match self.chunk.code[self.i] {
2 years ago
OpCode::Constant(constant) => write!(
f,
"{:<16} {:4} '{}'",
"OP_CONSTANT", constant, self.chunk.constants[constant]
)?,
2 years ago
OpCode::Add => write!(f, "OP_ADD")?,
OpCode::Subtract => write!(f, "OP_SUBTRACT")?,
OpCode::Multiply => write!(f, "OP_MULTIPLY")?,
OpCode::Divide => write!(f, "OP_DIVIDE")?,
2 years ago
OpCode::Negate => write!(f, "OP_NEGATE")?,
OpCode::Return => write!(f, "OP_RETURN")?,
}
2 years ago
Ok(())
}
}