Problemcore
Type inference problem
Also called type reconstruction, typability problem.
Given a term without type annotations, find types for its variables and the term that make it well typed, or report that none exist; ideally return a principal type.
The type inference problem takes a program with no type annotations and asks for types that make it well typed. For the simply typed lambda calculus, Hindley (1969) showed that the answer, when it exists, has a principal form from which every other typing follows by substitution, and that unification finds it. The same method, with polymorphism at let, is the core of ML and Haskell. The problem is harder than type checking, and for richer type systems it becomes undecidable.
In plain words
In many languages you can write a function without saying what types its arguments have. The compiler then works the types out. It gives each unknown type a name, reads the program once, and writes down an equation for each use: if f is called on x, then the type of f must be a function from the type of x to something. Then it solves all the equations at once. If they have a solution, the program is accepted, and the most general solution is its type. If they have no solution, for example because a value must be both a number and a function, the program is rejected. For simple types this is fast. For more powerful type systems, no program can always find the answer.
Definition
Fix a type system with a judgment on untyped (Curry-style) terms.
- Instance. An untyped term , and possibly a context that fixes the types of some free variables.
- Output. A pair with and extending , or the answer "untypable".
The decision version is typability: does such a pair exist? A typing is principal for if each typing of is , possibly with more variables in the context, for some substitution of types for type variables. A type system has principal typings if each typable term has one. An inference algorithm is sound if each typing it returns is derivable, and complete if it returns a typing whenever one exists. A complete algorithm for a system with principal typings should return a principal one.
The input size is the number of nodes in the syntax tree of . The cost model is a word RAM.
Variants
- Type checking gives and asks only yes or no. It is a different problem, often much easier when the term carries annotations. See the type checking problem.
- Inference for simple types (Curry-style STLC). Decidable in linear time.
- Inference with let-polymorphism (Hindley-Milner). Decidable and DEXPTIME-complete. The algorithms are W, J and constraint-based inference.
- Inference with polymorphic recursion (Milner-Mycroft typing). Undecidable (polymorphic recursion undecidability), by equivalence with semi-unification.
- Inference for System F. Undecidable (Wells' theorem). For the rank- fragments, rank 2 is decidable and every rank of 3 or more is undecidable (Kfoury and Wells 1994).
- Partial inference. The programmer writes some annotations and the checker fills in the rest. Bidirectional type checking is the common method in modern languages.
- Inference with recursive types. With equi-recursive types, drop the occurs check and unify regular infinite trees (recursive types). Then every pure lambda term is typable, so the question is interesting only with base types.
Examples
Twice. Take . Give the type variable and the type variable . The inner application gets a fresh and the equation . The outer application gets and the equation . The term has type . Unification of with gives and . So the principal type is , or after renaming . A script that generates the two constraints and unifies them returns this type.
Self-application. For , give the type . The application gives . The variable occurs inside , so the occurs check fails, no finite type solves the equation, and the term is untypable. A type checker that is given a candidate type would answer "no" for each candidate, but it could never say "no candidate works". Inference proves that.
S and B. The script gives and . Each is principal: for example is the instance of the second.
Exponential principal types. Let and with copies of . If the argument of has type , the result has type , which holds two copies of . The script gives these numbers.
| term nodes | constraints | type tree nodes | type DAG nodes | |
|---|---|---|---|---|
| 0 | 2 | 0 | 3 | 2 |
| 1 | 10 | 3 | 9 | 6 |
| 2 | 18 | 6 | 21 | 10 |
| 3 | 26 | 9 | 45 | 14 |
| 6 | 50 | 18 | 381 | 26 |
The term has nodes, the principal type has tree nodes, and the DAG with shared subtypes has nodes. For the type is . So an algorithm that prints the type as text needs exponential time, but one that returns a DAG does not.
Known algorithms
Constraint generation, then unification. This is Wand's (1987) split of Hindley's method, and Chapter 22 of Pierce's book. For the Curry-style STLC with and , define where is a set of equations:
- .
- , where is fresh and .
- , where is fresh.
- , and constants give their base type.
For a closed term, start with . Then compute a most general unifier of . If none exists, is untypable. Otherwise is the principal type.
Theorem (soundness and completeness of constraint typing; Pierce, Section 22.3). Let . (1) If a substitution solves , then . (2) If for some substitution , then there is a solution of that agrees with on the variables of and has .
Proof sketch. Both parts go by induction on . For (1), at an application, solves and , so the induction gives and . also solves , so , and T-App gives . At an abstraction, the induction gives , and T-Abs gives the arrow. For (2), inversion on the derivation of gives the types of the parts. At , inversion gives , so extend with , which is safe because is fresh, and use the induction. At an application, inversion gives a type for the argument. The induction gives solutions for and , which agree on and touch disjoint sets of fresh variables, so their union is a function; add .
Corollary (principal types). If is a most general unifier of , then is a principal typing: each solution factors as , so each typing is an instance of it.
Choice of unification algorithm. Robinson's algorithm on trees can take exponential time, because the solved form can be exponentially large. Martelli-Montanari with a union-find structure on a DAG runs in time if the occurs check is done once at the end. Paterson-Wegman runs in time. The constraint set has symbols, so Curry-style STLC inference takes time with the type returned as a DAG.
Inline solving. Algorithm W (Milner 1978) solves each equation as soon as it appears and returns a substitution. Algorithm J keeps one global substitution in a union-find structure. Both add let-polymorphism: at let x = e1 in e2 they solve the constraints of , generalize its type over the variables that are not free in the context, and give that type scheme.
| Algorithm | Time | Space | Properties | Code |
|---|---|---|---|---|
| Algorithm J | 2^O(n) worst | 2^O(n) extra | deterministicrecursive | 1 language |
| Algorithm W | 2^(2^O(n)) worst | 2^(2^O(n)) extra | deterministicrecursive | 1 language |
Bounds
| system | typability | source |
|---|---|---|
| Curry-style STLC | time | Hindley 1969, Paterson and Wegman 1978 |
| Hindley-Milner (ML) | DEXPTIME-complete | Mairson 1990; Kfoury, Tiuryn and Urzyczyn 1990 |
| ML with polymorphic recursion | undecidable | Henglein 1993; Kfoury, Tiuryn and Urzyczyn 1993 |
| System F, rank 2 | decidable | Kfoury and Wells 1994 |
| System F, rank 3 or more, and full System F | undecidable | Kfoury and Wells 1994; Wells 1999 |
For ML, the exponent comes from nested let: each let can double the size of a type, as in the example with polymorphic copies. When the nesting depth of let is bounded by a constant, inference is polynomial. The table is about the decision problem. An algorithm that must print the principal type as a tree can need time exponential in even for the STLC, as the example shows.
Reductions
- STLC typability to unification. The constraint generation above is a linear-time reduction from typability to first-order unification, and it preserves most general solutions.
- Typability to checking. For ML and for System F, typability reduces to checking: is typable if and only if has type in ML, and Wells gives a similar term for System F. So checking is at least as hard as typability in these systems. See the type checking problem.
- Semi-unification. Typability with polymorphic recursion and typability in System F both reduce from semi-unification, which is undecidable (Kfoury, Tiuryn and Urzyczyn 1993).
- Second-order unification. Partial type reconstruction for System F, where the positions of type abstractions and applications are given but the types are not, reduces from second-order unification (Pfenning 1988), which is undecidable (higher-order unification undecidability).
Applications
- ML, OCaml, F# and Haskell infer the types of all functions without annotations, by Hindley-Milner inference with extensions. The error message for an ill-typed program is a unification failure, and its location is a known weak point.
- Local inference in mainstream languages. C++
auto, Javavar, C#var, Go:=, Rustletand TypeScript infer the type of a variable from its initializer and use bidirectional rules elsewhere. They require annotations on function signatures, which keeps inference decidable and local. - Program analysis. Constraint generation followed by solving is also the shape of many static analyses, for example Steensgaard's points-to analysis, which is unification on the points-to graph.
- Proof search. Principal types of combinators are the most general theorems they prove (Curry-Howard correspondence).
References
- Benjamin C. Pierce, Types and Programming Languages, MIT Press, 2002, Chapter 22 (Section 22.3 constraint-based typing with its soundness and completeness theorems, Section 22.4 unification, Section 22.5 principal types)
- J. Roger Hindley, The principal type-scheme of an object in combinatory logic, Transactions of the American Mathematical Society 146, 1969, pages 29 to 60, the principal type-scheme theorem (each typable object has a principal type scheme, found by unification)
- Robin Milner, A theory of type polymorphism in programming, Journal of Computer and System Sciences 17(3), 1978, pages 348 to 375, Section 4 (algorithm W) and the soundness of W
- Mitchell Wand, A simple algorithm and proof for type inference, Fundamenta Informaticae 10, 1987, the separation of type inference into constraint generation and unification
- Michael S. Paterson and Mark N. Wegman, Linear unification, Journal of Computer and System Sciences 16(2), 1978, pages 158 to 167, the main theorem (unification in linear time on a DAG representation)
- Harry G. Mairson, Deciding ML typability is complete for deterministic exponential time, POPL 1990, pages 382 to 401, the DEXPTIME-hardness proof by simulation of an exponential time Turing machine with nested let
- Joe B. Wells, Typability and type checking in System F are equivalent and undecidable, Annals of Pure and Applied Logic 98(1-3), 1999, pages 111 to 156, Theorem 4.1 and Section 6 (undecidability of typability by reduction from semi-unification)
- Assaf J. Kfoury and Joe B. Wells, A direct algorithm for type inference in the rank-2 fragment of the second-order lambda-calculus, LFP 1994, pages 196 to 207, the main results (rank-2 typability is decidable by reduction to acyclic semi-unification; rank k of 3 or more is undecidable)
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 5X891X Edit this page History Report an error Markdown