试为如下文法构造LALR(1)分析表: G[E]: E→ E+T | T, T →TF | F ,F → F * | a | b
时间: 2024-01-21 19:03:01 浏览: 189
首先,我们需要构造该文法的LR(0)自动机,并计算每个状态的FIRST集和FOLLOW集。
LR(0)自动机如下:
```
State 0:
E -> .E+T
E -> .T
T -> .TF
T -> .F
F -> .F*
F -> .a
F -> .b
State 1:
E -> E.+T
T -> .TF
T -> .F
F -> .F*
F -> .a
F -> .b
State 2:
E -> T.
State 3:
T -> T.F
F -> .F*
F -> .a
F -> .b
State 4:
T -> F.
State 5:
F -> F*.
State 6:
E -> E+.T
T -> .TF
T -> .F
F -> .F*
F -> .a
F -> .b
State 7:
E -> E+T.
State 8:
T -> TF.
F -> .F*
F -> .a
F -> .b
State 9:
T -> T.F
F -> F*.
F -> .a
F -> .b
State 10:
F -> a.
F -> b.
State 11:
E -> E+T.
T -> TF.
F -> .F*
F -> .a
F -> .b
State 12:
T -> T.F
F -> a.
F -> b.
State 13:
E -> E+.T
T -> TF.
F -> .F*
F -> .a
F -> .b
State 14:
E -> E+T.
T -> F.
State 15:
T -> T.F
F -> F*.
F -> a.
F -> b.
State 16:
E -> E+T.
T -> TF.
F -> a.
State 17:
T -> T.F
F -> F*.
F -> b.
State 18:
E -> E+T.
T -> TF.
F -> b.
State 19:
T -> T.F
F -> a.
F -> b.
```
计算得到的FIRST集和FOLLOW集如下:
```
FIRST(E) = {a, b}
FIRST(T) = {a, b}
FIRST(F) = {a, b, *}
FOLLOW(E) = {$, +}
FOLLOW(T) = {+, $, +}
FOLLOW(F) = {*, +, $, a, b}
```
接下来,我们需要将LR(0)自动机合并为LALR(1)自动机。合并后的LALR(1)自动机如下:
```
State 0:
E -> .E+T
E -> .T
T -> .TF
T -> .F
F -> .F*
F -> .a
F -> .b
State 1:
E -> E.+T
T -> .TF
T -> .F
F -> .F*
F -> .a
F -> .b
State 2:
E -> T.
State 3:
T -> T.F
F -> .F*
F -> .a
F -> .b
State 4:
T -> F.
State 5:
F -> F*.
State 6:
E -> E+.T
T -> .TF
T -> .F
F -> .F*
F -> .a
F -> .b
State 7:
E -> E+T.
State 8:
T -> TF.
F -> .F*
F -> .a
F -> .b
State 9:
T -> T.F
F -> F*.
F -> .a
F -> .b
State 10:
F -> a.
F -> b.
State 11:
E -> E+T.
T -> TF.
F -> .F*
F -> .a
F -> .b
T -> TF.
State 12:
T -> T.F
F -> a.
F -> b.
State 13:
E -> E+.T
T -> TF.
F -> .F*
F -> .a
F -> .b
T -> TF.
State 14:
E -> E+T.
T -> F.
State 15:
T -> T.F
F -> F*.
F -> a.
F -> b.
State 16:
E -> E+T.
T -> TF.
F -> a.
State 17:
T -> T.F
F -> F*.
F -> b.
State 18:
E -> E+T.
T -> TF.
F -> b.
State 19:
T -> T.F
F -> a.
F -> b.
```
接下来,我们需要计算LALR(1)分析表。LALR(1)分析表的计算过程与SLR(1)分析表类似,这里直接给出结果:
```
State 0:
a -> s5
b -> s6
$ ->
E -> 2
T -> 3
F -> 4
State 1:
+ -> s7
State 2:
+ -> s1
$ -> acc
State 3:
+ -> r4
* -> s8
$ -> r4
E ->
T ->
State 4:
+ -> r6
* -> r6
$ -> r6
E ->
T ->
F ->
State 5:
+ -> r8
* -> r8
$ -> r8
E ->
T ->
F ->
State 6:
+ -> r9
* -> r9
$ -> r9
E ->
T ->
F ->
State 7:
a -> s5
b -> s6
T -> 10
F -> 4
State 8:
a -> s5
b -> s6
F -> 11
State 9:
a -> r3
b -> r3
$ -> r3
E ->
T ->
F ->
State 10:
+ -> r5
* -> s8
$ -> r5
E ->
T ->
State 11:
+ -> r7
* -> r7
$ -> r7
E ->
T ->
F ->
State 12:
+ -> r2
* -> s8
$ -> r2
E ->
T ->
State 13:
+ -> r1
* -> r1
$ -> r1
E ->
T ->
F ->
State 14:
a -> s5
b -> s6
T -> 15
F -> 4
State 15:
+ -> r4
* -> s8
$ -> r4
E ->
T ->
State 16:
+ -> r6
* -> r6
$ -> r6
E ->
T ->
F ->
State 17:
+ -> r9
* -> r9
$ -> r9
E ->
T ->
F ->
State 18:
+ -> r5
* -> s8
$ -> r5
E ->
T ->
State 19:
+ -> r7
* -> r7
$ -> r7
E ->
T ->
F ->
```
综上所述,我们成功构造了该文法的LALR(1)分析表。
阅读全文