Master the fundamental concepts of build a bytecode vm through this focused micro-challenge.
You have read the whole brief, and the concepts above stay free on every task. Writing and running the code needs a plan.
Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
Every task includes starter code, theory, and hidden tests so you can implement and verify locally in the browser.
How it worksEvery interpreter follows the same loop: fetch the next instruction, decode its opcode, execute the handler. CPython's `ceval.c` and Lua's `lvm.c` are this pattern at production scale. Your `switch` statement is the same structure CPython 3.11 later replaced with computed gotos for speed.
The program counter points at the next bytecode byte. Each cycle:
The operand stack is a fixed-size LIFO buffer:
For example, `(10 + 20) * 3 - 5` compiles to a sequence of pushes and arithmetic ops ending with a single value on the stack.
```c while (running) { uint8_t op = bytecode[pc++]; switch (op) { case OP_PUSH: ... case OP_ADD: ... } } ```
Start with a debug print of pc and stack contents each cycle while developing. Interpreter bugs show up as impossible stack states long before you get wrong final answers. Once handlers are correct, gate the trace behind a flag so benchmarks stay meaningful.
This exercise asks you to wire up a complete interpreter loop with overflow checks. You will implement `push`, `pop`, and handlers for arithmetic so later tasks add control flow without rewriting the core loop.
Implement the core of every stack VM: the fetch, decode, execute loop. Run programs written in the straight-line subset of this subtrack's ISA with 32-bit integer semantics (wrap-around on overflow, division truncating toward zero), and report runtime errors precisely: underflow, overflow, division by zero, and missing HALT.
cLoading…
Instructions (case-insensitive): HALT PUSH n POP ADD SUB MUL DIV NEG DUP SWAP PRINT.
b (the top), then a, and push a OP b. SWAP exchanges the top two values. PRINT pops the top and prints it.INT32_MIN / -1 is an error.error at PC (OP): stack underflowerror at PC (OP): stack overflow (limit N) (PUSH/DUP on a full stack)error at PC (DIV): division by zeroerror at PC (DIV): result does not fit in 32 bitserror: ran off the end of the program without HALThalted after K instructions, stack [..], where K counts every executed instruction including HALT. PC OP[ n] -> [stack] after each instruction except HALT. A PRINT's output line comes before its trace line.unsupported instruction X and PUSH needs a 32-bit integer (the line is skipped). stack: 1..256 is printed for a bad limit.cLoading…
Input:
cLoading…
Output:
cLoading…
Hidden tests cover underflow on an empty stack, overflow with a small stack limit, division by zero, INT32_MIN / -1, negative division, SWAP and POP, a missing HALT, and unsupported instructions.