interpreter: initial unary ops; tiny binops refactor

This commit is contained in:
Guillem L. Jara
2026-05-26 07:25:20 +02:00
parent 58f63c35a1
commit 3b9ce0e689
3 changed files with 29 additions and 21 deletions
+1 -1
View File
@@ -201,7 +201,7 @@ impl OpCode {
fn is_unary(self) -> bool {
matches!(
self,
Self::Record | Self::Negation | Self::ToInt | Self::Negative | Self::Concat
Self::Record | Self::Negation | Self::ToInt | Self::Negative
)
}
+2 -2
View File
@@ -53,7 +53,7 @@ impl Value<'_> {
}
}
fn to_num(&self) -> f64 {
pub fn to_num(&self) -> f64 {
match self {
&Self::Float(f) => f,
&Self::Bool(b) => b as usize as f64,
@@ -79,7 +79,7 @@ impl Value<'_> {
pub fn string_size_hint(&self) -> usize {
match self {
Self::String(s) | Self::Regex(s) => s.len(),
Self::Float(_) => 2,
Self::Float(_) => 8,
Self::Bool(_) => 1,
_ => 0,
}
+26 -18
View File
@@ -108,26 +108,34 @@ impl Interpreter<'_> {
pub fn run(&mut self) {
while let Some(instr) = self.bc.code.get(self.program_counter) {
match instr {
// ix if let Some(&(dest, src)) = ix.get_unary() => {}
ix if let Some(&(dest, src)) = ix.get_unary() => {
let src = self.registers.get(src);
let val = match ix.opcode {
OpCode::Record => todo!(),
OpCode::Negation => Value::Float(!src.to_bool() as usize as f64),
OpCode::ToInt => Value::Float(src.to_num()),
OpCode::Negative => Value::Float(-src.to_num()),
_ => unreachable!(),
};
self.registers.write(dest, val);
}
ix if let Some(&(dest, lhs, rhs)) = ix.get_binary() => {
let val = {
let lhs = self.registers.get(lhs);
let rhs = self.registers.get(rhs);
match ix.opcode {
OpCode::Add => lhs + rhs,
OpCode::Subtract => lhs - rhs,
OpCode::Multiply => lhs * rhs,
OpCode::Divide => lhs / rhs,
OpCode::Concat => {
let mut buf = StdVec::with_capacity(
lhs.string_size_hint() + rhs.string_size_hint(),
);
lhs.write_string(&mut buf);
rhs.write_string(&mut buf);
Value::String(buf.into())
}
_ => todo!(),
let lhs = self.registers.get(lhs);
let rhs = self.registers.get(rhs);
let val = match ix.opcode {
OpCode::Add => lhs + rhs,
OpCode::Subtract => lhs - rhs,
OpCode::Multiply => lhs * rhs,
OpCode::Divide => lhs / rhs,
OpCode::Concat => {
let mut buf = StdVec::with_capacity(
lhs.string_size_hint() + rhs.string_size_hint(),
);
lhs.write_string(&mut buf);
rhs.write_string(&mut buf);
Value::String(buf.into())
}
_ => todo!(),
};
self.registers.write(dest, val);
}