Algorithm Search⌘K

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
Properties
deterministicofflinerecursive

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 ff, let D(f)D(f) be its free variables that are not names of functions, and R(f)R(f) the functions whose names are free in ff. The extra parameters E(f)E(f) must satisfy E(f)⊇D(f)∪⋃g∈R(f)E(g)E(f) \supseteq D(f) \cup \bigcup_{g \in R(f)} E(g), because ff calls each gg and must pass E(g)E(g). The least solution is the union of D(g)D(g) over all gg that ff reaches along RR, which line L4 computes.

  1. LAMBDA-LIFT(e) ▷ e is closed
  2. 1rename every bound variable of e apart, and give each function f a new global name F
  3. 2for each function f: D(f) ← free variables of f that name no function; R(f) ← functions named free in f
  4. 3for each function f
  5. 4E(f) ← the union of D(g) over every g reachable from f along R, f included
  6. 5params(f) ← E(f), sorted
  7. 6for each function f = fun x -> b, or fix f x -> b, or a member f x = b of a letrec
  8. 7define F params(f) x = LIFT(b)
  9. 8return the definitions and LIFT(e)
  10. LIFT(e)
  11. 9if e is a variable that names a function g, return G params(g); otherwise return e
  12. 10if e is a function f, return F params(f)
  13. 11otherwise 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 E(f)E(f) is bound around the definition of ff or around a function that ff 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 DD RR EE
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 DD, 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 g∈R(f)g \in R(f), every function that gg reaches is also reached by ff, so E(g)⊆E(f)E(g) \subseteq E(f), and the call of line L9 inside the body of ff passes only parameters of ff. For a function ψ\psi defined inside the body of ff, each variable of E(ψ)E(\psi) is a parameter of ff or is bound by a let around ψ\psi inside that body. The second fact is a simulation. Relate a source function value made from function ff to the partial application F w1…wkF\ w_1 \dots w_k when each wiw_i is related to the value of the ii-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 F w1…wk aF\ w_1 \dots w_k\ a 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 ff (a fun, a fix, or a member of a letrec) has its own global FF. We write xfx_f for the parameter of ff, params(f)\mathrm{params}(f) for the sorted list E(f)E(f), and g^\hat g for the term G params(g)G\ \mathrm{params}(g) that lines L9 and L10 put in place of gg.

The source language is evaluated by call-by-value substitution, left to right, and we use the big-step form: e⇓re \Downarrow r means that the run of the closed term ee ends with rr, a value or the mark stuck\mathsf{stuck}. A stuck part makes the whole run stuck. In the target, G w1…wjG\ w_1 \dots w_j with jj less than the number of parameters of GG and values wiw_i is a value, and a full application steps to the body of GG with the arguments put in for the parameters. Section 3 treats fun and fix; section 4 adds letrec.

1. Scope

Lemma 1. If g∈R(f)g \in R(f) then E(g)⊆E(f)E(g) \subseteq E(f).

Proof. Every function reachable from gg along RR is reachable from ff, since ff reaches gg. Line L4 takes the union of DD over these sets. □\square

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 gg is visible at every point in the scope of that name.

Lemma 2. Let ψ\psi be a function, and let χ\chi be the innermost function whose body contains the definition of ψ\psi, if one exists. Each y∈E(ψ)y \in E(\psi) is a parameter in E(χ)∪{xχ}E(\chi) \cup \{x_\chi\}, or is bound by a let that encloses ψ\psi inside the body of χ\chi. If no χ\chi exists, each y∈E(ψ)y \in E(\psi) is bound by a let of the main term around ψ\psi.

Proof. Let y∈D(g)y \in D(g) for a path ψ=g0,g1,…,gk=g\psi = g_0, g_1, \dots, g_k = g along RR. First, yy is visible at the definition of ψ\psi: yy is free in gkg_k and the input is closed, so yy is visible at the definition of gkg_k; for each ii, the name of gi+1g_{i+1} is free in gig_i, so gig_i lies in the scope of that name, and what is visible at the definition of gi+1g_{i+1} is visible at the definition of gig_i. Now suppose χ\chi exists. If yy is xχx_\chi or is bound by a let inside the body of χ\chi, we are done. The binder of yy cannot be the parameter of a function inside the body of χ\chi, since χ\chi is the innermost function around ψ\psi. Otherwise yy is bound outside χ\chi. If all gig_i are defined inside χ\chi (or are χ\chi), then yy, free in gkg_k and bound outside χ\chi, is free in χ\chi and names no function, so y∈D(χ)⊆E(χ)y \in D(\chi) \subseteq E(\chi). If not, let gig_i be the first that is defined outside χ\chi. Its name is free in gi−1g_{i-1}, which is inside χ\chi, and is bound outside χ\chi, so gi∈R(χ)g_i \in R(\chi) and y∈E(gi)⊆E(χ)y \in E(g_i) \subseteq E(\chi) by Lemma 1. Without χ\chi, yy is visible at ψ\psi, and the only binders around ψ\psi are lets of the main term. □\square

