assembler: add while_loop

This commit is contained in:
Michael Sippel 2024-05-05 18:16:22 +02:00
parent ca6fd92932
commit b94723f1ba
Signed by: senvas
GPG key ID: F96CF119C34B64A6

View file

@ -42,6 +42,24 @@ impl Assembler {
self 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 { 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.push( if_branch.instructions.len() as VM_Word + 2);