Algorithm Search⌘K

Algorithmadvanced

Strictness analysis

Also called Mycroft strictness analysis.

Finds functions of a lazy language that surely evaluate an argument, by abstract interpretation over a two-point domain, so it can be passed by value.

Time
O(4^k n) worst · averageΘ(2^k n) best
Space
Θ(2^k + n) extra
Where
k = the number of parameters; n = the size of the function body
Properties
deterministiciterative
Origin
Alan Mycroft, 1980

Strictness analysis finds, at compile time, the arguments that a function of a lazy language always evaluates. If ff is strict in its argument xix_i, then a call f e1…ekf\ e_1 \ldots e_k is undefined whenever eie_i is undefined. The compiler can then compute eie_i before the call and pass it by value, with no thunk for it. Mycroft's analysis (1980) maps every defined value to 11 and the undefined value ⊥\bot to 00. It evaluates the body of ff over {0,1}\{0, 1\}, with ∧\wedge for the operators and x∧(y∨z)x \wedge (y \vee z) for a conditional. For a recursive function it computes the least fixed point of the abstract function f♯:{0,1}k→{0,1}f^\sharp : \{0,1\}^k \to \{0,1\} by Kleene iteration on its table of 2k2^k entries. Then ff is strict in xix_i when f♯(1,…,1,0,1,…,1)=0f^\sharp(1, \ldots, 1, 0, 1, \ldots, 1) = 0, with the 00 in place ii. This is abstract interpretation of a denotational semantics, with a two-point abstract domain.

In plain words

A lazy language such as Haskell does not compute an argument when a function is called. It makes a thunk, a small record that knows how to compute the argument later, and computes it on the first use. An argument that is never used is never computed. But this is slow. A thunk takes memory, and a function that adds to an accumulator in a loop can build a long chain of thunks.

If a function surely uses an argument, there is no point in delaying it. Computing it early changes nothing: if the argument loops, the call loops anyway. Strictness analysis finds such arguments. It runs the function on two abstract values only: 00 for "this loops for sure" and 11 for "this may give a value". If putting 00 in one argument and 11 in all others still gives 00, the function needs that argument.

The problem

The input is one function in a first-order language with lazy parameters:

f x1…xk=body.f\ x_1 \ldots x_k = \mathit{body}.

The body is built from the parameters, integer and boolean constants, the operators ++, −-, ×\times, << and ==, conditionals if e1 then e2 else e3\mathbf{if}\ e_1\ \mathbf{then}\ e_2\ \mathbf{else}\ e_3, lazy bindings let x=e1 in e2\mathbf{let}\ x = e_1\ \mathbf{in}\ e_2, and calls f e1…ekf\ e_1 \ldots e_k of ff itself with all kk arguments. The meaning of ff is a function φ:Dk→D\varphi : D^k \to D, where D=Z∪{true,false}∪{⊥}D = \mathbb{Z} \cup \{\mathit{true}, \mathit{false}\} \cup \{\bot\} and ⊥\bot stands for a computation that loops or fails. An argument is passed unevaluated, so φ\varphi may give a value even when an argument is ⊥\bot.

The function is strict in xix_i if φ(d1,…,dk)=⊥\varphi(d_1, \ldots, d_k) = \bot whenever di=⊥d_i = \bot, for all values of the other arguments. This is undecidable in general, since ff might loop for all inputs. So the analysis gives a safe answer: it may miss a strict argument, but it never calls an argument strict when it is not.

The abstract domain is 2={0,1}\mathbf{2} = \{0, 1\} with 0⊑10 \sqsubseteq 1. The meaning of 00 is {⊥}\{\bot\} and the meaning of 11 is all of DD. The abstraction of a value is abs(⊥)=0\mathit{abs}(\bot) = 0 and abs(d)=1\mathit{abs}(d) = 1 for every other dd. This is a Galois connection between sets of values and 2\mathbf{2}, in the Cousot order: the lower element says more.

The algorithm

The table TT holds the current approximation of f♯f^\sharp, one bit for each point of {0,1}k\{0,1\}^k. ABS computes the abstract value of an expression from the abstract values of the names in scope, with the table for the recursive calls.

  1. STRICTNESS(f, x1 … xk, body)
  2. 1for each v in {0,1}^k do T[v] ← 0
  3. 2repeat
  4. 3for each v in {0,1}^k do T′[v] ← ABS(body, {xi ↦ vi}, T)
  5. 4stable ← (T′ = T)
  6. 5T ← T′
  7. 6until stable
  8. 7for i ← 1 to k do strict[i] ← (T[1 … 1, 0 at place i, 1 … 1] = 0)
  9. 8return T, strict
  10. ABS(e, ρ, T)
  11. 9if e is a constant then return 1
  12. 10if e is a name x then return ρ(x)
  13. 11if e = e1 op e2 then return ABS(e1, ρ, T) ∧ ABS(e2, ρ, T)
  14. 12if e = if e1 then e2 else e3 then return ABS(e1, ρ, T) ∧ (ABS(e2, ρ, T) ∨ ABS(e3, ρ, T))
  15. 13if e = let x = e1 in e2 then return ABS(e2, ρ[x ↦ ABS(e1, ρ, T)], T)
  16. 14if e = f e1 … ek then return T[ABS(e1, ρ, T), …, ABS(ek, ρ, T)]

Line L11 holds because every operator needs both operands: if one of them is ⊥\bot, so is the result. Line L12 says that the condition is always computed, and that the result is defined only if the branch that is taken is defined. Since the analysis does not know which branch is taken, it uses the join ∨\vee of the two. Line L13 binds xx without computing e1e_1: a lazy let is defined even if e1e_1 is not, as long as e2e_2 does not use xx. Line L14 reads the current guess for the recursive call.

