How to Build an AST with the Top-Down Parsing?
E : T E' { $0.node := $2.syn; $2.inh := $1.node } // $0: E, $1: T, $2: E'
E' : + T E' { $3.inh := new BinExp('+', $0.inh, $2.node); $0.syn := $3.syn }
| - T E' { $3.inh := new BinExp('-', $0.inh, $2.node); $0.syn := $3.syn }
| ε { $0.syn := $0.inh }
T : int { $0.node := new Int($1) }
Input: 3 - 2 + 1
↑
E → T E' → int E' → int - T E' → int - int E' → int - int + int
_____________________________________________________________________
| |
___ E ___ |
/ \ |
T: N1 E1'_____ |
| / | \ N4: BinExp('+', E2'.inh, N3)
int - T: N2 E2'______ / \
| / | \ N5: BinExp('-', E1'.inh, N2) N3: Int(1)
int + T: N3 E3' / \
| | N1: Int(3) N2: Int(2)
int ε
E3' : ε E3'.syn = E3'.inh
E2' : + T E3' E3'.inh = N4, E2'.syn = E3'.syn
E1' : - T E2' E2'.inh = N5, E1'.syn = E2'.syn
E : T E1' E.node = E1'.syn, E1'inh = N1
E.node = E1'.syn = E2'.syn = E3'.syn = E3'.inh = N4