Property of a string or a grammar.
Ambiguous String
A string is ambiguous iff it has more than one derivation tree.
Unambiguous Grammar
A grammar is unambiguous iff every string has exactly one derivation tree.
Example:
Ambiguous Grammar
A grammar is ambiguous iff its not unambiguous (i.e. there exists a string in with multiple derivation trees). Ambiguity often arises due to operator precedence and associativity.
Some ambiguous grammars can be rewritten as an equivalent unambiguous grammar.
Associativity
Associativity defines how operators of the same precedence are grouped.
Left Associative
Grouping from left to right.
Right Associative
Grouping from right to left.
Precedence
Defines order of evaluation. For example, multiplication has higher precedence than addition.
When precedence is equal, associativity resolves ambiguity.
Examples:
-
Left associative
-
Right associative
4^3^2 =
Examples
Grammar of arithmetic
is ambiguous because has 2 possible leftmost derivations.
The above grammar can be made unambiguous, using precedence + associativity:
Precedence is defined for and using , and .
Dangling Else
Consider the grammar:
<stmt> →
if (<expr>) <stmt>
| if (<expr>) <stmt> else <stmt>
| <other_stmt>
Example statement:
if (expr1) if (expr2) f(); else g();
Two interpretations:
if (expr1) {
if (expr2) f();
}
else g();
if (expr1) {
if (expr2) f();
else g();
}
Programming languages usually adopt rule “else associates with the closest if.”