07 Shift Reduce
07 Shift Reduce
Unambiguous Grammars
LR(0) and SLR Parse Tables
by Wim Bohm and Michelle Strout
LR(k) postpones the decision until all tokens of the rhs plus k more tokens
have been seen. It therefore is more powerful.
LR(k) parser
– Left-to-right parse
– Right-most derivation
– K-token look ahead
LR parsing algorithm
– Performs a shift-reduce parse with an explicit stack
stack contains grammar symbols (T or V) mixed with states
– Look at state at top of stack and input symbol to find action in table
– shift(n): advance input, push state n on stack
– reduce(k): pop rhs of grammar rule k, look up state on top of stack
and lhs for goto n, push lhs(k) and n onto stack
– accept: stop and success
– error: stop and fail
LR(k) parsing scans the input Left to right and produces the
Rightmost derivation (looking k tokens ahead) in reverse.
It accepts the string of tokens when the input is empty or $/(EOF) and the
stack contains the start symbol.
Action Goto
State ( ) $ ID S
0 s3 s1 2
1 r2 r2 r2 r2
2 a
3 s3 s1 4
4 s5
5 r0 r0 r0 r0
In LR(0) parse tables, reduce actions happen for all
terminals, as the parser does not look ahead.