Professional Documents
Culture Documents
Syntax Analysis
Part III
S
rm aABe
rm aAderm
aAbcde
rm abbcde
S=0
rm
1
rm
2
rm ...
rm
n-1
rm =
n
input string
1. Shift : The next input symbol is shifted onto the top of the stack.
2. Reduce: Replace the handle on the top of the stack by the non-
terminal.
3. Accept: Successful completion of parsing.
4. Error: Parser discovers a syntax error, and calls an error
recovery routine.
StackInput Action
$ id+id*id$ shift
$id +id*id$ reduce by F id
$F +id*id$ reduce by T F
$T +id*id$ reduce by E T
$E +id*id$ shift
$E+ id*id$ shift
$E+id *id$reduce by F id
$E+F *id$reduce by T F
$E+T *id$shift
$E+T* id$ shift
$E+T*id $ reduce by F id
$E+T*F $ reduce by T T*F
$E+T $ reduce by E E+T
$E $ accept
1. Operator-Precedence Parser
simple, but only a small class of grammars. CFG
LR
LALR
2. LR-Parsers
SLR
covers wide range of grammars.
SLR – simple LR parser
LR – most general LR parser
LALR – intermediate LR parser (lookhead LR parser)
SLR, LR and LALR work same, only their parsing tables are different.
Sm
Xm
LR Parsing Algorithm output
Sm-1
Xm-1
.
. Action Table Goto Table
S1 terminals and $ non-terminal
s s
X1 t four different t each item is
a actions a a state number
S0 t t
e e
s s
LR(k) parsing.
1. shift s -- shifts the next input symbol and the state s onto the stack
( So X1 S1 ... Xm Sm, ai ai+1 ... an $ ) ( So X1 S1 ... Xm Sm ai s, ai+1 ... an $ )
2. reduce A
pop 2*|| (length of =r) items from the stack; r states and r symbols.
then push A and s where s=goto[sm-r, A] entering the state
( So X1 S1 ... Xm Sm, ai ai+1 ... an $ ) ( So X1 S1 ... Xm-r Sm-r A s, ai ... an $ )
Output is the reducing production reduce A
..
(four different possibility)
A aB b
A aBb
A a Bb
Sets of LR(0) items will be the states of action and goto table
of the SLR parser.
A collection of sets of LR(0) items (the canonical LR(0)
collection) is the basis for constructing SLR parsers.
Augmented Grammar:
G′ is G with a new production rule S′S where S′ is the new
starting symbol.
Dr. Azhar, KUET. 11/09/2022
The Closure Operation
22
.
If A B is in closure(I) and B is a production
rule of G; then B will be in the closure(I).
We will apply this rule until no more new LR(0) items can
be added to closure(I).
.
23
.
E’ E closure({E’ E}) =
.
E E+T { E’ E
.
ET E E+T
.
T T*F E T
.
TF T T*F
.
F (E) T F
.
F id F (E)
F id }
Algorithm:
.
C is { closure({S’ S}) }
repeat the followings until no more set of LR(0) items can be added to C.
for each I in C and each grammar symbol X
if goto(I,X) is not empty and not in C
add goto(I,X) to C
I0 E + I6 T I9 * to I7
I1
F to I
3
( to I
T 4
id
I2 to I5
F * I7
I3 F
(
( I10
I4 id to I4
id
to I5
id I5 See text book for
complete DFA
28
Thank You