Starting from:

$30

Assignment 5 Lexical/Dynamic Scoping

CS314 
Assignment 5
1 Lexical/Dynamic Scoping
procedure main():
int var = 10;
procedure set_var(int val):
var = val;
end set_var
procedure proc1():
set_var(1);
end proc1
procedure proc2():
int var = 2;
set_var(4);
print var;
end proc2
print var;
set_var(41);
proc1();
print var;
proc2();
end main
(a) Suppose the procedure main() uses static (lexical) scoping. What will
it print, and why?
(b) Suppose the procedure main() uses dynamic scoping. What will it
print, and why?
1
2 Lexical Scoping
This problem uses the following procedure. This procedure uses static (lexical) scoping.
procedure main():
int a;
procedure proc1(int i):
int b;
b = a + 1;
procedure recursion(int k):
print b;
b = b - 1;
if (b 1):
recursion(k * b);
else:
a = k;
end recursion
b = b + i;
recursion(1);
end proc1
a = 1;
proc1(4);
print a;
end main
(a) What does this procedure print? (Give the output of procedure main().)
(b) Rewrite the procedure main() where each variable (argument variables, declared variables, procedure names) is renamed by their (level,
offset) pairs.
(c) How does procedure proc1 find variable a in instruction b = a + 1;?
Show the RISC instructions corresponding to the high-level instruction b = a + 1; in this procedure. You should use the same ILOC
instruction format as used in class.
(d) Show the stack frames at the beginning of procedure proc1. Label
each frame with its procedures name, and make sure you include the
2
local variables and their values. Show all access links and control links
between the stack frames, and the frame pointer (FP), by drawing
arrows. You should use the frame layout in the figure below.
Figure 1: Figure for the frame layout
3

More products