<string literal> ::= <numeral> H <string>where the
<numeral>
is a base-ten integer (≥ 1), H
is a keyword, and <string>
is a sequence of characters.
The semantics of this string literal is correct if the numeric value of the base-ten numeral matches the length of the string.
Write an attribute grammar using only synthesized attributes for the nonterminals
in the definition of <string literal>
. (25%)Production | Semantic Rules | |
---|---|---|
1. | <string literal> ::= <numeral> H <string> |
if Val(<numeral>) == Len(<string>) |
2. | <numeral> ::= <numeral1> <digit> |
Val(<numeral>) = Val(<numeral1>) * 10 + Val(<digit>) |
3. | <numeral> ::= <digit> |
Val(<numeral>) = Val(<digit>) |
4. | <string> ::= <string1> <char> |
Len(<string>) = Len(<string1>) + Len(<char>) |
5. | <string> ::= <char> |
Len(<string>) = Len(<char>) |
6. | <digit> ::= 0 |
Val(<digit>) = 0 |
… | … | … |
14. | <digit> ::= 8 |
Val(<digit>) = 8 |
15. | <digit> ::= 9 |
Val(<digit>) = 9 |
16. | <char> ::= character |
Len(<char>) = 1 |
<numeral>
and an inherited attribute for <string>
. (25%)Production | Semantic Rules | |
---|---|---|
1. | <string literal> ::= <numeral> H <string> |
Len(<string>) = Val(<numeral>) |
2. | <numeral> ::= <numeral1> <digit> |
Val(<numeral>) = Val(<numeral1>) * 10 + Val(<digit>) |
3. | <numeral> ::= <digit> |
Val(<numeral>) = Val(<digit>) |
4. | <string> ::= <string1> <char> |
Len(<string1>) = Len(<string>) – Len(<char>) |
5. | <string> ::= <char> |
if Len(<string>) == Len(<char>) |
6. | <digit> ::= 0 |
Val(<digit>) = 0 |
… | … | … |
14. | <digit> ::= 8 |
Val(<digit>) = 8 |
15. | <digit> ::= 9 |
Val(<digit>) = 9 |
16. | <char> ::= character |
Len(<char>) = 1 |
xy
is the prefix notation for x–y
.
Give annotated parse trees for the inputs 9–5+2
and 9–5*2
. (50%)T
that represents the prefix notation for the expression generated by that nonterminal in a parse tree.
The symbol ‘||’ in the semantic rule is the operator for string concatenation.
Production | Semantic Rules | |
---|---|---|
1. | <expr> ::= <expr1> + <term> |
T(<expr>) = '+' || T(<expr1>) || T(<term>) |
2. | <expr> ::= <expr1> – <term> |
T(<expr>) = '–' || T(<expr1>) || T(<term>) |
3. | <expr> ::= <term> |
T(<expr>) = T(<term>) |
4. | <term> ::= <term1> * <factor> |
T(<expr>) = '*' || T(<term1>) || T(<factor>) |
5. | <term> ::= <factor> |
T(<term>) = T(<factor>) |
6. | <factor> ::= 0 |
T(<factor>) = '0' |
7. | <factor> ::= 1 |
T(<factor>) = '1' |
… | … | … |
15. | <factor> ::= 9 |
T(<factor>) = '9' |