Skip to content
Compiling Statements & Variables
step 1/3

Reading — step 1 of 3

Compiling Statements and Managing State

~2 min readCompiling to Bytecode

Compiling Statements & Variables

With expressions compiling to bytecode, we now add statements and variables — the constructs that give programs state and structure.

Print Statements

print 42;  →  OP_CONSTANT [42], OP_PRINT

Compile the expression, then emit OP_PRINT. The VM pops the value and outputs it.

Expression Statements

doSomething();  →  [compile expression], OP_POP

Compile the expression, then emit OP_POP to discard the unused result.

Global Variables

Declaration:

var x = 42;  →  OP_CONSTANT [42], OP_DEFINE_GLOBAL [name_index]

Reading:

print x;     →  OP_GET_GLOBAL [name_index], OP_PRINT

Assignment:

x = 10;      →  OP_CONSTANT [10], OP_SET_GLOBAL [name_index]

The variable name is stored as a string constant in the constant pool. The operand to the global instructions is the index of that string.

Local Variables

Locals are more efficient — they live on the stack:

{
    var x = 42;   // x is at stack slot 0
    var y = 10;   // y is at stack slot 1
    print x + y;  // OP_GET_LOCAL 0, OP_GET_LOCAL 1, OP_ADD, OP_PRINT
}                 // OP_POP, OP_POP (clean up locals)

The compiler tracks scope depth and assigns a stack slot to each local. No hash table lookup needed at runtime — just an array index.

The Compiler's Local Array

Local {
    name:  String
    depth: int      // scope depth where declared
    slot:  int      // stack slot index
}

The compiler maintains an array of locals. When a variable is referenced, it searches this array (innermost scope first) to find the matching local and its stack slot.

Blocks and Scope

When entering a block, increment the scope depth. When leaving, pop all locals at the current depth and decrement:

beginScope():  scopeDepth++
endScope():
    while locals.last().depth == scopeDepth:
        emit(OP_POP)     // clean up the local
        locals.pop()
    scopeDepth--

Your Task

Compile print statements, expression statements, global variable operations, local variable operations, and block scoping.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…