Example 2.4 I
The following CFG handles mathematical expressions
G4 = (V , Σ, R, hexpri)
V = {hexpri, htermi, hfactori}
Σ = {a, +, ×, (, )}
R:
hexpri → hexpri + htermi | htermi htermi → htermi × hfactori | hfactori hfactori → (hexpri) | a
Fig 2.5: check a + a × a
Example 2.4 II
E
E
T
F
a +
T
T
F
a × F
a
check (a + a) × a
Example 2.4 III
E T
T F
F E
E T
T F
F a
( + a ) × a
Design Grammars I
{0n1n | n ≥ 0} ∪ {1n0n | n ≥ 0}
S1 → 0S11 | S2 → 1S20 | S → S1 | S2 CFG versus DFA
For a CFG that is regular, it can be recognized by DFA
Design Grammars II
Rules of CFG can be
Ri → aRj if δ(qi, a) = qj
Ri → if qi ∈ F
We see the main difference between CFG and DFA CFG: a rule can be like
Ri → aRjb
Design Grammars III
DFA: a rule can only be
Ri → aRj,
where we treat each Ri as a state and let δ(Ri, a) = Rj
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?
hexpri → hexpri + hexpri | hexpri × hexpri | (hexpri)|a We see the following ways to parse
a + a × a
Ambiguity II
Fig 2.6
E
E
E
a + E
a × E
a
E
E
a +
E
E
a × E
a
This CFG does not give the precedence relation We want that a × a is done first
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
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
hexpri ⇒ hexpri + htermi
⇒ hexpri + htermi × hfactori where the second part is expanded.
On the other hand, we can handle the first one first.
hexpri ⇒ hexpri + htermi
⇒ htermi + htermi
Leftmost derivation II
This is not considered ambiguous
Definition of leftmost derivation: at every step the leftmost remaining variable is the one replaced.
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.