Skip to content

Commit

Permalink
Add imm() function for instructions
Browse files Browse the repository at this point in the history
  • Loading branch information
mliezun committed Jan 22, 2024
1 parent 360be4c commit af85ba1
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
15 changes: 11 additions & 4 deletions src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -400,8 +400,13 @@ impl Compiler {
}

fn binary_literal(&mut self, expr: &Expr, operator: &TokenData, literal: &LiteralExpr) -> Option<Chunk> {
let opcode = match operator.token {
Token::Plus => OpCode::Addi,
Token::Minus => OpCode::Subi,
_ => return None,
};
if let Literal::Number(n) = literal.value {
if operator.token == Token::Plus && n.fract() == 0.0 && n < 256.0 {
if operator.token == Token::Plus && n.fract() == 0.0 && n < 256.0 && n >= 0.0 {
let left_chunk = expr.accept(self);
let mut chunk = Chunk {
instructions: vec![],
Expand All @@ -412,7 +417,7 @@ impl Compiler {
.append(&mut left_chunk.instructions.clone());
chunk.push(
Instruction {
opcode: OpCode::Addi,
opcode: opcode,
a: chunk.result_register,
b: left_chunk.result_register,
c: (n as i32) as u8,
Expand Down Expand Up @@ -1650,8 +1655,10 @@ impl ExprVisitor<Chunk> for Compiler {
}
}
if let Expr::Literal(l) = &*expr.left {
if let Some(chunk) = self.binary_literal(&*expr.right, &expr.operator, l) {
return chunk;
if expr.operator.token != Token::Minus {
if let Some(chunk) = self.binary_literal(&*expr.right, &expr.operator, l) {
return chunk;
}
}
}
let left_chunk = expr.left.accept(self);
Expand Down
5 changes: 4 additions & 1 deletion src/instruction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,13 @@ impl Instruction {
let b = self.b as u16;
let c = self.c as u16;
let result = (b << 8 | c) as i16;
// println!("sbx = {:#?}", result);
return result;
}

pub fn imm(&self) -> f64 {
return self.c as f64
}

pub fn is_continue(&mut self) -> bool {
self.opcode == OpCode::Jmp && self.a == JMP_CONTINUE
}
Expand Down
4 changes: 2 additions & 2 deletions src/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1161,7 +1161,7 @@ impl VM {
.clone();
if let Record::Val(Value::Number(n)) = val_b {
self.activation_records[sp + inst.a as usize] = Record::Val(Value::Number(NumberValue {
n: n.n + inst.c as f64
n: n.n + inst.imm()
}));
} else {
match val_b
Expand Down Expand Up @@ -1194,7 +1194,7 @@ impl VM {
.clone();
if let Record::Val(Value::Number(n)) = val_b {
self.activation_records[sp + inst.a as usize] = Record::Val(Value::Number(NumberValue {
n: n.n - inst.c as f64
n: n.n - inst.imm()
}));
} else {
match val_b
Expand Down

0 comments on commit af85ba1

Please sign in to comment.