Parsing Programs: Declarations and Statements
- Partition a program into declarations and statements.
- Disambiguate assignment from equality without semantic lookup.
- Build statement fields and enforce v2 function placement.
1 / 6
Parse let x=2; x=x+3; if (x==5) { x; }:
| Segment | AST statement | Important child |
|---|---|---|
let x=2; |
variable declaration named x | Number(2) initializer |
x=x+3; |
assignment named x | Add(Ident(x),Number(3)) |
if (x==5) { x; } |
if statement | Eq(x,5), body containing an expression statement |
= and == have different token kinds. Assignment dispatch uses an identifier
followed by single =; the double-equality token remains inside the expression
parser. The parser accepts an assignment shape even if x is not declared; name
resolution is the next stage.
A declaration or expression statement owns its final semicolon. A block owns its closing brace. Recursive calls should leave the cursor at the first token after the construct they consumed. On EOF inside an open block, return an error rather than looping forever or pretending a brace appeared.
A parser handles x==2; as an assignment and rejects top-level return 2; before building a statement. Identify the token-dispatch defect and the phase-ownership defect.
Draw the Program tree for a function with two parameters followed by a call used as an expression statement. Then move the function inside an if block and predict the v2 parsing failure. Repeat that placement prediction after studying v3.
Carry complete statement trees into name analysis. Keep syntax tests free of assumptions about whether a referenced variable or function exists.