Top-down derivation tree generation COP4620 – Programming Language Translators Dr. Manuel E. Bermudez
Tree generation Red: now Possibilities: Derivation tree or Abstract Syntax Tree. Top-down, or Bottom-up. For original or modified grammar ! Leading up to: AST, bottom-up, for the original grammar (“the one”).
Top-down derivation tree generation In each procedure, For each alternative, Write out the selected production rule AS SOON AS IT IS KNOWN
Top-down derivation tree generation proc S; case Next_Token of T_begin : Write(S → begin SL end); Read(T_begin); SL(); Read(T_end); T_id : Write(S → id :=E;); Read(T_id); Read(T_:=); E(); Read(T_;); otherwise Error; end end;
Top-down derivation tree generation proc SL; Write(SL → SZ); S(); Z(); end; proc Z; case Next Token of T_begin, T_id: Write(Z → SZ); S();Z(); T_end: Write(Z → ); otherwise Error;
Top-down derivation tree generation proc E; Write(E → TY); T(); Y(); end; proc Y; if Next Token = T_+ then Write (Y → +TY); Read(T_+); T(); Y(); else Write (Y → ) ; // new: else clause
Top-down derivation tree generation proc T; Write (T → PX); P(); X(); end; proc X; if Next Token = T_* then Write (X → *T); Read(T_*); T(); else Write (X → ); // new: else clause T: Could have checked for T_( and T_id.. X: Could have used a case statement.
Top-down derivation tree generation proc P; case Next Token of T_(: Write (P → (E)); Read(T_(); E(); Read(T_)); T_id: Write (P → id); Read(T_id); otherwise Error; end;
Input String: begin id := (id + id) * id; end Output: Tree building Input String: begin id := (id + id) * id; end Output: S → begin SL end SL → SZ S → id :=E; E → TY T → PX P → (E) P → id X → Y → +TY T → PX P → id X → Y → X → *T Z →
Top-down derivation tree generation Obvious locations of the Write() statements: Locations where PT Lookups would take place. Works because grammar is LL(1). Two ways to build tree: As parsing proceeds (“as we go”). “Write(A->ω)” (or process A->ω) means: Create tree nodes for ω under “current”; Update current (complicated: need “current” for each procedure). Yuck. Better way ? Yep: Bottom-up ! (Coming Soon …) Build tree after parsing concludes.
summary Red: done Possibilities: Leading up to: Derivation tree or Abstract Syntax Tree. Top-down, or Bottom-up. For original or modified grammar. Leading up to: AST, bottom-up, for the original grammar (“the one”).