Algorithm Search⌘K

Data structureintro

Activation record

Also called stack frame, call frame.

The block of stack memory for one call of a procedure, with its arguments, return address, saved registers and local variables.

Time
O(h + s) worst
Space
Θ(s) extra
Where
h = the difference between the nesting depth of a use and that of its declaration; s = the number of parameters and locals of the callee

An activation record, or stack frame, is the block of memory that holds the state of one call of a procedure: its arguments, its local variables, the address to return to, and links to other frames. A call pushes a new record on the run-time stack, and the return pops it. So the records of the active calls form a stack, which is what makes recursion work. In a language with nested procedures, each record also has a static link to the record of the enclosing procedure, and the code reaches a variable of an outer procedure by following these links.

In plain words

Each time a function is called, it needs its own place to keep its arguments and its local variables. If a function calls itself, each call needs a separate place, or the calls would overwrite each other.

So the program keeps a stack. A call puts a new block, the frame, on top. The frame holds the arguments, the locals, and the place in the caller where the program continues after the return. When the call ends, its frame is taken off, and the caller's frame is on top again.

Some languages let you write a function inside another function. The inner function can use the variables of the outer one. To find them, each frame keeps a pointer to the frame of the function that it is written inside. This pointer is not always the caller. Mixing up the two gives wrong values.

The abstract type

The run-time stack is a stack of frames, with these operations:

  • call ff with arguments a1,…,ana_1, \ldots, a_n: push a frame for ff that holds the arguments, fresh locals, the return address, and the links;
  • return vv: pop the top frame and continue in the caller with the value vv;
  • load and store of a variable xx: read or write the slot of xx in the frame where xx lives.

The last operation is the hard one. A function gg at nesting depth dd can use a variable that is declared in an enclosing function at depth j≤dj \le d. The compiler knows dd and jj, so it names each variable by a pair (h,o)(h, o): go h=d−jh = d - j frames out along the lexical nesting, then take offset oo. The data structure must find the frame that is hh levels out quickly. That frame is the one of the most recent active call of the enclosing function that gg was created in, and with recursion this can be far down the stack.

Representation

The frame is a contiguous block, and a frame pointer FP holds the address of the current one. In the reference code, a frame on the toy stack machine has this layout:

Offset from FP Slot
0 return address RA
1 dynamic link DL: the FP of the caller
2 static link SL: the FP of the frame of the enclosing function
3, 4, ... the parameters, then the locals
above temporaries of the expression in progress

The dynamic link restores the FP of the caller on return. The static link, also called the access link, points to the frame of the function that lexically encloses the callee. Real machines add slots for saved registers and outgoing arguments, and they keep the first arguments in registers. The layout above shows only the parts that the access to variables needs.

Operations

The caller runs MARK, pushes the arguments, and runs CALL. The callee begins with ENTER. CALL has three operands: the address of the callee, the number hh of static links to follow, and the number nn of arguments.

  1. CALL(target, h, n)
  2. 1MARK: push three empty header slots, then push the n arguments
  3. 2base ← SP - n - 3
  4. 3stack[base + RA], stack[base + DL], stack[base + SL] ← pc, FP, FRAME(h); FP ← base; pc ← target
  5. 4ENTER: push the locals of the callee, each set to 0
  6. RETURN
  7. 5v ← pop; ra ← stack[FP + RA]; dl ← stack[FP + DL]
  8. 6pop the frame; push v; pc ← ra; FP ← dl
  9. FRAME(h)
  10. 7a ← FP; repeat h times: a ← stack[a + SL]
  11. LOAD(h, o)
  12. 8push stack[FRAME(h) + o]

STORE is LOAD with a write. The static link of the callee comes from line L3. If ff is declared in the function that is hh hops out from the caller, then the frame of that function is FRAME(hh) of the caller, and this is the frame that ff must see as its parent. For a function declared in the caller itself, h=0h = 0 and the static link is the FP of the caller.

A display replaces the chain by an array DD, where D[j]D[j] is the frame of the current function at depth jj of the lexical chain. A use at depth jj reads D[j]D[j], in one step. ENTER of a function at depth jj saves D[j]D[j] in the frame and sets D[j]D[j] to the new frame, and RETURN puts the saved value back.

