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
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Alan Mycroft, 1980
Strictness analysis finds, at compile time, the arguments that a function of a lazy language always evaluates. If is strict in its argument , then a call is undefined whenever is undefined. The compiler can then compute before the call and pass it by value, with no thunk for it. Mycroft's analysis (1980) maps every defined value to and the undefined value to . It evaluates the body of over , with for the operators and for a conditional. For a recursive function it computes the least fixed point of the abstract function by Kleene iteration on its table of entries. Then is strict in when , with the in place . 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: for "this loops for sure" and for "this may give a value". If putting in one argument and in all others still gives , the function needs that argument.
The problem
The input is one function in a first-order language with lazy parameters:
The body is built from the parameters, integer and boolean constants, the operators , , , and , conditionals , lazy bindings , and calls of itself with all arguments. The meaning of is a function , where and stands for a computation that loops or fails. An argument is passed unevaluated, so may give a value even when an argument is .
The function is strict in if whenever , for all values of the other arguments. This is undecidable in general, since 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 with . The meaning of is and the meaning of is all of . The abstraction of a value is and for every other . This is a Galois connection between sets of values and , in the Cousot order: the lower element says more.
The algorithm
The table holds the current approximation of , one bit for each point of . ABS computes the abstract value of an expression from the abstract values of the names in scope, with the table for the recursive calls.
STRICTNESS(f, x1 … xk, body)- 1
for each v in {0,1}^k do T[v] ← 0 - 2
repeat - 3
for each v in {0,1}^k do T′[v] ← ABS(body, {xi ↦ vi}, T) - 4
stable ← (T′ = T) - 5
T ← T′ - 6
until stable - 7
for i ← 1 to k do strict[i] ← (T[1 … 1, 0 at place i, 1 … 1] = 0) - 8
return T, strict ABS(e, ρ, T)- 9
if e is a constant then return 1 - 10
if e is a name x then return ρ(x) - 11
if e = e1 op e2 then return ABS(e1, ρ, T) ∧ ABS(e2, ρ, T) - 12
if e = if e1 then e2 else e3 then return ABS(e1, ρ, T) ∧ (ABS(e2, ρ, T) ∨ ABS(e3, ρ, T)) - 13
if e = let x = e1 in e2 then return ABS(e2, ρ[x ↦ ABS(e1, ρ, T)], T) - 14
if 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 , 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 of the two. Line L13 binds without computing : a lazy let is defined even if is not, as long as does not use . Line L14 reads the current guess for the recursive call.
Lines L1 to L6 are the Kleene iteration , with . Each is a monotone table, the tables only go up, and there are entries that can go from to . So the iteration stops, and it stops at the least fixed point of , 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 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 . The condition x == 0 gives , the branch y gives , and the call gives . The iteration runs over the 8 points.
| 0 | 0 | 0 | 0 | |
| 0 | 0 | 0 | 0 | |
| 0 | 0 | 0 | 0 | |
| 0 | 0 | 0 | 0 | |
| 0 | 0 | 0 | 0 | |
| 0 | 0 | 1 | 1 | |
| 0 | 1 | 1 | 1 | |
| 0 | 1 | 1 | 1 |
In closed form, and . Then , so line L4 finds the table stable after three rounds. Line L7 reads three entries:
- , so is strict in .
- , so is not known to be strict in .
- , so is not known to be strict in .
The entry says more: if both and are undefined, so is the result. The lazy runs agree. With 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 is really not strict in , and is not a safe answer: it would call strict in . 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 , and the iteration gives . 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 , and the least fixed point is safe.
The first is Kleene's theorem on the finite lattice of tables. is monotone, because , and a lookup in a monotone table are monotone. So , and every is below every fixed point. The chain stops after at most strict steps.
For the second, let be the meaning of . It is the limit of and , where is the concrete counterpart of . Say that a table covers a function if whenever for all . 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 shows that the least fixed point covers every . In a flat domain for some , so covers . If , then for every with . This is the proof by fixed-point induction. The full proof is in the correctness proof.
The denotation agrees with the running program: a lazy call stops with a value exactly when its denotation is not . 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 with . A table is a map . Tables are ordered point by point: if for all . A table is monotone if point by point implies . For a table , let , so line L3 computes .
The concrete meaning
Let be the flat domain: for all , and no other two elements are related. Here stands for a loop and also for a runtime error. An environment maps names to . For a function , the meaning of an expression is:
- for a constant , and for a name .
- is the result of when both operands are integers, and in all other cases.
- is if , if it is , and in all other cases.
- .
- .
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 . is continuous on the domain of functions , so the meaning of is its least fixed point
This is the standard denotational semantics of recursion equations under call by name. Its adequacy, that a lazy run of stops with a value exactly when , 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 and for . For an abstract environment that maps names to , write if for every name . A table covers a function if for all and with for every .
Part 1: the iteration
Lemma 1 (monotonicity). Let be a monotone table with , and let point by point. Then for every expression .
Proof. By induction on , for all at once.
- Line L9: both sides are .
- Line L10: .
- Lines L11 and L12: by induction each operand on the left is at most the matching operand on the right, and and are monotone in each argument.
- Line L13: by induction , so , and the induction hypothesis for gives the claim.
- Line L14: let and be the vectors of the abstract values of the arguments on the left and on the right. By induction . Then since is monotone, and since .
With , Lemma 1 says that is monotone when is monotone. With , it says that when is monotone and .
Theorem 1 (termination). Let be the table of line L1 and . Every is monotone, , and the loop of lines L2 to L6 stops after at most rounds, with for the first such that .
Proof. is constant, so it is monotone, and by Lemma 1 so is every . since is the least table. If , then by Lemma 1, since is monotone. So the chain goes up. Round computes from in line L3, and line L4 tests . While the test fails, has strictly more entries equal to than . There are only entries, so the test fails at most times, and the loop stops after at most rounds. When it stops, line L5 sets .
Theorem 2 (least fixed point). The table that the loop returns satisfies , and for every table with . So is the least fixed point of .
Proof. is the stopping test of line L4. Let . Then , and if , Lemma 1 gives , since is monotone. So .
Part 2: soundness
Lemma 2 (local soundness). If and covers , then for every expression .
Proof. By induction on , for all at once. Write and . By the induction hypothesis, .
- Line L9: the meaning is a constant, and of it is .
- Line L10: since .
- Line L11: if or , the meaning is and the claim holds since . Otherwise , so and the right side is .
- Line L12: if is not a boolean, the meaning is . Otherwise , so , and the meaning is or . Then its is at most or , so at most .
- Line L13: since . The induction hypothesis for with these environments gives the claim.
- Line L14: the meaning is with for every . Since covers , , which is the right side.
Theorem 3 (soundness). covers . So if line L7 sets , then for every with : is strict in .
Proof. First, covers every , by induction on . It covers , since . Suppose it covers , and let for every . Then , and Lemma 2 gives
Now fix and with . The values form a chain in the flat domain , so either they are all and , or they are equal to one value from some on and . In both cases .
If is set, then for the point with and for . Every with has for every , so and .
The proof of Theorem 3 used only . So every post-fixed point of 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 in the example of the main page, need not be safe. By adequacy, Theorem 3 also says that a lazy run of with an argument that loops in place never stops with a value.
Complexity
The table has entries, and each entry can change only from to . Every round but the last changes at least one entry, so there are at most rounds. A round evaluates the body at points, in time each. The total is 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 , reached by every function with no recursion. The space is for the two tables and 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 points and its points, which is often much smaller.
Properties
- Sound. If the analysis says that is strict in , then it is.
- Not complete. The analysis may miss strictness. For
g x y = if x == x then y else 0, it says that is not strict in , but theelsebranch is never taken, so is strict in . - Least fixed point. The result is the most precise table that is a fixed point of . Any other fixed point is also safe, but it gives fewer strict arguments.
- Monotone tables. Every table is monotone, and so is the result.
- Deterministic. The order of the points in line L3 does not matter, because every reads only .
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 at once in line L3, instead of into , 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 and the points with value , which can be much smaller than 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 makes the iteration go down to the greatest fixed point. That table is safe but weak. For
sumit gives , so it misses thatsumis strict inacc. Line L1 must start from . - 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, calls strict in , but
f 3 Ω 5gives 5. Line L6 must wait for a stable table. - A conditional as an operator. Writing line L12 as claims that both branches are computed. Then
h x y = if x == 0 then y else 1looks strict in , buth 1 Ωgives 1. Line L12 must join the two branches with . - A strict let. Writing line L13 as treats a lazy
letas strict. Thenk x = let y = x in 5looks strict in , butk Ωgives 5. Line L13 must bind to the abstract value of and not compute it. - The wrong probe. Writing line L7 with in all the other places, , tests something else. For
p x y = ythat entry is , so would look strict in , butp Ω 1gives 1. Line L7 must put in every place but .
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag GYNYB7 Edit this page History Report an error Markdown