40 Companion zmachine.js (19/28)
branch(cond) {
const b = this.mem[this.pc++];
let offset;
if (b & 0x40) offset = b & 0x3f;
else {
offset = ((b & 0x3f) << 8) | this.mem[this.pc++];
if (offset & 0x2000) offset -= 0x4000;
}
if (!!cond !== !!(b & 0x80)) return;
if (offset === 0) this.ret(0);
else if (offset === 1) this.ret(1);
else this.pc += offset - 2;
}
call(addr, args, store) {
// store: variable number, or -1 to discard the result
if (addr === 0) {
if (store >= 0) this.writeVar(store, 0);
return;
}
const a = this.routineAddr(addr);
const n = this.mem[a];
if (n > 15) throw new ZError(`bad routine at ${a.toString(16)}`);
let p = a + 1;
const locals = [];
for (let i = 0; i < n; i++) {
if (this.version <= 4) { locals.push(this.rw(p)); p += 2; } else locals.push(0);
}
for (let i = 0; i < Math.min(n, args.length); i++) locals[i] = u16(args[i]);
this.frames.push({ ret: this.pc, store, locals, argc: args.length, base: this.stack.length });
this.pc = p;
}
ret(v) {
const f = this.frames.pop();
if (!f) throw new ZError('return from the main routine');
this.stack.length = f.base;
this.pc = f.ret;
if (f.store >= 0) this.writeVar(f.store, v);
}
printNum(v) { this.print(String(s16(v))); }