Skip to content

Commit

Permalink
Start stack at sp, and move bp one byte down
Browse files Browse the repository at this point in the history
Signed-off-by: yzamir <[email protected]>
  • Loading branch information
yaacov committed Oct 5, 2023
1 parent 8c4f9d3 commit 2a42792
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions src/vm.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,13 @@ class VM {
}

pop() {
const value = this.memory[this.sp];
this.sp -= 1;

return value;
return this.memory[this.sp];
}

push(value) {
this.sp += 1;
this.memory[this.sp] = value;
this.sp += 1;
}

/**
Expand Down Expand Up @@ -67,11 +65,15 @@ class VM {
},
[opcodes.RET]: () => { this.pc = this.pop(); jumpFlag = true; },
[opcodes.LOADABP]: () => {
const address = (this.sp - this.fetchOperand()) & 0xff;
// base pointer is one less then current stack pointer
// to allow for [BP + 0] to point to return address.
const bp = this.sp - 1;
const address = (bp - this.fetchOperand()) & 0xff;
this.registerA = this.memory[address];
},
[opcodes.STOREABP]: () => {
const address = (this.sp - this.fetchOperand()) & 0xff;
const bp = this.sp - 1;
const address = (bp - this.fetchOperand()) & 0xff;
this.memory[address] = this.registerA;
},
[opcodes.END]: () => false,
Expand All @@ -85,8 +87,7 @@ class VM {

// Dont incriment the counter on jumps
if (!jumpFlag) {
// 1 opcode + 1 data (we always have paris of 1 opcode and 1 data bytes)
this.pc += 2;
this.pc += 2; /* +2 = code + operand */
}

// Memory gurd
Expand Down

0 comments on commit 2a42792

Please sign in to comment.