bottom up
bottom up
Syntax Analysis
Part II
Chapter 4
Bottom-Up Parsing
• LR methods (Left-to-right, Rightmost
derivation)
– SLR, Canonical LR, LALR
• Other special cases:
– Shift-reduce parsing
– Operator-precedence parsing
3
Operator-Precedence Parsing
• Special case of shift-reduce parsing
• We will not further discuss (you can skip
textbook section 4.6)
4
Shift-Reduce Parsing
Grammar: Reducing a sentence: Shift-reduce corresponds
SaABe abbcde to a rightmost derivation:
AAbc|b aAbcde S rm a A B e
Bd aAde rm a A d e
aABe rm a A b c d e
These match S
production’s rm a b b c d e
right-hand sides
S
A A A
A A A B A B
a b b c d e a b b c d e a b b c d e a b b c d e
5
Handles
A handle is a substring of grammar symbols in a
right-sentential form that matches a right-hand side
of a production
Grammar: abbcde
SaABe aAbcde
AAbc|b aAde Handle
Bd aABe
S
abbcde
aAbcde NOT a handle, because
aAAe further reductions will fail
…? (result is not a sentential form)
6
Stack Implementation of
Shift-Reduce Parsing
Stack Input Action
$ id+id*id$ shift
$id +id*id$ reduce E id How to
Grammar: $E +id*id$ shift
$E+ id*id$ shift
resolve
EE+E conflicts?
$E+id *id$ reduce E id
EE*E $E+E *id$ shift (or reduce?)
E(E) $E+E* id$ shift
E id $E+E*id $ reduce E id
$E+E*E $ reduce E E * E
$E+E $ reduce E E + E
Found handles $E $ accept
to reduce
7
Conflicts
• Shift-reduce and reduce-reduce conflicts
are caused by
– The limitations of the LR parsing method (even
when the grammar is unambiguous)
– Ambiguity of the grammar
8
Shift-Reduce Parsing:
Shift-Reduce Conflicts
Stack Input Action
$… …$ …
$…if E then S else…$ shift or reduce?
Ambiguous grammar:
S if E then S
| if E then S else S
| other
Resolve in favor
of shift, so else
matches closest if
9
Shift-Reduce Parsing:
Reduce-Reduce Conflicts
Stack Input Action
$ aa$ shift
$a a$ reduce A a or B a ?
Grammar:
CAB
Aa
Ba
Resolve in favor
of reducing A a,
otherwise we’re stuck!
10