LR Parsing. Parser Generators.: Lecture 7-8
LR Parsing. Parser Generators.: Lecture 7-8
Lecture 7-8
E E + ( E ) | int
E E
E E
E E E
A rightmost E E E
derivation in reverse
int + ( int ) + ( int )
Prof. Bodik CS 164 Lecture 7-8 10
Important Fact #1
Shift
Reduce
E + (I int ) E + (int I )
E + (E + ( E ) I ) E +(E I )
E E
E E
E E
E E
• Initially: I x1x2 . . . xn
• In context containing
E ! E + ² ( E ), +
– If ( follows then we can perform a shift to context
containing
E ! E + (² E ), +
• In context containing
E ! E + ( E ) ², +
– We can perform a reduction with E ! E + ( E )
– But only if a + follows
Prof. Bodik CS 164 Lecture 7-8 46
LR(1) Items (Cont.)
Closure(Items) =
repeat
for each [X ! ²Y, a] in Items
for each production Y !
for each b 2 First(a)
add [Y ! ², b] to Items
until Items is unchanged
Prof. Bodik CS 164 Lecture 7-8 48
Constructing the Parsing DFA (1)
Transition(State, y)
Items Ã
for each [X ! ²y, b] 2 State
add [X ! y², b] to Items
return Closure(Items)
Prof. Bodik CS 164 Lecture 7-8 51
Constructing the Parsing DFA. Example.
S ! ²E, $ 0 1
E ! int², $/+ E ! int
E ! ²E+(E), $/+ int on $, +
E ! ²int, $/+
E ! E+² (E), $/+ 3
2 E +
S ! E², $ (
E ! E²+(E), $/+ E ! E+(²E), $/+ 4
accept E E ! ²E+(E), )/+
on $ E ! ²int, )/+
E ! E+(E²), $/+ int 5
6
E ! E²+(E), )/+ E ! int², )/+ E ! int
on ), +
and so on… Prof. Bodik CS 164 Lecture 7-8 52
LR Parsing Tables. Notes
%left +
%left *
• Precedence of a rule = that of its last terminal
– See bison manual for ways to override this default
A B C A C
BE
D E F D F
• Parsing
– A solid foundation: context-free grammars
– A simple parser: LL(1)
– A more powerful parser: LR(1)
– An efficiency hack: LALR(1)
– LALR(1) parser generators
• In P an id is a
– N when followed by , or :
– T when followed by id
• In R an id is a
– N when followed by :
– T when followed by ,
• This is an LR(1) grammar.
• But it is not LALR(1). Why?
– For obscure reasons
N ² id :
N ² id , T id ² id/,
LALR merge
T ² id id N id ² :/,
R²T , 2 T id ² , 4
id
R²N:T , N id ² :
T ² id ,
N ² id : Prof. Bodik CS 164 Lecture 7-8 77
What Happened?
R.T , T id ² , 4
R.N:T , 2 N id ² :
T . id ,
N . id : Prof. Bodik CS 164 Lecture 7-8 79