Lines L1 to L6 are the Kleene iteration T0=λv. 0T_0 = \lambda v.\,0, Tj+1=F(Tj)T_{j+1} = F(T_j) with F(T)(v)=ABS(body,{xi↦vi},T)F(T)(v) = \mathrm{ABS}(\mathit{body}, \{x_i \mapsto v_i\}, T). Each TjT_j is a monotone table, the tables only go up, and there are 2k2^k entries that can go from 00 to 11. So the iteration stops, and it stops at the least fixed point of FF, as the Kleene fixed-point theorem gives. No widening is needed, since the domain is finite.

A runtime type error, such as 1 + true, is counted as ⊥\bot too. The analysis treats it the same way as a loop.

Example

Take this function, which swaps its second and third arguments on every call:

f x y z = if x == 0 then y else f (x - 1) z y

The abstract body is F(T)(x,y,z)=x∧(y∨T(x,z,y))F(T)(x, y, z) = x \wedge \bigl(y \vee T(x, z, y)\bigr). The condition x == 0 gives x∧1=xx \wedge 1 = x, the branch y gives yy, and the call gives T(x∧1,z,y)T(x \wedge 1, z, y). The iteration runs over the 8 points.

(x,y,z)(x, y, z) T0T_0 T1T_1 T2T_2 T3T_3
(0,0,0)(0, 0, 0) 0 0 0 0
(0,0,1)(0, 0, 1) 0 0 0 0
(0,1,0)(0, 1, 0) 0 0 0 0
(0,1,1)(0, 1, 1) 0 0 0 0
(1,0,0)(1, 0, 0) 0 0 0 0
(1,0,1)(1, 0, 1) 0 0 1 1
(1,1,0)(1, 1, 0) 0 1 1 1
(1,1,1)(1, 1, 1) 0 1 1 1

In closed form, T1=x∧yT_1 = x \wedge y and T2=x∧(y∨z)T_2 = x \wedge (y \vee z). Then T3=x∧(y∨(x∧(z∨y)))=T2T_3 = x \wedge (y \vee (x \wedge (z \vee y))) = T_2, so line L4 finds the table stable after three rounds. Line L7 reads three entries:

  • T(0,1,1)=0T(0, 1, 1) = 0, so ff is strict in xx.
  • T(1,0,1)=1T(1, 0, 1) = 1, so ff is not known to be strict in yy.
  • T(1,1,0)=1T(1, 1, 0) = 1, so ff is not known to be strict in zz.

The entry T(1,0,0)=0T(1, 0, 0) = 0 says more: if both yy and zz are undefined, so is the result. The lazy runs agree. With Ω\Omega a term that loops:

call the calls that follow result
f 3 Ω 5 f 2 5 Ω, f 1 Ω 5, f 0 5 Ω 5
f 2 Ω 5 f 1 5 Ω, f 0 Ω 5 loops
f Ω 1 5 the test Ω == 0 loops

So ff is really not strict in yy, and T1T_1 is not a safe answer: it would call ff strict in yy. Only the fixed point is safe.

A second function shows the common use:

sum n acc = if n == 0 then acc else sum (n - 1) (acc + n)

Here F(T)(n,a)=n∧(a∨T(n,a∧n))F(T)(n, a) = n \wedge (a \vee T(n, a \wedge n)), and the iteration gives T1=T2=n∧aT_1 = T_2 = n \wedge a. So sum is strict in both arguments. The compiler can compute acc + n before each call, and the chain of thunks ((0 + 4) + 3) + … never forms.

Correctness

Two facts are needed: the iteration computes the least fixed point of FF, and the least fixed point is safe.

The first is Kleene's theorem on the finite lattice of tables. FF is monotone, because ∧\wedge, ∨\vee and a lookup in a monotone table are monotone. So T0⊑T1⊑…T_0 \sqsubseteq T_1 \sqsubseteq \ldots, and every TjT_j is below every fixed point. The chain stops after at most 2k2^k strict steps.

For the second, let φ\varphi be the meaning of ff. It is the limit of φ0=λd. ⊥\varphi_0 = \lambda d.\,\bot and φj+1=Φ(φj)\varphi_{j+1} = \Phi(\varphi_j), where Φ\Phi is the concrete counterpart of FF. Say that a table TT covers a function ψ\psi if abs(ψ(d))≤T(a)\mathit{abs}(\psi(d)) \le T(a) whenever abs(di)≤ai\mathit{abs}(d_i) \le a_i for all ii. One induction on expressions shows that ABS covers the concrete evaluation of the body, case by case for lines L9 to L14. A second induction on jj shows that the least fixed point T∗T^* covers every φj\varphi_j. In a flat domain φ(d)=φj(d)\varphi(d) = \varphi_j(d) for some jj, so T∗T^* covers φ\varphi. If T∗(1,…,0,…,1)=0T^*(1, \ldots, 0, \ldots, 1) = 0, then φ(d)=⊥\varphi(d) = \bot for every dd with di=⊥d_i = \bot. This is the proof by fixed-point induction. The full proof is in the correctness proof.

The denotation φ\varphi agrees with the running program: a lazy call stops with a value exactly when its denotation is not ⊥\bot. This is the adequacy of the denotational semantics of recursion equations under call by name, which Winskel proves in The Formal Semantics of Programming Languages (1993), in the chapter on recursion equations.

Proof: STRICTNESS stops at the least fixed point of the abstract body, and every argument it calls strict is strictfull

We use the names of the pseudocode on the main page. Let 2={0,1}\mathbf{2} = \{0, 1\} with 0≤10 \le 1. A table is a map T:2k→2T : \mathbf{2}^k \to \mathbf{2}. Tables are ordered point by point: T≤ST \le S if T(a)≤S(a)T(a) \le S(a) for all aa. A table is monotone if a≤ba \le b point by point implies T(a)≤T(b)T(a) \le T(b). For a table TT, let F(T)(a)=ABS(body,{xi↦ai},T)F(T)(a) = \mathrm{ABS}(\mathit{body}, \{x_i \mapsto a_i\}, T), so line L3 computes T′=F(T)T' = F(T).

