如果这篇博客帮助到你,可以请我喝一杯咖啡~
CC BY 4.0 (除特别声明或转载文章外)
考虑以下语法制导定义(Syntax Directed Definition),对于输入串 gbbabbccd 构造带注释的分析树(annotated parse tree)
语法规则 | 语义规则 |
---|---|
$S\to ABCD$ | S.val = A.val + B.val + C.val + D.val |
$A\to gBa$ | A.val = B.val * 5 |
$B\to B1b$ | B.val = B1.val * 2 |
$B\to b$ | B.val = 2 |
$C\to C1c$ | C.val = C1.val * 3 |
$C\to c$ | C.val = 3 |
$D\to d$ | D.val = 1 |
flowchart TB
I0-->I1
I0-->I2
I0-->I3
I0-->I4
I1-->I5
I1-->I6
I1-->I7
I2-->I9
I2-->I10
I3-->I11
I3-->I12
I4-->I13
I6-->I14
I6-->I15
I9-->I16
I11-->I17
I14-->I18
I0["
S
S.val #equals; A.val + B.val + C.val + D.val #equals; 34
"]
I1["
A
A.val #equals; B.val * 5 #equals; 20
"]
I2["
B
B.val #equals; B1.val * 2 #equals; 4
"]
I3["
C
C #equals; C1.val * 3 #equals; 9
"]
I4["
D
D.val #equals; 1
"]
I5[g]
I6["
B
B.val #equals; B1.val * 2 #equals; 4
"]
I7[a]
I9["
B1
B1.val #equals; 2
"]
I10[b]
I11["
C1
C1.val #equals; 3
"]
I12[c]
I13[d]
I14["
B1
B1.val #equals; 2
"]
I15[b]
I16[b]
I17[c]
I18[b]
以下文法定义了二进制浮点数常量的语法规则。试给出一个 S 属性的语法制导定义,其作用是求出该二进制浮点数的十进制值,并存放在开始符号 S 相关联的一个综合属性 value 中。例如,对于输入串 101.101,S 的 value 属性值结果应该是 5.625。要求在编写语法制导定义时,不得改写文法
\[S\to L.L\vert L\\ L\to LB\vert B\\ B\to 0\vert 1\]语法规则 | 语义规则 |
---|---|
$S\to L$ | S.val = L.val |
$S\to L_1.L_2$ | S.val = L1.val + L2.val * pow(0.5, L2.len) |
$L\to L_1B$ | L.val = L1.val *2 + B.val, L.len = L1.len + 1 |
$L\to B$ | L.val = B.val, L.len = 1 |
$B\to 0$ | B.val = 0 |
$B\to 1$ | B.val = 1 |