Corollary. Every body LIFT(b)\mathrm{LIFT}(b) of a definition F params(f) xfF\ \mathrm{params}(f)\ x_f has no free variable but its parameters, and LIFT(e)\mathrm{LIFT}(e) 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 g^\hat g. A kept variable yy of bb is free in ff (so in D(f)D(f)), is xfx_f, or is bound by a let of bb. A function ψ\psi defined in bb has χ=f\chi = f, and Lemma 2 places the arguments of ψ^\hat\psi among the parameters of FF and the lets around it. A use of a function name gg in bb is g=fg = f, a function defined in bb, or g∈R(f)g \in R(f); the first two are as before and the third passes E(g)⊆E(f)E(g) \subseteq E(f) by Lemma 1. The main term is the same with no χ\chi. □\square

Define v∼wv \sim w between closed source values and closed target values:

  • c∼cc \sim c for each integer or boolean constant cc;
  • f[σ]∼F w1…wkf[\sigma] \sim F\ w_1 \dots w_k if ff is a function of the renamed term, σ\sigma maps the free variables of ff to closed source values, params(f)=p1,…,pk\mathrm{params}(f) = p_1, \dots, p_k, and the target substitution γ={pi↦wi}\gamma = \{p_i \mapsto w_i\} satisfies: σ(y)∼γ(y)\sigma(y) \sim \gamma(y) for each y∈D(f)y \in D(f), and σ(g)∼g^[γ]\sigma(g) \sim \hat g[\gamma] for each g∈R(f)g \in R(f).

By Lemma 1, g^[γ]\hat g[\gamma] is a closed term G wj1…wjlG\ w_{j_1} \dots w_{j_l}, a value. The definition is by induction on the size of the source value, since σ(y)\sigma(y) and σ(g)\sigma(g) are proper parts of f[σ]f[\sigma]. Results are related if both are stuck\mathsf{stuck} or both are related values.

An environment for a subterm ee is a pair of a source substitution σ\sigma on the free variables of ee and a target substitution γ\gamma such that σ(y)∼γ(y)\sigma(y) \sim \gamma(y) for each free yy of ee that names no function, and γ\gamma is defined on E(g)E(g) with σ(g)∼g^[γ]\sigma(g) \sim \hat g[\gamma] for each free function name gg of ee.

3. The main lemma

