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 );