CCWeek 05lecture10 P4
CCWeek 05lecture10 P4
(CS-342)
Lecture # 10 – Part 04
2
Context-Free Languages
n n R
{a b : n 0} {ww }
Regular Languages
a *b * ( a b) *
3
Derivation Order
and
Derivation Trees
4
Derivation Order
1. S AB 2. A aaA 4. B Bb
3. A 5. B
5
1. S AB 2. A aaA 4. B Bb
3. A 5. B
1 2 3 4 5
S AB aaAB aaB aaBb aab
1 4 5 2 3
S AB ABb Ab aaAb aab
At each step, we substitute the
rightmost variable
7
1. S AB 2. A aaA 4. B Bb
3. A 5. B
S AB A aaA | B Bb |
9
S AB A aaA | B Bb |
S AB
S
A B
yield AB
10
S AB A aaA | B Bb |
S AB aaAB
S
A B
yield aaAB
a a A
11
S AB A aaA | B Bb |
S AB aaAB aaABb
S
A B
a a A B b
yield aaABb
12
S AB A aaA | B Bb |
S AB aaAB aaABb aaBb
S
A B
a a A B b
yield
aaBb aaBb
13
S AB A aaA | B Bb |
S AB aaAB aaABb aaBb aab
Derivation Tree S
(parse tree)
A B
a a A B b
yield
aab aab
14
Sometimes, derivation order doesn’t matter
Leftmost derivation:
S AB aaAB aaB aaBb aab
Rightmost derivation:
S AB ABb Ab aaAb aab
S
Give same
A B
derivation tree
a a A B b
15
Ambiguity
16
Grammar for mathematical expressions
E E E | E E | (E) | a
Example strings:
(a a ) a (a a (a a ))
17
E E E | E E | (E) | a
E E E a E a EE
E
a a E a a*a
E E
A leftmost derivation
for a a a
a E E
a a
18
E E E | E E | (E) | a
a a
19
E E E | E E | (E) | a
E E E E
a E E E E a
a a a a
20
take a2
a a a 2 22
E E
E E E E
2 E E E E 2
2 2 2 2
21
Good Tree Bad Tree
2 22 6 2 22 8
6 Compute expression result 8
E using the tree E
2 4 4 2
E E E E
2 2 2 2
2 E E E E 2
2 2 2 2
22
Two different derivation trees
may cause problems in applications which
use the derivation trees:
• Evaluating expressions
• In general, in compilers
for programming languages
23
Ambiguous Grammar:
A context-free grammar G is ambiguous
if there is a string w L(G ) which has:
E E E E
a E E E E a
a a a a
25
E E E | E E | (E) | a
this grammar is ambiguous also because
string a a a has two leftmost derivations
E E E a E a EE
a a E a a*a
Variables Terminals
29
A successful example:
Equivalent
Ambiguous
Non-Ambiguous
Grammar
Grammar
E E E
E E T |T
E E E
T T F | F
E (E )
E a F (E ) | a
generates the same
language
30
E E T T T F T a T a T F
a F F a aF a aa
E
E E T |T
E T
T T F | F
F (E) | a T T F
Unique F F a
derivation tree
for a a a a a
31
An un-successful example:
L {a b c } {a b c }
n n m n m m
n, m 0
L is inherently ambiguous:
32
Example (ambiguous) grammar for L:
L {a b c } {a b c }
n n m n m m
S S1 | S2 S1 S1c | A S2 aS2 | B
A aAb | B bBc |
33
The string a n b n c n L
has always two different derivation trees
(for any grammar)
For example
S S
S1 S2
S1 c a S2
34
References
• http://matt.might.net/articles/gramm
ars-bnf-ebnf/
• https://en.wikipedia.org/wiki/Chomsky_
hierarchy
35
Thank You!
36