Techniqueresearch
Liquid types
Also called logically qualified data types.
Infers refinement types by abstract interpretation over conjunctions of given qualifiers, with SMT queries to check each subtyping step.
Liquid types is a method to infer refinement types automatically. The user gives a finite set of qualifiers, small predicate patterns such as or , where stands for any program variable. Every unknown refinement in the program is then a conjunction of instances of these qualifiers, and the method finds the strongest such conjunctions that make the program type check, using an SMT solver for each implication. The name stands for "logically qualified data types" (Rondon, Kawaguchi and Jhala 2008). The refinement type system decides whether given types are correct; liquid types finds the types. The method is predicate abstraction applied to types, and its fixed point loop is the same as the Houdini algorithm for program annotations.
In plain words
Writing refinement types by hand is a lot of work. Every helper function and every loop needs a fact such as "this index is between 0 and the length of the array". Liquid types guesses these facts from a short list of patterns that you give, such as "is at least 0" and "is less than some variable". For each unknown fact, it starts with every pattern that could apply, joined by "and". This is too strong to be true in most places. It then looks at each place where the fact must hold, asks the solver which patterns fail there, and drops them. It repeats until nothing more fails. Since the list of patterns is finite, the dropping must stop. What is left is the strongest fact that the patterns can say.
When it applies
- The program is in a typed functional language, or can be put in A-normal form with types from Hindley-Milner inference. The liquid types are refinements of those types.
- The refinements needed for the property are conjunctions of a few qualifier patterns. Bounds of array indices, sizes of lists, sortedness of adjacent elements, and ordering between arguments and results are typical.
- The qualifiers are in a decidable logic, such as linear integer arithmetic with uninterpreted functions, so each implication is one decidable SMT query.
- The properties to prove are given as refinements on primitives and on some function signatures, for example a precondition on array access or division.
The template
Liquid templates and constraints
Let be the set of qualifiers. For a refinement position whose scope contains the variables , let be the set of instances of where each is replaced by a variable of of the right base type. It is finite because and are finite. A liquid type is a refinement type whose refinements are conjunctions of such instances.
- Shapes. Run HM inference. Give each base type position that has no user annotation a fresh liquid variable , so the refinement there is unknown.
- Constraints. Walk the program with the rules of the refinement type system, with in place of each unknown. Each use of subtyping gives an implication , where the context, and may contain liquid variables under a pending substitution (from T-App and T-Var), written . A constraint whose right side is some is a -constraint. A constraint whose right side has no liquid variable is a check.
- Solve. Find an assignment of a subset of to each that makes all constraints valid, where a subset means its conjunction.
SOLVE(constraints C, qualifier instances Q*)- 1
for each liquid variable κ do A(κ) ← Q*(κ) ▷ all candidates, the strongest guess - 2
repeat - 3
changed ← false - 4
for each κ-constraint H ⇒ θ κ in C do - 5
for each q in A(κ) do - 6
if not VALID(A(H) ⇒ θ q) then ▷ one SMT query - 7
A(κ) ← A(κ) minus {q} ; changed ← true - 8
until not changed - 9
for each check H ⇒ φ in C do - 10
if not VALID(A(H) ⇒ φ) then report an error at its source position - 11
return A
Here replaces each liquid variable in by the conjunction that gives it. The liquid variables occur only as conjuncts on the left of an implication or alone on the right, so a larger set makes every left side stronger.
Termination
Theorem. SOLVE ends after at most validity queries, plus one query for each check.
Proof. Each pass of L2 to L8 other than the last removes at least one qualifier from some , and nothing is ever added. The sets start with elements in all, so there are at most that many passes that change something, and then one pass that changes nothing. A pass makes at most queries. Each query is an implication in a decidable logic, so each one ends.
The bound uses only the finiteness of . With an infinite candidate set, such as all linear inequalities, the same loop could remove candidates forever, which is why invariant inference in general needs widening or interpolation (CEGAR and loop invariant synthesis).
Correctness
Soundness. When SOLVE returns , every -constraint is valid under (the last pass removed nothing), and every check is valid. So the refinement typing with put in for each satisfies every premise of S-Base, and it is a valid refinement typing. By the soundness of refinement types, the program does not fail any refined precondition.
Strongest solution. Call an assignment a solution if it makes all -constraints valid. The invariant is: for every solution and every , . It holds at L1, since is all of . Suppose L7 removes from , because is not valid, and suppose . Since pointwise and liquid variables occur positively in , is valid. Since is a solution, is valid, and because is a conjunct. So is valid, a contradiction. So the invariant is kept, and the final is the greatest solution: the strongest liquid types. This is the greatest fixed point of a monotone map on a finite lattice of subsets (Knaster-Tarski), reached from the top.
Relative completeness. If any liquid assignment over makes all constraints valid, checks included, then SOLVE reports no error. Each check holds under , and by the invariant, so it holds under . An error therefore means that no liquid typing over the given qualifiers exists. The program may still be safe, with an invariant that the qualifiers cannot express.
Cost
is at most for qualifiers with holes and variables in scope, so it grows with the number of variables. In practice qualifiers have one or two holes, and most candidates are removed in the first pass. The SMT queries dominate the time.
Classic examples
Maximum. Let with ranging over the variables in scope and the constant 0, and infer the result of let max x y = if x > y then x else y, with unrefined arguments. The result has scope , so is . The two branches give
| Step | Constraint | Removed | after |
|---|---|---|---|
| start | all six | ||
| 1 | , , | , , | |
| 2 | , | ||
| 3 | , | nothing | , |
For example, is removed at step 1 because satisfies the left side of and not . The result is .
A loop invariant for array bounds. Take, with and requiring ,
let rec sum a i acc = if i >= len a then acc else sum a (i + 1) (acc + get a i)
let total a = sum a 0 0
with . The parameter i gets with candidates , and . The call in total gives , which keeps and and removes (the array may be empty). The recursive call gives , which keeps both and . The check at is , which is valid. The inferred invariant is , and the bound check in get can be removed with no annotation by the user. Rondon et al. (2008) report this kind of result on OCaml benchmarks.
A missing qualifier. With only, the call in total removes the one candidate, becomes , and the check at fails because could be negative. The program is safe, but no liquid type over this shows it, and the error says only that the qualifiers are not enough.
Variations
- Horn clause solving. The constraints are constrained Horn clauses with the as unknown predicates. Liquid Haskell's solver, liquid-fixpoint, solves them over qualifiers as above. General Horn clause solvers use interpolation and need no qualifiers, but they may not terminate.
- Liquid Haskell (Vazou et al. 2014) adds measures (functions such as the length of a list that may be used in refinements), abstract refinements and termination checking, and mines qualifiers from the type signatures in the program.
- Low-level liquid types (Rondon et al. 2010) infers refinements for C-like code with pointers and a heap.
- Houdini (Flanagan and Leino 2001) runs the same "start with all candidates, remove the refuted ones" loop with a program verifier in place of the SMT queries, to infer annotations for ESC/Java.
- Abstract interpretation view. The domain is the finite lattice of conjunctions over , ordered by inclusion, and the loop is a fixed point iteration in it. A richer domain, such as polyhedra, would need widening to end (abstract interpretation).
Pitfalls
- The qualifiers decide what can be proved. An error may mean a bug or a missing qualifier, and the tool cannot tell which. Good tools mine qualifiers from annotations and offer defaults.
- Candidate sets grow fast. Qualifiers with many holes, or many variables in scope, give large and many queries. Keep holes few and scopes small.
- Monotonicity is needed. The proof of the strongest solution uses that liquid variables occur only positively on the left of implications. A rule that puts a under a negation breaks the argument.
- Decidable logic only. A nonlinear qualifier makes the SMT queries incomplete. A query that returns "unknown" must be treated as "not valid", which removes the qualifier and may cause a false error.
- Precision at higher-order calls. A function passed as an argument gets one liquid type for all its uses inside the callee. Liquid types give each use of a polymorphic function fresh templates for its type variables, which keeps facts about the elements. A monomorphic signature loses them.
Exercises
- In the maximum example, why is kept by but removed by ? Answer. In the result is , so holds. In the result is with , and fails when , for example .
- Give the bound on the number of passes that change something, for one liquid variable with 6 candidates. Answer. At most 6, since each such pass removes at least one candidate, followed by one final pass that changes nothing.
- Why does SOLVE start from the conjunction of all candidates and not from ? Answer. Loop invariants are inductive: a fact about
iat the recursive call follows only if the same fact is assumed for the currenti. In the sum example, follows from and not from . A loop that starts from and adds a candidate only when the current facts imply it never adds . Starting from all candidates assumes them all and then removes those that fail. - In the array example, add the qualifier . Does the result change? Answer. No. In the scope of the only other variable is
a, which is an array, so has no well-sorted instance. for is the same, and the result is still .
References
- Patrick M. Rondon, Ming Kawaguchi and Ranjit Jhala, Liquid types, ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI 2008), pages 159 to 169, logical qualifiers and liquid types, the liquid typing rules, constraint generation with liquid type variables, the iterative weakening algorithm, and the experiments on array bound checks in OCaml programs
- Patrick M. Rondon, Ming Kawaguchi and Ranjit Jhala, Low-level liquid types, Thirty-Seventh ACM Symposium on Principles of Programming Languages (POPL 2010), pages 131 to 144, liquid type inference for a low-level imperative language with pointers and a heap
- Cormac Flanagan and K. Rustan M. Leino, Houdini, an annotation assistant for ESC/Java, FME 2001, Lecture Notes in Computer Science, pages 500 to 517, the algorithm that starts from all candidate annotations and removes those that the checker refutes until none is refuted
- Niki Vazou, Eric L. Seidel, Ranjit Jhala, Dimitrios Vytiniotis and Simon Peyton Jones, Refinement types for Haskell, ACM SIGPLAN International Conference on Functional Programming (ICFP 2014), pages 269 to 282, Liquid Haskell, liquid type inference under lazy evaluation, and termination checking
- Ranjit Jhala and Niki Vazou, Refinement types, a tutorial, Foundations and Trends in Programming Languages 6(3-4), 2021, pages 159 to 317, the chapters on refinement inference with Horn constraints and their solution over qualifiers
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 | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag YG0HVJ Edit this page History Report an error Markdown