Back to the 2026 paper

Module 2: Syntax Analysis (Parser)

20267m

Explain ambiguity in context-free grammars. Illustrate how ambiguity can lead to shift-reduce or reduce-reduce conflicts during LR parsing.

Worked SolutionAI Assisted

Ambiguity in a context-free grammar

A CFG is ambiguous if some string in its language has more than one parse tree (equivalently, more than one leftmost derivation or more than one rightmost derivation).

Example: E→E+E∣E∗E∣idE \to E + E \mid E * E \mid id on the string id+id∗idid + id * id has two parse trees.

MermaidDiagram
Rendering diagram…

The two trees give different meanings (different evaluation order), so the compiler cannot decide which one is intended.

How ambiguity causes conflicts in LR parsing

An LR parser must decide in every state whether to shift or reduce. An ambiguous grammar can never be LR(k) for any kk, so its LR table always has at least one multiply-defined entry.

1. Shift-reduce conflict. For the grammar above, after reading E + E the parser reaches a state containing both items

E→E+E⋅andE→E⋅∗EE \to E + E \cdot \qquad\text{and}\qquad E \to E \cdot * E

On the next input symbol * it could reduce by E→E+EE \to E+E (giving tree 2) or shift * (giving tree 1). The table entry for (state, *) holds both s and r.

2. Reduce-reduce conflict. Take S→A∣BS \to A \mid B, A→aA \to a, B→aB \to a. The string a has two parse trees. After shifting a the state contains

A→a⋅andB→a⋅A \to a \cdot \qquad\text{and}\qquad B \to a \cdot

On lookahead `‘theparsercanreduceby` the parser can reduce by A \to a∗∗or∗∗by **or** by B \to a$: two reduce actions in one cell.

Removing the conflicts

  • Rewrite the grammar to enforce precedence and associativity: E→E+T∣TE \to E+T \mid T, T→T∗F∣FT \to T*F \mid F, F→idF \to id.
  • Or keep the grammar and resolve conflicts with rules (precedence: * binds tighter than +; left associativity), as Yacc/Bison do.
  • Shift is the default choice in a shift-reduce conflict; the earlier rule is chosen in a reduce-reduce conflict.

Similar questions

Free AppAndroid App

Coursify Android App

Generate AI courses, take quick quizzes between classes, and master complex engineering concepts on the go.