REPLACING RECURSION WITH ITERATION COP 4620 Programming Language

  • Slides: 7
Download presentation
REPLACING RECURSION WITH ITERATION COP 4620 – Programming Language Translators Dr. Manuel E. Bermudez

REPLACING RECURSION WITH ITERATION COP 4620 – Programming Language Translators Dr. Manuel E. Bermudez

REPLACING RECURSION WITH ITERATION To make our grammar LL(1), we introduced nonterminals X, Y,

REPLACING RECURSION WITH ITERATION To make our grammar LL(1), we introduced nonterminals X, Y, Z. None are needed. SL isn’t needed, either.

GRAMMARS (SO FAR) Our “model” PL grammar. Modified, LL(1)) grammar. S S → →

GRAMMARS (SO FAR) Our “model” PL grammar. Modified, LL(1)) grammar. S S → → SL → → E → → T → → P → → begin SL end {begin} id : = E; {id} SL S {begin, id} E+T {(, id} P*T {(, id} P {(, id} (E) {(} id {id} SL Z E Y T X P → → → → begin SL end id : = E ; S Z T Y + T Y P X * T (E) id Procedures SL, X, Y and Z can all be eliminated. {begin} {id} {begin, id} {end} {(, id} {+} {; , )} {(, id} {*} {; , +, )} {(} {id}

REPLACING RECURSION S → begin SL end → id : = E ; SL

REPLACING RECURSION S → begin SL end → id : = E ; SL → S Z Z → S Z → proc S; case Next_Token of T_begin : Read(T_begin); repeat Replaces S(); until Next_Token {T_begin, T_id}; call Read(T_end); to SL, T_id : Read(T_id); and Read (T_: =); recursion E(); on Z. Read (T_; ); Regular Right-Part Grammar: otherwise Error; S → begin S+ end; → id : = E ; end; Still haven’t restored left associativity of ‘’ operator.

REPLACING RECURSION E → TY Y → +TY → T → PX X →

REPLACING RECURSION E → TY Y → +TY → T → PX X → *T → Replaces call to Y, and recursion on Y. Regular Right-Part Grammar: E → T(+T)* T → P(*T)? Still have not restored left associativity of ‘+’. proc E; T(); while Next_Token = T_+ do Read (T_+); T(); od; end; Replaces call to X. X is not recursive. proc T; P(); if Next_Token = T_* then Read (T_*); T(); end;

REPLACING RECURSION proc P; case Next Token of T_(: Read(T_(); E(); Read(T_)); T_id: Read(T_id);

REPLACING RECURSION proc P; case Next Token of T_(: Read(T_(); E(); Read(T_)); T_id: Read(T_id); otherwise Error; end; No change! Regular Right-Part Grammar: S → begin S+ end → id : = E ; E → T(+T)* T → P(*T)? P → (E) → id Simple, eh ? Simple code, too.

SUMMARY To make our grammar LL(1), we introduced nonterminals X, Y, Z. We just

SUMMARY To make our grammar LL(1), we introduced nonterminals X, Y, Z. We just got rid of them. Got rid of SL, too. Resulting code is remarkably simple: reflects RRPG. Still have not restored left associativity of operators.