From b94723f1baf8e3096681489ff2a2d7e4eb81900a Mon Sep 17 00:00:00 2001 From: Michael Sippel Date: Sun, 5 May 2024 18:16:22 +0200 Subject: [PATCH] assembler: add while_loop --- src/assembler.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/assembler.rs b/src/assembler.rs index d03d58f..e927e74 100644 --- a/src/assembler.rs +++ b/src/assembler.rs @@ -42,8 +42,26 @@ impl Assembler { self } + pub fn while_loop(mut self, mut condition: Assembler, mut body: Assembler) -> Assembler { + let cond_len = condition.instructions.len(); + let body_len = body.instructions.len(); + self.instructions.append( &mut condition.instructions ); + + // jump to end + self.instructions.push( VM_Instruction::Branch as VM_Word ); + self.instructions.push( body_len as VM_Word + 2 ); + + self.instructions.append( &mut body.instructions ); + + // jump back to condition + self.instructions.push( VM_Instruction::Jmp as VM_Word ); + self.instructions.push( -2-(body_len as VM_Word)-2-(cond_len as VM_Word) ); + + self + } + pub fn branch(mut self, mut if_branch: Assembler, mut else_branch: Assembler) -> Assembler { - self.instructions.push(VM_Instruction::Branch as VM_Word ); + self.instructions.push(VM_Instruction::Branch as VM_Word); self.instructions.push( if_branch.instructions.len() as VM_Word + 2); self.instructions.append( &mut if_branch.instructions );