Bottom Up Parsing-Shift Reduce Parsing
Bottom Up Parsing-Shift Reduce Parsing
Shift-Reduce Parsing
Reduce a string to the start symbol of the grammar.
At every step a particular sub-string is matched (in leftto-right fashion) to the right side of some production,
Replace this string by the LHS (called reduction).
If the substring is chosen correctly at each step, it is the
trace of a rightmost derivation in reverse
Bottom Up Parsing
Consider:
S aABe
A Abc | b
Bd
abbcde
aAbcde
aAde
aABe
S
Rightmost Derivation:
S aABe aAde aAbcde abbcde
Reverse
order
Handle
A Handle of a string
A substring that matches the RHS of some production
and whose reduction represents one step of a
rightmost derivation in reverse
So we scan tokens from left to right, find the handle,
and replace it by corresponding LHS
Formally:
handle of a right sentential form is a production A
, location of in , that satisfies the above
property.
i.e. A is a handle of at the location
immediately after the end of , if:
S => A =>
Handle-pruning
The process of discovering a handle & reducing it
to the appropriate left-hand side is called handle
pruning.
Handle pruning forms the basis for a bottom-up
parsing method.
Problems:
locate a handle
decide which production to use (if there
are more than two candidate productions).
aAAcde
Stack
Input String
num
num
num
num
num
num
SHIFT
num
num
num
SHIFT
num
num
num
REDUCE
num
num
num
REDUCE
Expr
num
*
num
num
SHIFT
Expr
num
*
num
num
SHIFT
Expr
num
(
num
num
Op
REDUCE
Expr
num
*
(
num
num
Op
SHIFT
Expr
num
*
(
num
num
(
Op
SHIFT
Expr
num
*
num
num
(
Op
SHIFT
Expr
num
*
num
num
SHIFT
num
(
Op
Expr
num
*
+
num
REDUCE
SHIFT
Expr
(
Op
Expr
num
num
+
num
SHIFT
Expr
(
Op
Expr
num
num
+
num
SHIFT
Expr
(
Op
Expr
num
num
num
Op
REDUCE
SHIFT
Expr
(
Op
Expr
num
num
+
num
Op
SHIFT
Expr
(
Op
Expr
num
num
+
num
Op
SHIFT
Expr
(
Op
Expr
num
num
+
num
REDUCE
SHIFT
Expr
(
Op
Expr
num
num
num
)
REDUCE
SHIFT
Expr
(
Op
Expr
Expr
Op
Expr
num
num
num
)
SHIFT
Expr
(
Op
Expr
Expr
Op
Expr
num
num
num
)
SHIFT
Expr
(
Op
Expr
Expr
Op
Expr
num
num
num
)
Expr
Expr
REDUCE
Expr
Op
Expr
num
Op
Expr
num
num
Expr
Expr
Op
REDUCE
Expr
Expr
num
num
num
Expr
Expr
Op
ACCEPT!
Expr
Expr
num
num
num
Basic Idea
Term
Term
Term
Fact.
Fact.
Fact.
<id,y>
<id,x> <num,2>
SEXP
EXP EXP -TERM |TERM
TERMTERM*FACT| FACT
FACT(EXP)|ID |NUM
left to right
scanning
right-most k lookhead
derivation
We cant tell
whether it is a
handle
Stack
if then stmt
Input
else
Conflicts Resolution
Conflict resolution by adapting the parsing
algorithm (e.g., in parser generators)
Shift-reduce conflict
Resolve in favor of shift
Reduce-reduce conflict
Use the production that appears earlier
Shift-Reduce Parsers
There are two main categories of shift-reduce
parsers
1. Operator-Precedence Parser
simple, but only a small class of grammars.
CFG
LR
2. LR-Parsers
covers wide range of grammars.
LALR
SLR