Compilers: Module 5: Bottom-Up Parsing
Homework p.92 #1, 8, 11
1) Show that the following grammar is not LR(0):
List -- > Id [ EList ]
EList -- > Id
EList -- > EList , Id
********** SOLUTION **********
An LR(0) grammar must be able to revert from an input
string to the starting symbol by parsing what are known as
handles. A handle is essentially a number of consectutive
symbols (terminal and non terminal) in the input string.
Given :
Id [ Id ]
the longest handle that matches a right hand side
production is Id. so the string is converted to:
Elist [ Id ]
the next handle is the Id is that is reduced to
Elist [ Elist ]
now there are no more possible conversions, and this is not
the starting symbol, so the parse failed for a valid string.
The above grammar is not LR(0).
8) Consider an item of the form E -- > E * + T. List five strings
to which this item might apply and indicate which part of the
string has been read and which part is still expected to read.
********** SOLUTION **********
Input | have read | left to read
===========*===========*==============
5 + 2 | 5 | + 2
3 * 4 + 7 | 3 * 4 | + 7
6 + 9 * 8 | 6 | + 9 * 8
1 + 1 + 5 | 1 + 1 | + 1
5 * 4 + 6 | 5 * 4 | + 6
11) Consider the grammar:
1) S -- > X X
2) X -- > x X
3) X -- > y
a) Create the LR(0) items and an SLR(1) parsing table
b) Using the table created in part (a), parse the string y x x y
********** SOLUTION **********
Let the asterisk (*) be the position marker:
State 0 State 1
============= =============
S' -- > *S S' --> S*
S -- > *X X
X -- > *x X
X -- > *y
State 2 State 3
============= =============
S -- > X *X S --> X X*
X -- > *x X
X -- > *y
State 4 State 5
============= =============
X -- > x *X X --> x X*
X -- > *x X
X -- > *y
State 6
=============
X -- > y*
State | x y $ | S X
=======*=====================*====================
0 | S4 S6 | 1 2
1 | accept |
2 | S4 S6 | 3
3 | R1 |
4 | S4 S6 | 5
5 | R2 R2 R2 |
6 | R3 R3 R3 |
Stack Input Action
============= ============= ============
$0 yxxy$ S6
$0y6 xxy$ R3
$0X2 xxy$ S4
$0X2x4 xy$ S4
$0X2x4x4 y$ S6
$0X2x4x4y6 $ R3
$0X2x4x4X5 $ R2
$0X2x4X5 $ R2
$0X2X3 $ R1
$0S1 $ accept