Ambiguous Grammar - CSU086 - Shoolini U

Ambiguous Grammar and Violations

Ambiguous Grammar

Ambiguous grammar is a formal grammar that allows more than one parse tree for the same string. This ambiguity leads to multiple interpretations, making it unsuitable for parsing in compilers. Such grammars often cause issues in syntax analysis, affecting compiler construction and program execution.

1. Definition of Ambiguous Grammar

A grammar is ambiguous if there exists at least one string in the language it generates that has more than one distinct parse tree. This means there are multiple ways to derive the same string using different rule applications.

2. Common Causes of Ambiguity

3. Violations Caused by Ambiguous Grammars

Ambiguous grammars lead to multiple issues in compilers and language interpretation:

4. Examples of Ambiguous Grammar

Consider the following expression grammar:


E → E + E | E * E | ( E ) | id

This grammar is ambiguous because it does not specify precedence or associativity of + and *. The string id + id * id can have two parse trees:

4.1 Parse Tree 1 (Multiplication has Higher Precedence)

.  E
  /|\
 E + E
   /|\
  E * E
 id  id id
4.2 Parse Tree 2 (Addition Evaluated First)

.   E
   /|\
  E * E
 /|\
E  +  E
id   id  id

The two parse trees indicate different evaluation orders, leading to ambiguity in interpretation.

5. Resolving Ambiguity

Ambiguity can be resolved using several methods:

6. The Dangling-Else Ambiguity

Another classic case of ambiguity is the dangling-else problem:


stmt → if expr then stmt | if expr then stmt else stmt | other

Given the input:


if E1 then if E2 then S1 else S2

The ambiguity arises because else S2 could be associated with either the first or second if.

Solution: Use separate rules for matched and unmatched statements:


stmt → matched_stmt | unmatched_stmt
matched_stmt → if expr then matched_stmt else matched_stmt | other
unmatched_stmt → if expr then stmt | if expr then matched_stmt else unmatched_stmt

This ensures each else is correctly matched with the nearest unmatched if.