Master the fundamental concepts of build a bytecode vm through this focused micro-challenge.
Without 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 instructions to your stack-based VM in C.
Requirements:
Test:
Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
All starter code and reference implementations are available for your local setup.
View on Github