Algorithm Search⌘K

Algorithmadvanced

k-CFA

Also called Shivers k-CFA, k-limited control flow analysis.

Control flow analysis of higher-order programs that keeps a separate binding of each variable for each string of the last k call sites.

Time
2^O((k+1) n log n) worst
Space
2^O((k+1) n log n) extra
Where
k = the length of the call strings; n = the number of nodes of the program
Properties
context sensitivedeterministicnot flow sensitiveofflineiterative
Origin
Olin Shivers, 1991

k-CFA is a family of control flow analyses for higher-order programs, one for each k≥0k \ge 0. Like 0-CFA, it finds the functions that each expression may evaluate to, which gives a call graph. Unlike 0-CFA, it binds each variable separately for each contour, the string of the last kk call sites that led to the binding. A closure records the contour of each of its free variables. For k=0k = 0 there is one contour, and k-CFA is 0-CFA. For k≥1k \ge 1 the answers are more precise, but the number of abstract closures can be exponential, and deciding k-CFA is EXPTIME-complete (the k-CFA theorem).

In plain words

0-CFA gives each variable one bag of functions for the whole program. If a helper such as id is called in two places, both arguments land in the same bag, and both callers get both back. k-CFA gives each variable one bag per context. The context of a binding is the list of the last k call sites on the way to it. With k = 1, the call id f at one place and id g at another use different bags, so each caller only gets its own function back. A function value also remembers the context of each variable it uses. More contexts mean more precise answers, but the number of these remembered contexts can explode.

The problem

The input is a closed term of the toy language of the 0-CFA page and a number k≥0k \ge 0. A contour δ\delta is a sequence of at most kk application labels. A call at application tt in contour δ\delta runs the body in the contour next(δ,t)\mathrm{next}(\delta, t), the last kk elements of δ\delta followed by tt. A let binds in the current contour. An abstract environment cece maps the free variables of a node to contours, and an abstract closure is a pair (λ,ce)(\lambda, ce).

The output is the least analysis (T,C,R)(T, C, R) where TT is a set of tasks (t,ce,δ)(t, ce, \delta) (the ways node tt may be evaluated), C[(t,δ)]C[(t, \delta)] is a set of abstract closures for each node and contour, and R[(b,δ)]R[(b, \delta)] is one for each binder and contour, closed under the rules of lines L6 to L15. The call graph forgets the contours: (t,λ)(t, \lambda) is an edge when some closure of λ\lambda is in C[(t1,δ)]C[(t_1, \delta)] for the operator t1t_1 of tt.

item value
direction none: flow-insensitive, one answer for the whole program
may or must may
domain tasks, and maps from (node, contour) and (binder, contour) to sets of abstract closures
order inclusion in all parts (bottom is precise)
join union in all parts
bottom and top everything empty, and every task with every set full
boundary value the task of the root, with the empty environment and the empty contour
initial value the root task only
transfer the rules below; monotone, and not distributive, since a call needs both a closure and its task

