Reading — step 1 of 3
Expanding the Instruction Set
VM Instructions — Push, Pop, Arithmetic
With the basic VM loop in place, we now expand the instruction set to handle all value types, comparisons, and boolean logic.
Value Instructions
OP_NIL // push nil onto the stack
OP_TRUE // push true
OP_FALSE // push false
OP_POP // discard top of stack
These instructions have no operands — they are single bytes. OP_POP is essential for expression statements (evaluate, then discard the result).
Comparison Instructions
OP_EQUAL // pop two, push (a == b)
OP_GREATER // pop two, push (a > b)
OP_LESS // pop two, push (a < b)
For <=, >=, and !=, we compose: a <= b compiles to a > b followed by OP_NOT. This keeps the instruction set small at the cost of one extra instruction. Lua takes the same approach.
Boolean Logic
OP_NOT // pop one, push !value (using truthiness rules)
OP_NOT returns true if the operand is falsy (false or nil), false otherwise.
Type Checking at Runtime
Arithmetic operations must check types:
case OP_ADD:
b = pop(); a = pop()
if isNumber(a) and isNumber(b):
push(a + b)
elif isString(a) and isString(b):
push(concatenate(a, b))
else:
runtimeError("Operands must be two numbers or two strings.")
OP_ADD is overloaded: it adds numbers and concatenates strings. This matches JavaScript, Python, and Lua behavior. Other arithmetic operators (-, *, /) only work on numbers.
The Print Instruction
OP_PRINT // pop one, print it, push nothing
print 42; compiles to: OP_CONSTANT 42, OP_PRINT. The print instruction pops the value and outputs it.
Runtime Errors
When a type error occurs (like "hello" - 3), the VM must:
- Report the error with the line number
- Reset the stack
- Stop execution
The line number comes from the chunk's lines array, indexed by the current instruction pointer. This is why we track line numbers during compilation.
Your Task
Add nil, boolean, comparison, not, and print instructions to the VM. Implement runtime type checking for all operations.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…