Algorithmcore
Lambda lifting
Also called Johnsson lambda lifting.
Moves local functions to the top level and passes their free variables as extra parameters at each call.
- Time
- O(n^3) worstΘ(n) best
- Space
- O(n^2) extra · output
- Where
- n = the number of nodes of the source term
- Model
- Word RAM
- Properties
- deterministicofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
Lambda lifting turns a program with nested functions into a set of global functions that are all closed. A local function that reads variables of an enclosing scope gets those variables as extra parameters, and every place that names the function passes them. After the transformation no function is nested in another, so the program is a set of recursive equations, one per function. Hughes (1982) used this idea to compile functional programs to supercombinators. Johnsson (1985) gave the algorithm with its main difficulty solved: a function must also receive the free variables of every function that it calls, and with mutual recursion these sets depend on each other.
In plain words
A helper function written inside another function often uses names of the outer function. The compiler moves the helper out to the top level and adds those names to its list of parameters. Each call of the helper now hands over the values it needs. If the helper calls a second helper that needs more values, the first helper must take those values too, so that it can pass them on. When helpers call each other in a circle, the compiler repeats this until no helper needs anything new. At the end every function stands alone and reads only its own parameters.
The problem
The input is a closed term of the call-by-value toy language: constants, fun x -> e, calls, let, if, operators, recursive functions fix f x -> e, and groups of mutually recursive functions letrec f1 x1 = e1 and ... and fk xk = ek in e. The output is a set of global definitions F p1 ... pk x = body and a main term. No body and no main term may contain a fun, a fix or a letrec. Every variable in a body must be one of its parameters, and the main term must be closed. The program must have the same outcome as the input. A global applied to fewer arguments than it has parameters is a value, a partial application, and it takes the place of a function value of the source.
The algorithm
For a function , let be its free variables that are not names of functions, and the functions whose names are free in . The extra parameters must satisfy , because calls each and must pass . The least solution is the union of over all that reaches along , which line L4 computes.
LAMBDA-LIFT(e) ▷ e is closed- 1
rename every bound variable of e apart, and give each function f a new global name F - 2
for each function f: D(f) ← free variables of f that name no function; R(f) ← functions named free in f - 3
for each function f - 4
E(f) ← the union of D(g) over every g reachable from f along R, f included - 5
params(f) ← E(f), sorted - 6
for each function f = fun x -> b, or fix f x -> b, or a member f x = b of a letrec - 7
define F params(f) x = LIFT(b) - 8
return the definitions and LIFT(e) LIFT(e)- 9
if e is a variable that names a function g, return G params(g); otherwise return e - 10
if e is a function f, return F params(f) - 11
otherwise apply LIFT to each part of e; a letrec becomes LIFT of its body
Line L1 makes every binder unique, so that adding a parameter never captures a name. Line L9 replaces each use of a function name by the global applied to the extra parameters, which is a value. Line L10 does the same for an anonymous function at the place where it is defined. The extra parameters at those places are in scope, because each variable in is bound around the definition of or around a function that reaches, and those binders enclose the use.
Example
Take let a = 1 in (fix f x -> if x < 1 then a else (fun y -> f y + x) (x - 1)) 3, whose value is 7. Line L1 names the outer function F2 and the inner fun y F5, and renames a, x and y to a1, x4 and y6.
| function | |||
|---|---|---|---|
F2 (fix f x) |
a1 |
none | a1 |
F5 (fun y) |
x4 |
F2 |
x4, a1 |
The inner function does not read a, but it calls f, which needs a, so line L4 adds a1 to it. The output is:
F2 a1 x4 = if x4 < 1 then a1 else F5 a1 x4 (x4 - 1)
F5 a1 x4 y6 = F2 a1 y6 + x4
main = let a1 = 1 in F2 a1 3
Its value is also 7. With mutual recursion the need for line L4 is plainer. In let d = 1 in letrec f n = if n < 1 then 0 else g n and g n = h n and h n = 1 + f (n - d) in f 3, only h reads d, but g calls h and f calls g. Line L4 gives all three the parameter d. With only , g would have to pass d to h without having it, and the program would get stuck.
Correctness
Two facts carry the proof. The first is that the output is well scoped. If , every function that reaches is also reached by , so , and the call of line L9 inside the body of passes only parameters of . For a function defined inside the body of , each variable of is a parameter of or is bound by a let around inside that body. The second fact is a simulation. Relate a source function value made from function to the partial application when each is related to the value of the -th extra parameter, and relate equal constants. An induction on the evaluation, with one case per form, shows that a source term with related values put in for its free variables, and its LIFT, have related outcomes: equal constants, related functions, stuck in both, or no end in both. The call case uses the first fact: the full application steps to the body with exactly the values that the source closure held. The proof file gives both proofs.
Proof: Lambda lifting gives closed global functions and keeps the outcomefull
We use the notation of the page. After line L1 every binder of the term is unique and differs from every free name, and each function (a fun, a fix, or a member of a letrec) has its own global . We write for the parameter of , for the sorted list , and for the term that lines L9 and L10 put in place of .
The source language is evaluated by call-by-value substitution, left to right, and we use the big-step form: means that the run of the closed term ends with , a value or the mark . A stuck part makes the whole run stuck. In the target, with less than the number of parameters of and values is a value, and a full application steps to the body of with the arguments put in for the parameters. Section 3 treats fun and fix; section 4 adds letrec.
1. Scope
Lemma 1. If then .
Proof. Every function reachable from along is reachable from , since reaches . Line L4 takes the union of over these sets.
Say that a variable is visible at a point of the term if a binder (a parameter, a let, a fix or a letrec name) that encloses the point binds it. Since binders are unique, a variable visible at the binder of a function name is visible at every point in the scope of that name.
Lemma 2. Let be a function, and let be the innermost function whose body contains the definition of , if one exists. Each is a parameter in , or is bound by a let that encloses inside the body of . If no exists, each is bound by a let of the main term around .
Proof. Let for a path along . First, is visible at the definition of : is free in and the input is closed, so is visible at the definition of ; for each , the name of is free in , so lies in the scope of that name, and what is visible at the definition of is visible at the definition of . Now suppose exists. If is or is bound by a let inside the body of , we are done. The binder of cannot be the parameter of a function inside the body of , since is the innermost function around . Otherwise is bound outside . If all are defined inside (or are ), then , free in and bound outside , is free in and names no function, so . If not, let be the first that is defined outside . Its name is free in , which is inside , and is bound outside , so and by Lemma 1. Without , is visible at , and the only binders around are lets of the main term.
Corollary. Every body of a definition has no free variable but its parameters, and of the main term is closed. The output has no fun, fix or letrec.
Proof. LIFT keeps variables that name no function, removes every function, and adds the arguments of . A kept variable of is free in (so in ), is , or is bound by a let of . A function defined in has , and Lemma 2 places the arguments of among the parameters of and the lets around it. A use of a function name in is , a function defined in , or ; the first two are as before and the third passes by Lemma 1. The main term is the same with no .
2. Related values
Define between closed source values and closed target values:
- for each integer or boolean constant ;
- if is a function of the renamed term, maps the free variables of to closed source values, , and the target substitution satisfies: for each , and for each .
By Lemma 1, is a closed term , a value. The definition is by induction on the size of the source value, since and are proper parts of . Results are related if both are or both are related values.
An environment for a subterm is a pair of a source substitution on the free variables of and a target substitution such that for each free of that names no function, and is defined on with for each free function name of .
3. The main lemma
Lemma 3. Let be an environment for , a subterm of the renamed term, and let also be defined on the extra parameters of every function defined in that are bound outside . 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, with one case per form.
- A variable that names no function. Both sides are values, .
- A function name (line L9). and , related by the environment.
- A function (line L10). is a value, and is a value, since it lacks the argument . Each is free in , so ; each is free in , so . These are the conditions of , and the side condition on makes defined.
- A call . The pair is an environment for both parts, and LIFT keeps the call. By induction both runs of end with related results or neither ends, and then the same for ; a stuck part is stuck in both. Let the values be and . If is a constant, is the same constant, and both calls are stuck. Otherwise and with as in the definition of . The source steps to , with also if is a
fix. The target is a full application and steps to . Set (and ) and . This is an environment for : a free of that names no function is or lies in ; a free function name of is itself, with , or some , with by Lemma 1. The side condition holds by Lemma 2 with : the extra parameters of a function in that are bound outside are in . The run of the body is a smaller derivation, so the induction hypothesis gives related results. let x = e1 in e2. As for the call, gives or both are stuck. Then is an environment for that meets the side condition: a function in may have as an extra parameter, and now binds it. Since is unique, the new binding hides nothing.- Constants,
ifand operators. Constants map to themselves. A boolean is related only to the same boolean, so both runs ofiftake the same branch, and any other value is stuck in both. Related integers are equal, so operators give equal results; a function is related only to a partial application, and the operators reject both.
The target run uses the runs of the parts in the same order as the source, so part 2 follows from the same case analysis with the induction on the target derivation.
Theorem. For a closed term without letrec, the run of and the run of the main term of LAMBDA-LIFT both end with related results, or both run forever. They give the same integer or boolean, a function value and a partial application, or stuck in both.
Proof. Renaming apart at line L1 does not change the outcome. The empty pair is an environment for the closed renamed term, and Lemma 2 without shows that the extra parameters of a function in the main term are bound by its lets, so the side condition of Lemma 3 holds with empty. Part 1 of Lemma 3 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.
4. Mutual recursion
Give letrec f1 x1 = b1 and ... and fk xk = bk in e its usual meaning: the run of the letrec is the run of , where is the value of , and a call of runs with and all put in. In the relation , a value is then with for the members . That definition is no longer by the size of the value, since appears inside ; read as indexed by the number of steps left, as in a step-indexed relation, where a call uses one step. The cases of Lemma 3 are unchanged, except that a letrec passes to its body with each and unchanged: LIFT removes the letrec, and by Lemma 1 each is defined. The fixed point of line L4 is used exactly here. Without it, could miss a variable of for some , and the call of in the body of would have a free variable. The page shows such a program, which gets stuck.
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. Let be the number of functions. Line L2 walks each function once, each and in all. For each function, line L4 walks the graph , which has at most edges, and unites at most sets of at most variables, so per function and in all. The output adds at most arguments at each of at most places, , and that is reached: in fun x1 -> fun x2 -> ... fun xk -> x1 + ... + xk the function of gets extra parameters. A term without functions takes . The sets take extra space. Danvy and Schultz solve the equations of line L4 in time with the strongly connected components of .
Properties
- First order in form. Every function is global and closed, so a compiler can give each one a fixed address and no environment.
- Function values remain. A local function that escapes becomes a partial application, which the target still has to represent at run time, for example as a record of the global and its arguments.
- No change to the order of evaluation. Extra arguments are variables, so passing them does no work and cannot diverge.
- Same number of calls. Every source call is one target call with more arguments.
Variants and improvements
- Quadratic time. Danvy and Schultz group the functions of into strongly connected components, give all members of a component the same set, and process the components in topological order. Their conference version of 2002 takes time; the 2004 versions take .
- Lambda dropping. The inverse transformation moves global functions back into the scope of their callers and removes the parameters that are the same at every call. Danvy and Schultz study it together with lifting.
- Selective lifting. Compilers such as GHC lift only functions whose extra parameters are few, and keep the others as closures, because many extra arguments cost registers at every call.
- Supercombinators. Hughes also lifts maximal free subexpressions, not only variables, so that work inside a function body can be shared between calls.
When to use it
Use lambda lifting when the target has global functions but no nested ones: the code generators of graph reduction machines, C as a target, and the equations of a partial evaluator. Use it for local functions whose every call site is known, where it avoids allocating a closure. For functions that escape and have many free variables, closure conversion is usually cheaper, because it builds the record once and does not pass every variable at every call.
Pitfalls
- Mutual recursion. The extra parameters of mutually recursive functions depend on each other. Taking only the variables that each function reads leaves calls that must pass values the caller does not have. Compute the least fixed point, as line L4 does by reachability.
- Calls through names. A function must also get the free variables of every function it calls, not only of functions it defines inside it, as
F5in the example shows. - Name capture. Adding a parameter named
ato a function whose body has its ownachanges the meaning. Rename all binders apart first, as line L1 does. - Order of extra parameters. The definition and every call must list them in the same order. Line L5 fixes one order per function.
- Assigned variables. Passing a variable as an argument copies its value. A variable that the source can assign to must be put in a box before lifting.
- Cost of many parameters. Deep nesting gives output, and functions with many free variables make every call slow.
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/lambda-lifting/. The authors are listed in prov/ZHK5BH.jsonl.
"""Johnsson's lambda lifting for the toy lambda language of toylam.py.
lambda_lift(e) returns (defs, main). defs maps a global name F to
(params, body), and main is the term to run. No body and no main contains a
fun or a fix. A source function with extra parameters p1 ... pk becomes the
global F p1 ... pk x, and the function value itself becomes the partial
application F p1 ... pk.
The source may also use ("letrec", ((f1, x1, b1), ..., (fk, xk, bk)), e),
which binds k mutually recursive functions in all the bodies and in e. The
toy evaluator of toylam.py does not run it, but the lifter accepts it, so that
the fixed point over mutual recursion can be tested.
Target terms are the toy terms without "lam" and "fix", plus the leaf
("global", F). A global applied to fewer arguments than its parameters is a
value; applied to all of them, it steps to its body with the arguments put in
for the parameters. evaluate(defs, main) runs a target program.
"""
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])
if tag == "letrec":
out = names(e[2])
for f, x, b in e[1]:
out |= {f, x} | names(b)
return out
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
def prepare(e, fresh):
"""Rename every binder of e apart and turn each fun and fix into
("fn", F, f, x, body), with F a new global name and f the name of the fix
(None for a fun)."""
env = {}
def bind(x):
old = env.get(x)
env[x] = fresh(x)
return env[x], old
def unbind(x, old):
if old is None:
del env[x]
else:
env[x] = old
def go(e):
tag = e[0]
if tag == "var":
return var(env.get(e[1], e[1]))
if tag in ("int", "bool"):
return e
if tag == "lam":
g = fresh("F")
y, old = bind(e[1])
body = go(e[2])
unbind(e[1], old)
return ("fn", g, None, y, body)
if tag == "fix":
g = fresh("F")
f2, old_f = bind(e[1])
y, old_x = bind(e[2])
body = go(e[3])
unbind(e[2], old_x)
unbind(e[1], old_f)
return ("fn", g, f2, y, body)
if tag == "let":
rhs = go(e[2])
y, old = bind(e[1])
body = go(e[3])
unbind(e[1], old)
return ("let", y, rhs, body)
if tag == "prim":
return ("prim", e[1], go(e[2]), go(e[3]))
if tag == "letrec":
gs = [fresh("F") for _ in e[1]]
olds = [bind(f) for f, _, _ in e[1]]
fns = []
for g, (f, x, b) in zip(gs, e[1]):
y, old = bind(x)
fns.append(("fn", g, env[f], y, go(b)))
unbind(x, old)
body = go(e[2])
for (f, _, _), (_, old) in reversed(list(zip(e[1], olds))):
unbind(f, old)
return ("letrec", tuple(fns), body)
return (tag,) + tuple(go(p) for p in e[1:])
return go(e)
def fv(e):
"""Free variables of a prepared term."""
tag = e[0]
if tag == "var":
return {e[1]}
if tag in ("int", "bool"):
return set()
if tag == "fn":
return fv(e[4]) - {e[2], e[3]}
if tag == "let":
return fv(e[2]) | (fv(e[3]) - {e[1]})
if tag == "prim":
return fv(e[2]) | fv(e[3])
if tag == "letrec":
out = fv(e[2])
for fn in e[1]:
out |= fv(fn)
return out - {fn[2] for fn in e[1]}
out = set()
for p in e[1:]:
out |= fv(p)
return out
def functions(e):
"""All ("fn", ...) nodes of a prepared term."""
tag = e[0]
if tag in ("var", "int", "bool"):
return []
if tag == "fn":
return [e] + functions(e[4])
if tag in ("let", "prim"):
return functions(e[2]) + functions(e[3])
if tag == "letrec":
out = []
for fn in e[1]:
out += functions(fn)
return out + functions(e[2])
out = []
for p in e[1:]:
out += functions(p)
return out
def call(g, args):
out = ("global", g)
for a in args:
out = ("app", out, var(a))
return out
def reachable(start, refs):
"""The globals reachable from start along refs, start included."""
seen, stack = {start}, [start]
while stack:
for g in refs[stack.pop()]:
if g not in seen:
seen.add(g)
stack.append(g)
return seen
def lambda_lift(e, transitive=True):
"""Lift every function of the closed term e to the top level: (defs, main).
With transitive=False each function gets only its own free variables as
extra parameters. That is wrong in general; it exists to show why line L4
is needed."""
fresh = Fresh(names(e))
e = prepare(e, fresh) # @line L1
fns = functions(e)
global_of = {fn[2]: fn[1] for fn in fns if fn[2] is not None}
direct, refs = {}, {}
for fn in fns: # @line L2
free = fv(fn)
direct[fn[1]] = {y for y in free if y not in global_of}
refs[fn[1]] = [global_of[y] for y in free if y in global_of]
extra = {}
for fn in fns: # @line L3
extra[fn[1]] = set(direct[fn[1]])
if transitive:
for g in reachable(fn[1], refs): # @line L4
extra[fn[1]] |= direct[g]
params = {g: sorted(s) for g, s in extra.items()} # @line L5
def lift(e):
tag = e[0]
if tag == "var": # @line L9
g = global_of.get(e[1])
return e if g is None else call(g, params[g])
if tag == "fn": # @line L10
return call(e[1], params[e[1]])
if tag in ("int", "bool"): # @line L11
return e
if tag == "let":
return ("let", e[1], lift(e[2]), lift(e[3]))
if tag == "prim":
return ("prim", e[1], lift(e[2]), lift(e[3]))
if tag == "letrec":
return lift(e[2])
return (tag,) + tuple(lift(p) for p in e[1:])
defs = {}
for fn in fns: # @line L6
defs[fn[1]] = (params[fn[1]] + [fn[3]], lift(fn[4])) # @line L7
return defs, lift(e) # @line L8
# ------------------------------------------------------------ the target language
def spine(e):
"""(head, args) of a chain of calls."""
args = []
while e[0] == "app":
args.append(e[2])
e = e[1]
return e, args[::-1]
def is_value(e, defs):
tag = e[0]
if tag in ("int", "bool", "global"):
return True
if tag != "app":
return False
head, args = spine(e)
return head[0] == "global" and len(args) < len(defs[head[1]][0]) and all(is_value(a, defs) for a in args)
def subst(e, x, v):
"""Replace the free occurrences of x in the target term 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", "global"):
return e
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 == "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, defs):
"""One call-by-value step of a target term: the next term, e if e is a value, or STUCK."""
if is_value(e, defs):
return e
tag = e[0]
if tag == "var":
return STUCK
if tag == "app":
f, a = e[1], e[2]
if not is_value(f, defs):
q = step(f, defs)
return STUCK if q == STUCK else ("app", q, a)
if not is_value(a, defs):
q = step(a, defs)
return STUCK if q == STUCK else ("app", f, q)
head, args = spine(e)
if head[0] != "global":
return STUCK
ps, body = defs[head[1]]
for p, arg in zip(ps, args):
body = subst(body, p, arg)
return body
if tag == "let":
if not is_value(e[2], defs):
q = step(e[2], defs)
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], defs):
q = step(e[1], defs)
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, defs):
q = step(a, defs)
return STUCK if q == STUCK else ("prim", e[1], q, b)
if not is_value(b, defs):
q = step(b, defs)
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(defs, e, fuel=10000):
"""Run the target program: ("value", v), ("stuck", t) or ("fuel",)."""
for _ in range(fuel):
if is_value(e, defs):
return ("value", e)
nxt = step(e, defs)
if nxt == STUCK:
return ("stuck", e)
e = nxt
return ("value", e) if is_value(e, defs) else ("fuel",)
def show(e):
"""The surface syntax of a target term; a global is written by its name."""
if e[0] == "global":
return e[1]
if e[0] == "app":
head, args = spine(e)
return "(" + " ".join(show(p) for p in [head] + args) + ")"
if e[0] in ("let", "if", "prim"):
parts = list(e)
start = 2 if e[0] in ("let", "prim") else 1
for i in range(start, len(parts)):
parts[i] = ("var", show(parts[i]))
return toylam.show(tuple(parts))
return toylam.show(e)
def show_program(defs, main):
lines = [f"{g} {' '.join(ps)} = {show(body)}" for g, (ps, body) in defs.items()]
return lines + [f"main = {show(main)}"]
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_lambda_lifting.py 177 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lambda-lifting/. The authors are listed in prov/ZHK5BH.jsonl.
import random
import lambda_lifting as ll
import toylam
def v(x):
return ("var", x)
def n(k):
return ("int", k)
def run(evaluate, *args):
"""evaluate(*args), with a term that grows too deep counted as out of fuel."""
try:
return evaluate(*args)
except RecursionError:
return ("fuel",)
def same_outcome(src, out):
"""Equal int and bool results, a global or a partial call 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 ll.spine(out[1])[0][0] == "global"
return src[1] == out[1]
def target_fv(e):
tag = e[0]
if tag == "var":
return {e[1]}
if tag in ("int", "bool", "global"):
return set()
if tag == "let":
return target_fv(e[2]) | (target_fv(e[3]) - {e[1]})
if tag == "prim":
return target_fv(e[2]) | target_fv(e[3])
assert tag in ("app", "if"), tag
out = set()
for p in e[1:]:
out |= target_fv(p)
return out
def first_order(e):
"""No fun, fix or letrec anywhere in a target term."""
tag = e[0]
if tag in ("lam", "fix", "letrec"):
return False
if tag in ("var", "int", "bool", "global"):
return True
start = 2 if tag in ("let", "prim") else 1
return all(first_order(p) for p in e[start:])
def check_top_level(defs, main):
assert first_order(main) and target_fv(main) == set()
for params, body in defs.values():
assert first_order(body)
assert target_fv(body) <= set(params)
# ------------------------------------------------------------ page examples
EXAMPLE = (
"let", "a", n(1),
("app",
("fix", "f", "x",
("if", ("prim", "<", v("x"), n(1)), v("a"),
("app", ("lam", "y", ("prim", "+", ("app", v("f"), v("y")), v("x"))), ("prim", "-", v("x"), n(1))))),
n(3)),
)
SIMPLE = (
"let", "a", n(1),
("let", "b", n(2),
("let", "f", ("lam", "x", ("prim", "+", ("prim", "+", v("x"), v("a")), v("b"))),
("app", v("f"), n(10)))),
)
MUTUAL = (
"let", "d", n(1),
("letrec",
(("f", "n", ("if", ("prim", "<", v("n"), n(1)), n(0), ("app", v("g"), v("n")))),
("g", "n", ("app", v("h"), v("n"))),
("h", "n", ("prim", "+", n(1), ("app", v("f"), ("prim", "-", v("n"), v("d")))))),
("app", v("f"), n(3))),
)
def test_page_example():
defs, main = ll.lambda_lift(EXAMPLE)
assert ll.show_program(defs, main) == [
"F2 a1 x4 = (if (x4 < 1) then a1 else (F5 a1 x4 (x4 - 1)))",
"F5 a1 x4 y6 = ((F2 a1 y6) + x4)",
"main = (let a1 = 1 in (F2 a1 3))",
]
assert toylam.evaluate(EXAMPLE) == ll.evaluate(defs, main) == ("value", n(7))
check_top_level(defs, main)
def test_function_value_becomes_partial_call():
defs, main = ll.lambda_lift(SIMPLE)
assert ll.show_program(defs, main) == [
"F3 a1 b2 x4 = ((x4 + a1) + b2)",
"main = (let a1 = 1 in (let b2 = 2 in (let f5 = (F3 a1 b2) in (f5 10))))",
]
assert toylam.evaluate(SIMPLE) == ll.evaluate(defs, main) == ("value", n(13))
def test_mutual_recursion_needs_the_fixed_point():
defs, main = ll.lambda_lift(MUTUAL)
assert ll.show_program(defs, main) == [
"F2 d1 n8 = (if (n8 < 1) then 0 else (F3 d1 n8))",
"F3 d1 n9 = (F4 d1 n9)",
"F4 d1 n10 = (1 + (F2 d1 (n10 - d1)))",
"main = (let d1 = 1 in (F2 d1 3))",
]
assert ll.evaluate(defs, main) == ("value", n(3))
check_top_level(defs, main)
# With only their own free variables, f and g get no parameter d,
# and the call of g inside f then passes an unbound d.
defs1, main1 = ll.lambda_lift(MUTUAL, transitive=False)
assert ll.show_program(defs1, main1) == [
"F2 n8 = (if (n8 < 1) then 0 else (F3 n8))",
"F3 n9 = (F4 d1 n9)",
"F4 d1 n10 = (1 + (F2 (n10 - d1)))",
"main = (let d1 = 1 in (F2 3))",
]
assert target_fv(defs1["F3"][1]) == {"d1", "n9"}
assert ll.evaluate(defs1, main1)[0] == "stuck"
# ------------------------------------------------------------ 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(toylam.evaluate, e, 300)
if want == ("fuel",):
continue
defs, main = ll.lambda_lift(e)
got = run(ll.evaluate, defs, main, 20000)
assert same_outcome(want, got), toylam.show(e)
compared += 1
if want[0] == "value" and want[1][0] in ("lam", "fix"):
for arg in (n(0), n(2), ("bool", True)):
w2 = run(toylam.evaluate, ("app", want[1], arg), 300)
if w2 == ("fuel",):
continue
assert same_outcome(w2, run(ll.evaluate, defs, ("app", got[1], arg), 20000))
applied += 1
assert compared > 1400 and applied > 300
def test_every_function_is_at_the_top_level():
rng = random.Random(7)
lifted = 0
for _ in range(1500):
e = toylam.random_term(rng, 6)
defs, main = ll.lambda_lift(e)
check_top_level(defs, main)
lifted += len(defs)
assert lifted > 1000
History
Hughes (1982) introduced supercombinators: closed functions, applied to their free variables, into which a functional program can be translated for graph reduction. Johnsson (1985) defined lambda lifting as the translation of block-structured programs into recursive equations, and set up the equations for the extra parameters of mutually recursive functions. Danvy and Schultz showed that the usual way to solve these equations is cubic, and gave an algorithm in time at FLOPS 2002 and in time in the 2004 versions of the paper.
References
- Thomas Johnsson, Lambda lifting, transforming programs to recursive equations, Functional Programming Languages and Computer Architecture (FPCA 1985), LNCS, pages 190-203, the algorithm, with the extra parameters of mutually recursive functions found as the least solution of a set of equations
- R. J. M. Hughes, Super-combinators, a new implementation method for applicative languages, Proceedings of the 1982 ACM Symposium on LISP and Functional Programming, pages 1-10, the translation of a program into supercombinators, closed functions that are applied to their free variables
- Olivier Danvy and Ulrik P. Schultz, Lambda-lifting in quadratic time, BRICS Report Series RS-04-12, 2004, the analysis of the cubic cost of the equations, and an algorithm that solves them in quadratic time with strongly connected components of the call graph
- Olivier Danvy and Ulrik P. Schultz, Lambda-lifting in quadratic time, Journal of Functional and Logic Programming, 2004, the journal version of the quadratic-time algorithm
- Olivier Danvy and Ulrik P. Schultz, Lambda-lifting in quadratic time, Sixth International Symposium on Functional and Logic Programming (FLOPS 2002), LNCS, the conference version, whose algorithm takes O(n^2 log n) time
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 ZHK5BH Edit this page History Report an error Markdown