Resolving Ambiguity
🔹 What Does Resolving Ambiguity Mean?
A CFG is ambiguous if some string has more than one parse tree.
🔹 Methods to Resolve Ambiguity
✅ (a) Enforce Operator Precedence
-
Ensure
*
is evaluated before+
. -
Example:
Ambiguous grammar:
Unambiguous grammar (with precedence):
Now in a + a * a
, multiplication (*
) happens before addition (+
).
So only one parse tree is possible.
✅ (b) Enforce Operator Associativity
-
Ambiguity also arises in expressions like
a - b - c
. -
Should it be
(a - b) - c
(left-associative) ora - (b - c)
(right-associative)?
We rewrite grammar for left-associativity:
So a - b - c
→ (a - b) - c
.
✅ (c) Use Parentheses Explicitly
-
Parentheses naturally remove ambiguity by forcing grouping.
-
Example: In arithmetic expressions,
(a + b) * c
vsa + (b * c)
.
✅ (d) Restrict the Grammar
-
Sometimes ambiguity comes from unrestricted productions.
-
Example: The dangling else problem in
if-then-else
.
Ambiguous grammar:
Ambiguity: if E1 then if E2 then S1 else S2
→ Does else
attach to first or second if
?
Unambiguous solution (force else
to match the closest if
):
Here, else
always binds to the innermost unmatched if
.
✅ (e) Detect Inherent Ambiguity
-
Some languages are inherently ambiguous, meaning no unambiguous CFG exists.
-
Example:
This language is inherently ambiguous.
👉 In such cases, ambiguity cannot be resolved.
🔹 Summary for Students
-
Ambiguity = multiple parse trees for the same string.
-
Resolve ambiguity by:
-
Enforcing precedence (e.g.,
*
before+
). -
Enforcing associativity (e.g., left-associative subtraction).
-
Using parentheses.
-
Rewriting grammar (e.g., dangling-else).
-
-
Some languages are inherently ambiguous → can’t be fixed.
Comments
Post a Comment