The concrete meaning

Let D=Z∪{true,false}∪{⊥}D = \mathbb{Z} \cup \{\mathit{true}, \mathit{false}\} \cup \{\bot\} be the flat domain: ⊥⊑d\bot \sqsubseteq d for all dd, and no other two elements are related. Here ⊥\bot stands for a loop and also for a runtime error. An environment ρ\rho maps names to DD. For a function ψ:Dk→D\psi : D^k \to D, the meaning C[e]ρψC[e]\rho\psi of an expression is:

  • C[c]ρψ=cC[c]\rho\psi = c for a constant cc, and C[x]ρψ=ρ(x)C[x]\rho\psi = \rho(x) for a name xx.
  • C[e1 op e2]ρψC[e_1\ \mathit{op}\ e_2]\rho\psi is the result of op\mathit{op} when both operands are integers, and ⊥\bot in all other cases.
  • C[if e1 then e2 else e3]ρψC[\mathbf{if}\ e_1\ \mathbf{then}\ e_2\ \mathbf{else}\ e_3]\rho\psi is C[e2]ρψC[e_2]\rho\psi if C[e1]ρψ=trueC[e_1]\rho\psi = \mathit{true}, C[e3]ρψC[e_3]\rho\psi if it is false\mathit{false}, and ⊥\bot in all other cases.
  • C[let x=e1 in e2]ρψ=C[e2]ρ[x↦C[e1]ρψ]ψC[\mathbf{let}\ x = e_1\ \mathbf{in}\ e_2]\rho\psi = C[e_2]\rho[x \mapsto C[e_1]\rho\psi]\psi.
  • C[f e1…ek]ρψ=ψ(C[e1]ρψ,…,C[ek]ρψ)C[f\ e_1 \ldots e_k]\rho\psi = \psi(C[e_1]\rho\psi, \ldots, C[e_k]\rho\psi).

The arguments of a call and the right side of a let are passed as meanings, not computed first: this is call by name. Let Φ(ψ)(d)=C[body]{xi↦di}ψ\Phi(\psi)(d) = C[\mathit{body}]\{x_i \mapsto d_i\}\psi. Φ\Phi is continuous on the domain of functions Dk→DD^k \to D, so the meaning of ff is its least fixed point

φ=⨆j≥0φj,φ0(d)=⊥,φj+1=Φ(φj).\varphi = \bigsqcup_{j \ge 0} \varphi_j, \qquad \varphi_0(d) = \bot, \qquad \varphi_{j+1} = \Phi(\varphi_j).

This is the standard denotational semantics of recursion equations under call by name. Its adequacy, that a lazy run of f d1…dkf\ d_1 \ldots d_k stops with a value exactly when φ(d)≠⊥\varphi(d) \ne \bot, is proved in Winskel's The Formal Semantics of Programming Languages (1993), in the chapter on recursion equations. We use it only to connect the result below with running programs.

Let abs(⊥)=0\mathit{abs}(\bot) = 0 and abs(d)=1\mathit{abs}(d) = 1 for d≠⊥d \ne \bot. For an abstract environment α\alpha that maps names to 2\mathbf{2}, write ρ⊲α\rho \lhd \alpha if abs(ρ(x))≤α(x)\mathit{abs}(\rho(x)) \le \alpha(x) for every name xx. A table TT covers a function ψ:Dk→D\psi : D^k \to D if abs(ψ(d))≤T(a)\mathit{abs}(\psi(d)) \le T(a) for all d∈Dkd \in D^k and a∈2ka \in \mathbf{2}^k with abs(di)≤ai\mathit{abs}(d_i) \le a_i for every ii.

Part 1: the iteration

Lemma 1 (monotonicity). Let TT be a monotone table with T≤ST \le S, and let α≤β\alpha \le \beta point by point. Then ABS(e,α,T)≤ABS(e,β,S)\mathrm{ABS}(e, \alpha, T) \le \mathrm{ABS}(e, \beta, S) for every expression ee.

