设计实现简单表达式的SLR(1)分析器
时间: 2024-02-23 16:01:31 浏览: 71
下面是设计实现简单表达式的SLR(1)分析器的具体步骤:
1. 构造文法的FIRST集和FOLLOW集。
假设文法为:
```
E -> E + T | T
T -> T * F | F
F -> ( E ) | id
```
其FIRST集和FOLLOW集如下:
- FIRST(E) = {(, id}
- FIRST(T) = {(, id}
- FIRST(F) = {(, id}
- FOLLOW(E) = {), $, +}
- FOLLOW(T) = {), $, +, *}
- FOLLOW(F) = {), $, +, *, id}
2. 构造DFA状态转移图。
首先,将S'->.E加入初始状态闭包中,即{S'->.E}。然后,对于每个状态,依次考虑每个文法符号X(包括终结符和非终结符),求出它的闭包,并将它们作为出边添加到DFA中。如果某个闭包已经存在于某个状态中,则不需要再次添加。
以状态{E->E+.T}为例:
- X = (,闭包为{E->.(E+T), T->.T*F, F->.(E), F->.id},添加出边E->{E->(E.+T), T->.T*F, F->.(E), F->.id}
- X = id,闭包为{F->.id},添加出边E->{F->id.}
- X = +,没有闭包,不添加出边
- X = *,没有闭包,不添加出边
最终得到的DFA状态转移图如下所示:
```
+-------+ ( +-------+
| 0 |-------->| 1 |
+-------+ +---+---+
| id | F->id |
| +-------+
+--+----+ E +-------+
| 2 |-------->| 3 |
+-------+ +-+---+-+
| ( | E->(E.+T)
| | T->.T*F
+--+----+ | F->.(E)
| 4 | id | F->.id
+-------+----------> +-+-+
| E->E+.T
+---+
```
3. 构造ACTION和GOTO表。
根据DFA状态转移图,ACTION和GOTO表可以如下构造:
```
STATE | ACTION | GOTO
------+----------------------------------+------
0 | ( -> shift 4, id -> shift 5 | E -> 2, T -> 6, F -> 7
+----------------------------------+
1 | + -> shift 8 |
| ) -> reduce E -> T |
| $ -> reduce E -> T |
+----------------------------------+
2 | + -> shift 9, $ -> accept |
| ) -> reduce E -> T |
+----------------------------------+
3 | + -> reduce T -> F |
| * -> shift 10, ) -> reduce T -> F |
| $ -> reduce T -> F |
+----------------------------------+
4 | ( -> shift 4, id -> shift 5 | E -> 2, T -> 6, F -> 7
+----------------------------------+
5 | + -> reduce F -> id |
| * -> reduce F -> id |
| ) -> reduce F -> id |
| $ -> reduce F -> id |
+----------------------------------+
6 | + -> reduce E -> E+T |
| * -> reduce E -> E+T |
| ) -> reduce E -> E+T |
| $ -> reduce E -> E+T |
+----------------------------------+
7 | + -> reduce T -> F* |
| * -> reduce T -> F* |
| ) -> reduce T -> F* |
| $ -> reduce T -> F* |
+----------------------------------+
8 | ( -> shift 4, id -> shift 5 | T -> 11, F -> 7
+----------------------------------+
9 | ( -> shift 4, id -> shift 5 | T -> 12, F -> 7
+----------------------------------+
10 | ( -> shift 4, id -> shift 5 | F -> 13
+----------------------------------+
11 | + -> reduce F -> id |
| * -> reduce F -> id |
| ) -> reduce F -> id |
| $ -> reduce F -> id |
+----------------------------------+
12 | + -> reduce T -> T*F |
| * -> reduce T -> T*F |
| ) -> reduce T -> T*F |
| $ -> reduce T -> T*F |
+----------------------------------+
13 | + -> reduce F -> (E) |
| * -> reduce F -> (E) |
| ) -> reduce F -> (E) |
| $ -> reduce F -> (E) |
+----------------------------------+
```
最后,将构造出的SLR(1)分析器实现为C语言程序即可。
阅读全文