Lec 05
Lec 05
• Syntax Analysis
• Recursive-Descent Parsing
• Bottom-Up Parsing
• Top-down Parsers
– Given a sentential form, xA , the parser must
choose the correct A-rule to get the next
sentential form in the leftmost derivation, using
only the first token produced by A
• Bottom-up parsers
– Given a right sentential form, , determine what substring
of is the right-hand side of the rule in the grammar that
must be reduced to produce the previous sentential form
in the right derivation
– The most common bottom-up parsing algorithms are in
the LR family
<program> => <stmts> => <stmt>
=> <var> = <expr>
=> a = <expr>
=> a = <term> + <term>
=> a = <var> + <term>
=> a = b + <term>
=> a = b + const
Copyright © 2015 Pearson. All rights reserved. 1-6
Recursive-Descent Parsing
/* Function factor
Parses strings in the language
generated by the rule:
<factor> -> id | (<expr>) */
void factor() {
Next token is: 25 Next lexeme is ( Next token is: 11 Next lexeme is total
Enter <expr> Enter <factor>
Enter <term> Next token is: -1 Next lexeme is EOF
Enter <factor> Exit <factor>
Next token is: 11 Next lexeme is sum Exit <term>
Enter <expr> Exit <expr>
Enter <term>
Enter <factor>
Next token is: 21 Next lexeme is +
Exit <factor>
Exit <term>
Next token is: 10 Next lexeme is 47
Enter <term>
Enter <factor>
Next token is: 26 Next lexeme is )
Exit <factor>
Exit <term>
Exit <expr>
Next token is: 24 Next lexeme is /
Exit <factor>
Replace E E + T
– X X1 | ... | Xm E T E E + T | T
| 1 | ... | n T T * F T T * F | F
T F F ( E ) | id
F ( E )
F id
With E T E'
– X 1X’ | ... | nX’ E' + T E' |
– X’ 1X’ | ... | mX’ | T F T'
T' * F T' |
F ( E ) | id
Copyright © 2015 Pearson. All rights reserved. 1-14
Bottom-up Parsing
E E + T | T
T T * F | F
F ( E ) | id
handle pruning
• Shift-Reduce Algorithms
– For a Reduce, remove the handle from the stack, along with
its state symbols. Push the LHS of the rule. Push the state
symbol from the GOTO table, using the state symbol just
below the new LHS in the stack and the LHS of the new rule
as the row and column into the GOTO table