Program Parser
Program Parser
Parse a token stream into an AST for the expanded language (v2).
Function signature
func Parse(tokens []Token) (*Program, error)
Grammar
program -> decl* EOF
decl -> funDecl | stmt
funDecl -> "fn" IDENT "(" params? ")" block
params -> IDENT ("," IDENT)*
stmt -> varDecl
| ifStmt
| whileStmt
| returnStmt
| block
| assignStmt
| exprStmt
varDecl -> ("let" | "var" | "const") IDENT ("=" expr)? ";"
assignStmt -> IDENT "=" expr ";"
exprStmt -> expr ";"
block -> "{" stmt* "}"
ifStmt -> "if" "(" expr ")" block ("else" block)?
whileStmt -> "while" "(" expr ")" block
returnStmt -> "return" expr? ";"
expr -> equality
equality -> comparison ( ("==" | "!=") comparison )*
comparison -> term ( ("<" | "<=" | ">" | ">=") term )*
term -> factor ( ("+" | "-") factor )*
factor -> unary ( ("*" | "/") unary )*
unary -> ("!" | "-") unary | primary
primary -> NUMBER | STRING | TRUE | FALSE | NIL
| IDENT ["(" args? ")"]
| "(" expr ")"
args -> expr ("," expr)*
IDENTmay be followed by a call suffix in this module (f(...)). Full postfix operators come in later modules.
AST shape
Use the provided structs.
ProgramwithStmts []*StmtStmtwithKind,VarKind,Name,Expr,Body,Else,ParamsExprwithKind,Value,Left,Right,Args
Rules
- Parse mode
- top-level
parseDecldrives everything.fnat top level is special and always parses as function declaration. - other top-level tokens route to statement parsing.
- Statement disambiguation
- if current token is identifier and next token is
=: parse assignment - otherwise parse expression statement
- Function declarations
- top-level only in this version; function bodies use statement parsing recursively.
- Call parsing
- callee is an identifier with optional argument list.
- Error handling
- return explicit errors for:
- unmatched parentheses/braces
- missing semicolons/equals and malformed params
- unexpected/unknown token in grammar position
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