26 Companion zmachine.js (5/28)
rb(a) { return this.mem[a]; }
rw(a) { return (this.mem[a] << 8) | this.mem[a + 1]; }
wb(a, v) {
if (a >= this.dynamicSize) throw new ZError(`write to static memory at ${a.toString(16)}`);
this.mem[a] = v & 0xff;
}
ww(a, v) { this.mem[a] = (v >> 8) & 0xff; this.mem[a + 1] = v & 0xff; }
wwChecked(a, v) {
if (a + 1 >= this.dynamicSize) throw new ZError(`write to static memory at ${a.toString(16)}`);
this.ww(a, v);
}
routineAddr(p) { return p * this.packScale + this.routineOffset; }
stringAddr(p) { return p * this.packScale + this.stringOffset; }
// ---------------------------------------------------------------- variables
readVar(n) {
if (n === 0) {
if (this.stack.length <= this.frameBase()) throw new ZError('stack underflow');
return this.stack.pop();
}
if (n < 16) return this.localsOf()[n - 1] ?? 0;
return this.rw(this.globals + 2 * (n - 16));
}
writeVar(n, v) {
v = u16(v);
if (n === 0) this.stack.push(v);
else if (n < 16) this.localsOf()[n - 1] = v;
else this.ww(this.globals + 2 * (n - 16), v);
}
// "Indirect" access (inc, dec, load, store, pull...): variable 0 is the top
// of the stack, read or replaced in place (spec 6.3.4).
peekVar(n) {
if (n === 0) {
if (this.stack.length <= this.frameBase()) throw new ZError('stack underflow');
return this.stack[this.stack.length - 1];
}
return this.readVar(n);
}