PeaBox Lab › PeaLang › Learn › Chapter 12 › Lesson 3

Part III — Advanced Systems · Chapter 12 · Lesson 3 of 7 · 5 min read

Lesson 3: Stack Bytecode, Constants, Code Objects, and Instructions

Lesson level: Advanced

Purpose: Learn how PeaLang compiles a syntax tree into stack-based bytecode: a flat instruction list, a constant pool, and code objects for each function.

Release note: instruction names, operand formats, and disassembly output in this lesson are illustrative. Verify them against your installed v0.63 release before relying on them.

Learning objectives

By the end of this lesson, you should be able to:

3.1 Why bytecode

The interpreter re-examines tree nodes every time code runs. A compiler does that work once and produces a compact list of simple instructions. The VM then runs those instructions in a tight loop, which is usually faster for repeated execution and can be saved to a file.

3.2 The operand stack

A stack machine keeps intermediate values on an operand stack. Instructions pop their inputs from the top and push their results. There are no named temporary registers.

a + b * c

LOAD_NAME a      stack: [a]
LOAD_NAME b      stack: [a, b]
LOAD_NAME c      stack: [a, b, c]
MUL              stack: [a, b*c]
ADD              stack: [a + b*c]

Compiling is a post-order walk of the tree: emit code for the children, then the operator. The tree shape from Lesson 1 fixes the instruction order.

3.3 The constant pool

Literal values such as numbers and strings are stored once in a constant pool. Instructions refer to them by index rather than embedding them.

constants: [0] 10   [1] "BULK"   [2] "NONE"

LOAD_CONST 0     push 10
LOAD_CONST 1     push "BULK"

3.4 Code objects

A code object packages everything needed to run one unit of code: the module body or a single function.

FieldContent
NameFunction or module name
ParametersParameter names and count
InstructionsThe flat instruction list
ConstantsLiteral values used by the instructions
NamesIdentifiers referenced by name
LocalsSlots for local variables
Line tableMapping from instruction offsets to source lines
Nested codeCode objects for inner functions

The line table is what lets the VM report rules.pea:3:6 even though it is executing instruction 7.

3.5 Instruction families

FamilyExamplesStack effect
Load and storeLOAD_CONST, LOAD_NAME, STORE_NAME, LOAD_LOCAL, STORE_LOCALPush a value, or pop and store one
Arithmetic and comparisonADD, SUB, MUL, DIV, MOD, LT, GE, EQPop two, push one
UnaryNEG, NOTPop one, push one
Control flowJUMP, JUMP_IF_FALSE, JUMP_IF_TRUEChange the instruction pointer
CallsCALL n, RETURNPop callee and n arguments; push result
CollectionsBUILD_LIST n, BUILD_MAP n, INDEXCombine or access stack values
OutputPRINTPop one and print it

3.6 Compiling an expression

The compiler walks the checked tree in post-order: operands first, then the operator. For price * qty + 5 it emits:

0  LOAD_NAME    price
1  LOAD_NAME    qty
2  BINARY_MUL
3  LOAD_CONST   #0   ; 5
4  BINARY_ADD

After instruction 4 the stack holds exactly one value, the result. Every expression compiles to code with a net stack effect of +1.

3.7 Compiling statements and jumps

Statements have a net stack effect of zero. Conditionals and loops become jumps to instruction offsets.

if qty >= 10 { reason = "BULK" } else { reason = "NONE" }

0  LOAD_NAME          qty
1  LOAD_CONST         #0  ; 10
2  COMPARE_GE
3  POP_JUMP_IF_FALSE  7
4  LOAD_CONST         #1  ; "BULK"
5  STORE_NAME         reason
6  JUMP               9
7  LOAD_CONST         #2  ; "NONE"
8  STORE_NAME         reason
9  ...

3.8 Short-circuit logic in bytecode

a and b uses a conditional jump that skips evaluation of b when a is false-like, leaving a on the stack. This reproduces the interpreter behaviour from Lesson 2 exactly; differential tests from Chapter 10 depend on that equivalence.

3.9 Loops

while count < 3 { count += 1 }

0  LOAD_NAME          count
1  LOAD_CONST         #0  ; 3
2  COMPARE_LT
3  POP_JUMP_IF_FALSE  9
4  LOAD_NAME          count
5  LOAD_CONST         #1  ; 1
6  BINARY_ADD
7  STORE_NAME         count
8  JUMP               0
9  ...

The backward jump at offset 8 is what makes repetition visible to an instruction budget: each pass executes a fixed number of instructions, which Chapter 14 uses for limits.

3.10 Functions as nested code objects

A function body compiles to its own code object, stored as a constant of the enclosing one. At runtime, a MAKE_FUNCTION instruction combines that code object with any captured variables to create a callable value.

3.11 Common mistakes

MistakeConsequenceFix
Assuming opcodes match another VMWrong mental modelRead the PeaLang disassembly
Ignoring stack effectMis-predicting resultsTrack depth instruction by instruction
Treating jump targets as line numbersConfused tracesUse the line table
Assuming bytecode skips semanticsBehaviour differencesCompare with the interpreter

3.12 Guided practice

3.13 Hands-on lab

Compile the order_rules reason function and disassemble it (Lesson 6 covers the command). Annotate each instruction with its stack effect and source line.

Deliverable: an annotated listing and a table mapping each branch to its jump targets.

3.14 Review questions

3.15 Applied challenge

Design a peephole optimization that removes a jump to the very next instruction. Explain how you would prove it never changes behaviour.

Lesson summary

Transition to Lesson 4

Code objects exist in memory. Lesson 4 covers PEAC, the file format that stores them on disk and moves them between machines.

Lesson status: Ready for review.

← Previous Next →