next up previous
Next: Elimination of left recursion Up: Context-free grammars Previous: Parse trees

Elimination of ambiguity.

AMBIGUITY. The context-free grammar G = (VT, VN, S, P) is

A language L over some alphabet $ \Sigma$ is said inherently ambiguous if it cannot be generated by an unambiguous grammar.

Example 8   Let us consider $ \Sigma$ = {a, b, c} and

L = {w $\displaystyle \in$ $\displaystyle \Sigma^{{{\ast}}}_{{}}$  |  ( | w$\displaystyle \mid_{{a}}^{{}}$ = | w$\displaystyle \mid_{{b}}^{{}}$or ( | w$\displaystyle \mid_{{b}}^{{}}$ = | w$\displaystyle \mid_{{c}}^{{}}$)}. (17)

One can show that L is an inherently ambiguous language.

Example 9   Consider VN = {S, E}, VT = {$ \bf if$,$ \bf then$,$ \bf else$} and a grammar G = (VT, VN, S, P) such that the following

S $\displaystyle \longmapsto$ $\displaystyle \bf if$ E $\displaystyle \bf then$ S | $\displaystyle \bf if$ E $\displaystyle \bf then$ S $\displaystyle \bf else$ S
(18)

are productions of G. Then the string

w  =  $\displaystyle \bf if$ E $\displaystyle \bf then$ $\displaystyle \bf if$ E $\displaystyle \bf then$ S $\displaystyle \bf else$ S (19)

has two parse trees as shown on Figure 5.
Figure 5: Two parse trees for the same if-then-else statement.
\begin{figure}\htmlimage
\centering\includegraphics[scale=.4]{ifThenElseParseTrees.eps}
\end{figure}
In all programming languages with if-then-else statements of this form, the second parse tree is preferred. Hence the general rule is: match each else with the previous closest then. This disambiguating rule can be incorporated directly into a grammar by using the following observations.

stmt $ \longmapsto$ matched-stmt | unmatched-stmt
matched-stmt $ \longmapsto$ if expr then matched-stmt else matched-stmt
matched-stmt $ \longmapsto$ non-alternative-stmt
unmatched-stmt $ \longmapsto$ if expr then stmt
unmatched-stmt $ \longmapsto$ if expr then matched-stmt else unmatched-stmt


next up previous
Next: Elimination of left recursion Up: Context-free grammars Previous: Parse trees
Marc Moreno Maza
2004-12-02