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

Readiness

  • Use v2 tokens and the expression precedence chain.
2 / 6

Worked reconstruction

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.

3 / 6

Diagnose before implementing

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.

4 / 6

Independent transfer

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.

5 / 6

Carry forward

Carry complete statement trees into name analysis. Keep syntax tests free of assumptions about whether a referenced variable or function exists.

6 / 6
←/→ or click edges to navigate · ? help · N notes · F fullscreen