The Dangling Else Problem
General
Original grammar:
S -> if E then S
S -> if E then S else S
S -> TNow:
S -> if E then S
S -> if E then L else S
L -> if E then L else L
L -> T- Insights
- Think of L as limited, in that
Lrule must have anelse. - We now require the statement in the middle must have an
elsepaired with it. - Otherwise, if the statement in the middle can have no
else, theelsecan be assigned to theifat the very beginning! - For any rules that have
Son the LHS, create another version withLon the LHS.
- Think of L as limited, in that
B-Minor
Code snippet from Bison grammar file for B-Minor compiler.
stmt : open_stmt | closed_stmt ;
open_stmt : if_stmt_open | for_stmt_open ;
closed_stmt : if_stmt_closed | for_stmt_closed | simple_stmt ;
if_stmt_open : if_cond stmt |
if_cond closed_stmt TOKEN_ELSE if_stmt_open
if_stmt_closed : if_cond closed_stmt TOKEN_ELSE closed_stmt
for_stmt_open : for_header open_stmt
for_stmt_closed : for_header closed_stmtMid-Term
This problem appears in mid-term. Simplified.
P -> S
S -> id = R
R -> R ^ R
R -> intSolution:
P -> S
S -> id = R
R -> L ^ R
L -> int
R -> int