Algorithmcore
CPS conversion
Also called CPS transformation, Plotkin CPS translation.
Translates a direct-style program into continuation-passing style, in one pass without administrative redexes by the Danvy-Filinski method.
- Time
- O(n) worstΘ(n) best
- Space
- O(n) extra · output
- Where
- n = the number of nodes of the source term
- Model
- Word RAM
- Properties
- deterministicofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
CPS conversion rewrites a program into continuation-passing style: every function gets one more argument, its continuation, and calls it with its result instead of returning. In the output every call is a tail call, the order of evaluation is written into the code, and every intermediate value has a name. Plotkin (1975) gave the translation rule by rule and proved it correct, but his rules leave many administrative redexes: calls of small functions that the translation itself made and that only pass values along. Danvy and Filinski (1990, 1992) moved those calls into the translator. Their one-pass translation keeps the continuation of the term it is translating as a function of the translator, so the output has no administrative redex and no extra η-redex at tail calls. It runs in linear time and its output has linear size.
In plain words
A normal program says: compute this, then give the result back to whoever asked. In continuation-passing style no function gives a result back. Each function gets one more argument, the continuation, which says what to do with the result, and the function calls it at the end. CPS conversion rewrites a program into that form. The simple rewrite, rule by rule, makes many tiny helper functions that only pass a value along. The one-pass method keeps those helpers inside the translator. They run while the program is translated and never appear in the output, so the output is about as small as the input.
The problem
The input is a closed term of a call-by-value lambda calculus with integer and boolean constants, fun x -> e, calls e1 e2, let x = e1 in e2, if, the operators + - * < == and recursive functions fix f x -> e, which evaluates from left to right. A term is trivial if it is a variable, a constant or a function. The output is a term of the same language with these properties:
- It has the same outcome: the same integer or boolean result, a function if the source gives a function, a stuck term if the source gets stuck, and no result if the source loops.
- Every call is a tail call whose operator and arguments are trivial: the call
f v kis the last thing that its function body does. - A source function
fun x -> ebecomesfun x -> fun k -> e', a function that takes its argument and then its continuation.
Plotkin's call-by-value translation maps each term to a function of a continuation :
The program is . Constants follow the rule for variables, and let, if and the operators get rules of the same shape. The rules are correct, but each of them makes new redexes such as . For the term (f x) (g y), the result has 6 of these redexes and 46 nodes, and it reduces at run time to f x (fun a -> g y (fun b -> a b k)). The goal is to give that reduced term at once, in one pass.
The algorithm
The translator has two kinds of functions. A word in fun is code of the output. A λ is a function of the translator, a meta-continuation, which runs now: it takes a trivial output term, the name or value of a result, and returns the output code that uses that result. TAIL translates a term whose continuation is an output variable . META translates a term whose continuation is a meta-continuation .
CPS(e) ▷ e is closed; the result returns the value of e- 1
rename every bound variable of e to a new name - 2
k0, a ← new names - 3
return let k0 = (fun a -> a) in TAIL(e, k0) VAL(v) ▷ v is trivial: a variable, a constant or a function- 4
if v is a variable or a constant then return v - 5
if v is fun x -> b then return fun x -> fun k -> TAIL(b, k) ▷ k new - 6
if v is fix f x -> b then return fix f x -> fun k -> TAIL(b, k) ▷ k new TAIL(e, k) ▷ k is an output variable that receives the value of e- 7
if e is trivial then return k VAL(e) - 8
if e is e1 e2 then return META(e1, λa. META(e2, λb. a b k)) - 9
if e is let x = e1 in e2 then return META(e1, λa. let x = a in TAIL(e2, k)) - 10
if e is if e1 then e2 else e3 then return META(e1, λa. if a then TAIL(e2, k) else TAIL(e3, k)) - 11
if e is e1 op e2 then return META(e, λa. k a) META(e, κ) ▷ κ maps a trivial output term to output code- 12
if e is trivial then return κ(VAL(e)) - 13
if e is e1 e2 then return META(e1, λa. META(e2, λb. a b (fun t -> κ(t)))) ▷ t new - 14
if e is let x = e1 in e2 then return META(e1, λa. let x = a in META(e2, κ)) - 15
if e is if e1 then e2 else e3 then return META(e1, λa. let j = (fun t -> κ(t)) in if a then TAIL(e2, j) else TAIL(e3, j)) ▷ j, t new - 16
if e is e1 op e2 then return META(e1, λa. META(e2, λb. let t = a op b in κ(t))) ▷ t new
Line L1 makes every binder unique. This matters because META puts the code of under binders that come from the term it translates, for example under let x = a at line L14. Line L13 is the only place where a meta-continuation turns into output code: a call that is not in tail position needs a real continuation, so is applied once to a new variable and wrapped in fun t -> .... Line L8 gives the same call in tail position, and there the continuation is the variable itself, with no fun t -> k t around it. Line L15 binds the continuation of an if to a join point before the branch, so that is used once and not copied into both branches.
Example
Take let f = fun x -> x + 1 in f (f 2), with 10 nodes. Line L1 renames x to x1 and f to f2, and line L3 calls TAIL with k3. Line L9 gives let f2 = VAL(fun x1 -> x1 + 1) in ..., and line L5 translates the body x1 + 1 with a new continuation k5. For the body f2 (f2 2) line L8 asks META for f2, which at line L12 hands f2 to its λ at once. That λ asks META for f2 2, a call in a non-tail position, so line L13 makes t7 and builds the call f2 2 (fun t7 -> ...), whose body is the code for the outer call in tail position. The result has 23 nodes:
let k3 = fun a4 -> a4 in
let f2 = fun x1 -> fun k5 -> let t6 = x1 + 1 in k5 t6 in
f2 2 (fun t7 -> f2 t7 k3)
| step | term being run |
|---|---|
| 1 | f2 2 (fun t7 -> f2 t7 k3) after the two lets |
| 2 | let t6 = 2 + 1 in (fun t7 -> f2 t7 k3) t6 |
| 3 | (fun t7 -> f2 t7 k3) 3 |
| 4 | f2 3 k3 |
| 5 | let t6 = 3 + 1 in k3 t6, then k3 4, then 4 |
Every call is the last thing done, so a machine that runs this needs no return stack. Plotkin's rules give 66 nodes for the same term, with 9 administrative redexes in the output and more that appear while they are reduced. Applied to a continuation variable k and with all of these redexes reduced, Plotkin's term for the source becomes let f2 = (fun x1 -> fun k15 -> let t18 = x1 + 1 in k15 t18) in f2 2 (fun v7 -> f2 v7 k), which is TAIL(e, k) up to the names of bound variables.
Correctness
Plotkin proved that his translation simulates call-by-value evaluation: for a closed term , has the same outcome as , where a function result maps to its image. His proof uses the colon translation , which is with the administrative steps at the head already done. One source step from to takes to in one or more steps, and the image of a value is applied to the image of . The one-pass translation computes the same term with every administrative redex reduced, also the ones under fun: by induction on , the output of TAIL is the administrative normal form of , and META is the normal form of . The join point of line L15 is one more redex let j = ... whose right side is a value. Every redex that is removed in this way has a value as its argument, so it is a step, and Plotkin showed that steps keep the outcome of call-by-value programs. Every call in the output is a tail call, because each line places a call at a position where the code of its continuation would go, and the λ functions put only let, if and calls there. The proof file gives these arguments in detail.
Proof: The one-pass CPS conversion keeps the outcome and makes no administrative redexesfull
We use the notation of the page. Source terms are closed and their binders are renamed apart by line L1, so no substitution below can capture a name. A trivial term is a variable, a constant, fun or fix. An administrative redex is a redex whose operator is a fun that the translation made, that is a fun k -> ..., a continuation fun a -> ... or fun t -> ..., and not the image of a source function. We extend Plotkin's translation to the whole language with the rules of the code:
- for trivial , where , , and ;
- ;
- ;
- ;
- .
The outcome of a closed term is an integer or boolean value, "a function", "stuck" or "no result". The proof has three parts. Part 1 is Plotkin's simulation theorem, given as a sketch in his style. Part 2 shows that the one-pass output is Plotkin's output with administrative redexes reduced. Part 3 shows that those reductions keep the outcome. Parts 4 to 6 prove the structural claims.
1. Plotkin's simulation (sketch)
Let range over closed continuation values. Plotkin's colon translation is defined on the shape of in evaluation order:
- for a value ;
- if is not a value;
- if is not a value;
- ;
and in the same way for let, if and the operators.
Lemma 1.1. .
Proof. By induction on . Each step is an administrative redex at the head: is a fun k, it takes , and then the translation of the first part of that is not a value takes the continuation that the rule builds. When that part is a value, the step moves on to the next part.
Lemma 1.2 (substitution). For a value , , and the same for .
Proof. By induction on . A variable is the only case that inspects , and becomes .
Lemma 1.3. If in one call-by-value step, then . If is stuck, then is stuck after finitely many steps.
Proof. The colon translation follows the evaluation context, so with redex gives , where depends only on and . For , by Lemma 1.2, and Lemma 1.1 continues to . A fix call is the same with two substitutions. For let x = v in b the step let x = Ψ(v) in b K_E goes the same way. For an operator, let t = c1 op c2 in K_E t steps to with the result , which is . For if true, the term if true then e2 K_E else ... steps to , and Lemma 1.1 finishes. If is stuck, the image has the same stuck call, condition or operator on the same constants. Finally, when is not a value, and when is a value the administrative steps of lead from to .
Theorem 1 (Plotkin). has the same outcome as , where a source function gives the function .
Proof. By Lemmas 1.1 and 1.3, each source step is matched by at least one target step, and target evaluation is deterministic, so the target run passes through for every term of the source run. If the source reaches a value , the target reaches . If the source gets stuck, so does the target. If the source runs forever, so does the target.
2. The one-pass output is the administrative normal form
Write for the result of reducing all administrative redexes of , also those under fun. This process ends: the administrative redexes are typed in the simply typed lambda calculus with one base type for answers, as in the two-level typing of Danvy and Filinski, and simply typed reduction ends. For the extended rules, generalize TAIL to any trivial output term : lines L7 to L11 only place as an argument or as the operator of K a.
Lemma 2.1. For every source term :
- for trivial , up to the names of bound variables;
- for an output variable ;
- for every output term in normal form with a free variable , ,
where means that reduces to by steps at join-point lets and at the administrative redexes that these steps create.
Proof. By induction on , with the three claims together.
- Trivial . Claim 1: and with the body. So gives , and up to the name , which is TAIL by claim 2. This is line L5, and
fixis line L6. Variables and constants are line L4. Claim 2: , normal form , line L7. Claim 3: , normal form , line L12. Substituting a trivial term for makes no administrative redex: a trivial term is a variable, a constant or the image of a source function, whose outer binder is a source binder. - Call . . By claim 3 for and then for , the normal form is META with . For this is line L8. For , is with , which is line L13.
letand operators. The same, with lines L9, L14 and L11, L16. For TAIL of an operator, is line L16 with , as line L11 asks.if. For , the normal form is META, line L10. For , Plotkin's term givesif w then adm(e2 K) else adm(e3 K), with two copies of . Line L15 giveslet j = K in if w then TAIL(e2, j) else TAIL(e3, j). One step at the join point gives TAIL in each branch, and by the generalized claim 2. So the two sides are related by .
With line L3, CPS = let k0 = I in TAIL(e, k0), which reduces by one step to TAIL, and by Lemma 2.1 TAIL. On terms without if, is equality up to names, which the test test_one_pass_is_plotkin_then_administrative_reduction checks on random terms.
3. Administrative steps keep the outcome
Every step used in Part 2 is a step or with a value, possibly under a fun. Plotkin proved that a step anywhere in a term keeps its call-by-value outcome. The argument also separates "stuck" from "no result": the redex itself never gets stuck, since its operator is a fun, and a stuck call, condition or operator in one term has a residual in the other with the same stuck shape. So CPS and have the same outcome, and by Theorem 1 so do CPS and . A source function gives in one and VAL of the reduced function in the other, both functions. This proves property 1 of the page.
4. No administrative redex
Every call node of the output comes from one of lines L7, L8, L11 and L13. TAIL is only called with a variable as its continuation: at line L3, a new at lines L5 and L6, and at line L15. So the operators at lines L7 and L11 are variables. At lines L8 and L13 the operator is the trivial term that a meta-continuation received, which is a variable, a constant or VAL of a source function. A source function in operator position gives a redex whose binder is a source binder: the image of a call that the source already has. The translation makes three kinds of fun: fun k -> at lines L5 and L6, which is the body of a source function and never an operator, fun t -> κ(t) at lines L13 and L15, which is the last argument of a call or the right side of let j, and fun a -> a at line L3, which is the right side of let k0. None of them is ever an operator, so the output has no administrative redex. A call in tail position passes the variable itself (line L8), never fun t -> k t, so there is no η-redex either.
5. Every call is a tail call
Define serious terms and trivial output terms by
By induction on : VAL returns a ; TAIL returns an ; and META returns an whenever maps each to an . Each line checks this directly. Line L12 applies to a . Lines L13 and L16 build an around , which is an . Every meta-continuation built at lines L8 to L16 maps a to an . In a call occurs only as a whole , the body of a fun, a let or a branch, and never as an argument, a condition or the right side of a let. So every call is the last action of the code around it. This is property 2, and the test test_every_call_is_a_tail_call checks the grammar.
6. Linear size
Each call of META that receives calls it exactly once or passes it on exactly once (lines L12 to L16), and each meta-continuation built at lines L8 to L16 contains one call of META or one node. TAIL copies only the variable at line L10. So each source node gives a constant number of output nodes, and the output has nodes.
Complexity
The model is the word RAM. Names are small integers, so the renaming table of line L1 is an array, and the unit step is one table access or the creation of one node of the output. Each node of the source is handled by one call of TAIL or META, which does a constant amount of work besides its recursive calls. Each meta-continuation is called exactly once: at line L12, or inside the code it builds at lines L13, L15 and L16. So the time and the size of the output are . For the terms of the tests the output has at most nodes. The recursion is as deep as the term, and the meta-continuations that wait form a chain of the same length, so the extra space is . A two-pass method, Plotkin's rules followed by administrative reduction, first builds a term several times larger: 66 nodes against 23 in the example.
Properties
- No administrative redexes. Every call in the output has a variable as its operator, or the image of a source function at a place where the source has the same call.
- Properly tail recursive. A call in tail position passes its own continuation on, so a loop written with tail calls runs in constant control space.
- Linear size. No meta-continuation is used twice, so no code is copied.
- Compositional. The output for a term is built from the outputs for its parts, which makes proofs by induction simple.
- Deterministic. The result depends only on the input, up to the choice of new names.
Variants and improvements
- Call by name. Plotkin's call-by-name translation maps a variable to itself, since a variable then stands for a computation, and a call to . Its output runs the same under both evaluation orders, which Plotkin called indifference.
- Continuation first. Fischer (1972) put the continuation as the first parameter of each function. The two orders give the same results.
- First-class continuations. Once a program is in CPS,
call/ccis an ordinary function that passes its own continuation , wrapped asfun v -> fun k' -> k v, to its argument. Theshiftandresetoperators of Danvy and Filinski (1990) are defined in the same way. - Several continuations. Passing one continuation for normal returns and one for exceptions gives exceptions without special support in the back end.
- Non-compositional one-pass. Sabry and Felleisen (1993) give a one-pass translation that is not compositional and is based on a syntactic theory of the source calculus. Danvy, Millikin and Nielsen (2007) relate the two methods.
- A-normal form. If the continuations are not passed but left implicit, the translation gives A-normal form instead, which names every intermediate value in the same way.
When to use it
Use CPS conversion in a compiler for a functional language, especially one with first-class continuations, exceptions or coroutines, or one that must not grow the stack for tail calls. Steele's Rabbit compiler for Scheme and Appel's compiler for Standard ML of New Jersey both work on a CPS intermediate language. CPS also helps with partial evaluation and makes control flow explicit for analyses. Compilers that need no control operators often use A-normal form or SSA form instead, which have the same structure without the extra function arguments, see the SSA and CPS correspondence. For a small interpreter, CPS conversion of the interpreter itself, and not of the program, removes the dependence on the host stack.
Pitfalls
- Call by value and call by name differ. Plotkin gives two translations. The call-by-value one forces the argument before the call, so
(fun y -> 1) looploops after the translation, as it does in the source. Using the call-by-name translation for a strict language, or the other way around, changes which programs terminate. - Name capture. META places code from outer parts of the term under binders of inner parts. Without line L1, a source
let x = ...inside an argument can capture an outerxin that code. - Copying the continuation. Applying in both branches of an
ifcopies its code, and nestedifs then make the output exponential. The join point of line L15 avoids this. - η-redexes at tail calls. A one-pass translation with only META wraps the continuation of a tail call as
fun t -> k t. Each such call then wraps the continuation once more, so a loop of tail calls builds a chain of continuations and no longer runs in constant space. TAIL passes itself. - Evaluation order. The order of the META calls fixes the order in which the arguments are evaluated. Line L8 evaluates the function before the argument. A different order changes the effects of the program.
- New names. The new names of the translation must not clash with the names of the source, or a continuation may capture a user variable.
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/cps-conversion/. The authors are listed in prov/J9VE11.jsonl.
"""Call-by-value CPS conversion of the toy lambda language of toylam.py.
The output is again a toylam term, so toylam.evaluate runs it. A function
fun x -> e becomes fun x -> fun k -> ..., a curried function that takes its
argument and then its continuation k. A call becomes a b k.
cps(e) is the one-pass translation of Danvy and Filinski: the translator
keeps the continuation of a non-tail expression as a Python function (the
meta-continuation) and builds object code only when it has a trivial term to
give it. So the output has no administrative redex.
plotkin(e, fresh) is Plotkin's translation, rule by rule. It makes many
redexes whose operator is a lambda of the translation itself; reducing them
(administrative_normal) gives the output of the one-pass translation, up to
the names of bound variables.
"""
import toylam
def var(x):
return ("var", x)
def names(e):
"""Every variable name in 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 == "app":
return names(e[1]) | names(e[2])
if tag == "let":
return {e[1]} | names(e[2]) | names(e[3])
if tag == "if":
return names(e[1]) | names(e[2]) | names(e[3])
if tag == "prim":
return names(e[2]) | names(e[3])
if tag == "fix":
return {e[1], e[2]} | names(e[3])
raise ValueError(f"not a term: {e!r}")
class Fresh:
"""Makes names that are new: not in avoid and not made before."""
def __init__(self, avoid=()):
self.avoid = set(avoid)
self.n = 0
self.source = set() # the new names of the binders of the source term
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 binder(self, x):
y = self(x)
self.source.add(y)
return y
def rename_apart(e, fresh):
"""Give every binder of e its own new name. Free variables stay."""
env = {}
def bind(x):
old = env.get(x)
env[x] = fresh.binder(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":
y, old = bind(e[1])
body = go(e[2])
unbind(e[1], old)
return ("lam", y, body)
if tag == "app":
return ("app", go(e[1]), go(e[2]))
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 == "if":
return ("if", go(e[1]), go(e[2]), go(e[3]))
if tag == "prim":
return ("prim", e[1], go(e[2]), go(e[3]))
if tag == "fix":
g, 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 ("fix", g, y, body)
raise ValueError(f"not a term: {e!r}")
return go(e)
def trivial(e):
"""Variables, constants and functions: terms that need no continuation."""
return e[0] in ("var", "int", "bool", "lam", "fix")
# ------------------------------------------------------------ one pass
def cps(e, fresh=None):
"""The CPS program of the term e. It returns the value of e when run."""
if fresh is None:
fresh = Fresh(names(e))
e = rename_apart(e, fresh) # @line L1
k0, a = fresh("k"), fresh("a") # @line L2
return ("let", k0, ("lam", a, var(a)), tail(e, var(k0), fresh)) # @line L3
def val(v, fresh):
"""The CPS image of a trivial term."""
if v[0] in ("var", "int", "bool"): # @line L4
return v
k = fresh("k")
if v[0] == "lam": # @line L5
return ("lam", v[1], ("lam", k, tail(v[2], var(k), fresh)))
return ("fix", v[1], v[2], ("lam", k, tail(v[3], var(k), fresh))) # @line L6
def tail(e, k, fresh):
"""The CPS of e, which gives its value to k, a variable of the output."""
tag = e[0]
if trivial(e): # @line L7
return ("app", k, val(e, fresh))
if tag == "app": # @line L8
return meta(e[1], lambda a: meta(e[2], lambda b: ("app", ("app", a, b), k), fresh), fresh)
if tag == "let": # @line L9
return meta(e[2], lambda a: ("let", e[1], a, tail(e[3], k, fresh)), fresh)
if tag == "if": # @line L10
return meta(e[1], lambda a: ("if", a, tail(e[2], k, fresh), tail(e[3], k, fresh)), fresh)
return meta(e, lambda a: ("app", k, a), fresh) # @line L11
def meta(e, kappa, fresh):
"""The CPS of e, which gives its value to kappa, a Python function from a
trivial output term to an output term."""
tag = e[0]
if trivial(e): # @line L12
return kappa(val(e, fresh))
if tag == "app": # @line L13
t = fresh("t")
return meta(e[1], lambda a: meta(e[2], lambda b: ("app", ("app", a, b), ("lam", t, kappa(var(t)))), fresh), fresh)
if tag == "let": # @line L14
return meta(e[2], lambda a: ("let", e[1], a, meta(e[3], kappa, fresh)), fresh)
if tag == "if": # @line L15
j, t = fresh("j"), fresh("t")
return meta(e[1], lambda a: ("let", j, ("lam", t, kappa(var(t))), ("if", a, tail(e[2], var(j), fresh), tail(e[3], var(j), fresh))), fresh)
t = fresh("t") # @line L16
return meta(e[2], lambda a: meta(e[3], lambda b: ("let", t, ("prim", e[1], a, b), kappa(var(t))), fresh), fresh)
# ------------------------------------------------------------ Plotkin
def plotkin(e, fresh):
"""Plotkin's call-by-value translation of e: a function of a continuation."""
tag = e[0]
k = fresh("k")
if tag in ("var", "int", "bool"):
return ("lam", k, ("app", var(k), e))
if tag == "lam":
return ("lam", k, ("app", var(k), ("lam", e[1], plotkin(e[2], fresh))))
if tag == "fix":
return ("lam", k, ("app", var(k), ("fix", e[1], e[2], plotkin(e[3], fresh))))
if tag == "app":
a, b = fresh("v"), fresh("v")
call = ("app", ("app", var(a), var(b)), var(k))
return ("lam", k, ("app", plotkin(e[1], fresh), ("lam", a, ("app", plotkin(e[2], fresh), ("lam", b, call)))))
if tag == "let":
a = fresh("v")
body = ("let", e[1], var(a), ("app", plotkin(e[3], fresh), var(k)))
return ("lam", k, ("app", plotkin(e[2], fresh), ("lam", a, body)))
if tag == "if":
a = fresh("v")
branch = ("if", var(a), ("app", plotkin(e[2], fresh), var(k)), ("app", plotkin(e[3], fresh), var(k)))
return ("lam", k, ("app", plotkin(e[1], fresh), ("lam", a, branch)))
if tag == "prim":
a, b, t = fresh("v"), fresh("v"), fresh("t")
op = ("let", t, ("prim", e[1], var(a), var(b)), ("app", var(k), var(t)))
return ("lam", k, ("app", plotkin(e[2], fresh), ("lam", a, ("app", plotkin(e[3], fresh), ("lam", b, op)))))
raise ValueError(f"not a term: {e!r}")
def plotkin_program(e, fresh=None):
"""Plotkin's translation of e applied to the identity continuation."""
if fresh is None:
fresh = Fresh(names(e))
e = rename_apart(e, fresh)
a = fresh("a")
return ("app", plotkin(e, fresh), ("lam", a, var(a)))
def administrative_normal(e, source):
"""Reduce every redex (fun x -> b) a whose binder x is not in source, that
is every redex that the translation made. The names of e must be distinct
and each such x must occur at most once, as in Plotkin's output for terms
without if."""
tag = e[0]
if tag == "app":
f, a = administrative_normal(e[1], source), administrative_normal(e[2], source)
if f[0] == "lam" and f[1] not in source:
return administrative_normal(toylam.subst(f[2], f[1], a), source)
return ("app", f, a)
if tag == "lam":
return ("lam", e[1], administrative_normal(e[2], source))
if tag == "fix":
return ("fix", e[1], e[2], administrative_normal(e[3], source))
if tag == "let":
return ("let", e[1], administrative_normal(e[2], source), administrative_normal(e[3], source))
if tag == "if":
return ("if",) + tuple(administrative_normal(x, source) for x in e[1:])
if tag == "prim":
return ("prim", e[1], administrative_normal(e[2], source), administrative_normal(e[3], source))
return e
def administrative_redexes(e, source):
"""The number of redexes (fun x -> b) a in e with x not in source."""
tag = e[0]
here = 1 if tag == "app" and e[1][0] == "lam" and e[1][1] not in source else 0
if tag in ("var", "int", "bool"):
return 0
if tag == "lam":
return administrative_redexes(e[2], source)
if tag == "fix":
return administrative_redexes(e[3], source)
parts = e[2:] if tag in ("prim", "let") else e[1:]
return here + sum(administrative_redexes(x, source) for x in parts)
def alpha_equal(a, b):
"""True if a and b differ only in the names of bound variables."""
def go(a, b, ea, eb, d):
if a[0] != b[0]:
return False
tag = a[0]
if tag == "var":
ia, ib = ea.get(a[1]), eb.get(b[1])
return ia == ib and (ia is not None or a[1] == b[1])
if tag in ("int", "bool"):
return a == b
if tag == "lam":
return go(a[2], b[2], {**ea, a[1]: d}, {**eb, b[1]: d}, d + 1)
if tag == "fix":
return go(a[3], b[3], {**ea, a[1]: d, a[2]: d + 1}, {**eb, b[1]: d, b[2]: d + 1}, d + 2)
if tag == "let":
return go(a[2], b[2], ea, eb, d) and go(a[3], b[3], {**ea, a[1]: d}, {**eb, b[1]: d}, d + 1)
if tag == "prim":
return a[1] == b[1] and go(a[2], b[2], ea, eb, d) and go(a[3], b[3], ea, eb, d)
return all(go(x, y, ea, eb, d) for x, y in zip(a[1:], b[1:]))
return go(a, b, {}, {}, 0)
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_cps_conversion.py 196 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cps-conversion/. The authors are listed in prov/J9VE11.jsonl.
import random
import toylam
from cps_conversion import (
Fresh,
administrative_normal,
administrative_redexes,
alpha_equal,
cps,
names,
plotkin,
plotkin_program,
rename_apart,
tail,
)
def v(x):
return ("var", x)
def app(*ts):
out = ts[0]
for t in ts[1:]:
out = ("app", out, t)
return out
def run(e, fuel):
"""toylam.evaluate, with a term that grows too deep counted as out of fuel."""
try:
return toylam.evaluate(e, fuel)
except RecursionError:
return ("fuel",)
def same_outcome(src, out):
"""Equal int and bool results, a function for a function, stuck for stuck."""
if src[0] != out[0]:
return False
if src[0] != "value":
return True
fun = ("lam", "fix")
if src[1][0] in fun or out[1][0] in fun:
return src[1][0] in fun and out[1][0] in fun
return src[1] == out[1]
def random_pure(rng, depth, scope=()):
"""A random term built from variables, functions and calls only."""
if depth <= 0 or (scope and rng.random() < 0.25):
return v(rng.choice(scope)) if scope else ("lam", "x", v("x"))
if rng.random() < 0.4:
x = rng.choice(toylam.NAMES)
return ("lam", x, random_pure(rng, depth - 1, scope + (x,)))
return ("app", random_pure(rng, depth - 1, scope), random_pure(rng, depth - 1, scope))
# ------------------------------------------------------------ the CPS grammar
def trivial_ok(e):
tag = e[0]
if tag in ("var", "int", "bool"):
return True
body = e[3] if tag == "fix" else e[2] if tag == "lam" else None
if body is None:
return False
if body[0] == "lam": # fun x -> fun k -> S
body = body[2]
return serious_ok(body)
def serious_ok(e):
"""e is a serious CPS term: every call in it is a tail call whose operator
and arguments are trivial."""
tag = e[0]
if tag == "app":
parts = []
while e[0] == "app":
parts.append(e[2])
e = e[1]
parts.append(e)
return len(parts) in (2, 3) and all(trivial_ok(p) for p in parts)
if tag == "let":
rhs = e[2]
if rhs[0] == "prim":
ok = trivial_ok(rhs[2]) and trivial_ok(rhs[3])
else:
ok = trivial_ok(rhs)
return ok and serious_ok(e[3])
if tag == "if":
return trivial_ok(e[1]) and serious_ok(e[2]) and serious_ok(e[3])
return False
# ------------------------------------------------------------ page examples
EXAMPLE = ("let", "f", ("lam", "x", ("prim", "+", v("x"), ("int", 1))), app(v("f"), app(v("f"), ("int", 2))))
def test_page_example():
out = cps(EXAMPLE)
assert toylam.show(out) == (
"(let k3 = (fun a4 -> a4) in (let f2 = (fun x1 -> (fun k5 -> (let t6 = (x1 + 1) in (k5 t6))))"
" in ((f2 2) (fun t7 -> ((f2 t7) k3)))))"
)
assert toylam.evaluate(out) == ("value", ("int", 4))
fresh = Fresh(names(EXAMPLE))
p = plotkin_program(EXAMPLE, fresh)
assert toylam.size(p) == 66 and toylam.size(out) == 23
assert administrative_redexes(p, fresh.source) == 9
assert toylam.evaluate(p) == ("value", ("int", 4))
fresh = Fresh(names(EXAMPLE) | {"k"})
e = rename_apart(EXAMPLE, fresh)
reduced = administrative_normal(app(plotkin(e, fresh), v("k")), fresh.source)
assert toylam.show(reduced) == (
"(let f2 = (fun x1 -> (fun k15 -> (let t18 = (x1 + 1) in (k15 t18)))) in ((f2 2) (fun v7 -> ((f2 v7) k))))"
)
assert alpha_equal(reduced, tail(e, v("k"), fresh))
def test_nested_call():
e = app(app(v("f"), v("x")), app(v("g"), v("y")))
assert toylam.show(tail(e, v("k"), Fresh(names(e)))) == "((f x) (fun t1 -> ((g y) (fun t2 -> ((t1 t2) k)))))"
fresh = Fresh(names(e))
p = plotkin(e, fresh)
assert administrative_redexes(p, fresh.source) == 6 and toylam.size(p) == 46
reduced = administrative_normal(app(p, v("k")), fresh.source)
assert toylam.show(reduced) == "((f x) (fun v2 -> ((g y) (fun v3 -> ((v2 v3) k)))))"
def test_call_by_value_order_is_kept():
loop = app(("fix", "f", "x", app(v("f"), v("x"))), ("int", 0))
e = app(("lam", "y", ("int", 1)), loop)
assert run(e, 2000) == ("fuel",)
# A call-by-name reading would return 1. The CBV translation must loop.
assert run(cps(e), 20000) == ("fuel",)
assert run(plotkin_program(e), 20000) == ("fuel",)
# ------------------------------------------------------------ random terms
def test_random_terms_keep_their_outcome():
rng = random.Random(20261115)
compared = 0
for _ in range(1500):
e = toylam.random_term(rng, 5)
want = run(e, 300)
if want == ("fuel",):
continue
assert same_outcome(want, run(cps(e), 20000)), toylam.show(e)
assert same_outcome(want, run(plotkin_program(e), 20000)), toylam.show(e)
compared += 1
assert compared > 1400
def test_every_call_is_a_tail_call():
rng = random.Random(7)
for _ in range(1500):
out = cps(toylam.random_term(rng, 6))
assert out[0] == "let" and serious_ok(out[3])
def test_no_administrative_redex():
rng = random.Random(11)
made = 0
for _ in range(1000):
e = toylam.random_term(rng, 6)
fresh = Fresh(names(e))
assert administrative_redexes(cps(e, fresh), fresh.source) == 0
fresh = Fresh(names(e))
made += administrative_redexes(plotkin_program(e, fresh), fresh.source)
assert made > 1000
def test_one_pass_is_plotkin_then_administrative_reduction():
rng = random.Random(3)
for _ in range(800):
e = random_pure(rng, 6)
fresh = Fresh(names(e) | {"k"})
e = rename_apart(e, fresh)
reduced = administrative_normal(app(plotkin(e, fresh), v("k")), fresh.source)
assert alpha_equal(reduced, tail(e, v("k"), fresh)), toylam.show(e)
def test_output_size_is_linear():
rng = random.Random(5)
for _ in range(1500):
e = toylam.random_term(rng, 7)
assert toylam.size(cps(e)) <= 6 * toylam.size(e) + 4
History
Continuations appeared in several places in the 1960s. Reynolds (1972) used them to write an interpreter whose meaning does not depend on the evaluation order of its host language, and Fischer (1972) used a translation of lambda terms into CPS in his study of lambda calculus schemata. Plotkin (1975) gave the call-by-value and call-by-name translations, proved them correct by simulation and introduced the colon translation for the proof. Steele built the first compiler that uses CPS as its intermediate language, Rabbit for Scheme, in 1978. Appel's book of 1992 describes the CPS compiler of Standard ML of New Jersey, whose conversion builds the output with continuations of the translator. Danvy and Filinski presented the one-pass translation in 1990 and studied it in full in 1992, with a proof that its output has no administrative redexes. Danvy, Millikin and Nielsen (2007) note that the compositional higher-order method was found independently by Appel, by Danvy and Filinski, and by Wand.
References
- Gordon D. Plotkin, Call-by-name, call-by-value and the λ-calculus, Theoretical Computer Science 1(2), 1975, pages 125-159, the call-by-value and call-by-name CPS translations, the colon translation, and the simulation and indifference theorems
- Michael J. Fischer, Lambda calculus schemata, Proceedings of the ACM Conference on Proving Assertions about Programs, 1972, pages 104-109, the translation of lambda terms into a form where every function takes its continuation as an extra argument
- Olivier Danvy and Andrzej Filinski, Representing control, a study of the CPS transformation, Mathematical Structures in Computer Science 2(4), 1992, pages 361-391, the one-pass call-by-value CPS transformation with static (translation-time) continuations, the treatment of tail calls without η-redexes, and the proof that its output has no administrative redexes
- Olivier Danvy and Andrzej Filinski, Abstracting control, Proceedings of the 1990 ACM Conference on LISP and Functional Programming, pages 151-160, the first presentation of the one-pass CPS transformation, used there for the control operators shift and reset
- Olivier Danvy, Kevin Millikin and Lasse R. Nielsen, On one-pass CPS transformations, Journal of Functional Programming 17(6), 2007, pages 793-812, the comparison of the compositional higher-order one-pass transformation with the non-compositional one of Sabry and Felleisen
- Andrew W. Appel, Compiling with Continuations, Cambridge University Press, 1992, the chapter on CPS conversion of the ML compiler, which builds the output with continuations of the translator
- John C. Reynolds, Definitional interpreters for higher-order programming languages, Proceedings of the ACM Annual Conference, 1972, pages 717-740, the use of continuations to make an interpreter independent of the evaluation order of the language it is written in
- Amr Sabry and Matthias Felleisen, Reasoning about programs in continuation-passing style, LISP and Symbolic Computation 6(3-4), 1993, pages 289-360, the equational correspondence between a source calculus and its CPS image, and the one-pass transformation without administrative redexes
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 J9VE11 Edit this page History Report an error Markdown