Algorithmcore
Closure conversion
Also called closure representation.
Turns each function with free variables into closed code plus an environment record, so that functions can be compiled as plain code.
- Time
- O(n^2) worstΘ(n) best
- Space
- O(n) extraO(n^2) output
- Where
- n = the number of nodes of the source term
- Model
- Word RAM
- Properties
- deterministicofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
Closure conversion makes every function of a program closed. A function fun x -> b whose body reads variables from outside becomes a closure: a record that holds a closed piece of code and the values of those free variables. The code takes the record as an extra parameter, usually called self or env, and reads each free variable from it. A call f a becomes "fetch the code from the record f, and call it with f and a". After the conversion no function body refers to a variable of an enclosing function, so each function can be compiled to machine code on its own and placed anywhere in memory, and the records live in the heap. Landin (1964) introduced closures in the SECD machine. The flat form below, where each record holds copies of the values, is the one of Cardelli's ML compiler (1984) and of most compilers for functional languages since.
In plain words
A function written inside another function often uses names from the outside, like a helper that adds a fixed amount chosen by its caller. Machine code cannot reach into another function's local names. So the compiler packs the function together with the values it needs into a small box, and changes the code to take its values out of the box. Calling the function now means: open the box, take out the code, and run it with the box and the argument. Every function becomes a plain piece of code that needs nothing from outside, and the boxes carry what is left.
The problem
The input is a closed term of the call-by-value toy language: constants, fun x -> e, calls, let, if, operators and recursive functions fix f x -> e. The output is a term of the same language plus records: [e0, e1, ..., em] builds a record and e.i reads part , counted from 0. The output must have the same outcome as the input, with a closure record in place of each function value, and every fun in it must be closed. The free variables of a term are those it reads but does not bind; for fun x -> x + a + b they are a and b.
The algorithm
CONVERT carries a map that says how to read each variable that is free in the current term: as itself when it is local to the current function, or as a part self.i of the current record.
CLOSURE-CONVERT(e) ▷ e is closed- 1
return CONVERT(e, empty map) CONVERT(e, ρ) ▷ ρ maps each free variable of e to the target term that reads it- 2
if e is a variable x then return ρ(x) - 3
if e is fun x -> b, or fix f x -> b, then ▷ self new - 4
y1, ..., ym ← the free variables of e, sorted - 5
ρ' ← {y1 ↦ self.1, ..., ym ↦ self.m, x ↦ x}, and f ↦ self for a fix - 6
code ← fun self -> fun x -> CONVERT(b, ρ') - 7
return [code, ρ(y1), ..., ρ(ym)] - 8
if e is e1 e2 then return let c = CONVERT(e1, ρ) in let a = CONVERT(e2, ρ) in (c.0 c) a ▷ c, a new - 9
if e is let x = e1 in e2 then return let x = CONVERT(e1, ρ) in CONVERT(e2, ρ[x ↦ x]) - 10
otherwise apply CONVERT with ρ to each part of e (constants, if, operators)
Line L7 builds the record in the scope where the function is defined, so it reads each free variable through the outer map . Line L6 converts the body with the inner map , in which only self and the parameter are variables, so the code is closed. Line L8 evaluates the function before the argument, as the source does, and then passes the record itself as the first argument of its code. A recursive function needs no special record: line L5 maps its own name to self, the record through which it was called. So the output has no fix at all.
Example
Take let a = 1 in let b = 2 in let f = fun x -> x + a + b in f 10. The function has the free variables a and b, so line L7 builds the record [code, a, b], and the body reads self1.1 and self1.2:
let a = 1 in let b = 2 in
let f = [fun self1 -> fun x -> x + self1.1 + self1.2, a, b] in
let c2 = f in let a3 = 10 in (c2.0 c2) a3
| step | term being run |
|---|---|
| 1 | the three lets give f = [code, 1, 2] |
| 2 | (c2.0 c2) a3 with c2 = [code, 1, 2] and a3 = 10 |
| 3 | code [code, 1, 2] 10 |
| 4 | 10 + [code, 1, 2].1 + [code, 1, 2].2, which is 10 + 1 + 2 = 13 |
For the recursive let m = 1 in (fix f n -> if n < 1 then m else n * f (n - 1)) 5, the free variable is m, and f becomes self. The record is [code, m], and the recursive call inside the code is let c4 = self3 in let a5 = n - 1 in (c4.0 c4) a5. The result is 120 in both programs.
Correctness
Relate a source value and a target value by : equal integers, equal booleans, or a source function and a record whose code is CONVERT of that function's body and whose parts are related to the values of its free variables. The main lemma says: if every free variable of has a source value , and evaluates in the target to a value related to , then with substituted and CONVERT have related outcomes. A value result maps to a related value, stuck maps to stuck, and a run without end maps to a run without end. The proof is an induction on the evaluation, with one case per line. The call case of line L8 is the heart of it: the code receives the record as self, and of line L5 then reads each free variable from the right part of the record. A second induction shows that the free variables of CONVERT are among those of the terms , so the code of line L6, with only self and in , is closed. The proof file gives both proofs.
Proof: Closure conversion keeps the outcome and makes every function closedfull
We use the notation of the page. The source language is evaluated by call-by-value substitution, left to right. We use the big-step form of the same semantics: means that the run of the closed term ends with , where is a value or the mark . A stuck subterm makes the whole run stuck, as in the small-step rules. A run that never ends has no . The target language is the same with records [e0, ..., em] and projections e.i. The new names self, c and a of the conversion are not names of the source.
1. Closed code
Lemma 1. .
Proof. By induction on . Line L2 gives . Line L7 gives a record whose parts are the code and the terms , . The code is . By induction its body has free variables among for . Every is , for a fix, or some , and maps them to , and . So the code is closed. Line L8 adds the bound names and only. Line L9 maps the bound to itself, which the let binds. Line L10 is direct.
So every fun that the conversion makes is closed, and a function body has no free variable but self and its parameter. Since the input is closed and is empty at line L1, the output is closed.
2. Related values
Define between closed source values and closed target values:
- for every integer or boolean constant ;
- if is or for a term , where are the free variables of (or of ), with as in line L5, and for each .
The definition is by induction on the size of , since each is a proper part of . Results are related by if both are or both are related values.
An environment for and is a pair of a source substitution , defined on with closed values, and a target substitution with closed values, such that for every , in at most one step with . The terms have the forms , and , so this holds when , or is the record for , or is a record whose part is .
3. The main lemma
Lemma 2. Let be an environment for and , and write .
- If then with .
- If then with .
Proof. Both parts by induction on the derivation, of the source run for part 1 and of the target run for part 2. The two parts have the same cases, in the order of the lines.
- L2, a variable . is a value, and with by the definition of an environment.
- L3 to L7, a function. is the value , since only touches the free variables . The code is closed by Lemma 1, so does not change it, and evaluates each part, left to right, to . The result is related to by the definition of with . The case of
fixis the same. - L8, a call . The pair is an environment for and for with the same , and , are new, so binding them does not change . By induction, and the target of both end, or neither does. If both are stuck, both calls are stuck. Otherwise they give , and in the same way gives or both are stuck. If is a constant, so is ; the source call is stuck, and the target
w1.0is stuck, because is not a record. If , then with . The source steps to . The target computesw1.0= code, applies it to and to , and reaches . Now and form an environment for and : evaluates in one step to , and gives . The run of the body is a smaller derivation, so the induction hypothesis gives related results. For , add to ; gives . - L9,
let x = e1 in e2. As for the call: gives or both are stuck. Then is an environment for and . A free variable of keeps its target term , which does not mention : the terms of use only source names that are bound around ,self, and parts ofself, and in the source the innerlet xhides any outer . - L10, constants,
ifand operators. Constants map to themselves. Forif, the conditions give related values; a boolean is related only to the same boolean, so both runs take the same branch, and anything else is stuck in both. For an operator, related integers are equal, so both give the same result; any other pair is stuck in both, since a function is related only to a record and the operators reject both.
In each case the target run uses the target runs of the parts in the same order as the source, so part 2 follows by the same case analysis, with the induction on the target derivation.
4. The theorem
Theorem. For a closed source term , the runs of and of CLOSURE-CONVERT both end with related results, or both run forever. In particular they give the same integer or boolean, both give a function value (a record in the target), or both get stuck.
Proof. At line L1, is empty and is closed, so the empty and form an environment. Lemma 2, part 1, shows that if the source ends then the target ends with a related result. Part 2 shows that if the target ends then so does the source. So if one runs forever, so does the other.
Complexity
The model is the word RAM, with names as small integers, and the unit step is the creation of one output node or one operation on one element of a set. Line L4 needs the free variables of each function. With one bottom-up pass that stores them, or with a fresh walk of each function, this costs per function and in all. The output is the source plus nodes per call and one record part for each pair of a function and one of its free variables. That sum can reach : in fun x1 -> fun x2 -> ... fun xk -> x1 + ... + xk, with nodes, the function of captures variables, and the records have parts in all. If every function has a bounded number of free variables, time and output are . The recursion depth and the map take extra space.
Properties
- Closed code. Every
funin the output is closed, and onlyselfand the parameter are free in a function body. - Calls are uniform. Every call has the same shape, whatever function is called, because the record carries the code.
- Safe for space. A flat record holds only the free variables of its function, so the garbage collector never keeps a value alive just because some enclosing scope had it.
- Copies. A record holds copies of values. A variable that the program can change after the record is made must be put in a box first.
Variants and improvements
- Linked closures. A record holds the free variables of its own function and a pointer to the record of the enclosing function, as in Landin's environments. Records are made faster and share data, but reading a variable follows a chain, and the chain can keep dead values alive.
- Shared and safe-for-space closures. Shao and Appel (1994, 2000) choose for each function between flat and shared parts, so that records are small and access is fast without keeping dead values alive.
- Typed closure conversion. Minamide, Morrisett and Harper (1996) give each record an existential type that hides the type of its environment, so that a typed compiler can keep types through the conversion.
- Known functions. A function whose every call site is known needs no record. Lambda lifting passes its free variables as extra arguments instead, and escape analysis or 0-CFA finds the functions that can be treated this way.
- Defunctionalization. Replaces the code part of the record by a tag and every call by a case analysis on the tag, which turns the whole program into a first-order one.
- Closure conversion after CPS. In a compiler that first applies CPS conversion, continuations become closures too, and the stack frames of a normal compiler appear as continuation records.
When to use it
Use closure conversion in a compiler for any language with first-class nested functions: ML, Haskell, Scheme, JavaScript, Rust and Java lambdas. It is the step that turns nested functions into code that a machine can run. Use it together with a cheaper path for known functions, as in most real compilers. For an interpreter that keeps environments at run time, closures appear without this transformation, as in the SECD machine.
Pitfalls
- Recursion. Treating the name of a recursive function as a free variable needs a record that contains itself, which the record cannot hold when it is built. Map the name to
self, as line L5 does. - Assigned variables. Flat records copy values. If the source can assign to a captured variable, every closure and the outer function must share one box, or they see different values.
- Order of the parts. Lines L5 and L7 must use the same order of free variables. A different order at the two places reads the wrong value without any error.
- Shadowing. A
let xor a parameter inside a function must hide an outerxof the same name in , as line L9 and line L5 do. - Quadratic size. Deeply nested functions copy the same variables into many records. Linked or shared records avoid this, at a cost in access time.
- Calls through the record. A call to a known function through its record costs a memory read and an indirect jump. Compilers call known functions directly.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/closure-conversion/. The authors are listed in prov/EGE7J5.jsonl.
"""Flat closure conversion of the toy lambda language of toylam.py.
The target language is the toy language with two more forms:
("tuple", (e0, e1, ..., em)) a record, a value when all parts are values
("proj", e, i) part i of the record e, counted from 0
A source function becomes a record (code, v1, ..., vm): code is the closed
term fun self -> fun x -> body, and v1 ... vm are the values of the free
variables. Inside body, the i-th free variable is read as self.i. A call
e1 e2 becomes let c = e1 in let a = e2 in (c.0 c) a. The target needs no fix,
since a recursive function reaches itself through self.
The module also has a small evaluator for the target language, with the same
call-by-value, left-to-right rules as toylam.
"""
import toylam
STUCK = toylam.STUCK
def var(x):
return ("var", x)
def names(e):
"""Every variable name in the source term e, bound or free."""
tag = e[0]
if tag == "var":
return {e[1]}
if tag in ("int", "bool"):
return set()
if tag == "lam":
return {e[1]} | names(e[2])
if tag == "let":
return {e[1]} | names(e[2]) | names(e[3])
if tag == "fix":
return {e[1], e[2]} | names(e[3])
if tag == "prim":
return names(e[2]) | names(e[3])
out = set()
for part in e[1:]:
out |= names(part)
return out
class Fresh:
"""Makes names that are not in avoid and were not made before."""
def __init__(self, avoid=()):
self.avoid = set(avoid)
self.n = 0
def __call__(self, base):
while True:
self.n += 1
name = f"{base}{self.n}"
if name not in self.avoid:
self.avoid.add(name)
return name
# ------------------------------------------------------------ the conversion
def closure_convert(e):
"""The target program of the closed source term e."""
return convert(e, {}, Fresh(names(e))) # @line L1
def convert(e, rho, fresh):
"""Convert e. rho maps each free variable of e to the target term that reads it."""
tag = e[0]
if tag == "var": # @line L2
return rho[e[1]]
if tag in ("lam", "fix"): # @line L3
ys = sorted(toylam.free_vars(e)) # @line L4
self = fresh("self")
x, body = (e[1], e[2]) if tag == "lam" else (e[2], e[3])
inner = {y: ("proj", var(self), i + 1) for i, y in enumerate(ys)} # @line L5
if tag == "fix":
inner[e[1]] = var(self)
inner[x] = var(x)
code = ("lam", self, ("lam", x, convert(body, inner, fresh))) # @line L6
return ("tuple", (code,) + tuple(rho[y] for y in ys)) # @line L7
if tag == "app": # @line L8
c, a = fresh("c"), fresh("a")
call = ("app", ("app", ("proj", var(c), 0), var(c)), var(a))
return ("let", c, convert(e[1], rho, fresh), ("let", a, convert(e[2], rho, fresh), call))
if tag == "let": # @line L9
return ("let", e[1], convert(e[2], rho, fresh), convert(e[3], {**rho, e[1]: var(e[1])}, fresh))
if tag in ("int", "bool"): # @line L10
return e
if tag == "if":
return ("if", convert(e[1], rho, fresh), convert(e[2], rho, fresh), convert(e[3], rho, fresh))
return ("prim", e[1], convert(e[2], rho, fresh), convert(e[3], rho, fresh))
# ------------------------------------------------------------ the target language
def is_value(e):
if e[0] == "tuple":
return all(is_value(p) for p in e[1])
return e[0] in ("int", "bool", "lam", "fix")
def free_vars(e):
tag = e[0]
if tag == "tuple":
out = set()
for p in e[1]:
out |= free_vars(p)
return out
if tag == "proj":
return free_vars(e[1])
if tag == "var":
return {e[1]}
if tag in ("int", "bool"):
return set()
if tag == "lam":
return free_vars(e[2]) - {e[1]}
if tag == "let":
return free_vars(e[2]) | (free_vars(e[3]) - {e[1]})
if tag == "fix":
return free_vars(e[3]) - {e[1], e[2]}
if tag == "prim":
return free_vars(e[2]) | free_vars(e[3])
out = set()
for p in e[1:]:
out |= free_vars(p)
return out
def subst(e, x, v):
"""Replace the free occurrences of x in e by the closed value v."""
tag = e[0]
if tag == "var":
return v if e[1] == x else e
if tag in ("int", "bool"):
return e
if tag == "tuple":
return ("tuple", tuple(subst(p, x, v) for p in e[1]))
if tag == "proj":
return ("proj", subst(e[1], x, v), e[2])
if tag == "lam":
return e if e[1] == x else ("lam", e[1], subst(e[2], x, v))
if tag == "let":
return ("let", e[1], subst(e[2], x, v), e[3] if e[1] == x else subst(e[3], x, v))
if tag == "fix":
return e if x in (e[1], e[2]) else ("fix", e[1], e[2], subst(e[3], x, v))
if tag == "prim":
return ("prim", e[1], subst(e[2], x, v), subst(e[3], x, v))
return (tag,) + tuple(subst(p, x, v) for p in e[1:])
def step(e):
"""One call-by-value step of a target term: the next term, e if e is a value, or STUCK."""
if is_value(e):
return e
tag = e[0]
if tag == "tuple":
parts = list(e[1])
for i, p in enumerate(parts):
if not is_value(p):
q = step(p)
if q == STUCK:
return STUCK
parts[i] = q
return ("tuple", tuple(parts))
if tag == "proj":
if not is_value(e[1]):
q = step(e[1])
return STUCK if q == STUCK else ("proj", q, e[2])
r = e[1]
if r[0] == "tuple" and 0 <= e[2] < len(r[1]):
return r[1][e[2]]
return STUCK
if tag == "var":
return STUCK
if tag == "app":
f, a = e[1], e[2]
if not is_value(f):
q = step(f)
return STUCK if q == STUCK else ("app", q, a)
if not is_value(a):
q = step(a)
return STUCK if q == STUCK else ("app", f, q)
if f[0] == "lam":
return subst(f[2], f[1], a)
if f[0] == "fix":
return subst(subst(f[3], f[1], f), f[2], a)
return STUCK
if tag == "let":
if not is_value(e[2]):
q = step(e[2])
return STUCK if q == STUCK else ("let", e[1], q, e[3])
return subst(e[3], e[1], e[2])
if tag == "if":
if not is_value(e[1]):
q = step(e[1])
return STUCK if q == STUCK else ("if", q, e[2], e[3])
if e[1][0] == "bool":
return e[2] if e[1][1] else e[3]
return STUCK
if tag == "prim":
a, b = e[2], e[3]
if not is_value(a):
q = step(a)
return STUCK if q == STUCK else ("prim", e[1], q, b)
if not is_value(b):
q = step(b)
return STUCK if q == STUCK else ("prim", e[1], a, q)
if a[0] == "int" and b[0] == "int":
return toylam._prim(e[1], a[1], b[1])
return STUCK
raise ValueError(f"not a term: {e!r}")
def evaluate(e, fuel=10000):
"""Run a target term: ("value", v), ("stuck", t) or ("fuel",)."""
for _ in range(fuel):
if is_value(e):
return ("value", e)
nxt = step(e)
if nxt == STUCK:
return ("stuck", e)
e = nxt
return ("value", e) if is_value(e) else ("fuel",)
def size(e):
tag = e[0]
if tag in ("var", "int", "bool"):
return 1
if tag == "tuple":
return 1 + sum(size(p) for p in e[1])
if tag == "proj":
return 1 + size(e[1])
if tag == "lam":
return 1 + size(e[2])
if tag == "fix":
return 1 + size(e[3])
if tag in ("let", "prim"):
return 1 + size(e[2]) + size(e[3])
return 1 + sum(size(p) for p in e[1:])
def show(e):
"""The surface syntax, with [e0, e1] for a record and e.i for a projection."""
tag = e[0]
if tag == "tuple":
return "[" + ", ".join(show(p) for p in e[1]) + "]"
if tag == "proj":
return f"{show(e[1])}.{e[2]}"
if tag == "var":
return e[1]
if tag == "int":
return str(e[1])
if tag == "bool":
return "true" if e[1] else "false"
if tag == "lam":
return f"(fun {e[1]} -> {show(e[2])})"
if tag == "app":
return f"({show(e[1])} {show(e[2])})"
if tag == "let":
return f"(let {e[1]} = {show(e[2])} in {show(e[3])})"
if tag == "if":
return f"(if {show(e[1])} then {show(e[2])} else {show(e[3])})"
if tag == "prim":
return f"({show(e[2])} {e[1]} {show(e[3])})"
if tag == "fix":
return f"(fix {e[1]} {e[2]} -> {show(e[3])})"
raise ValueError(f"not a term: {e!r}")
toylam.py 285 lines
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy lambda language: terms, types, call-by-value small steps.
Terms are tuples:
("var", x) a variable, x is a str
("lam", x, e) fun x -> e
("app", e1, e2) e1 e2
("let", x, e1, e2) let x = e1 in e2
("int", k) an integer constant, k is a Python int
("bool", b) true or false, b is a Python bool
("if", e1, e2, e3) if e1 then e2 else e3
("prim", op, e1, e2) e1 op e2, op is one of + - * < ==
("fix", f, x, e) a recursive function: f is the function itself, x its argument
Types are tuples:
("int",) ("bool",) ("fun", t1, t2) ("tv", n) with n an int
Values are int and bool constants, lambdas and fix terms. The semantics is
call by value, left to right. step(e) returns the next term when e can step,
e itself when e is a value, and the marker "stuck" otherwise. A free
variable, an application of a non-function, a non-boolean condition and an
operator on non-integers are stuck. Substitution only ever puts closed values
into terms, because evaluation starts from closed terms, so no renaming is
needed.
"""
STUCK = "stuck"
PRIMS = ("+", "-", "*", "<", "==")
def is_value(e):
return e[0] in ("int", "bool", "lam", "fix")
def free_vars(e):
"""The set of free term variables of e."""
tag = e[0]
if tag == "var":
return {e[1]}
if tag == "lam":
return free_vars(e[2]) - {e[1]}
if tag == "app":
return free_vars(e[1]) | free_vars(e[2])
if tag == "let":
return free_vars(e[2]) | (free_vars(e[3]) - {e[1]})
if tag in ("int", "bool"):
return set()
if tag == "if":
return free_vars(e[1]) | free_vars(e[2]) | free_vars(e[3])
if tag == "prim":
return free_vars(e[2]) | free_vars(e[3])
if tag == "fix":
return free_vars(e[3]) - {e[1], e[2]}
raise ValueError(f"not a term: {e!r}")
def subst(e, x, v):
"""Replace the free occurrences of x in e by the closed value v."""
tag = e[0]
if tag == "var":
return v if e[1] == x else e
if tag == "lam":
return e if e[1] == x else ("lam", e[1], subst(e[2], x, v))
if tag == "app":
return ("app", subst(e[1], x, v), subst(e[2], x, v))
if tag == "let":
body = e[3] if e[1] == x else subst(e[3], x, v)
return ("let", e[1], subst(e[2], x, v), body)
if tag in ("int", "bool"):
return e
if tag == "if":
return ("if", subst(e[1], x, v), subst(e[2], x, v), subst(e[3], x, v))
if tag == "prim":
return ("prim", e[1], subst(e[2], x, v), subst(e[3], x, v))
if tag == "fix":
if x in (e[1], e[2]):
return e
return ("fix", e[1], e[2], subst(e[3], x, v))
raise ValueError(f"not a term: {e!r}")
def _prim(op, a, b):
if op == "+":
return ("int", a + b)
if op == "-":
return ("int", a - b)
if op == "*":
return ("int", a * b)
if op == "<":
return ("bool", a < b)
if op == "==":
return ("bool", a == b)
raise ValueError(f"unknown operator {op!r}")
def step(e):
"""One call-by-value step: the next term, e itself if e is a value, or STUCK."""
if is_value(e):
return e
tag = e[0]
if tag == "var":
return STUCK
if tag == "app":
f, a = e[1], e[2]
if not is_value(f):
f2 = step(f)
return STUCK if f2 == STUCK else ("app", f2, a)
if not is_value(a):
a2 = step(a)
return STUCK if a2 == STUCK else ("app", f, a2)
if f[0] == "lam":
return subst(f[2], f[1], a)
if f[0] == "fix":
return subst(subst(f[3], f[1], f), f[2], a)
return STUCK
if tag == "let":
if not is_value(e[2]):
e1 = step(e[2])
return STUCK if e1 == STUCK else ("let", e[1], e1, e[3])
return subst(e[3], e[1], e[2])
if tag == "if":
c = e[1]
if not is_value(c):
c2 = step(c)
return STUCK if c2 == STUCK else ("if", c2, e[2], e[3])
if c[0] == "bool":
return e[2] if c[1] else e[3]
return STUCK
if tag == "prim":
a, b = e[2], e[3]
if not is_value(a):
a2 = step(a)
return STUCK if a2 == STUCK else ("prim", e[1], a2, b)
if not is_value(b):
b2 = step(b)
return STUCK if b2 == STUCK else ("prim", e[1], a, b2)
if a[0] == "int" and b[0] == "int":
return _prim(e[1], a[1], b[1])
return STUCK
raise ValueError(f"not a term: {e!r}")
def evaluate(e, fuel=10000):
"""Run e. Returns ("value", v), ("stuck", t) with the stuck term t, or ("fuel",)."""
for _ in range(fuel):
if is_value(e):
return ("value", e)
nxt = step(e)
if nxt == STUCK:
return ("stuck", e)
e = nxt
return ("value", e) if is_value(e) else ("fuel",)
NAMES = ("x", "y", "z", "f", "g")
def random_term(rng, depth, scope=()):
"""A random term of height at most depth whose free variables are in scope.
With the default empty scope the term is closed. rng is a random.Random.
"""
scope = tuple(scope)
if depth <= 0 or rng.random() < 0.15:
r = rng.random()
if scope and r < 0.6:
return ("var", rng.choice(scope))
if r < 0.8:
return ("int", rng.randint(0, 3))
return ("bool", rng.random() < 0.5)
d = depth - 1
kind = rng.choice(("var", "lam", "lam", "app", "app", "let", "let", "if", "prim", "fix"))
if kind == "var" and scope:
return ("var", rng.choice(scope))
if kind == "lam" or kind == "var":
x = rng.choice(NAMES)
return ("lam", x, random_term(rng, d, scope + (x,)))
if kind == "app":
return ("app", random_term(rng, d, scope), random_term(rng, d, scope))
if kind == "let":
x = rng.choice(NAMES)
return ("let", x, random_term(rng, d, scope), random_term(rng, d, scope + (x,)))
if kind == "if":
return ("if", random_term(rng, d, scope), random_term(rng, d, scope), random_term(rng, d, scope))
if kind == "prim":
return ("prim", rng.choice(PRIMS), random_term(rng, d, scope), random_term(rng, d, scope))
f, x = rng.sample(NAMES, 2)
return ("fix", f, x, random_term(rng, d, scope + (f, x)))
def size(e):
"""The number of nodes of the syntax tree of e."""
tag = e[0]
if tag in ("var", "int", "bool"):
return 1
if tag == "lam":
return 1 + size(e[2])
if tag == "app":
return 1 + size(e[1]) + size(e[2])
if tag == "let":
return 1 + size(e[2]) + size(e[3])
if tag == "if":
return 1 + size(e[1]) + size(e[2]) + size(e[3])
if tag == "prim":
return 1 + size(e[2]) + size(e[3])
if tag == "fix":
return 1 + size(e[3])
raise ValueError(f"not a term: {e!r}")
def show(e):
"""The surface syntax: fun x -> e, e1 e2, let x = e1 in e2."""
tag = e[0]
if tag == "var":
return e[1]
if tag == "int":
return str(e[1])
if tag == "bool":
return "true" if e[1] else "false"
if tag == "lam":
return f"(fun {e[1]} -> {show(e[2])})"
if tag == "app":
return f"({show(e[1])} {show(e[2])})"
if tag == "let":
return f"(let {e[1]} = {show(e[2])} in {show(e[3])})"
if tag == "if":
return f"(if {show(e[1])} then {show(e[2])} else {show(e[3])})"
if tag == "prim":
return f"({show(e[2])} {e[1]} {show(e[3])})"
if tag == "fix":
return f"(fix {e[1]} {e[2]} -> {show(e[3])})"
raise ValueError(f"not a term: {e!r}")
def type_vars(t):
"""The type variables of t, in order of first occurrence, left to right."""
out = []
def go(u):
if u[0] == "tv":
if u[1] not in out:
out.append(u[1])
elif u[0] == "fun":
go(u[1])
go(u[2])
go(t)
return out
def rename_type(t, mapping):
if t[0] == "tv":
return ("tv", mapping.get(t[1], t[1]))
if t[0] == "fun":
return ("fun", rename_type(t[1], mapping), rename_type(t[2], mapping))
return t
def normalize_type(t):
"""Rename the type variables of t to 0, 1, 2, ... in order of first occurrence."""
return rename_type(t, {v: i for i, v in enumerate(type_vars(t))})
def type_size(t):
"""The number of nodes of t as a tree."""
if t[0] == "fun":
return 1 + type_size(t[1]) + type_size(t[2])
return 1
def show_type(t):
"""int, bool, a, b, ... with right-associative arrows."""
if t[0] == "int":
return "int"
if t[0] == "bool":
return "bool"
if t[0] == "tv":
n = t[1]
return chr(ord("a") + n) if 0 <= n < 26 else f"t{n}"
left = show_type(t[1])
if t[1][0] == "fun":
left = f"({left})"
return f"{left} -> {show_type(t[2])}"
test_closure_conversion.py 174 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/closure-conversion/. The authors are listed in prov/EGE7J5.jsonl.
import random
import closure_conversion as cc
import toylam
def v(x):
return ("var", x)
def run(e, fuel, evaluate):
"""evaluate(e, fuel), with a term that grows too deep counted as out of fuel."""
try:
return evaluate(e, fuel)
except RecursionError:
return ("fuel",)
def same_outcome(src, out):
"""Equal int and bool results, a closure record for a function, stuck for stuck."""
if src[0] != out[0]:
return False
if src[0] != "value":
return True
if src[1][0] in ("lam", "fix"):
return out[1][0] == "tuple"
return src[1] == out[1]
def call_closure(w, arg):
"""The target term that calls the closure record w with arg."""
return ("app", ("app", ("proj", w, 0), w), arg)
def code_parts(e):
"""All code terms fun self -> fun x -> body of a target term."""
out = []
tag = e[0]
if tag == "tuple":
out.append(e[1][0])
for p in e[1]:
out += code_parts(p)
elif tag == "lam":
out += code_parts(e[2])
elif tag == "proj":
out += code_parts(e[1])
elif tag in ("let", "prim"):
out += code_parts(e[2]) + code_parts(e[3])
elif tag in ("app", "if"):
for p in e[1:]:
out += code_parts(p)
return out
def lambdas_only_in_code(e, in_code=False):
"""Every fun is the code of a record or the inner fun of such code, and there is no fix."""
tag = e[0]
if tag == "fix":
return False
if tag == "lam":
if not in_code:
return False
inner = e[2]
return inner[0] == "lam" and lambdas_only_in_code(inner[2])
if tag == "tuple":
return lambdas_only_in_code(e[1][0], True) and all(lambdas_only_in_code(p) for p in e[1][1:])
if tag == "proj":
return lambdas_only_in_code(e[1])
if tag in ("let", "prim"):
return lambdas_only_in_code(e[2]) and lambdas_only_in_code(e[3])
if tag in ("app", "if"):
return all(lambdas_only_in_code(p) for p in e[1:])
return True
# ------------------------------------------------------------ page examples
EXAMPLE = (
"let", "a", ("int", 1),
("let", "b", ("int", 2),
("let", "f", ("lam", "x", ("prim", "+", ("prim", "+", v("x"), v("a")), v("b"))),
("app", v("f"), ("int", 10)))),
)
FACT = (
"let", "m", ("int", 1),
("app",
("fix", "f", "n",
("if", ("prim", "<", v("n"), ("int", 1)), v("m"),
("prim", "*", v("n"), ("app", v("f"), ("prim", "-", v("n"), ("int", 1)))))),
("int", 5)),
)
def test_page_example():
out = cc.closure_convert(EXAMPLE)
assert cc.show(out) == (
"(let a = 1 in (let b = 2 in (let f = [(fun self1 -> (fun x -> ((x + self1.1) + self1.2))), a, b]"
" in (let c2 = f in (let a3 = 10 in ((c2.0 c2) a3))))))"
)
assert toylam.evaluate(EXAMPLE) == cc.evaluate(out) == ("value", ("int", 13))
def test_recursion_through_self():
out = cc.closure_convert(FACT)
assert cc.show(out) == (
"(let m = 1 in (let c1 = [(fun self3 -> (fun n -> (if (n < 1) then self3.1 else"
" (n * (let c4 = self3 in (let a5 = (n - 1) in ((c4.0 c4) a5))))))), m]"
" in (let a2 = 5 in ((c1.0 c1) a2))))"
)
assert cc.evaluate(out) == ("value", ("int", 120))
def test_flat_closures_can_be_quadratic():
for k in range(1, 12):
body = v("x1")
for i in range(2, k + 1):
body = ("prim", "+", body, v(f"x{i}"))
for i in range(k, 0, -1):
body = ("lam", f"x{i}", body)
out = cc.closure_convert(body)
captured = sum(len(code_record) - 1 for code_record in records(out))
assert captured == k * (k - 1) // 2
def records(e):
out = []
if e[0] == "tuple":
out.append(e[1])
for p in e[1:]:
if isinstance(p, tuple) and p and isinstance(p[0], str):
out += records(p)
elif isinstance(p, tuple):
for q in p:
out += records(q)
return out
# ------------------------------------------------------------ random terms
def test_random_terms_keep_their_outcome():
rng = random.Random(20261115)
compared = applied = 0
for _ in range(1500):
e = toylam.random_term(rng, 5)
want = run(e, 300, toylam.evaluate)
if want == ("fuel",):
continue
got = run(cc.closure_convert(e), 20000, cc.evaluate)
assert same_outcome(want, got), toylam.show(e)
compared += 1
if want[0] == "value" and want[1][0] in ("lam", "fix"):
for arg in (("int", 0), ("int", 2), ("bool", True)):
w2 = run(("app", want[1], arg), 300, toylam.evaluate)
if w2 == ("fuel",):
continue
assert same_outcome(w2, run(call_closure(got[1], arg), 20000, cc.evaluate))
applied += 1
assert compared > 1400 and applied > 500
def test_code_has_no_free_variable_but_its_environment():
rng = random.Random(7)
for _ in range(1500):
out = cc.closure_convert(toylam.random_term(rng, 6))
assert cc.free_vars(out) == set()
assert lambdas_only_in_code(out)
for code in code_parts(out):
assert cc.free_vars(code) == set()
History
Landin (1964) defined the closure in his SECD machine: the value of a lambda expression is the pair of the expression and the environment in which it was evaluated. Cardelli (1984) described the ML compiler with flat closures that hold the code and the values of the free variables. Appel's book of 1992 presents closure conversion of the Standard ML of New Jersey compiler on a CPS intermediate language. Shao and Appel (1994) studied closure sharing and the safe-for-space rule, and gave the full algorithm in 2000. Minamide, Morrisett and Harper (1996) made the conversion type-preserving, with a proof of correctness by a logical relation.
References
- Peter J. Landin, The mechanical evaluation of expressions, The Computer Journal 6(4), 1964, pages 308-320, the SECD machine, in which the value of a lambda expression is a closure made of the expression and its environment
- Luca Cardelli, Compiling a functional language, Proceedings of the 1984 ACM Symposium on LISP and Functional Programming, pages 208-217, the abstract machine of the ML compiler, whose closures hold the code and copies of the values of the free variables
- Andrew W. Appel, Compiling with Continuations, Cambridge University Press, 1992, the chapter on closure conversion, with flat and linked closures and the closure-passing calling convention
- Zhong Shao and Andrew W. Appel, Space-efficient closure representations, Proceedings of the 1994 ACM Conference on LISP and Functional Programming, pages 150-161, closure sharing, the safe-for-space rule and the comparison of flat and linked closures
- Zhong Shao and Andrew W. Appel, Efficient and safe-for-space closure conversion, ACM Transactions on Programming Languages and Systems 22(1), 2000, pages 129-161, the full closure conversion algorithm of SML/NJ and its measurements
- Yasuhiko Minamide, Greg Morrisett and Robert Harper, Typed closure conversion, Proceedings of the 23rd ACM Symposium on Principles of Programming Languages (POPL 1996), pages 271-283, closure conversion as a type-preserving translation, with environments hidden by existential types, and its correctness proof by a logical relation
- Andrew W. Appel, Modern Compiler Implementation in ML, Cambridge University Press, 1998, the chapter on functional programming languages, the section on closures
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag EGE7J5 Edit this page History Report an error Markdown