The algorithm

  1. K-CFA(e, k)
  2. 1label e; T <- {(root, {}, ())}
  3. 2repeat
  4. 3for each task (t, ce, d) in T do RULE(t, ce, d)
  5. 4until the last pass added no task and no set element
  6. 5return C and R
  7. RULE(t, ce, d)
  8. 6if t is a variable x with binder b then add R[(b, ce(x))] to C[(t, d)]
  9. 7if t is a function then add the closure (t, ce) to C[(t, d)]
  10. 8if t is let x = t1 in t2 then TASK(t1, ce, d); add C[(t1, d)] to R[(x, d)]; TASK(t2, ce[x -> d], d); add C[(t2, d)] to C[(t, d)]
  11. 9if t is if or an operator then TASK each subterm with (ce, d); for if, add C[(t2, d)] and C[(t3, d)] to C[(t, d)]
  12. 10if t is t1 t2 then TASK(t1, ce, d); TASK(t2, ce, d)
  13. 11for each closure (λ, ce') in C[(t1, d)] do
  14. 12d' <- the last k labels of d followed by t
  15. 13add C[(t2, d)] to R[(param(λ), d')]; for fix f x -> body, add (λ, ce') to R[(f, d')]
  16. 14TASK(body(λ), ce' with the parameters mapped to d', d')
  17. 15add C[(body(λ), d')] to C[(t, d)]
  18. TASK(t, ce, d)
  19. 16add (t, ce restricted to the free variables of t, d) to T

A task is one way that a node may be evaluated: with which contours for its free variables and in which current contour. Line L16 restricts the environment to the free variables, so two tasks that differ only in variables the node does not use are one task. Line L6 looks up the contour of xx in the environment, not the current contour, because xx may have been bound by an outer function in an older call. The loop of lines L2 to L4 applies every rule again until nothing changes. A worklist with dependencies, as on the 0-CFA page, gives the same result faster.

Example

The program of the 0-CFA page:

let id = fun x -> x in
let a = id (fun y -> y + 1) in     // call site s1
let b = id (fun z -> z * 2) in     // call site s2
a 3                                // call site s3

With k=1k = 1, the two calls of id run its body in different contours.

fact 1-CFA 0-CFA
xx in contour [s1][s_1]: λy\lambda_y; in contour [s2][s_2]: λz\lambda_z λy,λz\lambda_y, \lambda_z
body x of id in [s1][s_1]: λy\lambda_y; in [s2][s_2]: λz\lambda_z λy,λz\lambda_y, \lambda_z
aa λy\lambda_y λy,λz\lambda_y, \lambda_z
bb λz\lambda_z λy,λz\lambda_y, \lambda_z
targets of s3 λy\lambda_y λy,λz\lambda_y, \lambda_z

1-CFA finds exactly the calls of the run. Now wrap id in another function:

let id = fun x -> x in
let g = fun w -> id w in           // call site s0 inside g
let a = g (fun y -> y + 1) in      // s1
let b = g (fun z -> z * 2) in      // s2
a 3

With k=1k = 1, ww is split by [s1][s_1] and [s2][s_2], but both calls of id happen at s0s_0, so xx has the single contour [s0][s_0] and gets both functions back. a 3 again has two targets. With k=2k = 2, the contours of xx are [s1,s0][s_1, s_0] and [s2,s0][s_2, s_0], and the spurious target goes away. Every extra layer of wrappers needs one more unit of kk.

Correctness

Least solution. Every task and every element that a pass adds is the conclusion of one of the rules, applied to facts that are already forced. So by induction the result is inside every closed analysis. The loop stops only after a pass in which every rule held, so the result is closed. Termination holds because there are finitely many contours, abstract closures and tasks.

Soundness. Instrument the run with contours: a call at tt in contour δ\delta runs the body in next(δ,t)\mathrm{next}(\delta, t), and each binding stores the contour in which it was made. The abstraction of a closure keeps its function and the contours of its free variables. By induction on the evaluation, if node tt is evaluated in contour δ\delta with environment ρ\rho, then its task is in TT, and the abstraction of its value is in C[(t,δ)]C[(t, \delta)]. The step for a call uses that the concrete and the abstract contour of the callee are both next(δ,t)\mathrm{next}(\delta, t). So every call of the run is in the call graph. The full proofs are in the proof file.

Proof: The round-robin k-CFA stops with the least closed analysis, which is sound for call-by-value runs with contoursfull

Setting. The program is a closed term of the toy language of the 0-CFA page, with labels, binders, functions Λ\Lambda, param(λ)\mathrm{param}(\lambda) and body(λ)\mathrm{body}(\lambda) as there, and fv(t)\mathrm{fv}(t) the free names of node tt. Fix k≥0k \ge 0. A contour δ\delta is a sequence of at most kk application labels. For a contour δ\delta and an application tt, next(δ,t)\mathrm{next}(\delta, t) is the last kk elements of δ\delta followed by tt (the empty sequence when k=0k = 0). An abstract environment cece maps names to contours, and ce∣tce|_t is its restriction to fv(t)\mathrm{fv}(t). An abstract closure is a pair (λ,ce)(\lambda, ce) with cece defined exactly on fv(λ)\mathrm{fv}(\lambda).

An analysis is a triple (T,C,R)(T, C, R): a set TT of tasks (t,ce,δ)(t, ce, \delta) with cece defined on fv(t)\mathrm{fv}(t), a set C[(t,δ)]C[(t, \delta)] of abstract closures for each label and contour, and a set R[(b,δ)]R[(b, \delta)] for each binder and contour. It is closed if (root,∅,())(root, \emptyset, ()) is in TT and every task (t,ce,δ)∈T(t, ce, \delta) \in T satisfies the rule of lines L6 to L15:

  1. a variable xx with binder bb: R[(b,ce(x))]⊆C[(t,δ)]R[(b, ce(x))] \subseteq C[(t, \delta)];
  2. a function: (t,ce)∈C[(t,δ)](t, ce) \in C[(t, \delta)];
  3. let x = t1 in t2: (t1,ce∣t1,δ)∈T(t_1, ce|_{t_1}, \delta) \in T, C[(t1,δ)]⊆R[((t,x),δ)]C[(t_1, \delta)] \subseteq R[((t, x), \delta)], (t2,ce[x↦δ]∣t2,δ)∈T(t_2, ce[x \mapsto \delta]|_{t_2}, \delta) \in T and C[(t2,δ)]⊆C[(t,δ)]C[(t_2, \delta)] \subseteq C[(t, \delta)];
  4. if and operators: each direct subterm uu has (u,ce∣u,δ)∈T(u, ce|_u, \delta) \in T, and for if t1 then t2 else t3, C[(t2,δ)]∪C[(t3,δ)]⊆C[(t,δ)]C[(t_2, \delta)] \cup C[(t_3, \delta)] \subseteq C[(t, \delta)];
  5. t1 t2: (t1,ce∣t1,δ),(t2,ce∣t2,δ)∈T(t_1, ce|_{t_1}, \delta), (t_2, ce|_{t_2}, \delta) \in T, and for every (λ,ce′)∈C[(t1,δ)](\lambda, ce') \in C[(t_1, \delta)], with δ′=next(δ,t)\delta' = \mathrm{next}(\delta, t) and ce′′ce'' equal to ce′ce' with the parameters of λ\lambda mapped to δ′\delta': C[(t2,δ)]⊆R[(param(λ),δ′)]C[(t_2, \delta)] \subseteq R[(\mathrm{param}(\lambda), \delta')]; if λ\lambda is fix f x -> e, (λ,ce′)∈R[((λ,f),δ′)](\lambda, ce') \in R[((\lambda, f), \delta')]; (body(λ),ce′′∣body(λ),δ′)∈T(\mathrm{body}(\lambda), ce''|_{\mathrm{body}(\lambda)}, \delta') \in T; and C[(body(λ),δ′)]⊆C[(t,δ)]C[(\mathrm{body}(\lambda), \delta')] \subseteq C[(t, \delta)].

Each rule keeps holding when the sets on its right side grow, so the intersection of closed analyses is closed and a least closed analysis exists.

Lemma 1 (finiteness). There are finitely many tasks, keys and abstract closures. With nn nodes, the number of contours is N=∑i=0kni≤(n+1)kN = \sum_{i=0}^{k} n^i \le (n + 1)^k, the number of abstract closures is at most Q=n⋅NnQ = n \cdot N^{n}, and the number of tasks is at most n⋅Nn⋅Nn \cdot N^{n} \cdot N.

Proof. A contour is a sequence of at most kk labels. An abstract closure is a function label and a map from at most nn names to contours. A task is a label, a map from at most nn names to contours and a contour. □\square

Lemma 2 (termination). The loop of lines L2 to L4 stops.

Proof. Every pass that does not stop the loop adds a task or an element to some set. Sets and tasks never shrink, and by Lemma 1 they live in finite sets. So the number of passes is at most the number of possible tasks plus the number of possible pairs of a key and a closure, plus one. □\square

Lemma 3 (every fact is forced). Let (T∗,C∗,R∗)(T^*, C^*, R^*) be any closed analysis. At all times T⊆T∗T \subseteq T^*, C⊆C∗C \subseteq C^* and R⊆R∗R \subseteq R^*.

Proof. By induction over the steps. Line L1 adds the root task, which is in T∗T^*. Every other addition is made by the rule of a task (t,ce,δ)∈T⊆T∗(t, ce, \delta) \in T \subseteq T^*, and it is the conclusion of rule 1 to 5 for this task, with premises (the sets read and the closures picked in line L11) inside C∗C^* and R∗R^* by induction. Since (T∗,C∗,R∗)(T^*, C^*, R^*) is closed, the same conclusion holds there. □\square

Theorem 1 (least closed analysis). The algorithm stops and returns the least closed analysis.

Proof. It stops by Lemma 2. In the last pass, the rule of every task ran and changed nothing, so every task satisfies its rule with the final sets, and the result is closed. By Lemma 3 it is inside every closed analysis. □\square

The semantics with contours. A value is a constant or a closure (λ,ρ)(\lambda, \rho), where an environment ρ\rho maps each name to a pair of a contour and a value. Evaluation ρ⊢δt⇓v\rho \vdash_\delta t \Downarrow v is call-by-value with a current contour δ\delta. A let binds xx to (δ,v1)(\delta, v_1) and stays in δ\delta. A call at application tt of a closure (λ,ρ′)(\lambda, \rho') binds the parameters of λ\lambda to next(δ,t)\mathrm{next}(\delta, t), with the argument and, for a fix, the closure itself, and runs the body in the contour next(δ,t)\mathrm{next}(\delta, t). The contours do not change the values: dropping them gives the plain environment semantics. The abstraction of an environment is $|\rho|(x) = $ the contour of ρ(x)\rho(x), and of a closure is ∣(λ,ρ)∣=(λ,∣ρ∣ ∣λ)|(\lambda, \rho)| = (\lambda, |\rho|\,|_\lambda).

An environment ρ\rho is good if, for each name xx in it, with binder bb at the place where ρ\rho is used and ρ(x)=(c,v)\rho(x) = (c, v), either vv is a constant or v=(λ,ρ1)v = (\lambda, \rho_1) with ∣v∣∈R[(b,c)]|v| \in R[(b, c)] and ρ1\rho_1 good.

Lemma 4 (the evaluation invariant). Let (T,C,R)(T, C, R) be closed. If (t,∣ρ∣ ∣t,δ)∈T(t, |\rho|\,|_t, \delta) \in T, ρ\rho is good, and ρ⊢δt⇓v\rho \vdash_\delta t \Downarrow v, then vv is a constant or ∣v∣∈C[(t,δ)]|v| \in C[(t, \delta)] with a good environment. Every evaluation inside the derivation, ρ1⊢δ1t1⇓v1\rho_1 \vdash_{\delta_1} t_1 \Downarrow v_1, has its task (t1,∣ρ1∣ ∣t1,δ1)(t_1, |\rho_1|\,|_{t_1}, \delta_1) in TT and ρ1\rho_1 good; every binding of a closure v1v_1 to a binder bb in contour cc has ∣v1∣∈R[(b,c)]|v_1| \in R[(b, c)]; and every call at t′′t'' of a closure of λ\lambda has λ\lambda among the functions of C[(t1′′,δ1)]C[(t''_1, \delta_1)] for the contour δ1\delta_1 of the call.

Proof. By induction on the height of the derivation. A variable xx with binder bb and ρ(x)=(c,v)\rho(x) = (c, v): ∣ρ∣(x)=c|\rho|(x) = c, and ∣v∣∈R[(b,c)]⊆C[(t,δ)]|v| \in R[(b, c)] \subseteq C[(t, \delta)] by rule 1. A function gives (t,ρ)(t, \rho), whose abstraction is (t,∣ρ∣ ∣t)(t, |\rho|\,|_t), in C[(t,δ)]C[(t, \delta)] by rule 2. A let: rule 3 gives the task of t1t_1 with ∣ρ∣ ∣t1|\rho|\,|_{t_1}, so by induction v1v_1 is in C[(t1,δ)]⊆R[((t,x),δ)]C[(t_1, \delta)] \subseteq R[((t, x), \delta)]. The new environment binds xx to (δ,v1)(\delta, v_1), so it is good, its abstraction is ∣ρ∣[x↦δ]|\rho|[x \mapsto \delta], and rule 3 gives the task of t2t_2. By induction the value is in C[(t2,δ)]⊆C[(t,δ)]C[(t_2, \delta)] \subseteq C[(t, \delta)]. if and operators are the same with rule 4. An application t1 t2: rule 5 gives the tasks of t1t_1 and t2t_2, so by induction t1t_1 gives (λ,ρ′)(\lambda, \rho') with (λ,∣ρ′∣ ∣λ)∈C[(t1,δ)](\lambda, |\rho'|\,|_\lambda) \in C[(t_1, \delta)], which is the call fact, and the argument aa is a constant or in C[(t2,δ)]C[(t_2, \delta)]. Let δ′=next(δ,t)\delta' = \mathrm{next}(\delta, t), the same in both semantics. By rule 5, ∣a∣∈R[(param(λ),δ′)]|a| \in R[(\mathrm{param}(\lambda), \delta')], and for a fix, (λ,∣ρ′∣ ∣λ)∈R[((λ,f),δ′)](\lambda, |\rho'|\,|_\lambda) \in R[((\lambda, f), \delta')]. So the environment of the body is good, its abstraction is ∣ρ′∣ ∣λ|\rho'|\,|_\lambda with the parameters mapped to δ′\delta', and rule 5 gives the task of the body. By induction its value is in C[(body(λ),δ′)]⊆C[(t,δ)]C[(\mathrm{body}(\lambda), \delta')] \subseteq C[(t, \delta)]. The facts about inner evaluations come from the induction hypothesis on each premise. □\square

Theorem 2 (soundness). Let (T,C,R)(T, C, R) be the result. In every run of the closed program, finished or not, every evaluation of a node tt in contour δ\delta to a closure vv has ∣v∣∈C[(t,δ)]|v| \in C[(t, \delta)], every binding of a closure vv to binder bb in contour cc has ∣v∣∈R[(b,c)]|v| \in R[(b, c)], and every call at application tt runs a function λ\lambda that appears in C[(t1,δ)]C[(t_1, \delta)]. Dropping the contours, the result contains the 0-CFA facts of the run.

Proof. The root task is in TT with the empty environment, which is good. Every finished evaluation of the run is a sub-derivation of the run from the root, so Lemma 4 applies to it. A call is made only after its operator and argument have finished. □\square

Theorem 3 (cost). The algorithm runs in time polynomial in nn, NN, QQ and the number of tasks, so in time 2O(nlog⁡n)2^{O(n \log n)} for fixed k≥1k \ge 1, and in time polynomial in nn for k=0k = 0.

Proof. By Lemma 2 there are at most (number of tasks) +(3nN)⋅Q+1+ (3 n N) \cdot Q + 1 passes, since there are at most nNn N cache keys and 2nN2 n N binder keys. Each pass runs the rule of every task once. A rule makes O(1)O(1) unions per closure of the operator, and each union of sets of at most QQ elements costs O(Q)O(Q) with hashing. With N≤(n+1)kN \le (n+1)^k, QQ and the number of tasks are at most n⋅(n+1)k(n+1)=2O(nlog⁡n)n \cdot (n+1)^{k(n+1)} = 2^{O(n \log n)} for fixed kk, so the number of passes and the cost of a pass are both 2O(nlog⁡n)2^{O(n \log n)}, and so is their product. For k=0k = 0 there is one contour, every abstract environment maps all names to the empty contour, so Q≤nQ \le n, there are at most nn tasks, and the time is polynomial. The exponential bound cannot be improved to a polynomial, since P is not EXPTIME by the time hierarchy theorem and Van Horn and Mairson prove that deciding a k-CFA fact is EXPTIME-complete for every k≥1k \ge 1 (see the theorem page). ■\blacksquare

Complexity

Proved. With nn nodes there are at most N≤(n+1)kN \le (n+1)^k contours. An abstract closure maps up to nn free variables to contours, so there are at most nNnn N^n of them, and as many tasks times NN. Each pass of the loop adds at least one fact, and each pass costs a polynomial in these numbers. So the time is 2O((k+1)nlog⁡n)2^{O((k+1) n \log n)}, which is 2O(nlog⁡n)2^{O(n \log n)} for fixed k≥1k \ge 1. For k=0k = 0 every closure has the one empty contour, and the time is polynomial.

Stated in the literature. Van Horn and Mairson (2008) prove that deciding whether a closure flows to an expression under k-CFA is EXPTIME-complete for every k≥1k \ge 1. Since P is not EXPTIME, by the time hierarchy theorem, no polynomial algorithm exists. Might, Smaragdakis and Van Horn (2010) show that the same idea is polynomial for object-oriented programs, where a closure (an object) copies its free values into fields instead of capturing an environment, and they define m-CFA, a polynomial analysis for functional programs with flat environments.

Measured, not proved. On 400 random closed terms (seed 1991), k=0k = 0 gives exactly the result of a plain 0-CFA. On 300 random terms (seed 2007), forgetting the contours, 2-CFA is inside 1-CFA and 1-CFA is inside 0-CFA. On 1500 random terms (seed 1988), every closure, binding and call of a concrete run with contours is in the result for k=1k = 1 and k=2k = 2.

Properties

  • Polyvariant. One variable has many abstract bindings, one per contour.
  • The environment problem. A closure keeps one contour per free variable, and these can differ. This is the source of the exponential number of abstract closures, and of the EXPTIME hardness.
  • Not distributive. A call rule fires only for closures that reach the operator in the same contour.
  • More precise as kk grows, in practice. In the tests, larger kk never gave a larger projected result. With the "last kk" truncation, the contours of k+1k + 1 map onto those of kk by dropping the oldest site, which is why this holds.
  • Call strings are functional k-CFA only here. In a first-order or object-oriented setting, a call-string analysis of length kk has no environment problem and is polynomial. Calling that "k-CFA" hides the difference.

Variants and improvements

  • Uniform k-CFA. Nielson, Nielson and Hankin index both the cache and the environment by the same contour of the current call. It is the form used on this page.
  • m-CFA. Might, Smaragdakis and Van Horn keep only the top mm stack frames and use flat environments, where all free variables of a closure share one contour. It is polynomial for fixed mm.
  • Object sensitivity. In object-oriented analysis, contexts made of receiver allocation sites often work better than call sites (object sensitivity).
  • Pushdown analyses. CFA2 and related analyses match calls with returns, like a pushdown system, so a return never goes to the wrong caller, even with k=0k = 0.
  • Abstract machines. Van Horn and Might derive k-CFA by bounding the store of an abstract machine, which gives the same analysis for richer languages.

When to use it

Use 1-CFA, or 2-CFA at most, when 0-CFA mixes the uses of small higher-order helpers and the extra precision pays off, for example to inline or specialize closures in a compiler for a functional language. Large kk rarely pays. For big programs, prefer a polynomial analysis: m-CFA, a pushdown analysis, or, in object-oriented code, call-site or object-sensitive points-to analysis, which are polynomial for fixed kk.

Pitfalls

  • Looking up a variable in the current contour. A version of line L6 that reads R[(b,d)]R[(b, d)] instead of R[(b,ce(x))]R[(b, ce(x))] is unsound. In let f = fun x -> fun y -> x in (f 1) 2, the inner body runs in the contour of the call (f 1) 2, but xx was bound in the contour of f 1. Line L6 must use the contour that the closure environment records.
  • Dropping the environment of closures. If line L7 stores only the function tt, line L14 has no contours for the free variables of the body. Keep the restricted environment cece in the closure.
  • Keeping the first kk call sites. A version of line L12 that keeps the oldest kk labels makes all deep calls share one contour. Line L12 must keep the most recent kk labels.
  • Expecting polynomial time for fixed kk. For k≥1k \ge 1 the problem is EXPTIME-complete, and real programs can show the blow-up. Bound the time, or use m-CFA.

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.

k_cfa.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/k-cfa/. The authors are listed in prov/WSCAQ1.jsonl.
"""k-CFA: control flow analysis of a higher-order program with the last k
call sites as the context of each binding.

label(term) numbers the nodes of a toylam term in preorder, as on the 0-CFA
page, and links each variable to its binder (label, name).

k_cfa(term, k) returns (nodes, C, R). A contour is a tuple of at most k
application labels, the most recent last. An abstract closure is (lam, ce)
where ce is a sorted tuple of (name, contour) pairs for the free variables of
the function lam. C[(t, d)] is the set of closures that node t may evaluate
to in contour d, and R[(b, d)] the set of closures bound to binder b in
contour d. The solver keeps a set of tasks (t, ce, d), one for each way in
which node t may be evaluated, and applies the rule of every task, round
after round, until nothing changes. The number of contours is at most n^k,
and the number of closures can be exponential in n, so k >= 1 is exponential
in the worst case.
"""


def label(term):
    nodes = []
    stack = [(term, {}, None, 0)]  # (term, scope, parent label, child slot)
    while stack:
        t, scope, parent, slot = stack.pop()
        here = len(nodes)
        tag = t[0]
        if tag == "var":
            nodes.append(("var", t[1], scope.get(t[1])))
        elif tag in ("int", "bool"):
            nodes.append(t)
        else:
            nodes.append(None)
        if parent is not None:
            node = list(nodes[parent])
            node[slot] = here
            nodes[parent] = tuple(node)
        if tag == "lam":
            nodes[here] = ("lam", t[1], None)
            stack.append((t[2], {**scope, t[1]: (here, t[1])}, here, 2))
        elif tag == "fix":
            nodes[here] = ("fix", t[1], t[2], None)
            inner = {**scope, t[1]: (here, t[1]), t[2]: (here, t[2])}
            stack.append((t[3], inner, here, 3))
        elif tag == "app":
            nodes[here] = ("app", None, None)
            stack.append((t[2], scope, here, 2))
            stack.append((t[1], scope, here, 1))
        elif tag == "let":
            nodes[here] = ("let", t[1], None, None)
            stack.append((t[3], {**scope, t[1]: (here, t[1])}, here, 3))
            stack.append((t[2], scope, here, 2))
        elif tag == "if":
            nodes[here] = ("if", None, None, None)
            for slot2 in (3, 2, 1):
                stack.append((t[slot2], scope, here, slot2))
        elif tag == "prim":
            nodes[here] = ("prim", t[1], None, None)
            stack.append((t[3], scope, here, 3))
            stack.append((t[2], scope, here, 2))
    return nodes


def free_names(nodes):
    """The free variable names of each node. Children have larger labels."""
    fv = [frozenset()] * len(nodes)
    for t in range(len(nodes) - 1, -1, -1):
        node = nodes[t]
        tag = node[0]
        if tag == "var":
            fv[t] = frozenset([node[1]])
        elif tag == "lam":
            fv[t] = fv[node[2]] - {node[1]}
        elif tag == "fix":
            fv[t] = fv[node[3]] - {node[1], node[2]}
        elif tag == "let":
            fv[t] = fv[node[2]] | (fv[node[3]] - {node[1]})
        elif tag == "app":
            fv[t] = fv[node[1]] | fv[node[2]]
        elif tag == "if":
            fv[t] = fv[node[1]] | fv[node[2]] | fv[node[3]]
        elif tag == "prim":
            fv[t] = fv[node[2]] | fv[node[3]]
    return fv


def k_cfa(term, k):
    nodes = label(term)
    fv = free_names(nodes)
    C, R = {}, {}
    tasks = {}  # an ordered set of (t, ce, d)
    changed = [False]

    def task(t, ce, d):
        key = (t, tuple(sorted((x, c) for x, c in ce.items() if x in fv[t])), d)  # @line L16
        if key not in tasks:
            tasks[key] = None
            changed[0] = True

    def add(table, key, items):
        s = table.setdefault(key, set())
        if not items <= s:
            s |= items
            changed[0] = True

    def rule(t, ce, d):
        node = nodes[t]
        tag = node[0]
        if tag == "var":
            if node[2] is not None:
                add(C, (t, d), R.get((node[2], ce[node[1]]), set()))  # @line L6
        elif tag in ("lam", "fix"):
            add(C, (t, d), {(t, tuple(sorted(ce.items())))})  # @line L7
        elif tag == "let":
            t1, t2 = node[2], node[3]
            task(t1, ce, d)  # @line L8
            add(R, ((t, node[1]), d), C.get((t1, d), set()))
            task(t2, {**ce, node[1]: d}, d)
            add(C, (t, d), C.get((t2, d), set()))
        elif tag in ("if", "prim"):
            kids = node[1:] if tag == "if" else node[2:]
            for u in kids:
                task(u, ce, d)  # @line L9
            if tag == "if":
                add(C, (t, d), C.get((node[2], d), set()) | C.get((node[3], d), set()))
        elif tag == "app":
            t1, t2 = node[1], node[2]
            task(t1, ce, d)  # @line L10
            task(t2, ce, d)
            for lam, ce2 in list(C.get((t1, d), ())):  # @line L11
                d2 = (d + (t,))[-k:] if k > 0 else ()  # @line L12
                fun = nodes[lam]
                inner = dict(ce2)
                if fun[0] == "lam":
                    x, body = fun[1], fun[2]
                else:
                    x, body = fun[2], fun[3]
                    add(R, ((lam, fun[1]), d2), {(lam, ce2)})  # @line L13
                    inner[fun[1]] = d2
                add(R, ((lam, x), d2), C.get((t2, d), set()))
                inner[x] = d2
                task(body, inner, d2)  # @line L14
                add(C, (t, d), C.get((body, d2), set()))  # @line L15

    task(0, {}, ())  # @line L1
    while changed[0]:  # @line L2 @line L4
        changed[0] = False
        for t, ce, d in list(tasks):  # @line L3
            rule(t, dict(ce), d)
    return nodes, C, R  # @line L5


def project(table):
    """Forget the contours and environments: a dict from each label or binder
    to the set of function labels."""
    out = {}
    for (key, _), closures in table.items():
        if closures:
            out.setdefault(key, set()).update(lam for lam, _ in closures)
    return out


def call_graph(nodes, C):
    """The pairs (application label, function label) of the result."""
    flat = project(C)
    return {(t, lam) for t, node in enumerate(nodes) if node[0] == "app" for lam in flat.get(node[1], ())}
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_k_cfa.py 228 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/k-cfa/. The authors are listed in prov/WSCAQ1.jsonl.

import random

import toylam
from k_cfa import call_graph, free_names, k_cfa, label, project


class Halt(Exception):
    pass


def run(nodes, k, fuel=3000, max_depth=150):
    """An environment-based call-by-value interpreter that keeps, for each
    binding, the contour in which it was made: the last k call sites. Records
    every closure that a node produces in a contour, every binding and every
    call, with the closures cut down to (function, contours of its free
    variables)."""
    fv = free_names(nodes)
    seen, binds, calls = [], [], []
    budget = [fuel]

    def abstract(v):
        lam, env = v[1], v[2]
        return (lam, tuple(sorted((x, env[x][0]) for x in fv[lam])))

    def ev(t, env, d, depth):
        budget[0] -= 1
        if budget[0] < 0 or depth > max_depth:
            raise Halt("fuel")
        node = nodes[t]
        tag = node[0]
        if tag == "var":
            if node[1] not in env:
                raise Halt("stuck")
            v = env[node[1]][1]
        elif tag in ("int", "bool"):
            v = node
        elif tag in ("lam", "fix"):
            v = ("clo", t, env)
        elif tag == "app":
            f = ev(node[1], env, d, depth + 1)
            a = ev(node[2], env, d, depth + 1)
            if f[0] != "clo":
                raise Halt("stuck")
            lam = f[1]
            fun = nodes[lam]
            d2 = (d + (t,))[-k:] if k > 0 else ()
            calls.append((t, lam))
            inner = dict(f[2])
            if fun[0] == "fix":
                inner[fun[1]] = (d2, f)
                binds.append((((lam, fun[1]), d2), f))
                x, body = fun[2], fun[3]
            else:
                x, body = fun[1], fun[2]
            inner[x] = (d2, a)
            binds.append((((lam, x), d2), a))
            v = ev(body, inner, d2, depth + 1)
        elif tag == "let":
            a = ev(node[2], env, d, depth + 1)
            binds.append((((t, node[1]), d), a))
            v = ev(node[3], {**env, node[1]: (d, a)}, d, depth + 1)
        elif tag == "if":
            c = ev(node[1], env, d, depth + 1)
            if c[0] != "bool":
                raise Halt("stuck")
            v = ev(node[2] if c[1] else node[3], env, d, depth + 1)
        else:
            a = ev(node[2], env, d, depth + 1)
            b = ev(node[3], env, d, depth + 1)
            if a[0] != "int" or b[0] != "int":
                raise Halt("stuck")
            v = toylam._prim(node[1], a[1], b[1])
        seen.append(((t, d), v))
        return v

    try:
        ev(0, {}, (), 0)
    except Halt:
        pass
    seen = [(key, abstract(v)) for key, v in seen if v[0] == "clo"]
    binds = [(key, abstract(v)) for key, v in binds if v[0] == "clo"]
    return seen, binds, calls


def plain_zero_cfa(nodes):
    """The 0-CFA rules of the 0-CFA page applied round after round."""
    C = {t: set() for t in range(len(nodes))}
    R = {}
    reached = {0}
    changed = True

    def put(s, items):
        if not items <= s:
            s |= items
            return True
        return False

    while changed:
        changed = False
        for t in sorted(reached):
            node = nodes[t]
            tag = node[0]
            kids = []
            if tag in ("lam", "fix"):
                changed |= put(C[t], {t})
            elif tag == "var" and node[2] is not None:
                changed |= put(C[t], R.setdefault(node[2], set()))
            elif tag == "let":
                changed |= put(R.setdefault((t, node[1]), set()), C[node[2]])
                changed |= put(C[t], C[node[3]])
                kids = [node[2], node[3]]
            elif tag == "if":
                changed |= put(C[t], C[node[2]] | C[node[3]])
                kids = [node[1], node[2], node[3]]
            elif tag == "prim":
                kids = [node[2], node[3]]
            elif tag == "app":
                kids = [node[1], node[2]]
                for lam in list(C[node[1]]):
                    fun = nodes[lam]
                    if fun[0] == "fix":
                        changed |= put(R.setdefault((lam, fun[1]), set()), {lam})
                        binder, body = (lam, fun[2]), fun[3]
                    else:
                        binder, body = (lam, fun[1]), fun[2]
                    changed |= put(R.setdefault(binder, set()), C[node[2]])
                    changed |= put(C[t], C[body])
                    kids.append(body)
            for u in kids:
                if u not in reached:
                    reached.add(u)
                    changed = True
    return {t: s for t, s in C.items() if s}, {b: s for b, s in R.items() if s}


def find(nodes, tag, name):
    return next(t for t, n in enumerate(nodes) if n[0] == tag and n[1] == name)


def last_app(nodes):
    return max(t for t, n in enumerate(nodes) if n[0] == "app")


def fun(x, body):
    return ("lam", x, body)


ID_EXAMPLE = (
    "let", "id", fun("x", ("var", "x")),
    ("let", "a", ("app", ("var", "id"), fun("y", ("prim", "+", ("var", "y"), ("int", 1)))),
     ("let", "b", ("app", ("var", "id"), fun("z", ("prim", "*", ("var", "z"), ("int", 2)))),
      ("app", ("var", "a"), ("int", 3)))),
)

WRAPPED = (
    "let", "id", fun("x", ("var", "x")),
    ("let", "g", fun("w", ("app", ("var", "id"), ("var", "w"))),
     ("let", "a", ("app", ("var", "g"), fun("y", ("prim", "+", ("var", "y"), ("int", 1)))),
      ("let", "b", ("app", ("var", "g"), fun("z", ("prim", "*", ("var", "z"), ("int", 2)))),
       ("app", ("var", "a"), ("int", 3))))),
)


def targets_of_last_call(term, k):
    nodes, C, R = k_cfa(term, k)
    last = last_app(nodes)
    return {lam for t, lam in call_graph(nodes, C) if t == last}, nodes


def test_page_example_one_cfa_splits_the_calls_of_id():
    zero, nodes = targets_of_last_call(ID_EXAMPLE, 0)
    one, _ = targets_of_last_call(ID_EXAMPLE, 1)
    ly, lz = find(nodes, "lam", "y"), find(nodes, "lam", "z")
    assert zero == {ly, lz}
    assert one == {ly}
    nodes, C, R = k_cfa(ID_EXAMPLE, 1)
    lx = find(nodes, "lam", "x")
    assert {d for (b, d) in R if b == (lx, "x")} == {(t,) for t, n in enumerate(nodes) if n[0] == "app"} - {(last_app(nodes),)}


def test_a_wrapper_needs_two_call_sites():
    one, nodes = targets_of_last_call(WRAPPED, 1)
    two, _ = targets_of_last_call(WRAPPED, 2)
    ly, lz = find(nodes, "lam", "y"), find(nodes, "lam", "z")
    assert one == {ly, lz}
    assert two == {ly}
    assert toylam.evaluate(WRAPPED) == ("value", ("int", 4))


def terms(seed, count, depth=6):
    rng = random.Random(seed)
    for _ in range(count):
        yield toylam.random_term(rng, rng.randint(1, depth))


def test_zero_contours_is_zero_cfa():
    for term in terms(1991, 400):
        nodes, C, R = k_cfa(term, 0)
        assert (project(C), project(R)) == plain_zero_cfa(nodes), toylam.show(term)


def test_more_contours_never_lose_precision():
    for term in terms(2007, 300):
        flat = [k_cfa(term, k) for k in (0, 1, 2)]
        for small, big in ((1, 0), (2, 1)):
            cs, cb = project(flat[small][1]), project(flat[big][1])
            assert all(s <= cb.get(t, set()) for t, s in cs.items()), toylam.show(term)
            rs, rb = project(flat[small][2]), project(flat[big][2])
            assert all(s <= rb.get(b, set()) for b, s in rs.items()), toylam.show(term)


def test_sound_against_concrete_runs():
    with_calls = 0
    for term in terms(1988, 1500, depth=7):
        nodes = label(term)
        for k in (1, 2):
            _, C, R = k_cfa(term, k)
            seen, binds, calls = run(nodes, k)
            with_calls += bool(calls)
            for key, clo in seen:
                assert clo in C.get(key, ()), toylam.show(term)
            for key, clo in binds:
                assert clo in R.get(key, ()), toylam.show(term)
            assert set(calls) <= call_graph(nodes, C)
    assert with_calls > 100

History

Shivers introduced control flow analysis for Scheme in 1988, with 0-CFA and 1-CFA, and defined the k-CFA hierarchy in his 1991 thesis by abstract interpretation of a continuation-passing semantics. Nielson, Nielson and Hankin (1999) gave a constraint-based uniform form in their textbook. For years it was believed that k-CFA was polynomial for fixed kk. Van Horn and Mairson (2008) proved that it is EXPTIME-complete for every k≥1k \ge 1, by encoding a Turing machine with exponential time in the closures of a program. Might, Smaragdakis and Van Horn (2010) explained why the same idea is polynomial for object-oriented programs and used it to define m-CFA.

References

  1. Olin Shivers, Control-flow analysis of higher-order languages, PhD thesis, Carnegie Mellon University, CMU-CS-91-145, 1991, the definition of the k-CFA hierarchy by abstract interpretation of a CPS semantics with contours of the last k call sites
  2. Olin Shivers, Control flow analysis in Scheme, Proceedings of PLDI '88, 164 to 174, 1988, the first control flow analyses, 0-CFA and 1-CFA, for Scheme
  3. David Van Horn and Harry G. Mairson, Deciding kCFA is complete for EXPTIME, Proceedings of ICFP 2008, 275 to 282, the EXPTIME-completeness of k-CFA for every k at least 1
  4. Matthew Might, Yannis Smaragdakis and David Van Horn, Resolving and exploiting the k-CFA paradox, Proceedings of PLDI 2010, 305 to 315, why k-CFA is polynomial for object-oriented programs, and m-CFA, a polynomial hierarchy for functional programs
  5. Flemming Nielson, Hanne Riis Nielson and Chris Hankin, Principles of Program Analysis, Springer, 1999, chapter 3, constraint-based analysis, with the section on adding context information (uniform k-CFA)

Where this leads

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 proofH2 full proof
  • correctness: no review record reviews/WSCAQ1/proof-correctness.yaml
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