AST to 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:Valueholds the number lexemeExprIdent:Valueholds the identifier nameExprUnary:Valueholds the operator,Leftholds the operandExprBinary:Valueholds the operator,LeftandRighthold operandsExprCall:Valueholds the function name,Argsholds arguments
Bytecode rules
Emit instructions in postfix (stack) order:
- Number:
PUSH_NUM <value> - Identifier:
PUSH_IDENT <name> - Unary: lower operand, then
NEGorNOT - 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.
Run tests to see results
No issues detected