Example

Take this program, where ff and gg are declared inside main:

main() { var x; x = 1; g() }
  f() { x }
  g() { var y; y = 2; f() }

The compiler emits this code. The first three instructions are the startup code, which calls main.

 0 MARK            7 MARK           14 PUSH 2
 1 CALL 3 0 0      8 CALL 13 0 0    15 STORE 0 3
 2 HALT            9 RET 0          16 POP
 3 ENTER 1 0      10 ENTER 0 1      17 MARK
 4 PUSH 1         11 LOAD 1 3       18 CALL 10 1 0
 5 STORE 0 3      12 RET 1          19 RET 1
 6 POP            13 ENTER 1 1

Instruction 11 is the use of xx in ff: ff has depth 1 and xx belongs to main at depth 0, so it follows 1 static link and reads offset 3. Instruction 18 is the call of ff from gg: ff is declared in main, which is 1 hop out from gg, so the static link of ff is the static link of gg. When instruction 11 runs, the stack is:

Address Value Meaning
0, 1, 2 0, 0, 0 the frame of the startup code
3, 4, 5 2, 0, 0 main: RA, DL, SL
6 1 main: xx
7, 8, 9 9, 3, 3 gg: RA, DL, SL
10 2 gg: yy
11, 12, 13 19, 7, 3 ff: RA, DL, SL

With FP = 11, one static link gives the frame at 3, and the slot 3+3=63 + 3 = 6 holds x=1x = 1, which is right. If the code followed the dynamic link instead, it would reach the frame of gg at 7 and read y=2y = 2 from slot 10. That is the answer of dynamic scope, not of lexical scope. The display version emits LOADD 0 3 at instruction 11, with the same result.

A second test computes 6!=7206! = 720 with a recursive fact(n)(n) that declares an inner times(k)=k⋅n(k) = k \cdot n. Each call of times must see the nn of the call of fact that created it, not of a deeper one. The static link gives exactly that.

Correctness

The proof file shows that the machine simulates a direct evaluator with environments. Each environment record maps to one frame, the slots of the frame hold the values of the record, and the static link of a frame points to the frame of the parent record. By induction on hh, FRAME(hh) reaches the record of the function that is hh levels out in the lexical chain, which is where the compiler resolved the name. The call keeps the invariant, because line L3 computes the static link with the same rule that the evaluator uses to find the parent. The return keeps it, because it reads RA and DL before it pops the frame. A second theorem shows that the display holds the same frames as the chain. The tests compare the machine, with static links and with a display, against the evaluator on 1,500 random programs with nesting up to depth 3. They also check that following the dynamic links gives a different result on many of them.

Proof: Static links and displays find the right frame for each variablefull

We use the language, the frame layout and the pseudocode of the page. The depth of main is 0, and a function declared inside a function of depth dd has depth d+1d + 1. The lexical chain of a function gg is the list g0,g1,…,gd=gg_0, g_1, \ldots, g_d = g, where g0g_0 is main and each gj+1g_{j+1} is declared inside gjg_j.

The reference semantics

