Compiler Design Viable Prefix
Compiler Design Viable Prefix
− Valid Items
Viable Prefixes:
Consider the CFG:
E -> E + T | T
T -> T * F | F
F -> id
$ id * id reduce
$F * id reduce
$T * id shift
$T * id shift
$T * id $ reduce
$T * F $ reduce
$T $ reduce
$E $ ACCEPT
We observe that at any point of time, the stack contents must be a prefix of
a right sentential form.
However, not all prefixes of a right sentential form can appear on the stack.
Here, ‘id *’ is a prefix of a right sentential form. But it can never appear on
the stack! This is because we will always reduce by F -> id before shifting ‘*’
Definition (viable prefix): The prefixes of right sentential forms that can
appear on the stack of a shift-reduce parser are called viable prefixes.
Example:
Let: S -> X1 X2 X3 X4
A -> X1 X2
Let w = X1 X2 X3
STACK INPUT
$ X1 X2 X3
$ X1 X2 X3
PAGE 1
$ X1 X2 X3
$A X3
$ A X3 $
Equivalently, this means that the set of viable prefixes for a given SLR (1)
grammar is a regular language!
Valid Items:
Consider the item: A -> β 1 . β 2
Every viable prefix is associated with a valid item. In general, an item will be
valid for many viable prefixes.
PAGE 2
Viable prefixes and valid items enable us to make shift reduce decisions, I e
if we know the valid items for a viable prefix, we can create our own rules
about when to shift and reduce.
Example:
Let w = α β 1 β 2 x
STACK INPUT
$ α β1 β2x $
A. Case 1: β 2 != ϵ
Action: shift
Case 2: β 2 = ϵ
Action: reduce A -> β 1
When the dot reaches the end, we know that we should try to
reduce.
PAGE 3
Limitations of SLR Parser:
For an SLR parser, if we are in a state with the item A -> α ., then we reduce
by A -> α iff the next input symbol ‘a’ belongs to Follow(A).
This is actually a weak rule and can lead to erroneous results and/or
shift/reduce conflicts.
Example:
Consider A -> α
State i: A -> α .
State j: A -> α .
String 1: ɣ α a
String 2: β α a State i
A -> α .
State S
State j
A -> α .
PAGE 4
Now suppose
S => ɣ A a -> ɣ α a
S =/=> β A a -> β α a
In both cases, since ‘a’ belongs to Follow(A), the parser will reduce by A -> α
PAGE 5