Professional Documents
Culture Documents
Context Free Grammars
Context Free Grammars
Grammar: G V ,T , S , P
Set of
variables
Set of Start Set of
terminal variable productions
symbols
A s
Variable String of
variables and
terminals
G V ,T , S , P
V {S}
T {a, b} start variable
variables
terminals
FLAT Dept. of CSE, VFSTR University 4
Language of a Grammar:
String of terminals or
L(G ) {a b : n 0}
n n
is a context-free language
since context-free grammar G :
S aSb |
generates L(G ) L
Context-free grammar G :
S aSa |bSb |
Example derivations:
S aSa abSba abba
S aSa abSba abaSaba abaaba
L(G ) {w : na ( w) nb ( w),
and na (v) nb (v)
Describes
in any prefix v}
matched
parentheses: () ((( ))) (( )) a (, b )
FLAT Dept. of CSE, VFSTR University 10
Derivation Order
and
Derivation Trees
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
FLAT Dept. of CSE, VFSTR University 14
1. S AB 2. A aaA 4. B Bb
3. A 5. B
Leftmost derivation of aab :
1 2 3 4 5
S AB aaAB aaB aaBb aab
S AB A aaA | B Bb |
A B
yield AB
A B
yield aaAB
a a A
A B
a a A B b
yield aaABb
FLAT Dept. of CSE, VFSTR University 19
S AB A aaA | B Bb |
S AB aaAB aaABb aaBb
S
A B
a a A B b
yield
aaBb aaBb
FLAT Dept. of CSE, VFSTR University 20
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
FLAT Dept. of CSE, VFSTR University 21
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
FLAT
Dept. of CSE, VFSTR University
22
Ambiguity
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
FLAT Dept. of CSE, VFSTR University 25
E E E | E E | (E) | a
a a
FLAT Dept. of CSE, VFSTR University 26
E E E | E E | (E) | a
E E E E
a E E E E a
a a a a
FLAT Dept. of CSE, VFSTR University 27
take a2
a a a 2 22
E E
E E E E
2 E E E E 2
2 2 2 2
FLAT Dept. of CSE, VFSTR University 28
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
FLAT Dept. of CSE, VFSTR University 29
Two different derivation trees
may cause problems in applications which
use the derivation trees:
• Evaluating expressions
• In general, in compilers
for programming languages
E E E E
a E E E E a
a a a a
FLAT Dept. of CSE, VFSTR University 32
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
Unique F F a
derivation tree
for a a a a a
FLAT Dept. of CSE, VFSTR University 38
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 | S2 S1 S1c | A S2 aS2 | B
A aAb | B bBc |
S1 S2
S1 c a S2
http://www.eecs.wsu.edu/~ananth/Cp
tS317/Lectures/