AST to Bytecode

medium · compilers, lowering, bytecode

AST to Bytecode

Lower an expression AST into a stack-based bytecode sequence.

This is a tiny compiler backend step: take structured AST nodes and produce a linear instruction list.

Function signature

func Lower(expr *Expr) []Instr

AST shape

Use the provided Expr struct with these conventions:

  • ExprNumber: Value holds the number lexeme
  • ExprIdent: Value holds the identifier name
  • ExprUnary: Value holds the operator, Left holds the operand
  • ExprBinary: Value holds the operator, Left and Right hold operands
  • ExprCall: Value holds the function name, Args holds arguments

Bytecode rules

Emit instructions in postfix (stack) order:

  • Number: PUSH_NUM <value>
  • Identifier: PUSH_IDENT <name>
  • Unary: lower operand, then NEG or NOT
  • Binary: lower left, lower right, then the operator
  • Call: lower args left-to-right, then CALL <name> <arity>

Operators map to opcodes as follows:

  • + -> ADD
  • - -> SUB
  • * -> MUL
  • / -> DIV
  • == -> EQ
  • != -> NEQ
  • < -> LT
  • <= -> LTE
  • > -> GT
  • >= -> GTE
  • unary - -> NEG
  • unary ! -> NOT

Notes

  • Parse numbers with base-10 integer conversion.
  • The output should be readable and deterministic.

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