4 Context Free Grammar
4 Context Free Grammar
•Parsing
Context-Free Pushdown
Grammars Automata
predicate verb
Dr. Ayman Ali 5
article a
article the
noun cat
noun dog
verb runs
verb sleeps
Dr. Ayman Ali 6
Derivation of string “the dog walks”:
L = { “a cat runs”,
“a cat sleeps”,
“the cat runs”,
“the cat sleeps”,
“a dog runs”,
“a dog sleeps”,
“the dog runs”,
“the dog sleeps” }
Dr. Ayman Ali 9
Productions
Sequence of
Terminals (symbols)
noun cat
Sequence of
terminals and variables
Grammar: S aSb
S
Variable The right side
may be
Derivation of string ab :
S aSb ab
S aSb S
Dr. Ayman Ali 12
Grammar: S aSb
S
S aSb S
Dr. Ayman Ali 13
Grammar: S aSb
S
Other derivations:
L {a b : n 0}
n n
Instead of:
If: w1 w2 w3 wn
in zero or more derivation steps
*
Trivially: w w
Dr. Ayman Ali 17
Example Grammar Possible Derivations
S aSb *
S
S *
S ab
*
S aaabbb
S aaSbb aaaaaSbbbb b
S aSb S aSb |
S
Grammar: G V ,T, S, P
Set of
variables
Set of Start Set of
terminal variable productions
symbols
As
Variable String of
variables and
terminals
G V ,T, S, P
V {S}
T {a,b} start variable
variables
terminals
Dr. Ayman Ali 22
More Example
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
Dr. Ayman Ali 28
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 aaAB
S
A B
yield aaAB
a a A
S AB aaAB aaABb
S
A B
a a A B b
yield aaABb
Dr. Ayman Ali 33
S AB A aaA | B Bb |
S AB aaAB aaABb aaBb
S
A B
a a A B b
yield
Dr. Ayman Ali
aaBb aaBb 34
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
Dr. Ayman Ali 35
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
E E E | E E | (E) | a
Example strings:
a aa
a a
Dr. Ayman Ali 39
E E E | E E | (E) | a
a a
Dr. Ayman Ali 40
E E E | E E | (E) | a
E E E E
a E E E E a
a a a a
Dr. Ayman Ali 41
take a2
a a a 2 22
E E
E E E E
2 E E E E 2
2 2 2 2
Dr. Ayman Ali 42
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
Dr. Ayman Ali 43
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
Dr. Ayman Ali 46
E E E | E E | (E) | a
Variables Terminals
F F a
Unique
derivation tree
for a aa a a
Dr. Ayman Ali 52
Compilers
Lexical parser
analyzer
input output
machine
program
code
Dr. Ayman Ali 55
A parser knows the grammar
of the programming language
derivation
Parser
input E -> E + E E => E + E
|E*E => E + E * E
10 + 2 * 5
| INT => 10 + E*E
=> 10 + 2 * E
=> 10 + 2 * 5
E => E + E E + E
=> E + E * E
=> 10 + E*E 10
E * E
=> 10 + 2 * E
=> 10 + 2 * 5 2 5
E machine code
E + E mult a, 2, 5
10 add b, 10, a
E * E
2 5