use crate::{Addr, Op};
use alloc::vec::Vec;
use value_lang::Value;
#[derive(Debug, Clone, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Chunk {
code: Vec<Op>,
constants: Vec<Value>,
registers: u16,
}
impl Chunk {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn emit(&mut self, op: Op) -> Addr {
if let Some(top) = max_register(op) {
self.registers = self.registers.max(top.saturating_add(1));
}
let addr = self.code.len() as Addr;
self.code.push(op);
addr
}
#[must_use = "the returned index is how the constant is later loaded"]
pub fn constant(&mut self, value: Value) -> Option<u16> {
let index = u16::try_from(self.constants.len()).ok()?;
self.constants.push(value);
Some(index)
}
pub fn patch(&mut self, addr: Addr, op: Op) -> bool {
let Some(slot) = self.code.get_mut(addr as usize) else {
return false;
};
*slot = op;
self.recompute_registers();
true
}
#[must_use]
pub fn code(&self) -> &[Op] {
&self.code
}
#[must_use]
pub fn constants(&self) -> &[Value] {
&self.constants
}
#[must_use]
pub fn registers(&self) -> u16 {
self.registers
}
#[must_use]
pub fn len(&self) -> usize {
self.code.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.code.is_empty()
}
fn recompute_registers(&mut self) {
self.registers = self
.code
.iter()
.filter_map(|op| max_register(*op))
.map(|top| top.saturating_add(1))
.max()
.unwrap_or(0);
}
}
#[inline]
fn max_register(op: Op) -> Option<u16> {
match op {
Op::Move { dst, src } | Op::Neg { dst, src } | Op::Not { dst, src } => Some(dst.max(src)),
Op::LoadConst { dst, .. }
| Op::LoadNil { dst }
| Op::LoadBool { dst, .. }
| Op::LoadInt { dst, .. } => Some(dst),
Op::Add { dst, lhs, rhs }
| Op::Sub { dst, lhs, rhs }
| Op::Mul { dst, lhs, rhs }
| Op::Div { dst, lhs, rhs }
| Op::Rem { dst, lhs, rhs }
| Op::Eq { dst, lhs, rhs }
| Op::Ne { dst, lhs, rhs }
| Op::Lt { dst, lhs, rhs }
| Op::Le { dst, lhs, rhs }
| Op::Gt { dst, lhs, rhs }
| Op::Ge { dst, lhs, rhs } => Some(dst.max(lhs).max(rhs)),
Op::JumpIfTrue { cond, .. } | Op::JumpIfFalse { cond, .. } | Op::Return { src: cond } => {
Some(cond)
}
Op::Jump { .. } | Op::Halt => None,
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used)]
use super::*;
#[test]
fn test_emit_returns_sequential_addresses() {
let mut c = Chunk::new();
assert_eq!(c.emit(Op::Halt), 0);
assert_eq!(c.emit(Op::Halt), 1);
assert_eq!(c.len(), 2);
}
#[test]
fn test_register_file_tracks_highest_index() {
let mut c = Chunk::new();
let _ = c.emit(Op::Add {
dst: 5,
lhs: 2,
rhs: 9,
});
assert_eq!(c.registers(), 10);
}
#[test]
fn test_constant_returns_incrementing_indices() {
let mut c = Chunk::new();
assert_eq!(c.constant(Value::int(1)), Some(0));
assert_eq!(c.constant(Value::int(2)), Some(1));
assert_eq!(c.constants().len(), 2);
}
#[test]
fn test_patch_replaces_instruction_and_reports_success() {
let mut c = Chunk::new();
let at = c.emit(Op::Jump { target: 0 });
assert!(c.patch(at, Op::Jump { target: 7 }));
assert_eq!(c.code()[at as usize], Op::Jump { target: 7 });
}
#[test]
fn test_patch_out_of_range_returns_false() {
let mut c = Chunk::new();
assert!(!c.patch(0, Op::Halt));
}
#[test]
fn test_patch_recomputes_register_file() {
let mut c = Chunk::new();
let at = c.emit(Op::LoadInt { dst: 40, val: 1 });
assert_eq!(c.registers(), 41);
assert!(c.patch(at, Op::Halt));
assert_eq!(c.registers(), 0);
}
#[test]
fn test_new_chunk_is_empty() {
let c = Chunk::new();
assert!(c.is_empty());
assert_eq!(c.registers(), 0);
}
}