Chapter-02 (Part-II) PDF
Chapter-02 (Part-II) PDF
Chapter 2
2
expr.t = 95-2+
expr.t = 9 term.t = 5
term.t = 9
9 - 5 + 2
5
Depth-First Traversals
procedure visit(n : node);
begin
for each child m of n, from left to right do
visit(m);
evaluate semantic rules at node n
end
Note:
Synthesized attributes are evaluated after visiting and
Inherited attributes are evaluated at first occurrence
6
expr.t = 95-2+
expr.t = 9 term.t = 5
term.t = 9
Translation Schemes
• A translation scheme is a CF grammar
embedded with semantic actions
rest + term { print(“+”) } rest
Embedded
semantic action
rest
expr { print(“+”) }
expr + term
{ print(“2”) }
{ print(“-”) }
- term 2
expr
{ print(“5”) }
term 5
{ print(“9”) }
9
Translates 9-5+2 into postfix 95-2+
10
Parsing
• Parsing = process of determining if a string of
tokens can be generated by a grammar
• For any CF grammar there is a parser that takes at
most O(n3) time to parse a string of n tokens
• Linear algorithms suffice for parsing
programming language
• Top-down parsing “constructs” parse tree from
root to leaves
• Bottom-up parsing “constructs” parse tree from
leaves to root
11
Predictive Parsing
• Recursive descent parsing is a top-down parsing
method
– Every nonterminal has one (recursive) procedure
responsible for parsing the nonterminal‟s syntactic
category of input tokens
– When a nonterminal has multiple productions, each
production is implemented in a branch of a selection
statement based on input look-ahead information
• Predictive parsing is a special form of recursive
descent parsing where we use one lookahead
token to unambiguously determine the parse
operations
12
type simple
| ^ id
| array [ simple ] of type
simple integer
| char
| num dotdot num
13
match(„array‟)
lookahead
16
match(„array‟) match(„[‟)
lookahead
17
match(„num‟)
lookahead
18
match(„num‟) match(„dotdot‟)
lookahead
19
lookahead
20
lookahead
21
lookahead
22
match(„integer‟)
Input: array [ num dotdot num ] of integer
lookahead
Limitations
• Can we apply the previous technique to every grammar?
• NO:
type simple
| array [ simple ] of type
simple integer
| array digit
digit 0|1|2|3|4|5|6|7|8|9