mirror of
https://github.com/uutils/awk.git
synced 2026-06-10 16:15:04 -07:00
interpreter: initial unary ops; tiny binops refactor
This commit is contained in:
@@ -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
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user