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 worksWithout jumps, a VM is a calculator. `JUMP`, `JUMP_IF_FALSE`, and comparison opcodes turn straight-line bytecode into real programs with loops and conditionals.
Comparison instructions pop two values and push a boolean (0 or 1):
An `if/else` in bytecode looks like:
``` <condition> JUMP_IF_FALSE else_label <then block> JUMP end_label else_label: <else block> end_label: ```
For example, summing 1 through 10 uses a loop that jumps back to `loop_start` until the counter exceeds 10.
Forward jumps need backpatching: the compiler emits a placeholder address and patches it once the target label's offset is known. CPython's `compile.c` does exactly this for every `if` and `while`.
Patch jump targets only after you know the final bytecode offset. If you patch too early, inserting another instruction later shifts every following address and silently breaks branches. Compiler writers keep a list of pending patches for this reason.
This exercise asks you to add branching to your VM and demonstrate a loop plus conditional. You will implement comparison opcodes and absolute jumps, including the backpatch pattern your compiler will rely on next.
Add control flow to the stack VM: comparisons that push 1 or 0, an unconditional JMP, and JZ, which pops a value and jumps if it is zero. Resolve jump labels after the whole program has been read, count the jumps taken, and stop runaway loops with a step limit.
cLoading…
Instructions: HALT PUSH n POP ADD SUB MUL DIV NEG DUP SWAP PRINT EQ LT GT JMP label JZ label.
stack underflow, stack overflow (limit N), division by zero and result does not fit in 32 bits are reported as error at PC (OP): ....a == b, a < b or a > b as 1 or 0.end. Any line N: undefined label X prevents the run. Line numbers count the non-empty lines of the program.error: step limit N reached at PC (infinite loop?).halted after K instructions, J jumps taken, stack [..]. PC JZ label -> [stack] plus (jump) when taken.line N: unsupported instruction X, line N: PUSH needs a 32-bit integer, line N: JMP needs a label / JZ needs a label, line N: duplicate label X, and steps: must be positive.cLoading…
Input:
cLoading…
Output:
cLoading…
pc directly. Do not also increment it. That off-by-one is the classic VM bug.Hidden tests cover a stepping loop that ends on GT, LT and GT results, JZ both taken and not taken, an infinite loop caught by a small step limit, duplicate labels, and missing jump operands.