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.

Before implementation

Use the module’s worked reconstruction and independent debugging lab to predict an intermediate artifact first. Preserve one failing counterexample while implementing the stated API. The lesson’s transfer task uses a fresh case after the guided trace.

Run tests to see results
No issues detected
    Join Discord