Introduction
The JVM, the .NET runtime and Python's interpreter are all stack machines. Building one demystifies how programs actually run: instructions push and pop values, jumps move the program counter, and calls save return addresses. You will write both the assembler that turns text into instructions and the machine that executes them.
Problem statement
Objectives
- Design an instruction encoding with enum class
- Write a two-pass assembler that resolves forward references
- Implement a fetch-decode-execute loop
- Detect signed overflow without undefined behaviour
Features
- 25 instructions, labels and
;comments - Registers a–z and a separate return stack for call/ret
- Overflow, underflow, division-by-zero and infinite-loop detection
- Disassembly listing with label annotations
Concepts demonstrated
- Virtual machines
- Assemblers
- Two-pass translation
- Overflow-safe arithmetic
- Interpreters
- Error handling
System architecture
assemble makes pass 1 over the text, stripping comments and recording each label's instruction index; pass 2 encodes Instr{op, arg, source_line} and resolves label operands, so forward jumps work. run keeps a data stack, a return stack and 26 registers. Each step fetches code[pc], executes it in a switch, and sets the next pc. Arithmetic is checked before it happens with integer comparisons (a > MAX - b), because signed overflow is undefined behaviour and floating-point checks are inexact above 2^53.
Folder structure
Complete source code
Makefile
What each file does
- src/vm.h
- The instruction set,
InstrandProgram, error types, and the assemble / run / disassemble interface. - src/vm.cpp
- The opcode table, the two-pass assembler, the execution loop with all safety checks and the disassembler.
- src/main.cpp
- Splits the input into named programs, assembles and runs each, and prints the results.
- Makefile
- Build automation:
makebuilds./app,make testruns the sample session and compares it with the expected output,make cleanremoves build files.
How to run it
Build
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
program arithmetic listing
push 6
push 7
mul ; 42
push 2
sub ; 40
print
halt
program countdown
push 5
store n
loop: load n
jz done ; stop when n == 0
load n
print
load n
push 1
sub
store n
jmp loop
done: push 'G'
printc
push 'o'
printc
push '!'
printc
push 10
printc
program factorial (subroutine)
push 12
call fact
print
push 20
call fact
print
halt
; fact: ( n -- n! ) iterative, uses registers a (counter) and r (result)
fact: store a
push 1
store r
f_loop: load a
push 1
gt
jz f_done
load r
load a
mul
store r
load a
push 1
sub
store a
jmp f_loop
f_done: load r
ret
program fibonacci
push 0
store a
push 1
store b
push 15
store n
next: load a
print
load a
load b
dup
store a
add
store b
load n
push 1
sub
dup
store n
jnz next
program primes below 40
push 2
store n
outer: load n
push 40
lt
jz end
push 2
store d
inner: load d
load d
mul
load n
gt
jnz is_prime ; d*d > n: no divisor found
load n
load d
mod
jz not_prime
load d
push 1
add
store d
jmp inner
is_prime: load n
print
not_prime: load n
push 1
add
store n
jmp outer
end: halt
program errors: division by zero
push 1
print
push 10
push 0
div
print
program errors: underflow
push 1
add
program errors: overflow
push 21
call fact2
print
halt
fact2: dup
push 1
gt
jz base
dup
push 1
sub
call fact2
mul
ret
base: ret
program errors: infinite loop
spin: jmp spin
program errors: bad assembly
push x
jmp nowhere
program errors: undefined label
jmp nowhereTesting
- Compare
./app < tests/sample-input.txtwithtests/expected-output.txt. factorialprints 12! = 479001600 and 20! = 2432902008176640000; 21! is reported as an integer overflow.primes below 40prints the 12 primes from 2 to 37.- Faults are reported with the source line: division by zero (line 5), underflow (line 2), the step limit for an infinite loop and undefined labels at assembly time.
Common errors
Jumps land on the wrong instruction
Labels must record the index of the next *instruction*, not the source line number, which counts blank and comment lines.
Wrong results for big multiplications
Don't detect overflow by computing in double or long double; check with integer comparisons before multiplying.
Possible improvements
- Add a
readinstruction for input - Add memory (an array) with load/store by address
- Write a compiler from the Expression Interpreter's AST to this bytecode
Additional challenges
- 1Add a single-step debugger that prints the stack after each instruction.
- 2Encode programs to a binary file and load them back.
- 3Add tail-call optimisation for
callfollowed byret.
Built and tested it yourself? Mark it to update your dashboard.