Can someone explain what this pseudo-code means? I don't really understand since I'm not familiar with this type of writing.
I also need to make the activation tree. It will be great if you can guide me.
(1) program ret (input, output) ;
(2) var f: function (integer): integer;
(3) function a : function (integer): integer ;
(4) var m : integer ;
(5) function addm(n: integer) : integer;
(6) begin return m + n end;
(7) begin m := 0; return addm end;
(8) procedure b(g: function (integer) : integer);
(9) begin writeln(g(2)) end;
(10) begin
(11) f := a ; b (f)
(12) end
Actually this is not really pseudocode, but straightforward Pascal coding. However, if you are doing a compiler course I would expect that your tutor has used examples like this before. You have however, made some mistakes when transcribing this example from your problem sheet!
This example is illustrating nested function calls and the issues with scoping and the necessary stack activation records that a compiler would need to maintain in the object code to enable the variable access and recursion to function.
In terms of nesting you have:
A main program called ret
that performs input and output. Within that are nested:
f
a function variable that is currently unassigned
a
a function that contains:
m
an integer variableaddm
a function called b
In the main program the procedure variable f
is assigned the function body a
That function b
is invoked passing the function variable f
Function b
takes the function variable f
by value, which contains the function a
in the local function variable g
.
g
is invoked with an argument of 2, which calls a
with that value
a
receives the value 2
addm
is invoked to calculate the return value of a
addm
computes m + n
which is 0 + 2
=> 2a
now returns 2
g
now returns 2
writeln
now outputs 2
b
returns
The program completes execution
Now this could be examined in more detail showing the contents of each stack activation record, but I will omit that level of detail.