Compile to Bytecode v4

hard · compilers, bytecode, lowering, control flow

Compile to Bytecode v4

Lower a v4 Program AST into stack-based bytecode with loops and short-circuit logic.

Function signature

func Compile(prog *Program) Bytecode

Bytecode types

Use the provided types:

  • Bytecode with Main []Instr and Functions []Function
  • Function with ID, Name, Params, and Code []Instr
  • Instr with Op, Int, and Str

Instruction rules

This builds on v3 (closures, arrays, maps, indexing) and adds:

for loop

ENTER_SCOPE
init
loopStart:
cond (or PUSH_BOOL 1 if omitted)
JUMP_IF_FALSE end
body
post
JUMP loopStart
end:
EXIT_SCOPE

break / continue

  • break emits a jump patched to loop end.
  • continue emits a jump patched to the loop's continue target.

logical operators

  • && and || must short-circuit and return a boolean.
  • Implement using jumps + PUSH_BOOL + POP (no new opcodes).

Notes

  • Assume the AST is already valid.
  • Keep the compiler readable and straightforward.
Run tests to see results
No issues detected