Exercises on Semantic Analysis

Anuncio
Exercises in Semantic Analysis
1 Semantic Rules
Consider the following attribute grammar:
Grammar Rule
Semantic Rules
S :- A B C
B.u = S.u
A.u = B.v + C.v
S.v = A.v
A :- a
A.v = 2 * A.u
B :- b
B.v = B.u
C :- c
C.v = 1
1.1 Draw the parse tree for the input ‘abc’, (the only string for the language), and show
the dependency graph for the associated attributes. Describe one correct order for the
evaluation of the attributes.
1.2 Assume that S.u is assigned the value of 3 before starting attribute evaluation,
What will be the value of S.v when evaluation has terminated.
1.3 Suppose that the attribute rules were instead:
Grammar Rule
Semantic Rules
S :- A B C
B.u = S.u
C.u = A.v
A.u = B.v + C.v
S.v = A.v
A :- a
A.v = 2 * A.u
B :- b
B.v = B.u
C :- c
C.v = C.u - 2
What value does S.v have after evauation of all attributes
if the initial value of S.u is 3 ?
Expain why this result occurred?
1
2 List Depth
Given the following attribute grammar:
List →
( IList )
IList →
{
IList1 ( IList2 ) {
ILIst → λ
{
IList.depth=IList.depth + 1;
print “Depth:”, List.depth }
if (IList1.depth > IList2.depth):
IList.depth = IList1.depth
else:
IList.depth = IList2.depth +1 }
IList.depth=0 }
Draw the parse tree and calculate attributes for:
((()) ((() ())))
Sept 07 Exam
A protocol for communication between computers is being designed. To increase the security of
the communication, it was decided that the structure of the sequences that are transmitted should
be made up from a sequence of subsequences, each subsequence having the same length. We
will call each of these subsequences a ‘block’.
Below is shown an incomplete attribute grammar for this task. The blocks are separated using an
asterisk ‘*’. There is no separator either at the beginning or end of the complete sequence.
A global variable named total, of type integer, is used to store the size that the blocks should
have. The value is calculated in the derivation of the nonterminal I (the initial block of the
sequence). Subsequent blocks each correspond to an instance of the nonterminal B. This
nonterminal has an integer attribute (named t - for ‘tamaño’), which holds the size of the block.
{
ΣT={0,1,*},
ΣN={ X(),
I(),
B(int t)
},
X,
P={
X→ I {}
X→ X*B {}
B1→ 0B2 { B1.t = B2.t++; }
B1→ 1B2 { B1.t = B2.t++; }
B→ 0 { B.t = 1; }
B→ 1 { B.t = 1; }
I→ 0I { total++; }
I→ 1I { total++; }
I→ 0 { total++; }
2
I→ 1 { total++; }
}
Global_information = {int total = 0}
}
Important Note: assume throughout this question that the attribute grammars are
compatible with one of the techniques of syntactic analysis seen in the course this year:
top-down or bottom-up.
Questions:
7. (0.5 points) Extend the grammar such that when a block does not have the same size as the
initial block, a semantic error is generated. Do not add any attribute for this step, only
modify the provided semantic actions.
8. (1 point) Extend the grammar to calculate the number of blocks in the generated sequence.
For this purpose, add a new global variable num_sub of type integer, to contain the number
of blocks, and any semantic actions needed.
9. (1.5 points) Rewrite the grammar to eliminate the global variable total, using instead
synthesised and/or inherited attributes, and whatever semantic actions are necessary to
achieve the same task. Describe briefly the modifications made, and show the parse tree for
the sequence 101*111*000, annotating each node with the following information.
• The names and values of the attributes of each nonterminal node.
• The values of the global variables. If the semantic rules of a node change the value of the
global variable, show the value after applying the rules.
• The order in which the nodes are visited in the process of attribute evaluation (if multiple
orderings are possible, just show one).
JUNE 07
3. What is an attribute called if it is associated with the nonterminal symbol on the left of
a CFG rule, and its value is calculated using the attributes of the symbols on the right of
the CFG rule?
a)
b)
c)
d)
Synthesized attributes
Attributes inherited from the right
Attributes inherited from the left
Calculated attributes
3
19. Considere el siguiente gráfico como el esquema del árbol de derivación de cierto programa
según cierta gramática de atributos. Considere también que los números anotados en sus nodos
se corresponden con un orden compatible con la evaluación de los atributos involucrados en el
análisis semántico de ese programa. Teniendo en cuenta el temario de la asignatura de este año
¿cuál de las siguientes afirmaciones es más correcta?
4
7
3
8
5
6
2
1
a) El orden sugerido por la evaluación de los atributos es compatible con un
analizador sintáctico ascendente.
b) El orden sugerido por la evaluación de los atributos es compatible con un
analizador sintáctico descendente.
c) Un analizador sintáctico ascendente podría incluir la siguiente secuencia en el
recorrido de los nodos {5, 6, 7, 4, 2, 1, 3, 8}
d) Ninguna de las anteriores es correcta.
PARTIAL 07
7. (1 point) Consider the following grammar, that represents numbers in the form of
integers (eg. 123), reals (eg. 32,6), and numbers in exponent format (eg. 27.6E7).
Note: ‘^’ indicates ‘to the power of’.
Note: single quotes indicate a string literal.
Num :- SNum
Num :- CNum
SNum :- Int
SNum :- Float
Float :- Int1 ‘.’ Int2
CNum : - SNum ‘E’ Int
Int : - digit
Int :- Int1 digit
{ Num.val = SNum.val }
{ Num.val = CNum.val }
{ SNum.val = Int.val }
{ SNum.val = Float.val }
{ Float.val = Int1.val + Int2.val / 10 ^ Int2.len }
{ CNum .val = SNum.val * 10 ^ Int.val }
{ Int.val = digit.val; Int.len= 1 }
{ Int.val = Int1.val * 10 + digit.val; Int.len = Int1.len +1 }
a) Show the parse tree for “7.35E12”
b) Draw arrows indicating the dependency of the attributes of the nodes of the tree.
8. (1 point) Using the grammar of attributes of question 7, and the input string
"72.5E3", we can construct the derivation tree that appears below. Calculate the value
of all the attributes of the tree.
4
Num val=
CNum val=
SNum val=
Float val=
Int val=
len=
Int val=
Int val=
Int val=
len=
len=
len=
digit val=7
digit val=2
‘.’
digit val=5
‘E’
digit val=3
4. (1,2 puntos) La siguiente gramática de atributos genera números naturales como
los siguientes:
011201 12193 0001203268
Y además, el axioma tiene atributos semánticos para el cálculo de algunas propiedades de los
mismos.
{
ΣT={0,1,2,3,4,5,6,7,8,9},
ΣN={N(suma,unos_antes,unos_despues)},
N,
P={
N→1Ni
{
Ni.unos_antes = 1 + N.unos_antes;
N.unos_despues = Ni.unos_despues;
N.suma = 1 + Ni.suma;
}
N→xNi ,, x∈ ΣT-{1}
{
Ni.unos_antes = N.unos_antes;
N.unos_despues = Ni.unos_despues;
N.suma = x + Ni.suma;
}
N→1
{
N.unos_despues =
N.suma = 1;
}
N→x ,, x∈ ΣT-{1}
{
N.unos_despues =
N.suma = x;
}
1 + N.unos_antes;
N.unos_antes;
5
}
}
Se pide:
a) Al lado de cada acción semántica en la que lo considere oportuno escriba claramente el
atributo semántico calculado y su tipo (heredado o sintetizado)
b) Complete el siguiente árbol de derivación con los valores de todos los atributos indicados
(observe que el atributo unos_antes del axioma tiene como valor inicial 0):
N unos_antes=0
unos_después
suma
0
N unos_antes
unos_después
suma
1
N unos_antes
unos_después
suma
0
N unos_antes
unos_después
suma
2
N unos_antes
unos_después
suma
0
6
Descargar