v3 Parsing: Postfix, Maps, and Arrays
Lesson, slides, and applied problem sets.
View SlidesLesson
v3 Parsing: Postfix Calls, Indexing, and Literals
Why this module exists
The parser must now handle richer expressions and nested function declarations. The grammar stays small but now includes postfix operators and literal collections.
1) Program grammar (v3)
program -> stmt* EOF
stmt -> varDecl
| funDecl
| ifStmt
| whileStmt
| returnStmt
| block
| assignStmt
| exprStmt
funDecl -> "fn" IDENT "(" params? ")" block
params -> IDENT ("," IDENT)*
varDecl -> ("let" | "var" | "const") IDENT ("=" expr)? ";"
assignStmt -> lvalue "=" expr ";"
exprStmt -> expr ";"
block -> "{" stmt* "}"
ifStmt -> "if" "(" expr ")" block ("else" block)?
whileStmt -> "while" "(" expr ")" block
returnStmt -> "return" expr? ";"
lvalue is an identifier with optional indexing:
lvalue -> IDENT ("[" expr "]")*
2) Expression grammar
expr -> equality
equality -> comparison ( ("==" | "!=") comparison )*
comparison -> term ( ("<" | "<=" | ">" | ">=") term )*
term -> factor ( ("+" | "-") factor )*
factor -> unary ( ("*" | "/") unary )*
unary -> ("!" | "-") unary | postfix
postfix -> primary ( call | index )*
call -> "(" args? ")"
index -> "[" expr "]"
args -> expr ( "," expr )*
primary -> NUMBER | STRING | TRUE | FALSE | NIL
| IDENT
| "(" expr ")"
| arrayLit
| mapLit
arrayLit -> "[" (expr ("," expr)*)? "]"
mapLit -> "{" (pair ("," pair)*)? "}"
pair -> expr ":" expr
3) Block vs map literal
A { at statement level starts a block. A { inside an expression starts a map literal. That context split keeps parsing deterministic.
4) Readability
Postfix parsing is just a loop. Keep it simple.