Lecture 9
Lecture 9
Context-free grammar
EE+E N 0N Variables: E, N
EE*E N 1N Terminals: +, *, (, ), 0,
E (E) N0 1
EN N1 Start variable: E
derivation
(E + E ) * N from with one production
(E + E ) * 1
(E + N) * 1 *
(N + N) * 1
means can be obtained
(N + 1N) * 1
from after zero or more
(N + 10) * 1
productions
(1 + 10) * 1
Example 1
A → 0A1 | B variables: A, B
B→# terminals: 0, 1, #
start variable: A
L = {0n#1n: n ≥ 0}
Example 2
S SS | (S) |
convention: variables in uppercase,
terminals in lowercase, start variable first
• Give derivations of (), (()())
E E + E | E - E | (E) | E
V
Vx|y|z E+E
EE+E
V+E V ( E )
x+E
x + (E)
x
x + (E E) E E
x + (V E)
x + (y E) V V
x + (y V)
x + (y z)
y z
Definition of parse tree
• Example: E E + E | E E | (E) |
V
Vx|y|z
E E
E +E E +E
x+y+z
V E +E E +E V
x V V V V z
y z x y
Why ambiguity matters
• The parse tree represents the intended meaning:
E E
E +E E +E
x+y+z
V E +E E +E V
x V V V V z
y z x y
E E + E | E E | E E | (E) |
V
Vx|y|z
E E
E * E E +E
xy+z
V E +E E E V
x V V V V z
y z x y
V V V
x y + z