Add the second instruction: i64.add. It pops two values and pushes their sum.
Extend the WAT to include i64.add, then add an else if branch to the dispatch.
const wat: [:0]const u8 =
\\i64.const 3
\\i64.const 4
\\i64.add
;
// ... line walker unchanged ...
if (stringStartsWith(line, "i64.const ")) {
stack[stack_pointer] = @as(i64, line[line.len - 1]) - '0';
stack_pointer += 1;
}
// YOU: else if line equals "i64.add", pop y, pop x, push x + y.
else {
printString("error: unknown instruction\n");
return;
}
Then change the final print to "vm result: " and print stack[0] -- after the add, the stack should hold one value, the answer.
} else if (stringsEqual(line, "i64.add")) {
const y: i64 = stack[stack_pointer - 1];
const x: i64 = stack[stack_pointer - 2];
stack_pointer -= 2;
stack[stack_pointer] = x + y;
stack_pointer += 1;
}
y was pushed last, so it sits on top. Doesn't matter for +. Will matter when subtraction shows up.
vm result: 7. Same answer as the interpreter, computed by a stack machine.