Lemma 3. Let (σ,γ)(\sigma, \gamma) be an environment for ee, a subterm of the renamed term, and let γ\gamma also be defined on the extra parameters of every function defined in ee that are bound outside ee. Write T=LIFT(e)[γ]T = \mathrm{LIFT}(e)[\gamma].

  1. If e[σ]⇓re[\sigma] \Downarrow r then T⇓r′T \Downarrow r' with r∼r′r \sim r'.
  2. If T⇓r′T \Downarrow r' then e[σ]⇓re[\sigma] \Downarrow r with r∼r′r \sim r'.

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 yy that names no function. Both sides are values, σ(y)∼γ(y)\sigma(y) \sim \gamma(y).
  • A function name gg (line L9). e[σ]=σ(g)e[\sigma] = \sigma(g) and T=g^[γ]T = \hat g[\gamma], related by the environment.
  • A function ff (line L10). e[σ]=f[σ]e[\sigma] = f[\sigma] is a value, and T=F γ(p1)…γ(pk)T = F\ \gamma(p_1) \dots \gamma(p_k) is a value, since it lacks the argument xfx_f. Each y∈D(f)y \in D(f) is free in ee, so σ(y)∼γ(y)\sigma(y) \sim \gamma(y); each g∈R(f)g \in R(f) is free in ee, so σ(g)∼g^[γ]\sigma(g) \sim \hat g[\gamma]. These are the conditions of ∼\sim, and the side condition on γ\gamma makes γ(pi)\gamma(p_i) defined.
  • A call e1 e2e_1\ e_2. The pair is an environment for both parts, and LIFT keeps the call. By induction both runs of e1e_1 end with related results or neither ends, and then the same for e2e_2; a stuck part is stuck in both. Let the values be v1∼w1v_1 \sim w_1 and v2∼w2v_2 \sim w_2. If v1v_1 is a constant, w1w_1 is the same constant, and both calls are stuck. Otherwise v1=f[σ1]v_1 = f[\sigma_1] and w1=F w1′…wk′w_1 = F\ w_1' \dots w_k' with γ1={pi↦wi′}\gamma_1 = \{p_i \mapsto w_i'\} as in the definition of ∼\sim. The source steps to b[σ1,xf:=v2]b[\sigma_1, x_f := v_2], with also f:=v1f := v_1 if ff is a fix. The target F w1′…wk′ w2F\ w_1' \dots w_k'\ w_2 is a full application and steps to LIFT(b)[γ1,xf:=w2]\mathrm{LIFT}(b)[\gamma_1, x_f := w_2]. Set σ′=σ1∪{xf↦v2}\sigma' = \sigma_1 \cup \{x_f \mapsto v_2\} (and f↦v1f \mapsto v_1) and γ′=γ1∪{xf↦w2}\gamma' = \gamma_1 \cup \{x_f \mapsto w_2\}. This is an environment for bb: a free yy of bb that names no function is xfx_f or lies in D(f)D(f); a free function name of bb is ff itself, with f^[γ′]=w1∼v1\hat f[\gamma'] = w_1 \sim v_1, or some g∈R(f)g \in R(f), with E(g)⊆E(f)E(g) \subseteq E(f) by Lemma 1. The side condition holds by Lemma 2 with χ=f\chi = f: the extra parameters of a function in bb that are bound outside bb are in E(f)∪{xf}E(f) \cup \{x_f\}. 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, e1e_1 gives v1∼w1v_1 \sim w_1 or both are stuck. Then (σ[x↦v1],γ[x↦w1])(\sigma[x \mapsto v_1], \gamma[x \mapsto w_1]) is an environment for e2e_2 that meets the side condition: a function in e2e_2 may have xx as an extra parameter, and γ\gamma now binds it. Since xx is unique, the new binding hides nothing.
  • Constants, if and operators. Constants map to themselves. A boolean is related only to the same boolean, so both runs of if take 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. □\square

Theorem. For a closed term ee without letrec, the run of ee and the run of the main term of LAMBDA-LIFT(e)(e) 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 χ\chi 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 γ\gamma 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. □\square

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 e[f1:=u1,…,fk:=uk]e[f_1 := u_1, \dots, f_k := u_k], where uiu_i is the value of fif_i, and a call of uiu_i runs bib_i with xix_i and all uju_j put in. In the relation ∼\sim, a value uiu_i is then fi[σ]f_i[\sigma] with σ(fj)=uj\sigma(f_j) = u_j for the members fj∈R(fi)f_j \in R(f_i). That definition is no longer by the size of the value, since uiu_i appears inside σ\sigma; read ∼\sim 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 σ(fi)=ui\sigma(f_i) = u_i and γ\gamma unchanged: LIFT removes the letrec, and by Lemma 1 each f^i[γ]\hat f_i[\gamma] is defined. The fixed point of line L4 is used exactly here. Without it, E(fi)E(f_i) could miss a variable of E(fj)E(f_j) for some fj∈R(fi)f_j \in R(f_i), and the call of f^j\hat f_j in the body of FiF_i 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 m≤nm \le n be the number of functions. Line L2 walks each function once, O(n)O(n) each and O(n2)O(n^2) in all. For each function, line L4 walks the graph RR, which has at most m2m^2 edges, and unites at most mm sets of at most nn variables, so O(n2)O(n^2) per function and O(n3)O(n^3) in all. The output adds at most nn arguments at each of at most nn places, O(n2)O(n^2), and that is reached: in fun x1 -> fun x2 -> ... fun xk -> x1 + ... + xk the function of xix_i gets i−1i - 1 extra parameters. A term without functions takes Θ(n)\Theta(n). The sets EE take O(n2)O(n^2) extra space. Danvy and Schultz solve the equations of line L4 in O(n2)O(n^2) time with the strongly connected components of RR.

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 RR 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 O(n2log⁡n)O(n^2 \log n) time; the 2004 versions take O(n2)O(n^2).
  • 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 F5 in the example shows.
  • Name capture. Adding a parameter named a to a function whose body has its own a changes 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 Θ(n2)\Theta(n^2) 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.

lambda_lifting.pyI0RawGitHub
# 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 O(n2log⁡n)O(n^2 \log n) time at FLOPS 2002 and in O(n2)O(n^2) time in the 2004 versions of the paper.

References

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
  • a full proof of space.output
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)
WritingW2 basic
  • History with a source
  • a scene preset for the example