Section 4.8 Aggelos Kiayias Computer Science & Engineering Department The University of Connecticut 371 Fairfield Road, Box U-155 Storrs, CT 06269-1155 aggelos@cse.uconn.edu http://www.cse.uconn.edu/~akiayias
Ambiguous Grammars Ambiguous Grammars produce “conflicts” Shift/reduce, or reduce/reduce. Three “typical examples” The dangling else The “expression” grammar Eqn pre-processor of Troff
Dangling Else Ambiguity Recall Grammar Can be rewritten as: S iSeS | iS | a We compute LR(0) items + Goto and the SLR Parsing table. stmt if expr then stmt | if expr then stmt else stmt | other (any other statement)
Canonical sets of LR(0) items I0 I3 S’ .S S a. S .iSeS S .iS I4 S .a S iS.eS S iS. I1 S’ S. I5 S iSe.S I2 S .iSeS S i.SeS S .iS S i.S S .a S .iS I6 S .a S iSeS. Follow(S)= $,e
Parsing Table i e a $ S 0 s2 s3 1 1 acc 2 s2 s3 4 3 r3 r3 4 s5/r2 r2 1. S iSeS 2. S iS 3. S a i e a $ S 0 s2 s3 1 1 acc 2 s2 s3 4 3 r3 r3 4 s5/r2 r2 5 s2 s3 6 6 r1 r1 Resolve: choose s5 e.g. parse iiaea to understand the conflict resolution.
Tracing $0 iiaea$ STACK INPUT Remark
Expressions Recall grammar: 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 E’ E E E + T | T T T * F | F F ( E ) | id
Canonical Sets I0 I2 I5 I8 I1 I3 I6 I9 Follow(E’)=$ Follow(E)=+*)$ E’ .E E .( E ) E E * . E E E * E . E .E + E E .E + E E .E + E E E . + E E .E * E E .E * E E .E * E E E . * E E .( E ) E .( E ) E .( E ) E .id E .id E .id I1 I3 I6 I9 E’ E. E id. E ( E . ) E ( E ) . E E . + E E E . + E E E . * E I4 E E . * E E E + . E E .E + E I7 E .E * E E E + E . E .( E ) E E . + E E .id E E . * E Follow(E’)=$ Follow(E)=+*)$
The Parsing Table id + * ( ) $ E 0 s3 s2 1 1 s4 s5 acc 2 s3 s2 6 1. E E+E 2. E E*E 3. E (E) 4. E id id + * ( ) $ E 0 s3 s2 1 1 s4 s5 acc 2 s3 s2 6 3 r4 r4 r4 r4 4 s3 s2 7 5 s3 s2 8 6 s4 s5 s9 7 s4/r1 s5/r1 r1 r1 8 s4/r2 s5/r2 r2 r2 9 r3 r3 r3 r3
Resolving Ambiguity 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)
Subscript/Superscript 1. E EsubEsupE 2. E EsubE 3. E EsupE 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.