CS 415: Lecture 10: Review: LR (K) Grammars
CS 415: Lecture 10: Review: LR (K) Grammars
T LR Parsing (backtrack)
S ⇒ γ 0 ⇒ γ1 ⇒ γ 2 ⇒ L ⇒ γ n ⇒ w
we can, for each right-sentential form in the derivation
1
LR(1) Parsing
Input: a1 a2 a3 a4...
stack with sn j n
(symbol, state) sn-1 j n-1
pairs sn-2 j n-2 actions
gotos
LR(1) Parsing
2
LR(1) Parsing
token = next_token()
repeat
s = state from top of stack
if action[s,token] = “shift r” then
push (token, r)
token = next_token()
else if action[s,token] = “reduce A ::= B” then
pop |B| pairs off of the stack
s = state from top of stack
push (A, goto[s,A])
else if action[s,token] = “accept” then
return
else error()
endrepeat
LR(1) Parsing
3
SLR(1)
Viable Prefix
4
LR(0) Items
Example
S→B
B → aB | b
❚ How about the following?
S′ → S
S → aSb | ab
5
DFA States
I0 : S’ → . S I2 : S → a S . b
S → . aSb
S → . ab I3 : S’ → S .
I1 : S → a . S b I4 : S → a b.
S →a.b
S → . aSb I5 : S → a S b .
S → . ab
DFA
a
S b
I0 I1 I2 I5
b
S
I3 I4
6
Encoding the Parser
If A → α . a β in Ik and
actions gotos goto(Ik , a) = Ij table entry
a b $ S for (k,a) is sj for terminal a.
0 s1 _ _ 3
1 s1 s4 _ 2
2 _ s5 _ If A → α . in Ik then table
3 _ _ accept entry for (k,b) is r-rule#
4 r3 r3 r3 where b is any input symbol.
5 r2 r2 r2
If S’ → S. in Ik then table
entry for (k,$) is accept.
Example
7
SLR(1)
SLR(1)
8
Shift/Reduce Conflict
S’ → S
S →Ab|dc|bAc
A →d
A very simple language = {db, dc, bdc}
Follow(S) = {$}, Follow(A) = {b,c}
Form part of the SLR(1) parser:
I0 : S’ → . S I1 : S → d . c
S → .A b A → d.
S → .dc But since c is in Follow(A), we don’t
S → .b A c know whether to reduce or shift in state
A → .d I if c is next input symbol!
1
Reduce/Reduce Conflict
S’ → S Deriv1: S’ → S →Ac → dc
S→bAe|bBd|Ac Deriv2: S’ → S → bBd →bEcd →bdcd
A→d Deriv3: S’ → S → bAe → bde
B→Ec
E→d
I0 : S’ →. S I1 : S → b . A e I2 : A → d.
S→.bAe S→b.Bd E → d.
S→.bBd A→.d
S→.Ac B→.Ec Which reduction to take?
A → .d E→.d Follow set too imprecise
here to decide.
9
LR(k)
LR(k)
10