Proof. By induction on ee, for all α≤β\alpha \le \beta at once.

  • Line L9: both sides are 11.
  • Line L10: α(x)≤β(x)\alpha(x) \le \beta(x).
  • Lines L11 and L12: by induction each operand on the left is at most the matching operand on the right, and ∧\wedge and ∨\vee are monotone in each argument.
  • Line L13: by induction ABS(e1,α,T)≤ABS(e1,β,S)\mathrm{ABS}(e_1, \alpha, T) \le \mathrm{ABS}(e_1, \beta, S), so α[x↦ABS(e1,α,T)]≤β[x↦ABS(e1,β,S)]\alpha[x \mapsto \mathrm{ABS}(e_1, \alpha, T)] \le \beta[x \mapsto \mathrm{ABS}(e_1, \beta, S)], and the induction hypothesis for e2e_2 gives the claim.
  • Line L14: let bb and b′b' be the vectors of the abstract values of the arguments on the left and on the right. By induction b≤b′b \le b'. Then T(b)≤T(b′)T(b) \le T(b') since TT is monotone, and T(b′)≤S(b′)T(b') \le S(b') since T≤ST \le S. □\square

With S=TS = T, Lemma 1 says that F(T)F(T) is monotone when TT is monotone. With α=β\alpha = \beta, it says that F(T)≤F(S)F(T) \le F(S) when TT is monotone and T≤ST \le S.

Theorem 1 (termination). Let T0T_0 be the table of line L1 and Tj+1=F(Tj)T_{j+1} = F(T_j). Every TjT_j is monotone, T0≤T1≤T2≤…T_0 \le T_1 \le T_2 \le \ldots, and the loop of lines L2 to L6 stops after at most 2k+12^k + 1 rounds, with T=TjT = T_j for the first jj such that Tj+1=TjT_{j+1} = T_j.

Proof. T0T_0 is constant, so it is monotone, and by Lemma 1 so is every TjT_j. T0≤T1T_0 \le T_1 since T0T_0 is the least table. If Tj≤Tj+1T_j \le T_{j+1}, then Tj+1=F(Tj)≤F(Tj+1)=Tj+2T_{j+1} = F(T_j) \le F(T_{j+1}) = T_{j+2} by Lemma 1, since TjT_j is monotone. So the chain goes up. Round j+1j + 1 computes T′=Tj+1T' = T_{j+1} from T=TjT = T_j in line L3, and line L4 tests Tj+1=TjT_{j+1} = T_j. While the test fails, Tj+1T_{j+1} has strictly more entries equal to 11 than TjT_j. There are only 2k2^k entries, so the test fails at most 2k2^k times, and the loop stops after at most 2k+12^k + 1 rounds. When it stops, line L5 sets T=T′=Tj+1=TjT = T' = T_{j+1} = T_j. □\square

Theorem 2 (least fixed point). The table T∗T^* that the loop returns satisfies F(T∗)=T∗F(T^*) = T^*, and T∗≤ST^* \le S for every table SS with F(S)≤SF(S) \le S. So T∗T^* is the least fixed point of FF.

Proof. F(T∗)=T∗F(T^*) = T^* is the stopping test of line L4. Let F(S)≤SF(S) \le S. Then T0≤ST_0 \le S, and if Tj≤ST_j \le S, Lemma 1 gives Tj+1=F(Tj)≤F(S)≤ST_{j+1} = F(T_j) \le F(S) \le S, since TjT_j is monotone. So T∗=Tj≤ST^* = T_j \le S. □\square

Part 2: soundness

Lemma 2 (local soundness). If ρ⊲α\rho \lhd \alpha and TT covers ψ\psi, then abs(C[e]ρψ)≤ABS(e,α,T)\mathit{abs}(C[e]\rho\psi) \le \mathrm{ABS}(e, \alpha, T) for every expression ee.

Proof. By induction on ee, for all ρ⊲α\rho \lhd \alpha at once. Write ci=C[ei]ρψc_i = C[e_i]\rho\psi and ai=ABS(ei,α,T)a_i = \mathrm{ABS}(e_i, \alpha, T). By the induction hypothesis, abs(ci)≤ai\mathit{abs}(c_i) \le a_i.

  • Line L9: the meaning is a constant, and abs\mathit{abs} of it is 1≤11 \le 1.
  • Line L10: abs(ρ(x))≤α(x)\mathit{abs}(\rho(x)) \le \alpha(x) since ρ⊲α\rho \lhd \alpha.
  • Line L11: if c1=⊥c_1 = \bot or c2=⊥c_2 = \bot, the meaning is ⊥\bot and the claim holds since abs(⊥)=0\mathit{abs}(\bot) = 0. Otherwise abs(c1)=abs(c2)=1\mathit{abs}(c_1) = \mathit{abs}(c_2) = 1, so a1=a2=1a_1 = a_2 = 1 and the right side is 11.
  • Line L12: if c1c_1 is not a boolean, the meaning is ⊥\bot. Otherwise abs(c1)=1\mathit{abs}(c_1) = 1, so a1=1a_1 = 1, and the meaning is c2c_2 or c3c_3. Then its abs\mathit{abs} is at most a2a_2 or a3a_3, so at most a2∨a3=a1∧(a2∨a3)a_2 \vee a_3 = a_1 \wedge (a_2 \vee a_3).
  • Line L13: ρ[x↦c1]⊲α[x↦a1]\rho[x \mapsto c_1] \lhd \alpha[x \mapsto a_1] since abs(c1)≤a1\mathit{abs}(c_1) \le a_1. The induction hypothesis for e2e_2 with these environments gives the claim.
  • Line L14: the meaning is ψ(c1,…,ck)\psi(c_1, \ldots, c_k) with abs(ci)≤ai\mathit{abs}(c_i) \le a_i for every ii. Since TT covers ψ\psi, abs(ψ(c))≤T(a)\mathit{abs}(\psi(c)) \le T(a), which is the right side. □\square

Theorem 3 (soundness). T∗T^* covers φ\varphi. So if line L7 sets strict[i]\mathit{strict}[i], then φ(d)=⊥\varphi(d) = \bot for every d∈Dkd \in D^k with di=⊥d_i = \bot: ff is strict in xix_i.

Proof. First, T∗T^* covers every φj\varphi_j, by induction on jj. It covers φ0\varphi_0, since abs(φ0(d))=0\mathit{abs}(\varphi_0(d)) = 0. Suppose it covers φj\varphi_j, and let abs(di)≤ai\mathit{abs}(d_i) \le a_i for every ii. Then {xi↦di}⊲{xi↦ai}\{x_i \mapsto d_i\} \lhd \{x_i \mapsto a_i\}, and Lemma 2 gives

abs(φj+1(d))=abs(C[body]{xi↦di}φj)≤ABS(body,{xi↦ai},T∗)=F(T∗)(a)=T∗(a).\mathit{abs}(\varphi_{j+1}(d)) = \mathit{abs}(C[\mathit{body}]\{x_i \mapsto d_i\}\varphi_j) \le \mathrm{ABS}(\mathit{body}, \{x_i \mapsto a_i\}, T^*) = F(T^*)(a) = T^*(a).

Now fix dd and aa with abs(di)≤ai\mathit{abs}(d_i) \le a_i. The values φj(d)\varphi_j(d) form a chain in the flat domain DD, so either they are all ⊥\bot and φ(d)=⊥\varphi(d) = \bot, or they are equal to one value v≠⊥v \ne \bot from some jj on and φ(d)=v=φj(d)\varphi(d) = v = \varphi_j(d). In both cases abs(φ(d))≤T∗(a)\mathit{abs}(\varphi(d)) \le T^*(a).

If strict[i]\mathit{strict}[i] is set, then T∗(p)=0T^*(p) = 0 for the point pp with pi=0p_i = 0 and pl=1p_l = 1 for l≠il \ne i. Every dd with di=⊥d_i = \bot has abs(dl)≤pl\mathit{abs}(d_l) \le p_l for every ll, so abs(φ(d))≤0\mathit{abs}(\varphi(d)) \le 0 and φ(d)=⊥\varphi(d) = \bot. □\square

The proof of Theorem 3 used only F(T∗)≤T∗F(T^*) \le T^*. So every post-fixed point of FF is safe, the greatest fixed point too. By Theorem 2 the least fixed point is below every post-fixed point, so of all these safe tables it finds the most strict arguments. A table below it, such as T1T_1 in the example of the main page, need not be safe. By adequacy, Theorem 3 also says that a lazy run of ff with an argument that loops in place ii never stops with a value. ■\blacksquare

Complexity

The table has 2k2^k entries, and each entry can change only from 00 to 11. Every round but the last changes at least one entry, so there are at most 2k+12^k + 1 rounds. A round evaluates the body at 2k2^k points, in O(n)O(n) time each. The total is O((2k+1)⋅2k⋅n)=O(4kn)O((2^k + 1) \cdot 2^k \cdot n) = O(4^k n) time in the worst case. At least two rounds are always needed, one to compute and one to see that nothing changed, so the best case is Θ(2kn)\Theta(2^k n), reached by every function with no recursion. The space is Θ(2k)\Theta(2^k) for the two tables and O(n)O(n) for the code of the body and the stack of ABS.

The cost is exponential in the number of parameters, not in the size of the program. For the small arities of real functions this is fine. For functions with many parameters, or for higher-order functions, where the abstract domains of functions grow much faster, the table is too large. The frontiers method of Clack and Peyton Jones (1985) stores a monotone table by the border between its 00 points and its 11 points, which is often much smaller.

Properties

  • Sound. If the analysis says that ff is strict in xix_i, then it is.
  • Not complete. The analysis may miss strictness. For g x y = if x == x then y else 0, it says that gg is not strict in yy, but the else branch is never taken, so gg is strict in yy.
  • Least fixed point. The result is the most precise table that is a fixed point of FF. Any other fixed point is also safe, but it gives fewer strict arguments.
  • Monotone tables. Every table TjT_j is monotone, and so is the result.
  • Deterministic. The order of the points in line L3 does not matter, because every T′[v]T'[v] reads only TT.

Variants and improvements

  • Systems of functions. For functions that call each other, keep one table for each function and update all tables in each round. The bound on the number of rounds becomes the total number of entries plus one.
  • In-place updates. Writing T[v]T[v] at once in line L3, instead of into T′T', often needs fewer rounds. It reaches the same least fixed point, by the theory of chaotic iterations.
  • Higher-order functions. Burn, Hankin and Abramsky (1986) extended the analysis to typed higher-order functions. The abstract value of a function is a monotone function between abstract domains, so the tables grow very fast with the order of the types.
  • Frontiers. Clack and Peyton Jones (1985) store each monotone table by its frontier, the border between the points with value 00 and the points with value 11, which can be much smaller than 2k2^k entries.
  • Data structures. A two-point domain cannot say "this function evaluates the whole list". Wadler (1987) used a four-point domain for lists, and Wadler and Hughes (1987) used projections to describe how much of a structure a function needs.
  • Demand analysis. Modern compilers for lazy languages, such as GHC, run a backward analysis that records how each argument is used, which descends from this line of work.

When to use it

Use it in a compiler for a lazy language, where it is one of the most useful optimizations: strict arguments can be computed early, kept unboxed and passed in registers, and accumulators no longer build chains of thunks. It also tells a parallel implementation which arguments can be computed at the same time as the call, which was the aim of Clack and Peyton Jones. A language that passes all arguments by value has no use for it, since every function is already strict in all its arguments in that semantics. For more than a handful of parameters, use frontiers or a type-based analysis instead of full tables.

Pitfalls

  • Starting from the top. Writing line L1 as T[v]←1T[v] \leftarrow 1 makes the iteration go down to the greatest fixed point. That table is safe but weak. For sum it gives T=nT = n, so it misses that sum is strict in acc. Line L1 must start from 00.
  • Stopping early. Writing line L6 as a fixed number of rounds, such as one, returns a table below the least fixed point, and that is not safe. In the example, T1=x∧yT_1 = x \wedge y calls ff strict in yy, but f 3 Ω 5 gives 5. Line L6 must wait for a stable table.
  • A conditional as an operator. Writing line L12 as ABS(e1)∧ABS(e2)∧ABS(e3)\mathrm{ABS}(e_1) \wedge \mathrm{ABS}(e_2) \wedge \mathrm{ABS}(e_3) claims that both branches are computed. Then h x y = if x == 0 then y else 1 looks strict in yy, but h 1 Ω gives 1. Line L12 must join the two branches with ∨\vee.
  • A strict let. Writing line L13 as ABS(e1)∧ABS(e2,ρ[x↦1])\mathrm{ABS}(e_1) \wedge \mathrm{ABS}(e_2, \rho[x \mapsto 1]) treats a lazy let as strict. Then k x = let y = x in 5 looks strict in xx, but k Ω gives 5. Line L13 must bind xx to the abstract value of e1e_1 and not compute it.
  • The wrong probe. Writing line L7 with 00 in all the other places, T[0,…,0]=0T[0, \ldots, 0] = 0, tests something else. For p x y = y that entry is 00, so pp would look strict in xx, but p Ω 1 gives 1. Line L7 must put 11 in every place but ii.

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.

strictness_analysis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/strictness-analysis/. The authors are listed in prov/GYNYB7.jsonl.
"""Mycroft's strictness analysis on the first-order fragment of toylam.py.

The input is one function, written as a toylam term:

    ("fix", f, x1, ("lam", x2, ... ("lam", xk, body)))   a recursive function
    ("lam", x1, ... ("lam", xk, body))                   a function with no recursion

The body may use the parameters, int and bool constants, the operators of
toylam, if, let, and full calls f e1 ... ek of the function itself. It may not
contain lambdas, fix terms or partial calls. The parameters are passed lazily
(call by name or call by need): an argument is only computed when it is used.

The abstract value 0 means "surely undefined" (the computation loops or fails)
and 1 means "may be defined". The analysis computes the least fixed point of
the abstract function f# : {0,1}^k -> {0,1} by Kleene iteration on its table,
and says f is strict in x_i when f#(1, ..., 1, 0, 1, ..., 1) = 0, with the 0
in place i. Then f e1 ... ek is undefined whenever e_i is undefined, so e_i
can be computed before the call.

Cost: with n the size of the body, at most 2^k + 1 rounds of 2^k evaluations
of the body, each O(n) time, so O((2^k + 1) 2^k n) time and O(2^k + n) space.
No function recurses on the term: the body is compiled once to postfix code.
"""

from itertools import product

CONST, VAR, AND, IF, BIND, UNBIND, CALL = range(7)


class FirstOrderFunction:
    """A parsed function: its name (None if not recursive), parameters and postfix code."""

    def __init__(self, name: str | None, params: list[str], code: list[tuple]):
        self.name = name
        self.params = params
        self.code = code


def parse_function(term: tuple) -> FirstOrderFunction:
    """Check that term is in the first-order fragment and compile its body.

    Raises ValueError otherwise. O(n) time, iterative.
    """
    if term[0] == "fix":
        name, params, body = term[1], [term[2]], term[3]
    elif term[0] == "lam":
        name, params, body = None, [term[1]], term[2]
    else:
        raise ValueError("a function must be a fix or a lam term")
    while body[0] == "lam":
        params.append(body[1])
        body = body[2]
    if len(set(params)) != len(params) or name in params:
        raise ValueError("the parameters and the name must be distinct")
    k = len(params)
    scope = {x: 1 for x in params}
    code: list[tuple] = []
    todo: list[tuple] = [("visit", body)]
    while todo:
        kind, item = todo.pop()
        if kind == "emit":
            code.append(item)
            if item[0] == UNBIND:
                scope[item[1]] -= 1
            continue
        if kind == "enter":
            scope[item] = scope.get(item, 0) + 1
            continue
        e = item
        tag = e[0]
        if tag in ("int", "bool"):
            code.append((CONST,))
        elif tag == "var":
            if scope.get(e[1], 0) == 0:
                raise ValueError(f"free or higher-order use of {e[1]!r}")
            code.append((VAR, e[1]))
        elif tag == "prim":
            todo += [("emit", (AND,)), ("visit", e[3]), ("visit", e[2])]
        elif tag == "if":
            todo += [("emit", (IF,)), ("visit", e[3]), ("visit", e[2]), ("visit", e[1])]
        elif tag == "let":
            if e[1] == name:
                raise ValueError("a let may not hide the function name")
            todo += [("emit", (UNBIND, e[1])), ("visit", e[3]), ("enter", e[1]),
                     ("emit", (BIND, e[1])), ("visit", e[2])]
        elif tag == "app":
            args = []
            head = e
            while head[0] == "app":
                args.append(head[2])
                head = head[1]
            if head != ("var", name) or name is None or len(args) != k:
                raise ValueError("only full calls of the function itself are allowed")
            todo.append(("emit", (CALL, k)))
            todo += [("visit", a) for a in args]  # args is reversed, so the first runs first
        else:
            raise ValueError(f"{tag} is not in the first-order fragment")
    return FirstOrderFunction(name, params, code)


def abstract_eval(fn: FirstOrderFunction, point: tuple[int, ...], table: dict) -> int:
    """ABS(body, {x_i -> point_i}, table): the abstract value of the body, O(n) time."""
    env = dict(zip(fn.params, point))
    stack: list[int] = []
    saved: list[int | None] = []
    for op in fn.code:
        t = op[0]
        if t == CONST:
            stack.append(1)  # @line L9
        elif t == VAR:
            stack.append(env[op[1]])  # @line L10
        elif t == AND:
            b = stack.pop()
            stack.append(stack.pop() & b)  # @line L11
        elif t == IF:
            e3 = stack.pop()
            e2 = stack.pop()
            stack.append(stack.pop() & (e2 | e3))  # @line L12
        elif t == BIND:
            saved.append(env.get(op[1]))  # @line L13
            env[op[1]] = stack.pop()  # @line L13
        elif t == UNBIND:
            old = saved.pop()
            if old is None:
                del env[op[1]]
            else:
                env[op[1]] = old
        else:
            k = op[1]
            args = tuple(stack[len(stack) - k:])
            del stack[len(stack) - k:]
            stack.append(table[args])  # @line L14
    return stack.pop()


def kleene_step(fn: FirstOrderFunction, table: dict) -> dict:
    """One round: the table F(T) with F(T)[v] = ABS(body, v, T)."""
    return {v: abstract_eval(fn, v, table) for v in table}  # @line L3


def analyse(term: tuple) -> tuple[dict, list[bool], int]:
    """Return (table of the least fixed point f#, strict flags per parameter, rounds)."""
    fn = parse_function(term)
    k = len(fn.params)
    table = {v: 0 for v in product((0, 1), repeat=k)}  # @line L1
    rounds = 0
    while True:  # @line L2
        new = kleene_step(fn, table)  # @line L3
        rounds += 1
        stable = new == table  # @line L4
        table = new  # @line L5
        if stable:  # @line L6
            break
    strict = []
    for i in range(k):  # @line L7
        probe = tuple(0 if j == i else 1 for j in range(k))
        strict.append(table[probe] == 0)  # @line L7
    return table, strict, rounds  # @line L8
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_strictness_analysis.py 274 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/strictness-analysis/. The authors are listed in prov/GYNYB7.jsonl.

import random
import sys
from itertools import product

import toylam as L
from strictness_analysis import abstract_eval, analyse, kleene_step, parse_function

sys.setrecursionlimit(20000)

U = "u_"  # the dummy parameter of a thunk
FUEL = 300  # the step bound; every run of the random test that stops at all stops well before it


def V(x):
    return ("var", x)


def app(a, b):
    return ("app", a, b)


def lam(x, e):
    return ("lam", x, e)


def num(k):
    return ("int", k)


def prim(op, a, b):
    return ("prim", op, a, b)


def call(f, *args):
    e = V(f)
    for a in args:
        e = app(e, a)
    return e


def function(name, params, body):
    """fix name p1 -> fun p2 -> ... -> body, or a plain lambda when name is None."""
    for p in reversed(params[1:]):
        body = lam(p, body)
    return ("fix", name, params[0], body) if name else lam(params[0], body)


# Omega: a closed term whose call-by-value run never stops.
OMEGA = app(("fix", "w", "y", app(V("w"), V("y"))), num(0))


def thunk(e):
    return lam(U, e)


def by_name(e, name):
    """Translate a body so that toylam's call-by-value run passes arguments by name.

    Every lazily bound name holds a thunk; a use forces it with (x 0).
    """
    tag = e[0]
    if tag == "var":
        return app(e, num(0))
    if tag in ("int", "bool"):
        return e
    if tag == "prim":
        return prim(e[1], by_name(e[2], name), by_name(e[3], name))
    if tag == "if":
        return ("if", by_name(e[1], name), by_name(e[2], name), by_name(e[3], name))
    if tag == "let":
        return ("let", e[1], thunk(by_name(e[2], name)), by_name(e[3], name))
    args = []
    while e[0] == "app":
        args.append(e[2])
        e = e[1]
    out = e
    for a in reversed(args):
        out = app(out, thunk(by_name(a, name)))
    return out


def run_lazily(name, params, body, args):
    """Run f a1 ... ak with lazy arguments; args are closed terms. Returns toylam's result."""
    f = function(name, params, by_name(body, name))
    return L.evaluate(call_term(f, [thunk(a) for a in args]), FUEL)


def call_term(f, args):
    e = f
    for a in args:
        e = app(e, a)
    return e


# The worked example: f x y z = if x == 0 then y else f (x - 1) z y.
SWAP_BODY = ("if", prim("==", V("x"), num(0)), V("y"),
             call("f", prim("-", V("x"), num(1)), V("z"), V("y")))
SWAP = function("f", ["x", "y", "z"], SWAP_BODY)


def test_worked_example():
    table, strict, rounds = analyse(SWAP)
    for (x, y, z), r in table.items():
        assert r == x & (y | z)
    assert strict == [True, False, False]
    assert rounds == 3
    fn = parse_function(SWAP)
    zero = {v: 0 for v in table}
    t1 = kleene_step(fn, zero)
    assert all(t1[v] == v[0] & v[1] for v in t1)
    t2 = kleene_step(fn, t1)
    assert t2 == table


def test_worked_example_runs():
    params = ["x", "y", "z"]
    assert run_lazily("f", params, SWAP_BODY, [num(3), OMEGA, num(5)]) == ("value", num(5))
    assert run_lazily("f", params, SWAP_BODY, [num(2), OMEGA, num(5)]) == ("fuel",)
    assert run_lazily("f", params, SWAP_BODY, [OMEGA, num(1), num(5)]) == ("fuel",)


def test_omega_diverges():
    assert L.evaluate(OMEGA, FUEL) == ("fuel",)


def test_accumulator_is_strict():
    body = ("if", prim("==", V("n"), num(0)), V("a"),
            call("s", prim("-", V("n"), num(1)), prim("+", V("a"), V("n"))))
    _, strict, _ = analyse(function("s", ["n", "a"], body))
    assert strict == [True, True]
    assert run_lazily("s", ["n", "a"], body, [num(4), num(0)]) == ("value", num(10))


def test_small_cases():
    # no recursion
    assert analyse(function(None, ["x", "y"], prim("+", V("x"), num(1))))[1] == [True, False]
    # a constant function is strict in nothing
    table, strict, _ = analyse(function(None, ["x"], num(3)))
    assert strict == [False] and table[(0,)] == 1
    # f x = f x is undefined everywhere, so it is strict
    table, strict, _ = analyse(function("f", ["x"], call("f", V("x"))))
    assert strict == [True] and set(table.values()) == {0}
    # a lazy let does not force its right side
    assert analyse(function(None, ["x"], ("let", "y", V("x"), num(5))))[1] == [False]
    assert analyse(function(None, ["x"], ("let", "y", V("x"), V("y"))))[1] == [True]
    # a let may hide a parameter
    body = ("let", "x", num(1), V("x"))
    assert analyse(function(None, ["x"], body))[1] == [False]
    # a condition is always computed, a branch is not
    body = ("if", prim("<", V("x"), num(1)), V("y"), num(0))
    assert analyse(function(None, ["x", "y"], body))[1] == [True, False]


def test_rejects_other_terms():
    bad = [
        num(1),
        function("f", ["x"], V("f")),
        function("f", ["x", "y"], call("f", V("x"))),
        function(None, ["x"], prim("+", V("x"), app(lam("y", V("y")), num(1)))),
        function(None, ["x"], V("y")),
        function("f", ["x"], ("let", "f", num(1), V("x"))),
    ]
    for t in bad:
        try:
            parse_function(t)
        except ValueError:
            continue
        raise AssertionError(f"accepted {t!r}")


def is_monotone(table):
    return all(table[a] <= table[b] for a in table for b in table
               if all(p <= q for p, q in zip(a, b)))


def brute_force_lfp(fn, k):
    """The least fixed point found among all 2^(2^k) tables."""
    points = list(product((0, 1), repeat=k))
    fixed = []
    for bits in product((0, 1), repeat=len(points)):
        t = dict(zip(points, bits))
        if kleene_step(fn, t) == t:
            fixed.append(t)
    least = [t for t in fixed if all(all(t[v] <= s[v] for v in points) for s in fixed)]
    assert len(least) == 1
    return least[0]


# A random generator of well typed first-order functions with int results.
def gen_int(rng, depth, scope, name, k):
    if depth <= 0 or rng.random() < 0.2:
        if scope and rng.random() < 0.7:
            return V(rng.choice(scope))
        return num(rng.randint(0, 3))
    r = rng.random()
    d = depth - 1
    if r < 0.3:
        return ("if", gen_bool(rng, d, scope, name, k), gen_int(rng, d, scope, name, k),
                gen_int(rng, d, scope, name, k))
    if r < 0.55:
        return prim(rng.choice("+-*"), gen_int(rng, d, scope, name, k), gen_int(rng, d, scope, name, k))
    if r < 0.7:
        x = rng.choice(("p", "q"))
        return ("let", x, gen_arg(rng, scope), gen_int(rng, d, scope + [x], name, k))
    if name and r < 0.9:
        return call(name, *[gen_arg(rng, scope) for _ in range(k)])
    return V(rng.choice(scope)) if scope else num(1)


def gen_arg(rng, scope):
    """An argument of a call: at most one name, so the thunks of a lazy run stay small."""
    r = rng.random()
    if not scope or r < 0.2:
        return num(rng.randint(0, 3))
    x = V(rng.choice(scope))
    if r < 0.6:
        return x
    return prim(rng.choice("+-"), x, num(rng.randint(1, 2)))


def gen_bool(rng, depth, scope, name, k):
    return prim(rng.choice(("<", "==")), gen_int(rng, depth, scope, name, k),
                gen_int(rng, depth, scope, name, k))


def random_function(rng):
    k = rng.randint(1, 3)
    params = ["x", "y", "z"][:k]
    name = "f" if rng.random() < 0.8 else None
    if name:
        # guard the recursion with a test on the first argument, so many runs stop
        body = ("if", prim("<", V("x"), num(1)), gen_int(rng, 2, params, None, k),
                gen_int(rng, 3, params, name, k))
    else:
        body = gen_int(rng, 4, params, None, k)
    return name, params, body


def test_random_against_lazy_runs():
    """If the analysis says f is strict in x_i, then f with a looping x_i must not stop."""
    rng = random.Random(2024)
    checked = stopped_when_lazy = 0
    for _ in range(600):
        name, params, body = random_function(rng)
        table, strict, rounds = analyse(function(name, params, body))
        k = len(params)
        assert is_monotone(table)
        assert rounds <= 2 ** k + 1
        for i in range(k):
            args = [num(rng.randint(-2, 4)) for _ in range(k)]
            args[i] = OMEGA
            result = run_lazily(name, params, body, args)
            if strict[i]:
                checked += 1
                assert result[0] != "value", (L.show(body), i, result)
            elif result[0] == "value":
                stopped_when_lazy += 1
    assert checked >= 300 and stopped_when_lazy >= 100


def test_random_against_brute_force_lfp():
    rng = random.Random(7)
    for _ in range(500):
        name, params, body = random_function(rng)
        if len(params) > 2:
            continue
        fn = parse_function(function(name, params, body))
        table, _, _ = analyse(function(name, params, body))
        assert table == brute_force_lfp(fn, len(params))
        for v in table:
            assert abstract_eval(fn, v, table) == table[v]

History

Mycroft introduced the analysis in 1980, at the International Symposium on Programming in Paris, and developed it in his Edinburgh thesis of 1981. He framed it as an abstract interpretation in the sense of Cousot and Cousot (1977), applied to the denotational semantics of recursion equations, and used it to change call by need into call by value where it is safe. Clack and Peyton Jones (1985) looked at the cost of the fixed point and introduced frontiers. Burn, Hankin and Abramsky (1986) gave the higher-order version and its proof of soundness. Wadler and Hughes (1987) handled data structures with projections. Strictness analysis became a standard part of compilers for lazy languages.

References

  1. Alan Mycroft, The theory and practice of transforming call-by-need into call-by-value, International Symposium on Programming 1980, LNCS 83, pages 269 to 281, the two-point abstraction of a flat domain, the abstract functions of first-order recursive programs, their computation as least fixed points, and the use of the result to evaluate arguments before the call
  2. Geoffrey Burn, Chris Hankin and Samson Abramsky, Strictness analysis for higher-order functions, Science of Computer Programming 7(3), 1986, pages 249 to 278, the extension of the two-point analysis to typed higher-order functions, with abstract domains of monotone functions, and its proof of soundness
  3. Chris Clack and Simon Peyton Jones, Strictness analysis, a practical approach, FPCA 1985, LNCS 201, pages 35 to 49, the cost of computing the fixed point by full tables, and the frontiers method that stores a monotone table by the border between its points with value 0 and its points with value 1

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.average
  • a full proof of time.best
  • 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
  • a scene preset for the example