Algorithm Search⌘K

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

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 (SS) when the specializer can compute its value from the static inputs alone, and dynamic (DD) 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 SS parts and rebuilds the DD 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 SS or DD, with S⊑DS \sqsubseteq D. An annotated type puts a binding time on every type constructor:

τ::=baseβ∣(τ1→βτ2),β∈{S,D}.\tau ::= \mathrm{base}^{\beta} \mid (\tau_1 \to^{\beta} \tau_2), \qquad \beta \in \{S, D\}.

top(τ)\mathrm{top}(\tau) is the binding time of the outer constructor. A static function (τ1→Sτ2)(\tau_1 \to^S \tau_2) is a closure that the specializer can call, which unfolds its body. A dynamic function (τ1→Dτ2)(\tau_1 \to^D \tau_2) is code. Code can only take code and give code, so a type is well formed when top(τ)=D\mathrm{top}(\tau) = D implies that its parts have DD on top, at every level.

Flow. When a value of type τ\tau goes to a place of type τ′\tau', we write flow(τ,τ′)\mathrm{flow}(\tau, \tau'). At base type it means top(τ)=D⇒top(τ′)=D\mathrm{top}(\tau) = D \Rightarrow \mathrm{top}(\tau') = D: a static constant can be lifted into code, so an SS value may go to a DD place. At function type it means τ=τ′\tau = \tau' 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 DD on top, a function-typed program has DD on top, and every node obeys its rule:

node, with type τ\tau rule
variable x, binder type τx\tau_x flow(τx,τ)\mathrm{flow}(\tau_x, \tau)
constant none
fun x -> e1, τ=(τx→βτr)\tau = (\tau_x \to^{\beta} \tau_r) flow(τ1,τr)\mathrm{flow}(\tau_1, \tau_r); top(τx)=D⇒top(τr)=D\mathrm{top}(\tau_x) = D \Rightarrow \mathrm{top}(\tau_r) = D
e1 e2, τ1=(τa→βτr)\tau_1 = (\tau_a \to^{\beta} \tau_r) flow(τ2,τa)\mathrm{flow}(\tau_2, \tau_a); flow(τr,τ)\mathrm{flow}(\tau_r, \tau)
let x = e1 in e2 flow(τ1,τx)\mathrm{flow}(\tau_1, \tau_x); flow(τ2,τ)\mathrm{flow}(\tau_2, \tau); top(τx)=D⇒top(τ)=D\mathrm{top}(\tau_x) = D \Rightarrow \mathrm{top}(\tau) = D
if e0 then e1 else e2 flow(τ1,τ)\mathrm{flow}(\tau_1, \tau); flow(τ2,τ)\mathrm{flow}(\tau_2, \tau); top(τ0)=D⇒top(τ)=D\mathrm{top}(\tau_0) = D \Rightarrow \mathrm{top}(\tau) = D
e1 op e2 top(τi)=D⇒top(τ)=D\mathrm{top}(\tau_i) = D \Rightarrow \mathrm{top}(\tau) = D for i=1,2i = 1, 2
fix f x -> e1, τ=τf=(τx→βτr)\tau = \tau_f = (\tau_x \to^{\beta} \tau_r) as for fun, and top(τx)=D⇒β=D\mathrm{top}(\tau_x) = D \Rightarrow \beta = D

Here τi\tau_i is the type of the subterm eie_i. 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 top(τx)=D⇒top(τr)=D\mathrm{top}(\tau_x) = D \Rightarrow \mathrm{top}(\tau_r) = D. 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 DD 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 SS node it computes a value: a constant or a closure. On a DD node it builds code with fresh variable names. Where an SS constant meets a DD 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 SS.

The algorithm

  1. BTA(e, static, dynamic)
  2. 1infer the simple types of all nodes and binders of e by unification; fail if there are none
  3. 2copy each simple type into an annotated type, with a fresh variable on every constructor
  4. 3for each dynamic input x add the fact top(x) = D
  5. 4walk e and add the implications of the rule of each node; flow at function type adds both directions
  6. 5for each annotated function type (t1 ->b t2) add b = D => top(t1) = D and b = D => top(t2) = D
  7. 6if e has a function type then add the fact top(e) = D
  8. 7Dset <- the variables reachable from a fact along the implications
  9. 8if the variable of a static input is in Dset then fail
  10. 9return 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 top(d)=D\mathrm{top}(d) = D. L7 marks 18 variables DD. 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 n:intSn : \mathrm{int}^S, x:intDx : \mathrm{int}^D and p:(intS→S(intD→SintD))p : (\mathrm{int}^S \to^S (\mathrm{int}^D \to^S \mathrm{int}^D)). 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 DD. 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 t:((intD→SintD)→S(intD→SintD))t : ((\mathrm{int}^D \to^S \mathrm{int}^D) \to^S (\mathrm{int}^D \to^S \mathrm{int}^D)): 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 DD: (_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.

  1. 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.
  2. No binding-time error. For a congruent annotation, by induction on the run of the specializer: a node marked SS gives a value, a constant at base type and a closure at function type; a node marked DD 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.
  3. 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, a let of a value becomes a substitution, a static if on 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 DD variable to SS 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 ee 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 XX of binding-time variables that are DD. BTA is lines L1 to L9 of the page, and RR 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. RR is congruent, and every congruent annotation XX satisfies R⊆XR \subseteq X.

Proof. Let FF be the facts of L3 and L6, and II the implications of L4 and L5. Each implication is a pair of variables u⇒vu \Rightarrow v.

First, an annotation XX is congruent if and only if F⊆XF \subseteq X and XX is closed under II, that is, u∈Xu \in X and (u⇒v)∈I(u \Rightarrow v) \in I give v∈Xv \in X. We compare the two lists rule by rule.

  • A dynamic input must be DD: these are the facts of L3. A function-typed root must be DD: this is the fact of L6.
  • Well formedness says that a DD function type has DD parts. L5 adds b⇒top(t1)b \Rightarrow \mathrm{top}(t_1) and b⇒top(t2)b \Rightarrow \mathrm{top}(t_2) for every annotated function type, and applied at every level this gives well formedness for the parts too.
  • flow(τ,τ′)\mathrm{flow}(\tau, \tau') at base type is the implication top(τ)⇒top(τ′)\mathrm{top}(\tau) \Rightarrow \mathrm{top}(\tau'). 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 fun or fix node and its binder share their variables by L2, so the equality between them holds in every annotation.

So the congruence rules and F∪IF \cup I say the same thing.

RR is the set of variables reachable from FF along II. It holds FF. If u∈Ru \in R and u⇒vu \Rightarrow v, then vv is reachable too, so RR is closed. Hence RR is congruent.

Let XX be congruent. Every v∈Rv \in R is reached by a path f=v0⇒v1⇒⋯⇒vk=vf = v_0 \Rightarrow v_1 \Rightarrow \cdots \Rightarrow v_k = v with f∈Ff \in F. By induction on kk: v0∈F⊆Xv_0 \in F \subseteq X, and vi∈Xv_{i} \in X gives vi+1∈Xv_{i+1} \in X by closure. So R⊆XR \subseteq X.

Finally, L8 never fails when all inputs have base type. The variable of an input xx appears in implications only through flow(τx,τ)\mathrm{flow}(\tau_x, \tau) at the uses of xx, at base type, where it is on the left side. No implication ends at it, and it is a fact only when xx is dynamic. □\square

Theorem 2: no binding-time error

A specializer value is (S,c)(S, c) with cc a constant, (S,k)(S, k) with kk a closure (a fun or fix node of the program and an environment), or (D,q)(D, q) with qq a residual term. A residual term is trivial when it is a variable or a constant. Fix a congruent annotation. An environment ρ\rho for a node is good when, for each variable xx in scope with binder type τx\tau_x:

  • if top(τx)=S\mathrm{top}(\tau_x) = S and τx\tau_x is a base type, then ρ(x)=(S,c)\rho(x) = (S, c) with cc a constant of that type;
  • if top(τx)=S\mathrm{top}(\tau_x) = S and τx\tau_x is a function type, then ρ(x)=(S,k)\rho(x) = (S, k) where kk is a closure of a node whose annotated type is τx\tau_x, and whose environment is good for that node;
  • if top(τx)=D\mathrm{top}(\tau_x) = D, then ρ(x)=(D,q)\rho(x) = (D, q) with qq trivial.

Claim. If the environment is good for a node ee of type τ\tau, and the specializer on ee returns, then it raises no binding-time error, and its result rr fits τ\tau: r=(D,q)r = (D, q) when top(τ)=D\mathrm{top}(\tau) = D; r=(S,c)r = (S, c) with cc a constant of the simple type of ee when τ\tau is a base type with SS on top; and r=(S,k)r = (S, k) with kk a closure as above when τ\tau is a function type with SS on top.

A coercion of a result rr that fits τ\tau to a place of type τ′\tau' with flow(τ,τ′)\mathrm{flow}(\tau, \tau') never fails, and the result fits τ′\tau'. At base type, the only change is SS to DD, and a constant can be lifted. At function type, τ=τ′\tau = \tau', so nothing changes.

Proof. By induction on the length of the run of the specializer on ee, 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 τx\tau_x, and the coercion along flow(τx,τ)\mathrm{flow}(\tau_x, \tau) makes it fit τ\tau.
  • Constant. It is returned as (S,c)(S, c) or as the code cc, as the mark says.
  • fun x -> e1, marked SS. The result is a closure of this node with the current environment, which is good. It fits τ\tau.
  • fun x -> e1, marked DD. Well formedness makes τx\tau_x and τr\tau_r dynamic on top. The body runs with xx bound to a fresh variable, which is trivial code, so the environment stays good. By induction the body result fits τ1\tau_1, and the coercion along flow(τ1,τr)\mathrm{flow}(\tau_1, \tau_r) gives code. The result (D,fun x′→q)(D, \texttt{fun } x' \to q) fits τ\tau. A dynamic fix is the same, with ff also bound to a fresh variable; its binder type is τ\tau, which is DD on top.
  • e1 e2, function marked DD. Well formedness makes τa\tau_a and τr\tau_r dynamic. The argument result, coerced along flow(τ2,τa)\mathrm{flow}(\tau_2, \tau_a), is code. flow(τr,τ)\mathrm{flow}(\tau_r, \tau) with top(τr)=D\mathrm{top}(\tau_r) = D makes top(τ)=D\mathrm{top}(\tau) = D, so the code of the call fits τ\tau.
  • e1 e2, function marked SS. By induction the function gives a closure kk of a node with type τ1=(τa→Sτr)\tau_1 = (\tau_a \to^S \tau_r) and a good environment ρk\rho_k. The argument is coerced along flow(τ2,τa)\mathrm{flow}(\tau_2, \tau_a), so it fits τa\tau_a. If it is static or trivial code, the parameter is bound to it. Otherwise it is bound to a fresh variable, and a residual let is put around the body result. Then top(τa)=D\mathrm{top}(\tau_a) = D, and the rule top(τx)=D⇒top(τr)=D\mathrm{top}(\tau_x) = D \Rightarrow \mathrm{top}(\tau_r) = D makes the body result, coerced to τr\tau_r, code, so the let can be built. For a fix, ff is bound to (S,k)(S, k), which fits the binder type of ff, the type of the fix node. 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 τr\tau_r and then along flow(τr,τ)\mathrm{flow}(\tau_r, \tau).
  • let x = e1 in e2. If top(τx)=D\mathrm{top}(\tau_x) = D, the bound value is coerced along flow(τ1,τx)\mathrm{flow}(\tau_1, \tau_x) to code, xx is bound to a fresh variable, and the rule top(τx)=D⇒top(τ)=D\mathrm{top}(\tau_x) = D \Rightarrow \mathrm{top}(\tau) = D with flow(τ2,τ)\mathrm{flow}(\tau_2, \tau) makes the body result code. If top(τx)=S\mathrm{top}(\tau_x) = S, then flow(τ1,τx)\mathrm{flow}(\tau_1, \tau_x) forces τ1=τx\tau_1 = \tau_x at function type and top(τ1)=S\mathrm{top}(\tau_1) = S at base type, so the bound value is static and fits τx\tau_x. The environment stays good, and the body result is coerced to τ\tau.
  • if e0 then e1 else e2. If the test is DD, then τ\tau is DD on top, and both branches are coerced to code. If the test is SS, its result is a boolean constant, by the claim and the simple type of e0e_0, and one branch runs and is coerced to τ\tau.
  • e1 op e2. If the node is DD, both operands are base values, static constants or code, and both can be made code. If the node is SS, the rule makes both operands SS, 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 DD, and Theorem 1 shows that static inputs stay SS, so this environment is good. The root result fits the type of ee. If it is SS, the root is not a function, by the fact of L6, so it is a constant and can be lifted. □\square

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 =v=_v is the least congruence (closed under all term constructors, including under fun) that holds the following rules, where ww is a value (a constant, a variable, a fun or a fix):

  • (fun x→b) w=vb[w/x](\texttt{fun } x \to b)\ w =_v b[w/x];
  • (fix f x→b) w=vb[(fix f x→b)/f][w/x](\texttt{fix } f\ x \to b)\ w =_v b[(\texttt{fix } f\ x \to b)/f][w/x];
  • let x=e1 in e2=v(fun x→e2) e1\texttt{let } x = e_1 \texttt{ in } e_2 =_v (\texttt{fun } x \to e_2)\ e_1;
  • if true then e1 else e2=ve1\texttt{if true then } e_1 \texttt{ else } e_2 =_v e_1, and the same for false and e2e_2;
  • c1opc2=vcc_1 \mathbin{op} c_2 =_v c when the operator gives cc on the constants c1,c2c_1, c_2.

Plotkin proved that M=vNM =_v N implies that MM and NN are operationally equivalent: in every context CC that makes both closed, C[M]C[M] and C[N]C[N] both run forever, or both stop, with the same constant when one of them gives a constant. His proof is for βv\beta_v 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. [ ⁣[(D,q)] ⁣]=q[\![(D, q)]\!] = q, [ ⁣[(S,c)] ⁣]=c[\![(S, c)]\!] = c, and [ ⁣[(S,k)] ⁣][\![(S, k)]\!] is the fun or fix node of the closure kk with each of its free variables yy replaced by [ ⁣[ρk(y)] ⁣][\![\rho_k(y)]\!]. Each meaning is a value. For a term ee and an environment ρ\rho, e[ ⁣[ρ] ⁣]e[\![\rho]\!] is ee with each free variable yy replaced by [ ⁣[ρ(y)] ⁣][\![\rho(y)]\!]. 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 ρ\rho for ee, if the specializer on ee returns rr, then e[ ⁣[ρ] ⁣]=v[ ⁣[r] ⁣]e[\![\rho]\!] =_v [\![r]\!].

Proof. By induction on the length of the run, with the cases of Theorem 2.

  • Variable, constant, static fun or fix. e[ ⁣[ρ] ⁣]e[\![\rho]\!] and [ ⁣[r] ⁣][\![r]\!] are the same term.
  • Dynamic fun x -> e1. After renaming xx to the fresh x′x', e[ ⁣[ρ] ⁣]e[\![\rho]\!] is fun x′→e1[ ⁣[ρ,x↦x′] ⁣]\texttt{fun } x' \to e_1[\![\rho, x \mapsto x']\!]. By induction the body is =v=_v to its residual code, and =v=_v is a congruence under fun. A dynamic fix is the same.
  • Dynamic application, let with a dynamic variable, if with a dynamic test, dynamic operator. The result is the same construct around the results of the parts. By induction each part is =v=_v to its residual code, and =v=_v is a congruence.
  • Static application. By induction e1[ ⁣[ρ] ⁣]=v[ ⁣[k] ⁣]e_1[\![\rho]\!] =_v [\![k]\!] and e2[ ⁣[ρ] ⁣]=v[ ⁣[r2] ⁣]e_2[\![\rho]\!] =_v [\![r_2]\!]. Let kk be a closure of fun x→b\texttt{fun } x \to b with environment ρk\rho_k, so [ ⁣[k] ⁣]=fun x→b[ ⁣[ρk] ⁣][\![k]\!] = \texttt{fun } x \to b[\![\rho_k]\!]. If the argument is static or trivial, [ ⁣[r2] ⁣][\![r_2]\!] is a value ww, and βv\beta_v gives (fun x→b[ ⁣[ρk] ⁣]) w=vb[ ⁣[ρk,x↦w] ⁣](\texttt{fun } x \to b[\![\rho_k]\!])\ w =_v b[\![\rho_k, x \mapsto w]\!], which is =v=_v to the result by induction. Otherwise the result is let x2=q in q′\texttt{let } x_2 = q \texttt{ in } q' with q=[ ⁣[r2] ⁣]q = [\![r_2]\!], and by induction b[ ⁣[ρk,x↦x2] ⁣]=vq′b[\![\rho_k, x \mapsto x_2]\!] =_v q'. By the let rule and renaming, (fun x→b[ ⁣[ρk] ⁣]) q=vlet x2=q in b[ ⁣[ρk,x↦x2] ⁣]=vlet x2=q in q′(\texttt{fun } x \to b[\![\rho_k]\!])\ q =_v \texttt{let } x_2 = q \texttt{ in } b[\![\rho_k, x \mapsto x_2]\!] =_v \texttt{let } x_2 = q \texttt{ in } q'. No βv\beta_v step is used on qq, which need not be a value. For a fix closure, the fix rule is used in the same way, with ff bound to kk, whose meaning is the fix term itself.
  • Static let x = e1 in e2. The bound value r1r_1 is static, so w=[ ⁣[r1] ⁣]w = [\![r_1]\!] is a value, and by induction e1[ ⁣[ρ] ⁣]=vwe_1[\![\rho]\!] =_v w. Then let x=w in e2[ ⁣[ρ] ⁣]=ve2[ ⁣[ρ,x↦r1] ⁣]\texttt{let } x = w \texttt{ in } e_2[\![\rho]\!] =_v e_2[\![\rho, x \mapsto r_1]\!] by the let rule and βv\beta_v, and this is =v[ ⁣[r] ⁣]=_v [\![r]\!] by induction.
  • Static if. By induction the test is =v=_v to a constant true or false, the if rule picks the branch that the specializer runs, and induction applies to that branch.
  • Static operator. By induction both operands are =v=_v to constants, and the operator rule gives the constant the specializer computes. □\square

Theorem. Let the annotation be congruent, σ\sigma the values of the static inputs, and suppose the specializer stops with residual program rr. Then ee with σ\sigma substituted and rr are operationally equivalent. In particular, for every choice δ\delta of values of the dynamic inputs, e[σ,δ]e[\sigma, \delta] and r[δ]r[\delta] both run forever or both stop, with the same constant when the program has base type.

Proof. The root environment ρ0\rho_0 of Theorem 2 is good, and e[ ⁣[ρ0] ⁣]e[\![\rho_0]\!] is ee with σ\sigma substituted and the dynamic inputs left as variables. The lemma gives e[ ⁣[ρ0] ⁣]=vre[\![\rho_0]\!] =_v r, where rr is the root code or the lifted root constant. Plotkin's theorem gives operational equivalence. The context that binds the dynamic inputs to δ\delta, for example (fun d→[ ]) δ(\texttt{fun } d \to [\,])\ \delta for one input dd, gives the second sentence. □\square

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: βv\beta_v 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. NN is the number of nodes of the term, and TT is the total size of the simple types of all nodes and binders, written as trees, so T≥NT \ge N. L1 makes O(N)O(N) unification steps, and each occurs check walks a type of size at most TT, so L1 takes O(NT)O(N T) time. L2 makes TT variables. L4 and L5 add O(T)O(T) 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 O(T)O(T) time. The total time is O(NT)O(N T) and the space is Θ(T)\Theta(T).

TT is usually O(N)O(N), but simple types written as trees can be exponential in NN. A version that keeps types as shared graphs and unifies binding times with them, as Henglein did, runs in almost linear time in NN.

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 n in 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 SS or DD 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 d with static s, the call g d makes the parameter of g dynamic everywhere. For s = 5 the 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 DD.
  • 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.

binding_time_analysis.pyI0RawGitHub
# 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

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example