Back to the 2023 paper

Module 2: Syntax Analysis (Parser)

20234m

What is shift-reduce conflict?

Worked SolutionAI Assisted

What is a shift–reduce conflict?

A shift–reduce conflict (S–R conflict) is a parsing-table conflict in an LR-family bottom-up parser: in one state (looking at one input symbol), the parser has both a valid shift action and a valid reduce action.

Why it happens: When constructing the parsing table, a single cell M[state,terminal]M[\text{state}, \text{terminal}] ends up with two entries: one saying "shift a (push onto the stack / go to next state)" and the other saying "reduce using production A→αA\to\alpha". Since the parser cannot decide deterministically, the grammar is not LR with the given method (and the table entry is ambiguous).

Example grammar with S–R conflict: classic ambiguous grammar
E→E+E∣E∗E∣(E)∣idE\to E+E \mid E*E \mid (E) \mid \text{id}
produces S–R conflict in LR(0)/SLR(1)/LALR(1) because, e.g. after parsing E + E . with input + or *, the parser doesn't know whether to shift the operator (deferring) or reduce E+E.

Remedies:

  • Add precedence/associativity (%left, %right, %prec in YACC) — e.g. make * bind tighter than +.
  • Refactor the grammar to an unambiguous form (e.g. with separate term/factor levels).
  • Use a more powerful parsing method (canonical LR can resolve conflicts that SLR can't) — but a true ambiguity cannot be removed by switching methods.

Reduction internal form: in LR table notation, a cell with both s and r actions is marked as a conflict, and the grammar is rejected by the parser generator (unless a rule like "shift wins on S–R conflict" is chosen YACC's default: prefer shift).

S–R conflict = a parsing table state where shift and reduce are both valid → grammar not LR for that method.\boxed{\text{S–R conflict = a parsing table state where shift and reduce are both valid → grammar not LR for that method.}}

Similar questions

Budget AppAndroid App

Pocketly on Android

Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.