refactor if/else to match in guard compilation

This commit is contained in:
Scott Richmond 2024-12-26 23:48:38 -05:00
parent f5965fdb44
commit 6f582bff06
2 changed files with 42 additions and 36 deletions

View File

@ -479,7 +479,10 @@ impl Compiler {
self.emit_op(Op::JumpIfNoMatch); self.emit_op(Op::JumpIfNoMatch);
let jnm_jump_idx = self.len(); let jnm_jump_idx = self.len();
self.emit_byte(0xff); self.emit_byte(0xff);
if let Some(expr) = guard.as_ref() { // conditional compilation of guards
// hard to DRY out
match guard.as_ref() {
Some(expr) => {
self.visit(expr); self.visit(expr);
self.emit_op(Op::JumpIfFalse); self.emit_op(Op::JumpIfFalse);
let jif_idx = self.len(); let jif_idx = self.len();
@ -501,7 +504,8 @@ impl Compiler {
self.chunk.bytecode[jnm_jump_idx] = self.chunk.bytecode[jnm_jump_idx] =
self.len() as u8 - jnm_jump_idx as u8 - 1; self.len() as u8 - jnm_jump_idx as u8 - 1;
self.chunk.bytecode[jif_idx] = self.len() as u8 - jif_idx as u8 - 1; self.chunk.bytecode[jif_idx] = self.len() as u8 - jif_idx as u8 - 1;
} else { }
None => {
self.visit(body); self.visit(body);
self.emit_op(Op::Store); self.emit_op(Op::Store);
self.scope_depth -= 1; self.scope_depth -= 1;
@ -520,6 +524,7 @@ impl Compiler {
self.len() as u8 - jnm_jump_idx as u8 - 1; self.len() as u8 - jnm_jump_idx as u8 - 1;
} }
} }
}
self.emit_op(Op::PanicNoMatch); self.emit_op(Op::PanicNoMatch);
self.emit_op(Op::Load); self.emit_op(Op::Load);
for idx in jump_idxes { for idx in jump_idxes {

View File

@ -69,8 +69,9 @@ pub fn run(src: &'static str) {
pub fn main() { pub fn main() {
let src = " let src = "
match :foo with { match :foo with {
:foo if true -> :oops :foo if nil -> :oops
:foo if true -> :yay! :foo if true -> :yay!
:bar -> :thing
} }
"; ";
run(src); run(src);