Program Parser v3
Program Parser v3
Parse tokens into an AST for the v3 language (arrays, maps, nested functions, indexing).
Function signature
func Parse(tokens []Token) (*Program, error)
Grammar
program -> stmt* EOF
stmt -> varDecl
| ifStmt
| whileStmt
| returnStmt
| block
| fnDecl
| assignOrExpr
fnDecl -> "fn" IDENT "(" params? ")" block
params -> IDENT ("," IDENT)*
varDecl -> ("let" | "var" | "const") IDENT ("=" expr)? ";"
assignOrExpr-> expr ("=" 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 | postfix
postfix -> primary ("(" args? ")" | "[" expr "]")*
args -> expr ("," expr)*
primary -> NUMBER | STRING | TRUE | FALSE | NIL | IDENT
| "(" expr ")"
| array
| map
array -> "[" (expr ("," expr)*)? "]"
map -> "{" (pair ("," pair)*)? "}"
pair -> expr ":" expr
AST shape
Use the provided structs:
ProgramwithStmts []*StmtStmtwith fields:Kind,VarKind,Name,Expr,Target,Body,Else,ParamsExprwith fields:Kind,Value,Left,Right,Args,Elems,PairsMapPairwithKey,Value
Rules
- Functions are statements and can appear in any block.
- An assignment statement must have a valid target: an identifier or an index expression (like
a[i]).
Errors
Return a non-nil error if:
- tokens do not match the grammar
- parentheses or braces are unbalanced
- an assignment target is not valid
- extra tokens remain after parsing
Notes
- Keep the parser readable. A simple recursive descent is perfect.
Run tests to see results
No issues detected