The direct evaluator gives the meaning. An environment is a record (g,V,P)(g, V, P): the function gg, a map VV from the parameters and locals of gg to values, and the environment PP of the enclosing function. A variable xx is looked up by following PP from the current record to the first record whose VV has xx. A call to ff follows PP to the first record (gi,⋅,⋅)(g_i, \cdot, \cdot) such that ff is declared in gig_i, and the new record is (f,V′,that record)(f, V', \text{that record}). So the PP chain of an environment of gg has one record for each function of the lexical chain of gg, in order, and the record of gjg_j is d−jd - j steps away.

The compiler resolves names in the same way at compile time. For xx in the body of gg, it takes the largest jj such that gjg_j declares xx, and emits LOAD with h=d−jh = d - j hops and the offset of xx in the frame of gjg_j. Since the PP chain of gg follows the lexical chain, this gjg_j is the record where the evaluator finds xx. The same holds for STORE, and for CALL, where the compiler takes the largest ii such that gig_i declares ff and emits d−id - i hops.

The invariant

Map each environment record EE to a frame ϕ(E)\phi(E) on the stack: the frame of the activation that created EE. We say that the machine simulates the evaluator when:

  1. each active frame ϕ(E)\phi(E) holds, at the offset of each variable of EE, the value that EE maps it to;
  2. for each active frame ϕ(E)\phi(E) with E=(g,V,P)E = (g, V, P) and g≠g \ne main, the static link slot of ϕ(E)\phi(E) holds the address of ϕ(P)\phi(P);
  3. the frames of the records on the current PP chain are active.

Lemma 1. If the machine simulates the evaluator and the current function is gg of depth dd, then following h≤dh \le d static links from FP reaches ϕ\phi of the record of gd−hg_{d-h}.

Proof. By induction on hh. For h=0h = 0 it is the current frame. Each step goes from ϕ(E)\phi(E) to ϕ(P)\phi(P) by part 2, which is one step along the PP chain, and by part 3 the frame is still there. □\square

Theorem 1. For each program and each limit on the number of calls, the machine with static links returns the same value as the evaluator, or both run out of calls.

Proof. We show that each step of the machine keeps the invariant, and that each expression leaves on the stack the value that the evaluator computes. The proof is by induction on the steps of the evaluator.

  • LOAD and STORE: by Lemma 1 and the compile-time resolution, the frame reached is ϕ\phi of the record where the evaluator finds xx, and by part 1 the slot holds its value. STORE changes the slot and the record in the same way.
  • CALL to ff (lines L1 to L3): MARK reserves the header and the arguments are evaluated on top of it, so the new frame starts at SP−n−3\mathrm{SP} - n - 3, with the arguments at offsets 3,…,n+23, \ldots, n + 2. The static link is found with d−id - i hops, which by Lemma 1 reaches ϕ\phi of the record of gig_i, the record that the evaluator takes as PP for the new record. So part 2 holds for the new frame. ENTER (line L4) puts the locals, set to 0, after the arguments, as the evaluator does. The new frame is on top of the old ones, so the frames of the PP chain stay active, and part 3 holds.
  • RET (lines L5 and L6) reads the return address and the dynamic link before it pops the frame, pushes the result, and gives the caller back its FP. The frames below are unchanged, so the invariant holds for the caller.

The machine counts a call at CALL, after the arguments, and the evaluator counts it after it evaluates the arguments, in the same left-to-right order. So both stop at the same call when the limit is reached. ■\blacksquare

The display

Theorem 2. The display variant returns the same value as the static link variant.

Proof. Let D[0..63]D[0..63] be the display. We show that, while the current function is gg of depth dd, D[j]D[j] is ϕ\phi of the record of gjg_j for each j≤dj \le d. Then LOADD with the depth jj of the declaring function reaches the same frame as LOAD with d−jd - j hops, by Lemma 1.

When gg calls ff, declared in gig_i, the depth of ff is i+1≤d+1i + 1 \le d + 1. The entries D[0..i]D[0..i] are ϕ\phi of the records of g0,…,gig_0, \ldots, g_i, which are also the first i+1i + 1 functions of the lexical chain of ff, with the same records, since the evaluator takes the record of gig_i as PP. ENTER saves D[i+1]D[i+1] in the frame and sets D[i+1]D[i+1] to the new frame. So the claim holds for ff. RET restores the saved D[i+1]D[i+1], and the entries D[0..i]D[0..i] were not changed by ff when it returns, because every call inside ff restores the entry it changed. So the claim holds again for gg. The entries above the depth of the current function are never read. ■\blacksquare

The dynamic link of a frame points to the frame of the caller. It equals the static link only when the caller is the enclosing function. In the program of the page, gg calls ff, and both are declared in main. In the frame of ff, the static link points to main and the dynamic link points to gg. LOAD of xx with 1 hop along the dynamic link reads the slot at offset 3 of the frame of gg, which holds y=2y = 2, not x=1x = 1. This is the rule of dynamic scoping, not of lexical scoping.

Complexity

A call costs O(h+s)O(h + s): O(h)O(h) to follow the static links at line L3, and O(s)O(s) to push the header, the arguments and the locals. A return costs O(1)O(1) beyond the pop of the frame. A variable access costs O(h)O(h) with static links and O(1)O(1) with a display. In real programs hh is almost always 0 or 1, so the chain is cheap. A frame takes Θ(s)\Theta(s) words, and the stack holds one frame for each active call, so its size is the depth of the recursion times the size of the largest frame.

Variants

  • Display. As above, with O(1)O(1) access to every level. It costs a save and a restore on each call, and it is harder to make right with procedures passed as values, which must carry their own display or static link.
  • No static link. In C, functions are not nested, so a frame has only the dynamic link, and many compilers omit even that and address the frame from the stack pointer.
  • Lambda lifting. The compiler passes the free variables of an inner function as extra parameters, and the static link is no longer needed.
  • Closure conversion and heap frames. When an inner function can outlive the call that created it, its free variables cannot stay in a frame on the stack. They move to a heap record, and the closure holds a pointer to it. Escape analysis finds which frames can stay on the stack.
  • Tail calls. A call in tail position reuses the frame of the caller, so a loop written as recursion runs in constant stack space.
  • Register windows. Some machines, such as SPARC, give each call a fresh set of registers that overlap with those of the caller, so small frames need no memory at all.

When to use it

Every compiler for a language with recursion uses activation records on a stack. Static links are the usual choice for nested functions, because the nesting is shallow and the cost of a call stays small. A display pays off when the code often reads variables several levels out. When functions are first-class values that can escape, the frames, or at least the escaping variables, must live on the heap, or in regions whose lifetime the compiler can prove. A garbage collector must find the pointers in the frames, because the slots of the active frames are part of its roots. So the compiler records, for each call site, which slots of the frame hold pointers.

Pitfalls

  • Dynamic link for static link. Following the caller instead of the enclosing function gives dynamic scope. The two links agree only when the caller is the enclosing function, so simple tests may not catch the error.
  • Returning the address of a local. The frame is gone after the return, and a later call writes over it.
  • Escaping closures. An inner function that is returned or stored keeps a static link to a frame that has been popped. This is the upward funarg problem. Such variables must go to the heap.
  • Popping too early. The return must read the return address and the dynamic link before it frees the frame, or it reads slots that are no longer there.
  • Hops counted from the wrong frame. The number of hops for a call is the distance from the caller to the function that declares the callee, not to the callee.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

activation_record.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/activation-record/. The authors are listed in prov/4XG2M7.jsonl.

"""Activation records for a language with nested functions.

A function is ("fun", name, params, locals, body, children). The children
are the functions declared inside it; they can read and write the
parameters and locals of every enclosing function. The program is a
function named main with no parameters. Expressions are:

    ("int", k)  ("var", x)  ("assign", x, e)  ("seq", e1, e2)
    ("add", e1, e2)  ("sub", e1, e2)  ("mul", e1, e2)  ("lt", e1, e2)
    ("if", c, e1, e2)    the test is true when c is not 0
    ("call", f, [e1, ...])

The compiler emits code for a stack machine. A frame (activation record)
starts at the frame pointer FP:

    FP + 0   return address
    FP + 1   dynamic link: the FP of the caller
    FP + 2   static link: the FP of the frame of the enclosing function,
             or the saved display entry in the display variant
    FP + 3   the parameters, then the locals
"""

RA, DL, SL, HEADER = 0, 1, 2, 3


class OutOfFuel(Exception):
    """The program made more calls than the limit allows."""


def find_fun(chain: list, f: str) -> int:
    """The index in chain of the innermost function whose children declare f."""
    for i in range(len(chain) - 1, -1, -1):
        if any(c[1] == f for c in chain[i][5]):
            return i
    raise NameError(f)


def compile_program(main: tuple, mode: str = "static") -> list[tuple]:
    """Compile to stack machine code. mode is "static" (static links) or
    "display" (a display of frame pointers indexed by depth)."""
    code: list[tuple] = []
    labels: dict[str, int] = {}
    fixups: list[tuple] = []
    names: dict[int, str] = {id(main): "main"}
    count = [0]

    def new_label() -> str:
        count[0] += 1
        return "L%d" % count[0]

    def slot(chain: list, x: str) -> tuple[int, int]:
        # (depth of the function that declares x, offset of x in its frame)
        for d in range(len(chain) - 1, -1, -1):
            declared = list(chain[d][2]) + list(chain[d][3])
            if x in declared:
                return d, HEADER + declared.index(x)
        raise NameError(x)

    def access(op: str, chain: list, x: str) -> None:
        d, off = slot(chain, x)
        if mode == "display":
            code.append((op + "D", d, off))
        else:
            code.append((op, len(chain) - 1 - d, off))  # hops along the static links

    def expr(e: tuple, chain: list) -> None:
        k = e[0]
        if k == "int":
            code.append(("PUSH", e[1]))
        elif k == "var":
            access("LOAD", chain, e[1])
        elif k == "assign":
            expr(e[2], chain)
            access("STORE", chain, e[1])
        elif k == "seq":
            expr(e[1], chain)
            code.append(("POP",))
            expr(e[2], chain)
        elif k in ("add", "sub", "mul", "lt"):
            expr(e[1], chain)
            expr(e[2], chain)
            code.append((k.upper(),))
        elif k == "if":
            other, end = new_label(), new_label()
            expr(e[1], chain)
            fixups.append((len(code), other))
            code.append(("JZ", None))
            expr(e[2], chain)
            fixups.append((len(code), end))
            code.append(("JMP", None))
            labels[other] = len(code)
            expr(e[3], chain)
            labels[end] = len(code)
        elif k == "call":
            i = find_fun(chain, e[1])
            callee = next(c for c in chain[i][5] if c[1] == e[1])
            if len(e[2]) != len(callee[2]):
                raise TypeError("wrong number of arguments for " + e[1])
            code.append(("MARK",))
            for a in e[2]:
                expr(a, chain)
            fixups.append((len(code), names[id(callee)]))
            # The callee is declared in chain[i], so its static link is the frame
            # of chain[i], len(chain) - 1 - i hops from the frame of the caller.
            code.append(("CALL", None, len(chain) - 1 - i, len(e[2])))
        else:
            raise ValueError("bad expression: %r" % (e,))

    def function(fn: tuple, chain: list) -> None:
        chain = chain + [fn]
        for c in fn[5]:
            names[id(c)] = "%s.%s.%d" % (names[id(fn)], c[1], len(names))
        labels[names[id(fn)]] = len(code)
        code.append(("ENTER", len(fn[3]), len(chain) - 1))
        expr(fn[4], chain)
        code.append(("RET", len(chain) - 1))
        for c in fn[5]:
            function(c, chain)

    code.append(("MARK",))
    fixups.append((len(code), "main"))
    code.append(("CALL", None, 0, 0))
    code.append(("HALT",))
    function(main, [])
    for at, lab in fixups:
        ins = code[at]
        code[at] = (ins[0], labels[lab]) + ins[2:]
    return code


def run_machine(code: list[tuple], max_calls: int = 1000, follow: str = "static") -> int:
    """Run the code and return the value of main. With follow="dynamic",
    LOAD and STORE follow the dynamic links instead of the static links,
    which is wrong; it is here to show the difference."""
    stack: list[int] = [0, 0, 0]  # the frame of the startup code
    fp, pc, calls = 0, 0, 0
    display: list[int] = [0] * 64
    link = SL if follow == "static" else DL
    uses_display = any(c[0] in ("LOADD", "STORED") for c in code)

    def frame(hops: int) -> int:
        a = fp
        for _ in range(hops):  # @line L7
            a = stack[a + link]
        return a

    while True:
        ins = code[pc]
        pc += 1
        op = ins[0]
        if op == "PUSH":
            stack.append(ins[1])
        elif op == "POP":
            stack.pop()
        elif op in ("ADD", "SUB", "MUL", "LT"):
            b = stack.pop()
            a = stack.pop()
            stack.append({"ADD": a + b, "SUB": a - b, "MUL": a * b, "LT": int(a < b)}[op])
        elif op == "LOAD":
            stack.append(stack[frame(ins[1]) + ins[2]])  # @line L8
        elif op == "STORE":
            stack[frame(ins[1]) + ins[2]] = stack[-1]
        elif op == "LOADD":
            stack.append(stack[display[ins[1]] + ins[2]])
        elif op == "STORED":
            stack[display[ins[1]] + ins[2]] = stack[-1]
        elif op == "JZ":
            if stack.pop() == 0:
                pc = ins[1]
        elif op == "JMP":
            pc = ins[1]
        elif op == "MARK":
            stack += [0, 0, 0]  # @line L1
        elif op == "CALL":
            calls += 1
            if calls > max_calls:
                raise OutOfFuel()
            _, target, hops, nargs = ins
            base = len(stack) - nargs - HEADER  # @line L2
            stack[base + RA] = pc
            stack[base + DL] = fp
            stack[base + SL] = frame(hops)  # @line L3
            fp, pc = base, target
        elif op == "ENTER":
            stack += [0] * ins[1]  # @line L4
            if uses_display:
                stack[fp + SL] = display[ins[2]]  # save the old entry
                display[ins[2]] = fp
        elif op == "RET":
            result = stack.pop()
            ra, dl = stack[fp + RA], stack[fp + DL]  # @line L5
            if uses_display:
                display[ins[1]] = stack[fp + SL]
            del stack[fp:]
            stack.append(result)
            pc, fp = ra, dl  # @line L6
        elif op == "HALT":
            return stack[-1]
        else:
            raise ValueError("bad instruction: %r" % (ins,))


def evaluate(main: tuple, max_calls: int = 1000) -> int:
    """A direct evaluator with environments, for comparison. An environment
    is (function, variables, the environment of the enclosing function)."""
    calls = [0]

    def lookup(env: tuple, x: str) -> dict:
        while x not in env[1]:
            env = env[2]
        return env[1]

    def ev(e: tuple, env: tuple) -> int:
        k = e[0]
        if k == "int":
            return e[1]
        if k == "var":
            return lookup(env, e[1])[e[1]]
        if k == "assign":
            v = ev(e[2], env)
            lookup(env, e[1])[e[1]] = v
            return v
        if k == "seq":
            ev(e[1], env)
            return ev(e[2], env)
        if k in ("add", "sub", "mul", "lt"):
            a, b = ev(e[1], env), ev(e[2], env)
            return {"add": a + b, "sub": a - b, "mul": a * b, "lt": int(a < b)}[k]
        if k == "if":
            return ev(e[2], env) if ev(e[1], env) != 0 else ev(e[3], env)
        if k == "call":
            outer = env
            while not any(c[1] == e[1] for c in outer[0][5]):
                outer = outer[2]
            fn = next(c for c in outer[0][5] if c[1] == e[1])
            args = [ev(a, env) for a in e[2]]
            calls[0] += 1
            if calls[0] > max_calls:
                raise OutOfFuel()
            local = dict(zip(fn[2], args))
            for x in fn[3]:
                local[x] = 0
            return ev(fn[4], (fn, local, outer))
        raise ValueError("bad expression: %r" % (e,))

    calls[0] += 1
    return ev(main[4], (main, {x: 0 for x in main[3]}, None))
test_activation_record.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/activation-record/. The authors are listed in prov/4XG2M7.jsonl.

import random

from activation_record import OutOfFuel, compile_program, evaluate, run_machine

# main has a local x. f reads x. g has its own local y and calls f.
F = ("fun", "f", [], [], ("var", "x"), [])
G = ("fun", "g", [], ["y"], ("seq", ("assign", "y", ("int", 2)), ("call", "f", [])), [])
SCOPE = ("fun", "main", [], ["x"], ("seq", ("assign", "x", ("int", 1)), ("call", "g", [])), [F, G])

# fact(n) declares times(k) = k * n, which reads n from the frame of fact.
TIMES = ("fun", "times", ["k"], [], ("mul", ("var", "k"), ("var", "n")), [])
FACT = (
    "fun",
    "fact",
    ["n"],
    [],
    ("if", ("lt", ("var", "n"), ("int", 2)), ("int", 1), ("call", "times", [("call", "fact", [("sub", ("var", "n"), ("int", 1))])])),
    [TIMES],
)
FACT_MAIN = ("fun", "main", [], [], ("call", "fact", [("int", 6)]), [FACT])


def outcome(f, *args) -> object:
    try:
        return f(*args)
    except OutOfFuel:
        return "fuel"


def test_static_link_against_dynamic_link() -> None:
    assert evaluate(SCOPE) == 1
    assert run_machine(compile_program(SCOPE)) == 1
    assert run_machine(compile_program(SCOPE, "display")) == 1
    # Following the dynamic link finds y in the frame of g: dynamic scope.
    assert run_machine(compile_program(SCOPE), follow="dynamic") == 2


def test_recursion_with_a_nested_function() -> None:
    assert evaluate(FACT_MAIN) == 720
    assert run_machine(compile_program(FACT_MAIN)) == 720
    assert run_machine(compile_program(FACT_MAIN, "display")) == 720


def random_program(rng: random.Random) -> tuple:
    """A random program with functions nested up to depth 3."""
    pool = ["a", "b", "c", "d"]
    fnames = ["f", "g", "h"]

    def skeleton(name: str, depth: int) -> dict:
        names = rng.sample(pool, rng.randint(0, 3))
        cut = 0 if name == "main" else rng.randint(0, len(names))
        kids = []
        if depth < 3:
            for fn in rng.sample(fnames, rng.randint(0, 2)):
                kids.append(skeleton(fn, depth + 1))
        return {"name": name, "params": names[:cut], "locals": names[cut:], "kids": kids}

    def visible(chain: list) -> tuple[list, list]:
        # An inner declaration hides an outer one with the same name.
        vs: list = []
        fs: dict = {}
        for s in chain:
            vs += s["params"] + s["locals"]
            for k in s["kids"]:
                fs[k["name"]] = k
        return sorted(set(vs)), list(fs.values())

    def expr(chain: list, size: int) -> tuple:
        vs, fs = visible(chain)
        r = rng.random()
        if size <= 1 or r < 0.15:
            if vs and rng.random() < 0.6:
                return ("var", rng.choice(vs))
            return ("int", rng.randint(-3, 5))
        if r < 0.3 and vs:
            return ("assign", rng.choice(vs), expr(chain, size - 1))
        if r < 0.4:
            return ("seq", expr(chain, size // 2), expr(chain, size // 2))
        if r < 0.55:
            return ("if", expr(chain, size // 3), expr(chain, size // 3), expr(chain, size // 3))
        if r < 0.75 and fs:
            f = rng.choice(fs)
            return ("call", f["name"], [expr(chain, size // 3) for _ in f["params"]])
        op = rng.choice(["add", "sub", "mul", "lt"])
        return (op, expr(chain, size // 2), expr(chain, size // 2))

    def build(s: dict, chain: list) -> tuple:
        chain = chain + [s]
        body = expr(chain, rng.randint(1, 10))
        return ("fun", s["name"], s["params"], s["locals"], body, [build(k, chain) for k in s["kids"]])

    return build(skeleton("main", 0), [])


def test_random_programs_against_the_evaluator() -> None:
    rng = random.Random(1960)
    differ = 0
    done = 0
    for _ in range(1500):
        prog = random_program(rng)
        want = outcome(evaluate, prog, 50)
        assert outcome(run_machine, compile_program(prog), 50) == want
        assert outcome(run_machine, compile_program(prog, "display"), 50) == want
        done += want != "fuel"
        try:
            differ += run_machine(compile_program(prog), 50, "dynamic") != want
        except (OutOfFuel, IndexError):
            differ += 1
    assert done > 1000
    assert differ > 20

History

Dijkstra described in 1960 how a run-time stack handles the recursive procedures of ALGOL 60, with a record for each call. The ALGOL 60 compilers of the early 1960s used static and dynamic chains, and some used a display, for access to the variables of enclosing blocks. Later textbooks, such as the dragon book and Appel's book, made the frame layout with access links the standard way to teach run-time environments.

References

  1. Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers, Principles, Techniques, and Tools, second edition, Addison-Wesley, 2007, Chapter 7 (Run-Time Environments), activation records, calling sequences, access links and displays
  2. Andrew W. Appel, Modern Compiler Implementation in ML, Cambridge University Press, 1998, Chapter 6 (Activation Records), stack frames, frame pointers, static links and escaping variables
  3. Keith D. Cooper and Linda Torczon, Engineering a Compiler, third edition, Morgan Kaufmann, 2022, Chapter 6 (The Procedure Abstraction), activation records, access links and global displays
  4. E. W. Dijkstra, Recursive programming, Numerische Mathematik 2, 1960, 312-318, the run-time stack for the recursive procedures of ALGOL 60

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/4XG2M7/text.yaml