Transcript Section 4.8
Section 4.8 CSE244 Aggelos Kiayias Computer Science & Engineering Department The University of Connecticut 371 Fairfield Road, Box U-155 Storrs, CT 06269-1155 [email protected] http://www.cse.uconn.edu/~akiayias CH4.1 Ambiguous Grammars CSE244 Ambiguous Grammars produce “conflicts” Shift/reduce, or reduce/reduce. Three “typical examples” The dangling else The “expression” grammar Eqn pre-processor of Troff CH4.2 Dangling Else Ambiguity Recall Grammar stmt if expr then stmt CSE244 | if expr then stmt else stmt | other (any other statement) Can be rewritten as: S iSeS | iS | a We compute LR(0) items + Goto and the SLR Parsing table. CH4.3 Canonical sets of LR(0) items I0 S’ .S S .iSeS CSE244 S .iS S .a I3 S a. Follow(S)= $,e I4 S iS.eS S iS. I1 S’ S. I2 S i.SeS S i.S S .iSeS S .iS S .a I5 S iSe.S S .iSeS S .iS S .a I6 S iSeS. CH4.4 Parsing Table 1. S iSeS 2. S iS 3. S a CSE244 0 1 2 3 4 5 6 i e s2 a s3 $ S 1 acc s2 s3 r3 s5/r2 s2 4 r3 r2 s3 r1 6 r1 Resolve: choose s5 e.g. parse iiaea to understand the conflict resolution. CH4.5 Tracing STACK $0 INPUT Remark iiaea$ CSE244 CH4.6 Expressions Recall grammar: E’ E EE+T | T TT*F | F F ( E ) | id CSE244 Originally written as: E E + E | E *E | (E) | id In fact we can try to construct the SLR parsing table and see what will happen CH4.7 Canonical Sets I0 I2 I5 I8 I1 I3 I6 I9 I4 EE+.E E .E + E E .E * E E .( E ) E .id I7 EE +E. EE.+E EE.*E E’ .E E .E + E CSE244 E .E * E E .( E ) E .id E’ E. EE.+E EE.*E E .( E ) E .E + E E .E * E E .( E ) E .id E id. EE*.E E .E + E E .E * E E .( E ) E .id E(E.) EE.+E EE.*E EE*E. EE.+E EE.*E E(E). Follow(E’)=$ Follow(E)=+*)$ CH4.8 The Parsing Table CSE244 1. E E+E 2. E E*E 3. E (E) 4. E id 0 1 2 3 4 5 6 7 8 9 id + s3 s4 s3 r4 s3 s3 s4 s4/r1 s4/r2 r3 * ( s2 ) s5 $ acc s2 r4 6 r4 r4 s2 s2 s5 s5/r1 s5/r2 r3 E 1 7 8 s9 r1 r2 r3 r1 r2 r3 CH4.9 Resolving Ambiguity CSE244 If the state contains E E op E . and we find op on the input we Reduce (left-association) Shift (right-association) If the state contains E E op E . and we find op’ on the input we Reduce (op’ has lower precedence than op) Shift (op’ has higher precedence than op) CH4.10 Subscript/Superscript 1. E EsubEsupE 2. E EsubE 3. E EsupE CSE244 4. E {E} 5. E c Even if we resolve conflicts using precedence and associations Rule 1 will still produce problems, i.e. when seeing a } or $ Being at the state that contains the item E EsubEsupE. We will have two possibilities for reduce: Either r3 or r1. (reduce/reduce conflict) Resolving for r1 allows a special meaning for it. CH4.11