• Introduction
• 1. 1.Introduction
• 2. 2.A Simple Syntax-Directed Translator
• 3. 3.Lexical Analysis
• 4. 4.Syntax Analysis
• 5. 5.Syntax-Directed Translation
• 6. 6.Intermediate-Code Generation
• 7. 7.Run-Time Environments
• 8. 8.Code Generation
• 9. 12.InterProcedural Analysis
• Published with GitBook

# 5.4 节的练习

### 5.4.2

``````A -> A {a} B | A B {b} | 0
B -> B {c} A | B A {d} | 1
``````

### 5.4.3 ！

``````B -> B_1 0 {B.val = 2 * B_1.val}
| B_1 1 {B.val = 2 * B_1.val + 1}
| 1 {B.val = 1}
``````

#### 解答

``````B -> B_1 digit {B.val = 2 * B_1.val + digit.val}
| 1 {B.val = 1}
digit -> 0 {digit.val = 0}
| 1 {digit.val = 1}
``````

``````B -> 1 {A.i = 1} A
A -> digit {A_1.i = 2 * A.i + digit.val} A_1 {A.val = A_1.val}
| ε {A.val = A.i}
digit -> 0 {digit.val = 0}
| 1 {digit.val = 1}
``````

### 5.4.4 ！

1. S -> if ( C ) S_1 else S_2
2. S -> do S_1 while ( C )
3. S -> '{' L '}'; L -> L S | ε

#### 解答

1. S -> if ( C ) S_1 else S_2

`````` L_1 = new()
C.false = L_1
S_1.next = S.next
S.code = C.code || S_1.code || label || L_1 || S_2.code
``````
2. S -> do S_1 while ( C )

``````L_1 = new()
C.true = L_1
S.code = label || L_1 || S_1.code || C.code
``````

### 5.4.5

#### 解答

1. S -> if ( C ) S_1 else S_2

`````` S -> if (     {new L_1; C.false = L_1}
C )      {S_1.next = S.next}
S_1 else
S_2      {S.code = C.code || S_1.code || label || L_1 || S_2.code}
``````
2. S -> do S_1 while ( C )

``````S -> do           {new L_1}
S_1 while (  {C.true = L_1}
C )          {S.code = label || L_1 || S_1.code || C.code}
``````

### 5.4.7

#### 5.4.6 和 5.4.7 的解答

``````1) S -> B               B.ps = 10
B.wd =

2) S -> B_1 B_2         B_1.ps = B.ps
B_2.ps = B.ps
B.wd = B_1.wd + B_2.wd
B.ht = max(B_1.ht, B_2.ht)
B.dp = max(B_1.dp, B_2.dp)

3) B -> B_1 sub B_2     B_1.ps = B.ps
B_2.ps = 0.7 * B.ps
B.wd = B_1.wd + B_2.wd
B.ht = max(B_1.ht, B_2.ht - 0.25 * B.ps)
B.dp = max(B_1.dp, B_2.dp + 0.25 * B.ps)

4) B -> B_1 sup B_2     B_1.ps = B.ps
B_2.ps = 0.6 * B.ps
B.wd = B_1.wd + B_2.wd
B.ht = max(B_1.ht, B_2.ht + 0.6 * B.ps)
B.dp = max(B_1.dp, B_2.dp - 0.6 * B.ps)

5) B -> ( B_1 )         B_1.ps = B.ps
B.wd = B_1.wd
B.ht = B_1.ht
B.dp = B_1.dp

6) B -> text            B.wd = getWd(B.ps, text.lexval)
B.ht = getHt(B.ps, text.lexval)
B.dp = getDp(B.ps, text.lexval)
``````