Toc File1
Toc File1
Context-Free Languages
n n R
{a b : n 0} {ww }
Regular Languages
a *b * ( a b) *
Context-Free Languages
Context-Free Pushdown
Grammars Automata
stack
automaton
Context-Free Grammars
Context-Free Grammar: G (V , T , S , P )
A s
Variable String of
variables and
terminals
Example of Context-Free Grammar
S aSb |
productions
P {S aSb, S }
G V ,T , S , P
V {S }
T {a, b} start variable
variables
terminals
Example:
L(G ) {a b : n 0}
n n
L {a b : n 0}
n n
is a context-free language
since context-free grammar G :
S aSb |
generates L(G ) L
Another Example
Context-free grammar G :
S aSa | bSb |
Example derivations:
S aSa abSba abba
S aSa abSba abaSaba abaaba
1. S AB 2. A aaA 4. B Bb
3. A 5. B
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
1. S AB 2. A aaA 4. B Bb
3. A 5. B
S AB A aaA | B Bb |
S AB
S
A B
yield AB
S AB A aaA | B Bb |
S AB aaAB
S
A B
yield aaAB
a a A
S AB A aaA | B Bb |
S AB aaAB aaABb
S
A B
a a A B b
yield aaABb
S AB A aaA | B Bb |
S AB aaAB aaABb aaBb
S
A B
a a A B b
yield
aa Bb aaBb
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
aa b aab
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
Ambiguity
Grammar for mathematical expressions
E E E | E E | (E) | a
Example strings:
(a a ) a (a a (a 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
E E E | E E | (E) | a
a a
E E E | E E | (E) | a
E E E E
a E E E E a
a a a a
take a2
a a a 2 22
E E
E E E E
2 E E E E 2
2 2 2 2
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
Two different derivation trees
may cause problems in applications which
use the derivation trees:
• Evaluating expressions
• In general, in compilers
for programming languages
Another ambiguous grammar:
Variables Terminals
Unique F F a
derivation tree
for a a a a a
An un-successful example:
L {a b c } {a b c }
n n m n m m
n, m 0
L is inherently ambiguous:
L {a b c } {a b c }
n n m n m m
S S1 | S 2 S1 S1c | A S 2 aS 2 | B
A aAb | B bBc |
The string a n b nc n L
has always two different derivation trees
(for any grammar)
For example
S S
S1 S2
S1 c a S2