LR Parser
LR Parser
LR(k) parsing
LR Parsers
• LR-Parsers
– covers wide range of grammars.
– SLR – simple LR parser
– CLR – Canonical LR parser
– LALR – intermediate LR parser (Look-Ahead LR parser) LLR
– SLR, LR and LALR work same (they used the same algorithm),
only their parsing tables are different.
1
LR Parsing Algorithm
Actions of a LR-Parser
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 $ )
4. Error - Parser detected an error (an empty entry in the action table)
45
Constructing SLR Parsing Tables
• It uses LR(0) item, augmented grammar, CLOSURE function and GOTO
function.
I. LR(0) item of a grammar G is a production of G a dot at the some
position of the right side.
• Ex: A aBb Possible LR(0) Items: ..
A aBb
A a Bb
(four different possibility)
A aB b
A aBb
..
• 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.
II . Augmented Grammar:
G’ is G with a new production rule S’S where S’ is the new starting
symbol. 49
..
2. 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).
3. Example:
E’ E closure({E’ .E}) =
E E+T { E’ .E kernel items
ET E .E+T
T T*F E .T
TF T .T*F
F (E) T .F
F id F .(E)
F .id } 50
Goto Operation
• If I is a set of LR(0) items and X is a grammar symbol (terminal or non-
terminal), then goto(I,X) is defined as follows:
.
– If A X in I
.
then every item in closure({A X }) will be in goto(I,X).
... ... .
Example:
I ={ E’ E, E E+T, E T,
T T*F, T F,
F (E), F id }
... ..
goto(I,E) = { E’ E , E E +T }
goto(I,T) = { E T , T T *F }
goto(I,F) = {T F }
.. ..
goto(I,() = { F ( E), E E+T, E
F (E), F id }
. T, T . T*F, T . F,
.
goto(I,id) = { F id }
52
59
• If the SLR parsing table of a grammar G has a conflict, we say that that
grammar is not SLR grammar.
70
2. Canonical LR Parser ( CLR Parser)
76
goto operation
77
Construction of LR(1) Parsing Tables
1. Construct the canonical collection of sets of LR(1) items for G’.
C{I0,...,In}
ii. In this we use the same LR(1) set of items, but we find out the set of items where the core
part (i.e. set of first components) of the items is same but the look ahead part is different.
We merge these sets with common core values into one set of items.
LALR Parsing Tables
• LALR stands for LookAhead LR.
• LALR parsers are often used in practice because LALR parsing tables
are smaller than LR(1) parsing tables.
• The number of states in SLR and LALR parsing tables for a grammar G
are equal.
• But LALR parsers recognize more grammars than SLR parsers.
• yacc creates a LALR parser for the given grammar.
• A state of LALR parser will be again a set of LR(1) items.
84