Algorithmadvanced
Binding-time analysis
Also called BTA.
Marks each expression static or dynamic by whether it depends only on known input, which guides offline partial evaluation.
- Time
- O(N T) worst
- Space
- Θ(T) extra
- Where
- N = the number of nodes of the program term; T = the total size of the simple types of all nodes and binders written as trees
- Model
- Word RAM
- Properties
- deterministicexactofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
Binding-time analysis (BTA) is the first phase of offline partial evaluation. The input is a program and a split of its inputs into static inputs, known at specialization time, and dynamic inputs, known only later. BTA marks every expression static () when the specializer can compute its value from the static inputs alone, and dynamic () when it must emit code for it. The result is a two-level program. The specializer then follows the marks without any more decisions: it runs the parts and rebuilds the parts. The marks must obey a congruence condition, which guarantees that the specializer never meets a dynamic value where it needs a static one. This page gives a BTA for a higher-order language with recursion as the least solution of Horn implications over annotated types.
In plain words
Some of a program's inputs are known early, and some only later. Before we specialize the program, we go through it once and label every part. A part gets the label "known now" if it only uses inputs that are known early. Everything else gets the label "known later", and the specializer must write code for it. The labels spread: a part that uses a "later" value is itself "later". A function that takes a "later" argument gives a "later" result. The analysis finds the labels that keep as much as possible "known now" while every rule still holds. The specializer then reads the labels and does the work without guessing. The labels do not promise that specialization stops: a loop that is "known now" can run forever.
The problem
The language. Terms of the toy lambda language with call by value: variables, constants, fun x -> e, application e1 e2, let x = e1 in e2, if e0 then e1 else e2, binary operators + - * < == on integers, and recursive functions fix f x -> e, where f names the function itself. The free variables of the program are its inputs, all of base type (int or bool). The program has a simple type; let is monomorphic.
Annotated types. A binding time is or , with . An annotated type puts a binding time on every type constructor:
is the binding time of the outer constructor. A static function is a closure that the specializer can call, which unfolds its body. A dynamic function is code. Code can only take code and give code, so a type is well formed when implies that its parts have on top, at every level.
Flow. When a value of type goes to a place of type , we write . At base type it means : a static constant can be lifted into code, so an value may go to a place. At function type it means on every constructor, because a closure cannot be turned into code in this setting.
Congruence. An annotation gives an annotated type with the same shape as the simple type to every node and every binder. It is congruent when all types are well formed, every dynamic input has on top, a function-typed program has on top, and every node obeys its rule:
| node, with type | rule |
|---|---|
variable x, binder type |
|
| constant | none |
fun x -> e1, |
; |
e1 e2, |
; |
let x = e1 in e2 |
; ; |
if e0 then e1 else e2 |
; ; |
e1 op e2 |
for |
fix f x -> e1, |
as for fun, and |
Here is the type of the subterm . Three rules need a reason. A static function with a dynamic parameter is unfolded with a residual let for the argument (let insertion), so its body result is code: that is the rule . The same holds for a let whose variable is dynamic. A recursive function with a dynamic parameter is made dynamic, because unfolding it would not stop: nothing static decides when the recursion ends.
Goal. Among the congruent annotations, find the least one, the one with the fewest marks. There is a least one, because the rules are Horn implications and the set of solutions is closed under intersection.
The specializer. Given a congruent annotation and values for the static inputs, the specializer works on the term. On an node it computes a value: a constant or a closure. On a node it builds code with fresh variable names. Where an constant meets a place, it lifts the constant into code. A static call with a dynamic argument binds the argument with a residual let, unless the argument is a variable or a constant. The residual program is the code for the root, or the lifted constant when the root is .
The algorithm
BTA(e, static, dynamic)- 1
infer the simple types of all nodes and binders of e by unification; fail if there are none - 2
copy each simple type into an annotated type, with a fresh variable on every constructor - 3
for each dynamic input x add the fact top(x) = D - 4
walk e and add the implications of the rule of each node; flow at function type adds both directions - 5
for each annotated function type (t1 ->b t2) add b = D => top(t1) = D and b = D => top(t2) = D - 6
if e has a function type then add the fact top(e) = D - 7
Dset <- the variables reachable from a fact along the implications - 8
if the variable of a static input is in Dset then fail - 9
return the annotation: a variable is D if it is in Dset, and S otherwise
L1 resolves a type variable that is left over to int; any base type would do. L2 gives a binder its own annotated type, and a fun or fix node shares its parameter part with the binder. L7 is the forward chaining of Horn satisfiability: every constraint is an implication between two variables or a fact, so the least model is the set of variables reachable from the facts. L8 cannot fire when all inputs have base type, because no implication ends at the variable of an input. It guards extensions with structured inputs.
Example
Power. The program, with static s and dynamic d:
(fix p n -> fun x -> if n == 0 then 1 else x * p (n - 1) x) s d
It has 20 nodes. L2 makes 36 binding-time variables, L4 and L5 add 67 implications, and the one fact is . L7 marks 18 variables . The annotated program, with a leading _ on dynamic operators, @ for a dynamic call and lift for a lifted constant:
(((fix p n -> (fun x -> (if (n == 0) then lift(1) else (x _* ((p (n - 1)) x))))) s) d)
The binders get , and . So p is a static function that the specializer unfolds, the test on n is done at specialization time, and only the multiplications on x stay. The residual programs:
| s | residual program | nodes | value at d = 2 |
|---|---|---|---|
| 0 | 1 |
1 | 1 |
| 1 | (d * 1) |
3 | 2 |
| 2 | (d * (d * 1)) |
5 | 4 |
| 3 | (d * (d * (d * 1))) |
7 | 8 |
With the roles swapped (s dynamic, d static), n is dynamic, the fix rule makes p dynamic, and 31 of the 36 variables are . Only the binder of d, its use and the three constants stay static:
(((_fix p n -> (_fun x -> (_if (n _== lift(0)) then lift(1) else (x _* ((p @ (n _- lift(1))) @ x))))) @ s) @ lift(d))
The residual program for d = 2 is the original program with fresh names and 2 in place of d. Nothing is gained, and nothing loops.
Let insertion. With static s and dynamic d:
let t = fun f -> fun z -> f (f z) in t (fun y -> y + s) d
The analysis gives : both t and the function passed to it are static, with dynamic arguments. For s = 5 the residual program is (let y1 = (d + 5) in (y1 + 5)), which gives 11 at d = 1. The inner call f z gets the variable d and needs no let. The outer call gets the code (d + 5), so the specializer binds it to a fresh y1. This keeps call by value: the argument is computed once, before the body, even if the body used y twice or not at all.
A function result. For fun x -> x + s with static s, the result is a function, so L6 makes the root : (_fun x -> (x _+ lift(s))). For s = 2 the residual program is (fun x1 -> (x1 + 2)).
A loop that does not stop. With static s and dynamic d:
(fix f n -> if d < n then n else f (n + 1)) s
The annotation is ((fix f n -> (_if (d _< lift(n)) then lift(n) else (f (n + 1)))) s). The parameter n is static, so f is static and the specializer unfolds it. The test is dynamic, so the specializer builds both branches, and the else branch calls f again with n + 1. With s = 0 the original program stops for every d (it gives 4 at d = 3), but the specializer unfolds forever. The implementation stops it after a budget of unfoldings (50 in the test).
Correctness
The full proof is in proofs/correctness.md. It has three parts.
- The result is the least congruent annotation. Every congruence rule is an implication between two variables or a fact, and L3 to L6 add exactly these. The set reachable from the facts in L7 satisfies every implication, and any set that satisfies all of them and holds the facts contains it.
- No binding-time error. For a congruent annotation, by induction on the run of the specializer: a node marked gives a value, a constant at base type and a closure at function type; a node marked gives code; and every variable is bound to a static value or to a variable or constant of code. So the specializer never needs the value of code, and never needs to turn a closure into code.
- The residual program is equivalent to the original. Each step of the specializer replaces a part of the program by a part that is equal in Plotkin's call-by-value calculus: a static call becomes a
let, aletof a value becomes a substitution, a staticifon a constant takes its branch, and a static operator on constants gives a constant. These equalities are sound for operational equivalence, so when the specializer stops, the residual program gives the same result as the original on every dynamic input.
The tests check the three parts on 250 random typed programs (the analysis is congruent, and changing any single variable to breaks a rule), and they compare the residual program with the original on random inputs of 400 random programs.
Proof: BTA gives the least congruent annotation, and congruence makes specialization safefull
Setting. The program is a simply typed term of the toy lambda language, whose free variables are its inputs, all of base type. The inputs are split into static and dynamic ones. An annotation gives each node and each binder an annotated type with the shape of its simple type, as defined on the page. We identify an annotation with the set of binding-time variables that are . BTA is lines L1 to L9 of the page, and is the set it returns as Dset. The specializer is the one described on the page.
Theorem 1: the result is the least congruent annotation
Claim. is congruent, and every congruent annotation satisfies .
Proof. Let be the facts of L3 and L6, and the implications of L4 and L5. Each implication is a pair of variables .
First, an annotation is congruent if and only if and is closed under , that is, and give . We compare the two lists rule by rule.
- A dynamic input must be : these are the facts of L3. A function-typed root must be : this is the fact of L6.
- Well formedness says that a function type has parts. L5 adds and for every annotated function type, and applied at every level this gives well formedness for the parts too.
- at base type is the implication . At function type it is equality on every pair of matching variables, which L4 adds as two implications, one in each direction.
- Each other rule of the table on the page is an implication between two variables, and L4 adds it as such.
- The parameter of a
funorfixnode and its binder share their variables by L2, so the equality between them holds in every annotation.
So the congruence rules and say the same thing.
is the set of variables reachable from along . It holds . If and , then is reachable too, so is closed. Hence is congruent.
Let be congruent. Every is reached by a path with . By induction on : , and gives by closure. So .
Finally, L8 never fails when all inputs have base type. The variable of an input appears in implications only through at the uses of , at base type, where it is on the left side. No implication ends at it, and it is a fact only when is dynamic.
Theorem 2: no binding-time error
A specializer value is with a constant, with a closure (a fun or fix node of the program and an environment), or with a residual term. A residual term is trivial when it is a variable or a constant. Fix a congruent annotation. An environment for a node is good when, for each variable in scope with binder type :
- if and is a base type, then with a constant of that type;
- if and is a function type, then where is a closure of a node whose annotated type is , and whose environment is good for that node;
- if , then with trivial.
Claim. If the environment is good for a node of type , and the specializer on returns, then it raises no binding-time error, and its result fits : when ; with a constant of the simple type of when is a base type with on top; and with a closure as above when is a function type with on top.
A coercion of a result that fits to a place of type with never fails, and the result fits . At base type, the only change is to , and a constant can be lifted. At function type, , so nothing changes.
Proof. By induction on the length of the run of the specializer on , which is finite because it returns. One case per kind of node. All rules used are from the table on the page.
- Variable. The good environment gives a value that fits , and the coercion along makes it fit .
- Constant. It is returned as or as the code , as the mark says.
fun x -> e1, marked . The result is a closure of this node with the current environment, which is good. It fits .fun x -> e1, marked . Well formedness makes and dynamic on top. The body runs with bound to a fresh variable, which is trivial code, so the environment stays good. By induction the body result fits , and the coercion along gives code. The result fits . A dynamicfixis the same, with also bound to a fresh variable; its binder type is , which is on top.e1 e2, function marked . Well formedness makes and dynamic. The argument result, coerced along , is code. with makes , so the code of the call fits .e1 e2, function marked . By induction the function gives a closure of a node with type and a good environment . The argument is coerced along , so it fits . If it is static or trivial code, the parameter is bound to it. Otherwise it is bound to a fresh variable, and a residualletis put around the body result. Then , and the rule makes the body result, coerced to , code, so theletcan be built. For afix, is bound to , which fits the binder type of , the type of thefixnode. In all cases the body environment is good, and by induction (the run on the body is shorter) the body result fits the body type. It is coerced to and then along .let x = e1 in e2. If , the bound value is coerced along to code, is bound to a fresh variable, and the rule with makes the body result code. If , then forces at function type and at base type, so the bound value is static and fits . The environment stays good, and the body result is coerced to .if e0 then e1 else e2. If the test is , then is on top, and both branches are coerced to code. If the test is , its result is a boolean constant, by the claim and the simple type of , and one branch runs and is coerced to .e1 op e2. If the node is , both operands are base values, static constants or code, and both can be made code. If the node is , the rule makes both operands , so they are integer constants, and the operator gives a constant of the right type.
At the root, the environment binds each static input to its constant and each dynamic input to its name. Congruence makes dynamic inputs , and Theorem 1 shows that static inputs stay , so this environment is good. The root result fits the type of . If it is , the root is not a function, by the fact of L6, so it is a constant and can be lifted.
The proof also shows that every variable is bound either to a static value or to trivial code. So the specializer never copies a residual term that does work, and never drops one: non-trivial code is only placed once, in the term it was built for, or in a residual let.
Theorem 3: the residual program is equivalent to the original
Calculus. We use the call-by-value calculus of Plotkin, extended with the constructs of the toy language. Its equality is the least congruence (closed under all term constructors, including under fun) that holds the following rules, where is a value (a constant, a variable, a fun or a fix):
- ;
- ;
- ;
- , and the same for false and ;
- when the operator gives on the constants .
Plotkin proved that implies that and are operationally equivalent: in every context that makes both closed, and both run forever, or both stop, with the same constant when one of them gives a constant. His proof is for and constants with their rules. Each added rule above is a step of the call-by-value semantics whose left side has only values in the positions that are evaluated, which is the form his standardization argument needs, so the result extends to this language. We use it in that form.
Meaning of a specializer value. , , and is the fun or fix node of the closure with each of its free variables replaced by . Each meaning is a value. For a term and an environment , is with each free variable replaced by . Fresh names of the specializer do not occur in the program, so these substitutions never capture a name. Lifting a constant and coercing do not change the meaning.
Lemma. With a congruent annotation and a good environment for , if the specializer on returns , then .
Proof. By induction on the length of the run, with the cases of Theorem 2.
- Variable, constant, static
funorfix. and are the same term. - Dynamic
fun x -> e1. After renaming to the fresh , is . By induction the body is to its residual code, and is a congruence underfun. A dynamicfixis the same. - Dynamic application,
letwith a dynamic variable,ifwith a dynamic test, dynamic operator. The result is the same construct around the results of the parts. By induction each part is to its residual code, and is a congruence. - Static application. By induction and . Let be a closure of with environment , so . If the argument is static or trivial, is a value , and gives , which is to the result by induction. Otherwise the result is with , and by induction . By the
letrule and renaming, . No step is used on , which need not be a value. For afixclosure, thefixrule is used in the same way, with bound to , whose meaning is thefixterm itself. - Static
let x = e1 in e2. The bound value is static, so is a value, and by induction . Then by theletrule and , and this is by induction. - Static
if. By induction the test is to a constant true or false, theifrule picks the branch that the specializer runs, and induction applies to that branch. - Static operator. By induction both operands are to constants, and the operator rule gives the constant the specializer computes.
Theorem. Let the annotation be congruent, the values of the static inputs, and suppose the specializer stops with residual program . Then with substituted and are operationally equivalent. In particular, for every choice of values of the dynamic inputs, and both run forever or both stop, with the same constant when the program has base type.
Proof. The root environment of Theorem 2 is good, and is with substituted and the dynamic inputs left as variables. The lemma gives , where is the root code or the lifted root constant. Plotkin's theorem gives operational equivalence. The context that binds the dynamic inputs to , for example for one input , gives the second sentence.
Remarks. The theorem says nothing when the specializer does not stop, and it may not stop on a congruent annotation (the loop example of the page). The let insertion is used in exactly one place, the static call with non-trivial code as argument, and the proof shows why: needs a value, so binding the code with a let is the only step that is sound there.
Complexity
The model is the word RAM. is the number of nodes of the term, and is the total size of the simple types of all nodes and binders, written as trees, so . L1 makes unification steps, and each occurs check walks a type of size at most , so L1 takes time. L2 makes variables. L4 and L5 add implications, because a flow at function type adds two per constructor and every other rule adds at most three. L7 visits each variable and each implication once, in time. The total time is and the space is .
is usually , but simple types written as trees can be exponential in . A version that keeps types as shared graphs and unifies binding times with them, as Henglein did, runs in almost linear time in .
Properties
- Monovariant. Each function in the program gets one annotated type. If one call of a function passes a dynamic argument, every call of that function treats the argument as dynamic.
- Least. The result is the most static congruent annotation for this set of rules.
- Offline. The marks depend on which inputs are static, not on their values. One analysis serves every value of the static inputs.
- Termination is not part of congruence. A congruent annotation can still make the specializer run forever, as in the loop example.
Variants and improvements
- Polyvariant BTA. Each function gets one annotated type for each pattern of binding times it is called with, and the specializer keeps one copy of the function per pattern. This avoids the loss shown in the Pitfalls.
- Constraint-based BTA in almost linear time. Henglein solves the binding-time constraints together with the types, with union-find on the type graph.
- Online partial evaluation. No BTA at all: the specializer looks at each value as it goes and decides then. It is more precise but slower, and it is hard to make it specialize itself (see Futamura projections).
- Termination analysis. Static variables that can grow without bound under dynamic control, like
nin the loop example, are made dynamic before specialization. This makes the specializer stop on more programs at the cost of less static work. - Partially static structures. Pairs and lists whose shape is static but whose elements are dynamic get a richer annotated type than the plain or used here.
When to use it
Use a BTA when the same program is specialized many times, or when the specializer itself must be specialized, as in the second and third Futamura projections: there the marks must be known before the static values are. Use it also when you want to see, before running anything, which parts of the program the specializer will remove. For one-off specialization with complex static data, an online specializer is often simpler and more precise.
Pitfalls
- Monovariance loses static work. In
let g = fun y -> y * 2 in g s + g dwith statics, the callg dmakes the parameter ofgdynamic everywhere. Fors = 5the residual program is((5 * 2) + (d * 2)). With two copies of the function, one per call, it is(10 + (d * 2)). A binding-time improvement, a rewrite of the source by hand, or a polyvariant BTA fixes this. - Specialization need not stop. Congruence makes specialization safe, not finite. A static recursion under a dynamic test unfolds forever. Use a budget, or a termination analysis that makes such a variable dynamic.
- Dropping the let insertion. If a static call with a code argument puts the code in place of the parameter, the residual program can compute the argument many times or never. Under call by value, a program whose argument does not stop would then stop. Bind the argument with a residual
let. - Lifting a function. A static closure cannot be turned into code in this setting. That is why flow at function type is equality and why a function-typed result must be .
- Untypable programs. This BTA needs simple types. An untyped program needs a different analysis, for example the one of Gomard and Jones for the untyped lambda calculus, where a value that cannot get a consistent annotated type is made dynamic.
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
"""Binding-time analysis for the toy lambda language (toylam.py).
The program is a term whose free variables are its inputs. Some inputs are
static (known before the run) and the others are dynamic. annotate gives
every node of the term an annotated type: its simple type with a binding
time, S or D, on every type constructor. It works in two passes:
1. simple types by monomorphic unification (let is not generalized, and a
type variable that is left over is read as int);
2. a binding-time variable on each constructor, Horn constraints from the
rules of the language, and the least solution by propagation.
congruent checks an annotation against the congruence rules directly, and
specialize is a specializer guided by the annotation: it runs the static
parts and builds a residual term from the dynamic parts.
"""
import itertools
import toylam
class NotTypable(Exception):
"""The term has no simple type (monomorphic let)."""
class StaticInputForced(Exception):
"""A static input would have to be dynamic."""
class Budget(Exception):
"""The specializer unfolded more static calls than its budget allows."""
# ------------------------------------------------------------- simple types
class _Types:
def __init__(self):
self.parent = {}
self.count = itertools.count()
def fresh(self):
return ("tv", next(self.count))
def find(self, t):
while t[0] == "tv" and t in self.parent:
t = self.parent[t]
return t
def occurs(self, v, t):
t = self.find(t)
if t == v:
return True
return t[0] == "fun" and (self.occurs(v, t[1]) or self.occurs(v, t[2]))
def unify(self, a, b):
a, b = self.find(a), self.find(b)
if a == b:
return
if b[0] == "tv":
a, b = b, a
if a[0] == "tv":
if self.occurs(a, b):
raise NotTypable("occurs check")
self.parent[a] = b
return
if a[0] != b[0]:
raise NotTypable("%s and %s" % (a[0], b[0]))
if a[0] == "fun":
self.unify(a[1], b[1])
self.unify(a[2], b[2])
def resolve(self, t):
t = self.find(t)
if t[0] == "tv":
return ("int",)
if t[0] == "fun":
return ("fun", self.resolve(t[1]), self.resolve(t[2]))
return t
def infer(e, inputs):
"""Simple types of every node (keyed by path) and of every binder.
A path is the tuple of indices into the term tuples from the root. A
binder key is ("in", x) for an input x, and (path, name) for a lam, let
or fix binder at path.
"""
ty = _Types()
node, binder = {}, {}
env0 = {}
for x in inputs:
env0[x] = binder[("in", x)] = ty.fresh()
def walk(e, path, env):
tag = e[0]
if tag == "var":
if e[1] not in env:
raise NotTypable("unbound " + e[1])
t = env[e[1]]
elif tag == "int":
t = ("int",)
elif tag == "bool":
t = ("bool",)
elif tag == "lam":
tx = binder[(path, e[1])] = ty.fresh()
t = ("fun", tx, walk(e[2], path + (2,), {**env, e[1]: tx}))
elif tag == "app":
tf = walk(e[1], path + (1,), env)
ta = walk(e[2], path + (2,), env)
t = ty.fresh()
ty.unify(tf, ("fun", ta, t))
elif tag == "let":
t1 = binder[(path, e[1])] = walk(e[2], path + (2,), env)
t = walk(e[3], path + (3,), {**env, e[1]: t1})
elif tag == "if":
ty.unify(walk(e[1], path + (1,), env), ("bool",))
t = walk(e[2], path + (2,), env)
ty.unify(t, walk(e[3], path + (3,), env))
elif tag == "prim":
ty.unify(walk(e[2], path + (2,), env), ("int",))
ty.unify(walk(e[3], path + (3,), env), ("int",))
t = ("int",) if e[1] in ("+", "-", "*") else ("bool",)
elif tag == "fix":
tx, tr = ty.fresh(), ty.fresh()
t = ("fun", tx, tr)
binder[(path, e[1])] = t
binder[(path, e[2])] = tx
ty.unify(walk(e[3], path + (3,), {**env, e[1]: t, e[2]: tx}), tr)
else:
raise ValueError("not a term: %r" % (e,))
node[path] = t
return t
walk(e, (), env0)
return ({p: ty.resolve(t) for p, t in node.items()},
{k: ty.resolve(t) for k, t in binder.items()})
# ---------------------------------------------------------- binding times
#
# An annotated type is ("base", v) or ("fun", v, t1, t2), where v is the
# number of a binding-time variable. The solution is the set of variables
# that are D; every other variable is S.
def top(t):
return t[1]
def bt_vars(t):
if t[0] == "base":
return [t[1]]
return [t[1]] + bt_vars(t[2]) + bt_vars(t[3])
class Annotation:
"""The result of annotate: node and binder annotated types and the
set D of the dynamic binding-time variables."""
def __init__(self, term, dynamic, node, binder, dyn, nvars, constraints):
self.term = term
self.dynamic = list(dynamic)
self.node = node
self.binder = binder
self.dyn = dyn
self.nvars = nvars
self.constraints = constraints
def is_dynamic(self, t):
return top(t) in self.dyn
def annotate(e, static, dynamic):
"""Binding-time analysis of e, whose free variables are the static and
the dynamic inputs. Returns an Annotation with the least solution."""
inputs = list(static) + list(dynamic)
if not toylam.free_vars(e) <= set(inputs):
raise NotTypable("free variable that is not an input")
stype, btype = infer(e, inputs) # @line L1
count = itertools.count()
implies = [] # pairs (a, b): if a is D then b is D
facts = []
made = []
def ann(t): # @line L2
if t[0] == "fun":
a = ("fun", next(count), ann(t[1]), ann(t[2]))
else:
a = ("base", next(count))
made.append(a)
return a
def equal(a, b):
for u, v in zip(bt_vars(a), bt_vars(b)):
implies.append((u, v))
implies.append((v, u))
def flow(a, b):
"""A value of type a is used where type b is expected. At base type
an S value can be lifted to D; function types must be equal."""
if a[0] == "base":
implies.append((top(a), top(b)))
else:
equal(a, b)
node, binder = {}, {}
env0 = {}
for x in inputs:
if btype[("in", x)][0] == "fun":
raise NotTypable("an input of function type")
env0[x] = binder[("in", x)] = ann(btype[("in", x)])
if x in dynamic:
facts.append(top(env0[x])) # @line L3
def walk(e, path, env): # @line L4
tag = e[0]
if tag == "var":
t = ann(stype[path])
flow(env[e[1]], t)
elif tag in ("int", "bool"):
t = ann(stype[path])
elif tag == "lam":
tx = binder[(path, e[1])] = ann(btype[(path, e[1])])
tb = walk(e[2], path + (2,), {**env, e[1]: tx})
t = ("fun", next(count), tx, ann(stype[path + (2,)]))
made.append(t)
flow(tb, t[3])
implies.append((top(tx), top(t[3])))
elif tag == "app":
tf = walk(e[1], path + (1,), env)
ta = walk(e[2], path + (2,), env)
t = ann(stype[path])
flow(ta, tf[2])
flow(tf[3], t)
elif tag == "let":
t1 = walk(e[2], path + (2,), env)
tx = binder[(path, e[1])] = ann(btype[(path, e[1])])
flow(t1, tx)
t2 = walk(e[3], path + (3,), {**env, e[1]: tx})
t = ann(stype[path])
flow(t2, t)
implies.append((top(tx), top(t)))
elif tag == "if":
tc = walk(e[1], path + (1,), env)
ta = walk(e[2], path + (2,), env)
tb = walk(e[3], path + (3,), env)
t = ann(stype[path])
flow(ta, t)
flow(tb, t)
implies.append((top(tc), top(t)))
elif tag == "prim":
ta = walk(e[2], path + (2,), env)
tb = walk(e[3], path + (3,), env)
t = ann(stype[path])
implies.append((top(ta), top(t)))
implies.append((top(tb), top(t)))
elif tag == "fix":
tx = binder[(path, e[2])] = ann(btype[(path, e[2])])
t = ("fun", next(count), tx, ann(stype[path + (3,)]))
made.append(t)
binder[(path, e[1])] = t
tb = walk(e[3], path + (3,), {**env, e[1]: t, e[2]: tx})
flow(tb, t[3])
implies.append((top(tx), top(t[3])))
# A recursive function with a dynamic parameter is not unfolded.
implies.append((top(tx), top(t)))
else:
raise ValueError("not a term: %r" % (e,))
node[path] = t
return t
root = walk(e, (), env0)
for a in made: # @line L5
if a[0] == "fun":
implies.append((top(a), top(a[2])))
implies.append((top(a), top(a[3])))
if root[0] == "fun":
# A function result is code. A base result can stay static: the
# specializer lifts it at the end.
facts.append(top(root)) # @line L6
# Least solution: everything reachable from a fact along implications.
nvars = next(count)
succ = [[] for _ in range(nvars)]
for a, b in implies:
succ[a].append(b)
dyn, work = set(), list(facts)
while work: # @line L7
v = work.pop()
if v not in dyn:
dyn.add(v)
work.extend(succ[v])
for x in static: # @line L8
if top(binder[("in", x)]) in dyn:
raise StaticInputForced(x)
return Annotation(e, dynamic, node, binder, dyn, nvars, (implies, facts)) # @line L9
# ------------------------------------------------------------- congruence
def congruent(a, dyn=None):
"""Check that the binding times dyn (default: the solution) obey the
congruence rules: no static part depends on a dynamic one, a dynamic
function has dynamic parts, and the result is dynamic. Returns a list
of the violated rules (empty when congruent)."""
if dyn is None:
dyn = a.dyn
bad = []
def D(t):
return top(t) in dyn
def same(s, t):
return all((u in dyn) == (v in dyn) for u, v in zip(bt_vars(s), bt_vars(t)))
def at_least(s, t):
"""A value of type s may be used at type t."""
if s[0] == "base":
return D(t) or not D(s)
return same(s, t)
def wf(t):
if t[0] == "fun":
if D(t) and not (D(t[2]) and D(t[3])):
bad.append("a dynamic function with a static part")
wf(t[2])
wf(t[3])
for t in list(a.node.values()) + list(a.binder.values()):
wf(t)
def walk(e, path, env):
t = a.node[path]
tag = e[0]
if tag == "var":
if not at_least(env[e[1]], t):
bad.append("a static use of a dynamic variable")
elif tag == "lam":
tx = a.binder[(path, e[1])]
if not same(tx, t[2]):
bad.append("lam parameter")
tb = walk(e[2], path + (2,), {**env, e[1]: tx})
if not at_least(tb, t[3]):
bad.append("a static lam result from a dynamic body")
if D(tx) and not D(t[3]):
bad.append("a static result of a call with a dynamic argument")
elif tag == "app":
tf = walk(e[1], path + (1,), env)
ta = walk(e[2], path + (2,), env)
if not at_least(ta, tf[2]):
bad.append("a dynamic argument to a static parameter")
if not at_least(tf[3], t):
bad.append("a static application with a dynamic result")
elif tag == "let":
tx = a.binder[(path, e[1])]
t1 = walk(e[2], path + (2,), env)
t2 = walk(e[3], path + (3,), {**env, e[1]: tx})
if not at_least(t1, tx):
bad.append("a static let variable bound to a dynamic value")
if not at_least(t2, t) or (D(tx) and not D(t)):
bad.append("a static let with a dynamic part")
elif tag == "if":
tc = walk(e[1], path + (1,), env)
ta = walk(e[2], path + (2,), env)
tb = walk(e[3], path + (3,), env)
if (D(tc) and not D(t)) or not at_least(ta, t) or not at_least(tb, t):
bad.append("a static if with a dynamic part")
elif tag == "prim":
ta = walk(e[2], path + (2,), env)
tb = walk(e[3], path + (3,), env)
if (D(ta) or D(tb)) and not D(t):
bad.append("a static operation on a dynamic operand")
elif tag == "fix":
tx = a.binder[(path, e[2])]
if not same(a.binder[(path, e[1])], t) or not same(tx, t[2]):
bad.append("fix binders")
tb = walk(e[3], path + (3,), {**env, e[1]: t, e[2]: tx})
if not at_least(tb, t[3]):
bad.append("a static fix result from a dynamic body")
if D(tx) and not D(t[3]):
bad.append("a static result of a call with a dynamic argument")
if D(tx) and not D(t):
bad.append("a static recursive function with a dynamic parameter")
return t
env0 = {k[1]: t for k, t in a.binder.items() if k[0] == "in"}
for x in a.dynamic:
if not D(env0[x]):
bad.append("a static dynamic input")
root = walk(a.term, (), env0)
if root[0] == "fun" and not D(root):
bad.append("a static function as the result")
return bad
# ------------------------------------------------------------ specializer
def specialize(a, static_values, budget=300):
"""The residual term of a.term for the given static input values.
Static parts are run, dynamic parts are rebuilt with fresh names. A
static call with a dynamic argument binds the argument with a residual
let, unless it is a variable or a constant, so the residual term keeps
the call-by-value meaning. Raises Budget when more than budget static
calls are unfolded: specialization need not terminate.
"""
fresh = itertools.count(1)
left = [budget]
D = a.is_dynamic
def name(x):
return "%s%d" % (x, next(fresh))
def code(r):
if r[0] == "D":
return r[1]
if r[1][0] in ("int", "bool"):
return r[1] # lift a static constant
raise ValueError("cannot lift a static function")
def coerce(r, t):
if D(t):
return ("D", code(r))
if r[0] == "D":
raise ValueError("a dynamic value at a static type")
return r
def bind(x, r, t, body):
"""Bind x to the argument r of type t around spec of body."""
r = coerce(r, t)
if r[0] == "S" or r[1][0] in ("var", "int", "bool"):
return body(r)
x2 = name(x)
res = body(("D", ("var", x2)))
return ("D", ("let", x2, r[1], code(res)))
def call(f, arg):
left[0] -= 1
if left[0] < 0:
raise Budget()
_, e, path, env = f
t = a.node[path]
if e[0] == "lam":
x, bpath, extra = e[1], path + (2,), {}
else:
x, bpath, extra = e[2], path + (3,), {e[1]: ("S", f)}
return bind(x, arg, t[2], lambda r: coerce(
spec(e[3] if e[0] == "fix" else e[2], bpath, {**env, **extra, x: r}), t[3]))
def spec(e, path, env): # returns ("S", value) or ("D", code)
t = a.node[path]
tag = e[0]
if tag == "var":
return coerce(env[e[1]], t)
if tag in ("int", "bool"):
return ("D", e) if D(t) else ("S", e)
if tag == "lam":
if not D(t):
return ("S", ("clo", e, path, env))
x = name(e[1])
body = spec(e[2], path + (2,), {**env, e[1]: ("D", ("var", x))})
return ("D", ("lam", x, code(body)))
if tag == "fix":
if not D(t):
return ("S", ("clo", e, path, env))
f, x = name(e[1]), name(e[2])
body = spec(e[3], path + (3,), {**env, e[1]: ("D", ("var", f)), e[2]: ("D", ("var", x))})
return ("D", ("fix", f, x, code(body)))
if tag == "app":
rf = spec(e[1], path + (1,), env)
ra = spec(e[2], path + (2,), env)
if rf[0] == "D":
return ("D", ("app", rf[1], code(ra)))
return coerce(call(rf[1], ra), t)
if tag == "let":
tx = a.binder[(path, e[1])]
r1 = spec(e[2], path + (2,), env)
if D(tx):
x = name(e[1])
r2 = spec(e[3], path + (3,), {**env, e[1]: ("D", ("var", x))})
return ("D", ("let", x, code(r1), code(r2)))
return coerce(spec(e[3], path + (3,), {**env, e[1]: r1}), t)
if tag == "if":
rc = spec(e[1], path + (1,), env)
if rc[0] == "D":
ra = spec(e[2], path + (2,), env)
rb = spec(e[3], path + (3,), env)
return ("D", ("if", rc[1], code(ra), code(rb)))
branch = 2 if rc[1][1] else 3
return coerce(spec(e[branch], path + (branch,), env), t)
if tag == "prim":
ra = spec(e[2], path + (2,), env)
rb = spec(e[3], path + (3,), env)
if D(t):
return ("D", ("prim", e[1], code(ra), code(rb)))
out = toylam.evaluate(("prim", e[1], ra[1], rb[1]))
return ("S", out[1])
raise ValueError("not a term: %r" % (e,))
env0 = {x: ("S", v) for x, v in static_values.items()}
for k in a.binder:
if k[0] == "in" and k[1] not in static_values:
env0[k[1]] = ("D", ("var", k[1]))
try:
return code(spec(a.term, (), env0))
except RecursionError:
raise Budget() from None
def show_annotated(a):
"""The term with each dynamic node underlined by a leading underscore
on its keyword or operator: _fun, _if, _let, _+, @ for a dynamic call,
and lift(...) around a static base value that is used where a dynamic
one is expected."""
def D(path):
return a.is_dynamic(a.node[path])
def sub(e, path, env, want):
"""The child e at path, lifted when it is a static base value and
the place it goes to (annotated type want) is dynamic."""
s = go(e, path, env)
t = a.node[path]
if t[0] == "base" and not a.is_dynamic(t) and a.is_dynamic(want):
s = "lift(%s)" % s
return s
def go(e, path, env):
tag = e[0]
t = a.node[path]
if tag == "var":
s = e[1]
if D(path) and not a.is_dynamic(env[e[1]]):
s = "lift(%s)" % s
return s
if tag == "int":
return "%d" % e[1]
if tag == "bool":
return "true" if e[1] else "false"
if tag == "lam":
env2 = {**env, e[1]: a.binder[(path, e[1])]}
kw = "_fun" if D(path) else "fun"
return "(%s %s -> %s)" % (kw, e[1], sub(e[2], path + (2,), env2, t[3]))
if tag == "app":
tf = a.node[path + (1,)]
sep = " @ " if a.is_dynamic(tf) else " "
s = "(%s%s%s)" % (go(e[1], path + (1,), env), sep, sub(e[2], path + (2,), env, tf[2]))
if tf[3][0] == "base" and not a.is_dynamic(tf[3]) and D(path):
s = "lift(%s)" % s
return s
if tag == "let":
tx = a.binder[(path, e[1])]
env2 = {**env, e[1]: tx}
kw = "_let" if a.is_dynamic(tx) else "let"
return "(%s %s = %s in %s)" % (kw, e[1], sub(e[2], path + (2,), env, tx),
sub(e[3], path + (3,), env2, t))
if tag == "if":
kw = "_if" if a.is_dynamic(a.node[path + (1,)]) else "if"
return "(%s %s then %s else %s)" % (kw, go(e[1], path + (1,), env),
sub(e[2], path + (2,), env, t), sub(e[3], path + (3,), env, t))
if tag == "prim":
op = "_" + e[1] if D(path) else e[1]
return "(%s %s %s)" % (sub(e[2], path + (2,), env, t), op, sub(e[3], path + (3,), env, t))
if tag == "fix":
env2 = {**env, e[1]: a.binder[(path, e[1])], e[2]: a.binder[(path, e[2])]}
kw = "_fix" if D(path) else "fix"
return "(%s %s %s -> %s)" % (kw, e[1], e[2], sub(e[3], path + (3,), env2, t[3]))
raise ValueError("not a term: %r" % (e,))
env0 = {k[1]: t for k, t in a.binder.items() if k[0] == "in"}
return go(a.term, (), env0)
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_binding_time_analysis.py 154 lines
# SPDX-License-Identifier: MIT
import random
import unittest
import toylam
from binding_time_analysis import (
Budget, NotTypable, annotate, congruent, infer, show_annotated, specialize,
)
def V(x):
return ("var", x)
def I(k):
return ("int", k)
POWER = ("app", ("app",
("fix", "p", "n", ("lam", "x",
("if", ("prim", "==", V("n"), I(0)), I(1),
("prim", "*", V("x"), ("app", ("app", V("p"), ("prim", "-", V("n"), I(1))), V("x")))))),
V("s")), V("d"))
TWICE = ("let", "t", ("lam", "f", ("lam", "z", ("app", V("f"), ("app", V("f"), V("z"))))),
("app", ("app", V("t"), ("lam", "y", ("prim", "+", V("y"), V("s")))), V("d")))
LOOP = ("app", ("fix", "f", "n", ("if", ("prim", "<", V("d"), V("n")), V("n"),
("app", V("f"), ("prim", "+", V("n"), I(1))))), V("s"))
def value_of(rng, t):
if t == ("bool",):
return ("bool", rng.random() < 0.5)
return ("int", rng.randint(-2, 4))
def run_original(e, values):
for x, v in values.items():
e = toylam.subst(e, x, v)
return toylam.evaluate(e, 3000)
def random_cases(seed, count):
"""Typable random programs with inputs s (static) and d (dynamic),
a result of base type and inputs of base type."""
rng = random.Random(seed)
out = []
while len(out) < count:
e = toylam.random_term(rng, rng.randint(2, 6), ("s", "d"))
try:
a = annotate(e, ["s"], ["d"])
except NotTypable:
continue
if a.node[()][0] != "base":
continue
out.append((e, a))
return rng, out
class AnalysisTest(unittest.TestCase):
def test_power_annotation(self):
a = annotate(POWER, ["s"], ["d"])
self.assertEqual(show_annotated(a),
"(((fix p n -> (fun x -> (if (n == 0) then lift(1) else (x _* ((p (n - 1)) x))))) s) d)")
a2 = annotate(POWER, ["d"], ["s"])
self.assertEqual(show_annotated(a2),
"(((_fix p n -> (_fun x -> (_if (n _== lift(0)) then lift(1) else"
" (x _* ((p @ (n _- lift(1))) @ x))))) @ s) @ lift(d))")
def test_random_annotations_are_congruent_and_least(self):
_, cases = random_cases(1, 250)
flips = 0
for e, a in cases:
self.assertEqual(congruent(a), [], toylam.show(e))
# Least: making any single dynamic variable static breaks a rule.
for v in sorted(a.dyn):
self.assertNotEqual(congruent(a, a.dyn - {v}), [])
flips += 1
self.assertGreater(flips, 300)
def test_all_static(self):
# With no dynamic input and a base result, nothing is D, and the
# residual program is the lifted value.
e = ("prim", "+", V("s"), I(1))
a = annotate(e, ["s", "d"], [])
self.assertEqual(show_annotated(a), "(s + 1)")
self.assertEqual(a.dyn, set())
self.assertEqual(specialize(a, {"s": I(4), "d": I(0)}), I(5))
def test_function_result_is_dynamic(self):
e = ("lam", "x", ("prim", "+", V("x"), V("s")))
a = annotate(e, ["s"], [])
self.assertEqual(show_annotated(a), "(_fun x -> (x _+ lift(s)))")
self.assertEqual(toylam.show(specialize(a, {"s": I(2)})), "(fun x1 -> (x1 + 2))")
def test_a_bad_annotation_is_caught(self):
a = annotate(POWER, ["s"], ["d"])
self.assertNotEqual(congruent(a, set()), [])
def test_untypable(self):
with self.assertRaises(NotTypable):
annotate(("app", I(1), I(2)), [], [])
with self.assertRaises(NotTypable):
annotate(("var", "q"), ["s"], ["d"])
class SpecializerTest(unittest.TestCase):
def test_power(self):
a = annotate(POWER, ["s"], ["d"])
shown = [toylam.show(specialize(a, {"s": I(n)})) for n in range(4)]
self.assertEqual(shown, ["1", "(d * 1)", "(d * (d * 1))", "(d * (d * (d * 1)))"])
r = specialize(a, {"s": I(3)})
self.assertEqual(toylam.evaluate(toylam.subst(r, "d", I(2))), ("value", I(8)))
def test_twice(self):
a = annotate(TWICE, ["s"], ["d"])
r = specialize(a, {"s": I(5)})
self.assertEqual(toylam.show(r), "(let y1 = (d + 5) in (y1 + 5))")
self.assertEqual(toylam.evaluate(toylam.subst(r, "d", I(1))), ("value", I(11)))
def test_static_loop_under_dynamic_test_does_not_stop(self):
a = annotate(LOOP, ["s"], ["d"])
self.assertEqual(show_annotated(a), "((fix f n -> (_if (d _< lift(n)) then lift(n) else (f (n + 1)))) s)")
self.assertEqual(run_original(LOOP, {"s": I(0), "d": I(3)}), ("value", I(4)))
with self.assertRaises(Budget):
specialize(a, {"s": I(0)}, budget=50)
def test_residual_agrees_with_original(self):
rng, cases = random_cases(2, 400)
agree = budget = 0
for e, a in cases:
types = infer(e, ["s", "d"])[1]
for _ in range(3):
s = value_of(rng, types[("in", "s")])
d = value_of(rng, types[("in", "d")])
want = run_original(e, {"s": s, "d": d})
self.assertNotEqual(want[0], "stuck")
if want[0] != "value":
continue
try:
r = specialize(a, {"s": s})
except Budget:
budget += 1
continue
self.assertLessEqual(toylam.free_vars(r), {"d"})
got = toylam.evaluate(toylam.subst(r, "d", d), 100000)
self.assertEqual(got, want, toylam.show(e))
agree += 1
self.assertGreater(agree, 600)
if __name__ == "__main__":
unittest.main()
History
Binding-time analysis came with the first self-applicable partial evaluator, the mix project of Jones, Sestoft and Søndergaard in 1985. Its purpose was to take the decisions out of the specializer, so that specializing the specializer gave good compilers. Gomard and Jones extended it to the untyped lambda calculus in 1991 with a two-level language and a type-based analysis. In the same year Henglein gave an almost linear algorithm for higher-order BTA by constraint solving. The book of Jones, Gomard and Sestoft (1993) made BTA and congruence the standard way to present offline partial evaluation.
References
- Neil D. Jones, Carsten K. Gomard and Peter Sestoft, Partial Evaluation and Automatic Program Generation, Prentice Hall, 1993, the chapters on offline partial evaluation, binding-time analysis, congruence and the partial evaluation of the lambda calculus
- Carsten K. Gomard and Neil D. Jones, A partial evaluator for the untyped lambda-calculus, Journal of Functional Programming 1(1), 1991, 21-69, the two-level lambda calculus, the binding-time rules with lift, and the correctness of the specializer for well-annotated terms
- Fritz Henglein, Efficient type inference for higher-order binding-time analysis, Functional Programming Languages and Computer Architecture (FPCA 1991), LNCS 523, 448-472, binding-time analysis as constraint solving over annotated types, in almost linear time
- Neil D. Jones, An introduction to partial evaluation, ACM Computing Surveys 28(3), 1996, 480-503, offline and online specialization, and the role of the binding-time analysis
- Gordon D. Plotkin, Call-by-name, call-by-value and the λ-calculus, Theoretical Computer Science 1(2), 1975, 125-159, the soundness of the call-by-value calculus for operational equivalence, used in the correctness proof
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 WE1B25 Edit this page History Report an error Markdown