Algorithm Search⌘K

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 Γ⊢e:τ\Gamma \vdash e : \tau on untyped (Curry-style) terms.

  • Instance. An untyped term ee, and possibly a context Γ0\Gamma_0 that fixes the types of some free variables.
  • Output. A pair (Γ,τ)(\Gamma, \tau) with Γ⊢e:τ\Gamma \vdash e : \tau and Γ\Gamma extending Γ0\Gamma_0, or the answer "untypable".

The decision version is typability: does such a pair exist? A typing (Γ,τ)(\Gamma, \tau) is principal for ee if each typing of ee is (SΓ,Sτ)(S\Gamma, S\tau), possibly with more variables in the context, for some substitution SS 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 nn is the number of nodes in the syntax tree of ee. The cost model is a word RAM.

Variants

  • Type checking gives τ\tau 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-kk 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 e=λf.λx. f (f x)e = \lambda f.\lambda x.\ f\ (f\ x). Give ff the type variable aa and xx the type variable bb. The inner application f xf\ x gets a fresh r1r_1 and the equation a=b→r1a = b \to r_1. The outer application gets r2r_2 and the equation a=r1→r2a = r_1 \to r_2. The term has type a→b→r2a \to b \to r_2. Unification of b→r1b \to r_1 with r1→r2r_1 \to r_2 gives b=r1b = r_1 and r1=r2r_1 = r_2. So the principal type is (b→b)→b→b(b \to b) \to b \to b, or after renaming (a→a)→a→a(a \to a) \to a \to a. A script that generates the two constraints and unifies them returns this type.

Self-application. For λx. x x\lambda x.\ x\ x, give xx the type aa. The application gives a=a→ra = a \to r. The variable aa occurs inside a→ra \to r, 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 λx.λy.λz. x z (y z):(a→b→c)→(a→b)→a→c\lambda x.\lambda y.\lambda z.\ x\,z\,(y\,z) : (a \to b \to c) \to (a \to b) \to a \to c and λf.λg.λx. f (g x):(a→b)→(c→a)→c→b\lambda f.\lambda g.\lambda x.\ f\,(g\,x) : (a \to b) \to (c \to a) \to c \to b. Each is principal: for example (Int→Int)→(Bool→Int)→Bool→Int(\mathsf{Int} \to \mathsf{Int}) \to (\mathsf{Bool} \to \mathsf{Int}) \to \mathsf{Bool} \to \mathsf{Int} is the instance a,b,c:=Int,Int,Boola, b, c := \mathsf{Int}, \mathsf{Int}, \mathsf{Bool} of the second.

Exponential principal types. Let D=λz.λw. w z zD = \lambda z.\lambda w.\ w\,z\,z and ek=λx. D (D (⋯(D x)⋯ ))e_k = \lambda x.\ D\,(D\,(\cdots(D\,x)\cdots)) with kk copies of DD. If the argument of DD has type σ\sigma, the result has type (σ→σ→b)→b(\sigma \to \sigma \to b) \to b, which holds two copies of σ\sigma. The script gives these numbers.

kk 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 8k+28k+2 nodes, the principal type has 6⋅2k−36 \cdot 2^k - 3 tree nodes, and the DAG with shared subtypes has 4k+24k+2 nodes. For k=1k = 1 the type is a→(a→a→b)→ba \to (a \to a \to b) \to b. 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 Int\mathsf{Int} and Bool\mathsf{Bool}, define gen(Γ,e)=(τ,C)\mathrm{gen}(\Gamma, e) = (\tau, C) where CC is a set of equations:

  • gen(Γ,x)=(Γ(x),∅)\mathrm{gen}(\Gamma, x) = (\Gamma(x), \emptyset).
  • gen(Γ,λx.e1)=(a→τ1,C1)\mathrm{gen}(\Gamma, \lambda x.e_1) = (a \to \tau_1, C_1), where aa is fresh and (τ1,C1)=gen((Γ,x:a),e1)(\tau_1, C_1) = \mathrm{gen}((\Gamma, x{:}a), e_1).
  • gen(Γ,e1 e2)=(r,C1∪C2∪{τ1=τ2→r})\mathrm{gen}(\Gamma, e_1\,e_2) = (r, C_1 \cup C_2 \cup \{\tau_1 = \tau_2 \to r\}), where rr is fresh.
  • gen(Γ,if e1 then e2 else e3)=(τ2,C1∪C2∪C3∪{τ1=Bool,τ2=τ3})\mathrm{gen}(\Gamma, \mathsf{if}\ e_1\ \mathsf{then}\ e_2\ \mathsf{else}\ e_3) = (\tau_2, C_1 \cup C_2 \cup C_3 \cup \{\tau_1 = \mathsf{Bool}, \tau_2 = \tau_3\}), and constants give their base type.

