Professional Documents
Culture Documents
CS164
Lecture 5-6
• Grammar
E E + E | E * E | ( E ) | int
• Strings
int + int + int
E + E E + E
E + E int int E + E
+ is left-associative
Prof. Bodik CS 164 Lecture 5-6 4
Ambiguity. Example
E + E E * E
E * E int int E + E
The int * int + int has ony one parse tree now
E E
E + T E * E
T int int E + E
int
Prof. Bodik CS 164 Lecture 5-6 8
Ambiguity: The Dangling Else
• The expression
if E1 then if E2 then S3 else S4
has two parse trees
if if
E1 if S4 E1 if
E2 S3 E2 S3 S4
E1 if E1 if S4
E2 S3 S4 E2 S3
• Examples …
E + E E + E
E + E int int E + E
E * E E + E
E + E int int E * E
• Next:
– How do we answer s L(G) and build a parse tree?
• Try E0 T1 + E2
• Then try a rule for T1 ( E3 )
– But ( does not match input token int5
• Try T1 int . Token matches.
– But + after T1 does not match input token *
• Try T1 int * T2
– This will match but + after T1 will be unmatched
• Have exhausted the choices for T1
– Backtrack to choice for E0
Prof. Bodik CS 164 Lecture 5-6 21
Recursive Descent Parsing. Example (Cont.)
• Try E0 T1
• Follow same steps as before for T1
– And succeed with T1 int * T2 and T2 int
– With the following parse tree
E0
T1
int5 * T2
int2
Prof. Bodik CS 164 Lecture 5-6 22
Recursive Descent Parsing. Notes.
• Consider a production S S a:
– In the process of parsing S we try the above rule
– What goes wrong?
can be rewritten as
S 1 S’
S’ 0 S’ |
• In general
S S 1 | … | S n | 1 | … | m
• All strings derived from S start with one of 1,
…,m and continue with several instances of 1,
…,n
• Rewrite as
S 1 S’ | … | m S’
S’ 1 S’ | … | n S’ |
• The grammar
SA|
AS
is also left-recursive because
S + S
• Left-factored grammar
ETX X+E|
T ( E ) | int Y Y*T|
• The LL(1) parsing table:
int * + ( ) $
T int Y (E)
E TX TX
X +E
Y *T
T E
+
Or…
Prof. Bodik CS 164 Lecture 5-6 47
Constructing Predictive Parsing Tables (Cont.)
Definition Follow(X) = { b | S * X b }
1. Compute the First sets for all non-terminals first
2. Add $ to Follow(S) (if S is the start non-terminal)