Compiler Design
Spring 2018
3.3 Top-down parsing
1
Compiler Design Spring 2018 3.3 Top-down parsing Thomas R. Gross - - PowerPoint PPT Presentation
Compiler Design Spring 2018 3.3 Top-down parsing Thomas R. Gross Computer Science Department ETH Zurich, Switzerland 1 Overview 3.1 Introduction 3.2 Lexical analysis 3.3 Top down parsing 3.4 Bottom up parsing 2 Is w
1
2
§ Guess what production will lead to w § “Top-down” parsing
§ Guess how w was generated § “Bottom-up” parsing
3
Yes
4
5
Parser control TOS $ a + b $ ip sp input string ($ is the end of input marker)
6
7
8
11
12
18
19
20
21
22
23
26
S $ x A $ A $ x A $ A $ x A $ A $ x A $ … S $ x B $ B $ x x x b x x x b x x b x x b x b x b B x b … x x x b x x x b x x b S à xA Match S à xA Match Sà xA Match Undo Undo … S à xB Match S à xB …
30
§ Many programming languages have LL(1) grammars
31
32
34
39
43
44
Predictive parser control TOS $ a + b $ ip sp input string ($ is the end of input marker)
45
Predictive parser control Parsing table M TOS $ a + b $ ip sp input string ($ is the end of input marker) Contains rules M[NT, T] = production NT à a
46
48
50
52
Non-terminal Input (terminal) symbol a b S A B
Non-terminal Input (terminal) symbol a b S S à AB A A à a B B à b
Non-terminal Input (terminal) symbol a b $ S S à AB A A à a B B à b $ ACCEPT
Non-terminal Input (terminal) symbol a b $ S S à AB Error Error A A à a Error Error B Error B à b Error $ Error Error ACCEPT
57
58
62
63
65
E à T E’ (1) E’ à + T E’ | (2) e (3) T à F T’ (4) T’ à * F T’| (5) e (6) F à ( E ) | (7) Id (8)
66
67
68
70
73
74
76
77
78
79
81
83
§ “+” ∉ FIRST(T’) § FIRST(T’) = {e, “*”)
§ So we can make T’ “disappear”
§ E’ follows T’
87
89
90
92
Productions: E à T E’ (1) E’ à + T E’ | (2) e (3) T à F T’ (4) T’ à * F T’| (5) e (6) F à ( E ) | (7) Id (8) FIRST(E) = { ”(“, Id } FIRST(E’) = { e, “+” } FIRST(T) = { “(“, Id } FIRST(T’) = { e, “*” } FIRST(F) = { “(“, Id } Iteration 0: FOLLOW(E) = {$} R1 FOLLOW(T) = {“+”} R2(2) FOLLOW(F) = {“*”} R2(5) Iteration 2: FOLLOW(E) = {$, “)”} FOLLOW(E’) = {$, “)”} R3(1) FOLLOW(T) = {“+”, $, “)”} R3(2) FOLLOW(T’) = {”+”, $, “)”} R3(4) FOLLOW(F) = {“*”, “+”, $, “)”} R3(5) Iteration 1: FOLLOW(E) = {$, “)”} R2(7) FOLLOW(T) = {“+”} FOLLOW(F) = {“*”}
94
95
96
97
FOLLOW(E) = {$, “)”} FOLLOW(E’) = {$, “)”} FOLLOW(T) = {“+”, $, “)”} FOLLOW(T’) = {”+”, $, “)”} FOLLOW(F) = {“*”, “+”, $, “)”} FIRST(E) = { ”(“, Id } FIRST(E’) = { e, “+” } FIRST(T) = { “(“, Id } FIRST(T’) = { e, “*” } FIRST(F) = { “(“, Id } E à T E’ (1) E’ à + T E’ | (2) e (3) T à F T’ (4) T’ à * F T’| (5) e (6) F à ( E ) | (7) Id (8)
98
NT / T Id + * ( ) $ E E’ T T’ F
104
105
109
110
B à x B | b
111
112