For a closed term, start with Γ=∅\Gamma = \emptyset. Then compute a most general unifier σ\sigma of CC. If none exists, ee is untypable. Otherwise στ\sigma\tau is the principal type.

Theorem (soundness and completeness of constraint typing; Pierce, Section 22.3). Let gen(Γ,e)=(τ,C)\mathrm{gen}(\Gamma, e) = (\tau, C). (1) If a substitution SS solves CC, then SΓ⊢e:SτS\Gamma \vdash e : S\tau. (2) If S′Γ⊢e:TS'\Gamma \vdash e : T for some substitution S′S', then there is a solution SS of CC that agrees with S′S' on the variables of Γ\Gamma and has Sτ=TS\tau = T.

Proof sketch. Both parts go by induction on ee. For (1), at an application, SS solves C1C_1 and C2C_2, so the induction gives SΓ⊢e1:Sτ1S\Gamma \vdash e_1 : S\tau_1 and SΓ⊢e2:Sτ2S\Gamma \vdash e_2 : S\tau_2. SS also solves τ1=τ2→r\tau_1 = \tau_2 \to r, so Sτ1=Sτ2→SrS\tau_1 = S\tau_2 \to Sr, and T-App gives SΓ⊢e1 e2:SrS\Gamma \vdash e_1\,e_2 : Sr. At an abstraction, the induction gives SΓ,x:Sa⊢e1:Sτ1S\Gamma, x{:}Sa \vdash e_1 : S\tau_1, and T-Abs gives the arrow. For (2), inversion on the derivation of TT gives the types of the parts. At λx.e1\lambda x.e_1, inversion gives T=T1→T2T = T_1 \to T_2, so extend S′S' with a:=T1a := T_1, which is safe because aa is fresh, and use the induction. At an application, inversion gives a type T11T_{11} for the argument. The induction gives solutions for C1C_1 and C2C_2, which agree on Γ\Gamma and touch disjoint sets of fresh variables, so their union is a function; add r:=Tr := T. □\square

Corollary (principal types). If σ\sigma is a most general unifier of CC, then (σΓ,στ)(\sigma\Gamma, \sigma\tau) is a principal typing: each solution SS factors as S=S′′∘σS = S'' \circ \sigma, 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 O(n α(n))O(n\,\alpha(n)) time if the occurs check is done once at the end. Paterson-Wegman runs in O(n)O(n) time. The constraint set has O(n)O(n) symbols, so Curry-style STLC inference takes O(n)O(n) 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 e1e_1, generalize its type over the variables that are not free in the context, and give xx that type scheme.

AlgorithmTimeSpacePropertiesCode
Algorithm J2^O(n) worst2^O(n) extradeterministicrecursive1 language
Algorithm W2^(2^O(n)) worst2^(2^O(n)) extradeterministicrecursive1 language

Bounds

system typability source
Curry-style STLC Θ(n)\Theta(n) 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 DD 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 nn 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: ee is typable if and only if let u=e in fun v→v\mathsf{let}\ u = e\ \mathsf{in}\ \mathsf{fun}\ v \to v has type Int→Int\mathsf{Int} \to \mathsf{Int} 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, Java var, C# var, Go :=, Rust let and 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

  1. 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)
  2. 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)
  3. 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
  4. Mitchell Wand, A simple algorithm and proof for type inference, Fundamenta Informaticae 10, 1987, the separation of type inference into constraint generation and unification
  5. 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)
  6. 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
  7. 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)
  8. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a contract.yaml