Example 2.4 I The following CFG handles mathematical expressions G 4 = ( V , Σ , R , � expr � ) V = {� expr � , � term � , � factor �} Σ = { a , + , × , ( , ) } R : � expr � → � expr � + � term � | � term � � term � → � term � × � factor � | � factor � � factor � → ( � expr � ) | a Fig 2.5: check a + a × a November 26, 2020 1 / 12
Example 2.4 II E E T T T F F F a + a × a check ( a + a ) × a November 26, 2020 2 / 12
Example 2.4 III E T T F F E E T T F F ( + ) × a a a November 26, 2020 3 / 12
Design Grammars I { 0 n 1 n | n ≥ 0 } ∪ { 1 n 0 n | n ≥ 0 } S 1 → 0 S 1 1 | ǫ S 2 → 1 S 2 0 | ǫ S → S 1 | S 2 CFG versus DFA For a CFG that is regular, it can be recognized by DFA November 26, 2020 4 / 12
Design Grammars II Rules of CFG can be R i → aR j if δ ( q i , a ) = q j R i → ǫ if q i ∈ F We see the main difference between CFG and DFA CFG: a rule can be like R i → aR j b November 26, 2020 5 / 12
Design Grammars III DFA: a rule can only be R i → aR j , where we treat each R i as a state and let δ ( R i , a ) = R j November 26, 2020 6 / 12
Ambiguity I The same string but obtained in different ways For the example of mathematical expressions discussed earlier, what if we consider the following rules? � expr � → � expr � + � expr � | � expr � × � expr � | ( � expr � ) | a We see the following ways to parse a + a × a November 26, 2020 7 / 12
Ambiguity II Fig 2.6 E E E E E E E E E E × × a + a a a + a a This CFG does not give the precedence relation We want that a × a is done first November 26, 2020 8 / 12
Ambiguity III By the more complicated CFG earlier, the parsing is unambiguous Question: how to formally define the ambiguity? We need to define “leftmost derivation” first November 26, 2020 9 / 12
Leftmost derivation I Even for an unambiguous CFG we may have the same parse tree, but different derivations For the CFG discussed earlier we can do � expr � ⇒ � expr � + � term � ⇒ � expr � + � term � × � factor � where the second part is expanded. On the other hand, we can handle the first one first. � expr � ⇒ � expr � + � term � ⇒ � term � + � term � November 26, 2020 10 / 12
Leftmost derivation II This is not considered ambiguous Definition of leftmost derivation: at every step the leftmost remaining variable is the one replaced. November 26, 2020 11 / 12
Formal definition of ambiguity I w ambiguous if there exist two leftmost derivations Some context-free languages can be generated by ambiguous & unambiguous grammars We say a CFG is inherently ambiguous if it only has ambiguous grammars See prob 2.29 in the textbook. Details not given here. November 26, 2020 12 / 12
Recommend
More recommend