Professional Documents
Culture Documents
1
R
n n
{a b } {ww }
Regular Languages
2
Context-Free Languages
R
n n
{a b } {ww }
Regular Languages
3
Context-Free Languages
Context-Free Pushdown
Grammars Automata
stack
automaton
4
Context-Free Grammars
5
Example
A derivation:
Another derivation:
n n
L(G ) = {a b : n ³ 0}
8
Example
A derivation:
Another derivation:
R
L(G ) = {ww : w Î{a, b}*}
11
Example
A derivation:
S Þ SS Þ aSbS Þ abS Þ ab
12
A context-free grammar G: S ® aSb
S ® SS
S ®l
A derivation:
L(G ) = {w : na ( w) = nb ( w),
and na (v) ³ nb (v)
in any prefix v}
14
Definition: Context-Free Grammars
Grammar G = (V , T , S , P )
A language L is context-free
if and only if
17
Recall
Language of a Grammar
For a grammar G
with start variable S :
*
L(G ) = {w : S Þ w}
String of terminals
18
Derivation Order
1. S ® AB 2. A ® aaA 4. B ® Bb
3. A ® l 5. B ® l
Leftmost derivation:
1 2 3 4 5
S Þ AB Þ aaAB Þ aaB Þ aaBb Þ aab
Rightmost derivation:
1 4 5 2 3
S Þ AB Þ ABb Þ Ab Þ aaAb Þ aab
19
S ® aAB
A ® bBb
B ® A|l
Leftmost derivation:
S Þ aAB Þ abBbB Þ abAbB Þ abbBbbB
Þ abbbbB Þ abbbb
Rightmost derivation:
S Þ aAB Þ aA Þ abBb Þ abAb
Þ abbBbb Þ abbbb 20
Derivation Trees
21
S ® AB A ® aaA | l B ® Bb | l
S Þ AB
S
A B
22
S ® AB A ® aaA | l B ® Bb | l
S Þ AB Þ aaAB
S
A B
a a A
23
S ® AB A ® aaA | l B ® Bb | l
S Þ AB Þ aaAB Þ aaABb
S
A B
a a A B b
24
S ® AB A ® aaA | l B ® Bb | l
A B
a a A B b
l 25
S ® AB A ® aaA | l B ® Bb | l
A B
a a A B b
l l 26
S ® AB A ® aaA | l B ® Bb | l
A B
yield
a a A B b aallb
= aab
l l 27
Partial Derivation Trees
S ® AB A ® aaA | l B ® Bb | l
S Þ AB
Partial derivation tree S
A B
28
S Þ AB Þ aaAB
A B
a a A
29
sentential
S Þ AB Þ aaAB form
A B
yield
a a A
aaAB
30
Sometimes, derivation order doesn’t matter
Leftmost:
S Þ AB Þ aaAB Þ aaB Þ aaBb Þ aab
Rightmost:
S Þ AB Þ ABb Þ Ab Þ aaAb Þ aab
S
Same derivation tree
A B
a a A B b
l l 31
Ambiguity
32
E ® E + E | E * E | (E) | a
a + a*a
E E Þ E + E Þ a+ E Þ a+ E*E
Þ a + a* E Þ a + a*a
E + E
leftmost derivation
a E * E
a a 33
E ® E + E | E * E | (E) | a
a + a*a
E + E a
a a 34
E ® E + E | E * E | (E) | a
a + a*a
Two derivation trees
E E
E + E E * E
a E * E E + E a
a a a a 35
The grammarE ® E + E | E * E | (E) | a
is ambiguous:
E E
E + E E * E
a E * E E + E a
a a a a
36
The grammarE ® E + E | E * E | (E) | a
is ambiguous:
E Þ E + E Þ a+ E Þ a+ E*E
Þ a + a* E Þ a + a*a
38
In other words:
39
Why do we care about ambiguity?
a + a*a
take a=2
E E
E + E E * E
a E * E E + E a
a a a a 40
2 + 2*2
E E
E + E E * E
2 E * E E + E 2
2 2 2 2 41
2 + 2*2 = 6 2 + 2*2 = 8
6 8
E E
2 4 4 2
E + E E * E
2 2 2 2
2 E * E E + E 2
2 2 2 2 42
Correct result: 2 + 2*2 = 6
6
E
2 4
E + E
2 2
2 E * E
2 2
43
• Ambiguity is bad for programming languages
44
We fix the ambiguous grammar:
E ® E + E | E * E | (E) | a
E a + a*a
E + T
T T * F
F F a
a a
47
The grammar G: E ® E +T
E ®T
T ®T *F
T ®F
F ® (E)
F ®a
is non-ambiguous:
Every string wÎ L(G ) has
a unique derivation tree
48