Compilers
Bottom up Parsing
LR-Parsing
5/22/2024 © 2002-08 Hal Perkins & UW CSE ex-1
LR Parser
LR parser is a very efficient bottom-up
syntax analyzer.
It is the most general non-backtracking
shift-reduce parsing technique known.
Most programming languages can be
parsed by LR parsers.
5/22/2024 © 2002-08 Hal Perkins & UW CSE ex-2
LR Parser
The algorithm relies on a parsing table that has
two parts (the action part and the go to part).
The program uses a stack to store a string of the
form:
S0X1S1X2 … XmSm, where Sm is in top of the
stack, Xi is a grammar symbol and Si is a state.
The combination of a state Sm on top of stack
and the current input token ai is used to access
the parsing table and decide what to do.
ex-3
LR Parser
The parser works as follows:
It consults action [Sm, ai] of the parsing
table which could be one of the 4-
possibilities.
1- Shift S, where S is a state.
2- Reduce r by a grammar rule A B.
3- accept().
4- error().
ex-4
The function go to has as a parameters
a state, a grammar symbol and return
state.
The configuration of an LR parser is:
S0X1S1X2 … XmSm, ai ai+1 … an, such that
(S0X1S1X2 … XmSm) is on stack
(ai ai+1 … an ) is the unprocessed input
5/22/2024 © 2002-08 Hal Perkins & UW CSE ex-5
1- If the action is [Sm,ai] = Shift S:
The parser action is to push aiS on stack,
where S on top. This is to say S = go to [Si,ai].
Next input token is ai+1.
2- If the action is [Sm,ai]= reduce A B: the
configuration now becomes
S0X1S1X2 … Xm-rSm-r, ai ai+1 … an. where r=|B|,
the parser pop off 2*r from the stack and
push A; push S, where S= go to [Sm-r, A].
3- If the entry is accept(), then parser is
complete.
4- If the entry is blank, then an error is
encountered.
5/22/2024 ex-6
LR parsing Algorithm
Set ip to first symbol of w$
Repeat forever begin
Let S be the state on top of stack, a symbol
pointed by ip
If action[S,a]=Shift S’ then begin
Push a then push S’ on top of stack
Advance ip
end
5/22/2024 © 2002-08 Hal Perkins & UW CSE ex-7
else if action [S,a] = reduce AB
then begin
Pop 2*|B| symbols of the stack
Let S’ be the state now on top of the stack
Push A then push goto [S’,A]
Output production AB
end
else
If action [S,a] = accepted then
return
else
Error()
End.
5/22/2024 © 2002-08 Hal Perkins & UW CSE ex-8
Example
Given the grammar:
1- EE+T
2- ET
3- T T*F
4- T F
5- F (E)
6- F id
5/22/2024 © 2002-08 Hal Perkins & UW CSE ex-9
LR Parsing table for the above grammar
state action go to
id + * ( ) $ E T F
0 S5 S4 1 2 3
1 S6 acc
2 r2 S7 r2 r2
3 r4 r4 r4 r4
4 S5 S4 8 2 3
5 r6 r6 r6 r6
6 S5 S4 9 3
7 S5 S4 10
8 S6 S11
9 r1 s7 r1 r1
10 r3 r3 r3 r3
11 r3 r3 r5 r5
Trace the string: id * id + id
Stack Input String action
id*id+id$ Shift 5
id5 *id+id$ reduce 6 (Fid)
F3 *id+id$ reduce 4 (TF)
T2 *id+id$ Shift 7
T2*7 id+id$ Shift 5
T2*7id5 +id$ reduce 6 (Fid)
T2*7F10 +id$ reduce 3 (TT*F)
T2 +id$ reduce 2 (ET)
E1 +id$ Shift 6
E1+6 id$ Shift 5
E1+6id5 $ reduce 6 (Fid)
E1+6F3 $ reduce 4 (TF)
E1+6T9 $ reduce 1 (EE+T)
E1 $ accept