Skip to content

Commit

Permalink
Compile binary literal expressions as immediates
Browse files Browse the repository at this point in the history
  • Loading branch information
mliezun committed Jan 20, 2024
1 parent 17ddd6a commit 2b3610a
Showing 1 changed file with 33 additions and 21 deletions.
54 changes: 33 additions & 21 deletions src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,32 @@ impl Compiler {
}
return chunk;
}

fn binary_literal(&mut self, expr: &Expr, operator: &TokenData, literal: &LiteralExpr) -> Option<Chunk> {
if let Literal::Number(n) = literal.value {
if operator.token == Token::Plus && n.fract() == 0.0 && n < 256.0 {
let left_chunk = expr.accept(self);
let mut chunk = Chunk {
instructions: vec![],
result_register: left_chunk.result_register,
};
chunk
.instructions
.append(&mut left_chunk.instructions.clone());
chunk.push(
Instruction {
opcode: OpCode::Addi,
a: chunk.result_register,
b: left_chunk.result_register,
c: (n as i32) as u8,
},
Some(operator.clone()),
);
return Some(chunk);
}
}
return None;
}
}

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand Down Expand Up @@ -1619,27 +1645,13 @@ impl ExprVisitor<Chunk> for Compiler {

fn visit_binary_expr(&mut self, expr: &BinaryExpr) -> Chunk {
if let Expr::Literal(l) = &*expr.right {
if let Literal::Number(n) = l.value {
if expr.operator.token == Token::Plus && n.fract() == 0.0 && n < 256.0 {
let left_chunk = expr.left.accept(self);
let mut chunk = Chunk {
instructions: vec![],
result_register: left_chunk.result_register,
};
chunk
.instructions
.append(&mut left_chunk.instructions.clone());
chunk.push(
Instruction {
opcode: OpCode::Addi,
a: chunk.result_register,
b: left_chunk.result_register,
c: (n as i32) as u8,
},
Some(expr.operator.clone()),
);
return chunk;
}
if let Some(chunk) = self.binary_literal(&*expr.left, &expr.operator, l) {
return chunk;
}
}
if let Expr::Literal(l) = &*expr.left {
if let Some(chunk) = self.binary_literal(&*expr.right, &expr.operator, l) {
return chunk;
}
}
let left_chunk = expr.left.accept(self);
Expand Down

0 comments on commit 2b3610a

Please sign in to comment.