Compare commits

..

2 commits

Author SHA1 Message Date
b94723f1ba
assembler: add while_loop 2024-05-05 18:16:22 +02:00
ca6fd92932
add pick & roll instructions 2024-05-05 18:16:07 +02:00
2 changed files with 38 additions and 3 deletions

View file

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

View file

@ -4,7 +4,7 @@ pub type VM_Word = i64;
#[repr(u64)]
pub enum VM_Instruction {
Nop, Jmp, Call, Branch, Ret,
Lit, Dup, Drop, Swap, Rot,
Lit, Pick, Roll, Dup, Drop, Swap, Rot,
Fetch, Store,
Accept, Emit,
Add, //Sub, Mul, Div, Rem,
@ -103,6 +103,23 @@ impl VM {
let val = char::from(self.data_stack.pop().expect("emit expects value") as u8);
print!("{}", val);
}
VM_Instruction::Pick => {
let n = self.data_stack.pop().expect("pick requires index") as usize;
self.data_stack.push( *self.data_stack.get( self.data_stack.len() - n ).expect("pick invalid index") );
}
VM_Instruction::Roll => {
let n = self.data_stack.pop().expect("pick requires index") as usize;
let l = self.data_stack.len();
if n <= l {
if n > 1 {
let val = self.data_stack.remove( l-n );
self.data_stack.push( val );
}
} else {
eprintln!("stack = {:?}", self.data_stack);
eprintln!("roll invalid index");
}
}
VM_Instruction::Dup => {
self.data_stack.push( *self.data_stack.last().expect("dup expect val") );
}