TOPDOWN DERIVATION TREE GENERATION COP 4620 Programming Language











- Slides: 11

TOP-DOWN DERIVATION TREE GENERATION COP 4620 – 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;

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; end;

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 end;

TOP-DOWN DERIVATION TREE GENERATION proc T; Write (T → PX); P(); X(); end; T: Could have checked for T_( and T_id. . proc X; if Next Token = T_* then Write (X → *T); X: Could have used a case statement. Read(T_*); T(); else Write (X → ); // new: else clause end;

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;

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) E → TY T → PX P → id X → Y T P X Y X T P X Y Z → → → +TY PX id *T PX id

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: – 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”).