Skip to content

Commit 135fbae

Browse files
committed
interpreter: while & do-while loops
1 parent c039db6 commit 135fbae

1 file changed

Lines changed: 32 additions & 1 deletion

File tree

interpreter/src/ir/lower.rs

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,15 +55,46 @@ impl Code<'_> {
5555
.emit(Instruction::branch(condition.reg(), label_then, Label(0)));
5656
self.free_reg(condition);
5757
self.lower_body(then_body);
58-
self.bc.nth(if_label).args.branch.2 = self.following_instr(1);
58+
self.bc.nth(if_label).args.branch.2 = self.following_instr(0);
5959

6060
if let Some(else_body) = else_body {
6161
state.reg_pointer += 1;
62+
unsafe { self.bc.nth(if_label).args.branch.2.0 += 1 };
6263
let end_label = self.bc.emit(Instruction::jump(Label(0)));
6364
state.scope_hwm(self, |c| c.lower_body(else_body));
6465
self.bc.nth(end_label).args.jump = self.following_instr(0);
6566
}
6667
}
68+
Statement::While {
69+
condition,
70+
then_body,
71+
} => {
72+
let cond_label = self.following_instr(0);
73+
let condition = self.lower_expr(condition);
74+
let while_label = self.bc.emit(Instruction::branch(
75+
condition.reg(),
76+
self.following_instr(1),
77+
Label(0),
78+
));
79+
self.free_reg(condition);
80+
self.lower_body(then_body);
81+
self.bc.emit(Instruction::jump(cond_label));
82+
self.bc.nth(while_label).args.branch.2 = self.following_instr(0);
83+
}
84+
Statement::DoWhile {
85+
then_body,
86+
condition,
87+
} => {
88+
let do_label = self.following_instr(0);
89+
self.lower_body(then_body);
90+
let condition = self.lower_expr(condition);
91+
self.bc.emit(Instruction::branch(
92+
condition.reg(),
93+
do_label,
94+
self.following_instr(1),
95+
));
96+
self.free_reg(condition);
97+
}
6798
Statement::Simple(SimpleStatement::Expression(expr)) => {
6899
let reg = self.lower_expr(expr);
69100
self.free_reg(reg);

0 commit comments

Comments
 (0)