2
对表达式((a)+(b))
(1)
按照表6.4属性文法构造抽象语法树
(2)
按6.17翻译模式构造表达式抽象语法树
5(1)
下列文法对整型常数、实型常熟世家加法运算符
+
生成表达式,当两个整型数相加,结果为整形,否则结果为实型
E
→
E
+
T
∣
T
E\rightarrow E+T|T
E→E+T∣T
T
→
n
u
m
,
n
u
m
∣
n
u
m
T\rightarrow num, num| num
T→num,num∣num
尝试给出确定每个子表达式结果类型的属性文法
E → E_1 + T {if(E_1.Type == int) and (T.Type == int)
then E.Type = int
else E.Type = real}
E → T {E.type = T.type}
T → num, num {T.type = real}
T → num {T.type = int}
7
下列文法由开始符号S产生一个二进制数,令综合属性val给出该数的值
S
→
L
.
L
∣
L
L
→
L
B
∣
B
B
→
0
∣
1
S\rightarrow L.L|L L\rightarrow LB|B B\rightarrow 0|1
S→L.L∣LL→LB∣BB→0∣1
设计S.val的属性文法,其中已知B的综合属性c,给出由B产生的二进制结果值,如输入101.101,S.val = 5.625
其中第一个二进制位值位4,最后一个为0.125
S
→
L
1
.
L
2
{
S
.
v
a
l
=
L
1
.
v
a
l
+
L
2
.
v
a
l
/
2
L
2
.
l
e
n
}
S
→
L
{
S
.
v
a
l
=
L
.
v
a
l
}
L
→
L
1
B
{
L
.
v
a
l
=
2
∗
L
1
.
v
a
l
+
B
.
c
L
.
l
e
n
=
L
1
.
l
e
n
+
1
}
L
→
B
{
L
.
v
a
l
=
B
.
c
L
.
l
e
n
=
1
}
B
→
0
{
B
.
c
=
0
}
B
→
1
{
B
.
c
=
1
}
S\rightarrow L_1 . L_2\{S.val = L_1.val+L_2.val/2^{L_2.len}\}\\ S\rightarrow L\{S.val = L.val\}\\ L\rightarrow L_1B\{L.val = 2*L_1.val + B.c\quad L.len = L_1.len+1\}\\ L\rightarrow B\{L.val = B.c\quad L.len = 1\}\\ B\rightarrow 0\{B.c = 0\}\\ B\rightarrow 1\{B.c = 1\}\\
S→L1.L2{S.val=L1.val+L2.val/2L2.len}S→L{S.val=L.val}L→L1B{L.val=2∗L1.val+B.cL.len=L1.len+1}L→B{L.val=B.cL.len=1}B→0{B.c=0}B→1{B.c=1}