Algorithm Search⌘K

Definitionadvanced

Value restriction

Also called Wright's value restriction.

Generalize the type of a let binding only when its right side is a syntactic value, which keeps polymorphism sound with mutable references.

The value restriction is the rule that makes let-polymorphism sound in a language with mutable references. The plain rule of the Hindley-Milner type system generalizes the type of every let definition. With references, this lets one cell hold an integer function and then be read as a boolean function, and the program gets stuck. The value restriction generalizes only when the right side of the let is a syntactic value, such as a function or a constant, whose evaluation cannot create a cell. Wright proposed it in 1995. Standard ML adopted it in its 1997 revision, in place of the imperative type variables of Tofte (1990). OCaml uses a relaxed form due to Garrigue (2004).

Definition

The language. Extend the terms of the Hindley-Milner page with references, as in Chapter 13 of Pierce's book:

e::=…∣ref e∣ !e∣e1:=e2∣e1; e2∣()τ::=…∣τ ref∣unit.e ::= \ldots \mid \texttt{ref } e \mid\ !e \mid e_1 := e_2 \mid e_1;\ e_2 \mid \texttt{()} \qquad \tau ::= \ldots \mid \tau\ \mathsf{ref} \mid \mathsf{unit}.

At run time, ref v allocates a new cell ll in the store, !l reads it, and l := v writes it and returns (). The typing rules are:

Gamma |- e1 : tau1                 Gamma |- e1 : tau1 ref           Gamma |- e1 : tau1 ref    Gamma |- e2 : tau1
--------------------------  T-Ref  ----------------------  T-Deref  ------------------------------------------  T-Assign
Gamma |- ref e1 : tau1 ref         Gamma |- !e1 : tau1              Gamma |- e1 := e2 : unit

Gamma |- e1 : unit    Gamma |- e2 : tau2
----------------------------------------  T-Seq
Gamma |- e1; e2 : tau2

Syntactic values. A syntactic value, also called a non-expansive expression, is a term of the form

v::=x∣c∣fun x -> e∣()∣l,v ::= x \mid c \mid \texttt{fun } x \texttt{ -> } e \mid \texttt{()} \mid l,

where ll is a store location, which appears only at run time. Standard ML also counts tuples and constructor applications whose parts are values, except the constructor ref. An application, ref e, !e, e1 := e2 and a let are not values. The test is purely syntactic: fun x -> ref x is a value, because its body runs only when it is called.

The rule. Replace T-Let' of the syntax-directed system by two rules:

e1 is a value    Gamma |- e1 : tau1    Gamma, x : Gen(Gamma, tau1) |- e2 : tau2
-------------------------------------------------------------------------------  T-LetV
Gamma |- let x = e1 in e2 : tau2

e1 is not a value    Gamma |- e1 : tau1    Gamma, x : tau1 |- e2 : tau2
-----------------------------------------------------------------------  T-LetE
Gamma |- let x = e1 in e2 : tau2

T-LetE binds xx to the plain type τ1\tau_1, as T-Abs would. So let x = e1 in e2 with a non-value e1e_1 types like (fun x -> e2) e1. In algorithm W, the change is one test at the let line: if e1e_1 is not a value, store τ1\tau_1 with no quantifier. The type variables of τ1\tau_1 stay free in the context, and later uses of xx may fix them. Type checkers often call them weak type variables.

Soundness. With the value restriction, a closed well-typed program never gets stuck. The proof is progress and preservation (Wright 1995). Preservation is shown for a term together with a store typing Σ\Sigma, which gives the type of each allocated cell, and Gen must also skip the type variables that are free in Σ\Sigma. Source programs contain no locations, so this changes nothing for them. Two steps of the proof use the restriction.

  • The let step. let x = v in e2 steps to [x:=v] e2[x := v]\,e_2. Each copy of vv needs its own instance of the scheme, and the type substitution lemma gives it, because the generalized variables are free neither in Γ\Gamma nor in Σ\Sigma. The step does nothing else, so the copying model of let-polymorphism is exact.
  • The allocation step. let x = ref v in e2 was typed with T-LetE, so xx has the plain type τ1 ref\tau_1\ \mathsf{ref}. After the step ref v becomes a new location ll with Σ(l)=τ1\Sigma(l) = \tau_1, and T-LetV for let x = l in e2 generalizes nothing, since all variables of τ1\tau_1 are now free in Σ\Sigma. So the same typing of e2e_2 still works.

A non-value can allocate a cell while it runs, and then its type mentions the type of the new cell. That is the case that the restriction refuses to generalize.

Examples and non-examples

The unsound program. Take the term

let r = ref (fun x -> x) in
r := (fun x -> x + 1);
(!r) true

Without the restriction, it has the type bool\mathsf{bool}. The derivation, step by step, with the plain rule T-Let':

  1. x:α⊢x:αx : \alpha \vdash x : \alpha by T-Var', so ⊢fun x -> x:α→α\vdash \texttt{fun x -> x} : \alpha \to \alpha by T-Abs.
  2. ⊢ref (fun x -> x):(α→α) ref\vdash \texttt{ref (fun x -> x)} : (\alpha \to \alpha)\ \mathsf{ref} by T-Ref.
  3. The context is empty, so T-Let' binds rr to Gen(∅,(α→α) ref)=∀α. (α→α) ref\mathrm{Gen}(\emptyset, (\alpha \to \alpha)\ \mathsf{ref}) = \forall \alpha.\, (\alpha \to \alpha)\ \mathsf{ref}. Let Γ=r:∀α. (α→α) ref\Gamma = r : \forall \alpha.\, (\alpha \to \alpha)\ \mathsf{ref}.
  4. Γ⊢r:(int→int) ref\Gamma \vdash r : (\mathsf{int} \to \mathsf{int})\ \mathsf{ref} by T-Var', with the instance α:=int\alpha := \mathsf{int}.
  5. Γ⊢fun x -> x + 1:int→int\Gamma \vdash \texttt{fun x -> x + 1} : \mathsf{int} \to \mathsf{int} by T-Abs.
  6. Γ⊢r := (fun x -> x + 1):unit\Gamma \vdash \texttt{r := (fun x -> x + 1)} : \mathsf{unit} by T-Assign, from steps 4 and 5.
  7. Γ⊢r:(bool→bool) ref\Gamma \vdash r : (\mathsf{bool} \to \mathsf{bool})\ \mathsf{ref} by T-Var', with the instance α:=bool\alpha := \mathsf{bool}.
  8. Γ⊢!r:bool→bool\Gamma \vdash \texttt{!r} : \mathsf{bool} \to \mathsf{bool} by T-Deref.
  9. Γ⊢(!r) true:bool\Gamma \vdash \texttt{(!r) true} : \mathsf{bool} by T-App.
  10. Γ⊢r := (fun x -> x + 1); (!r) true:bool\Gamma \vdash \texttt{r := (fun x -> x + 1); (!r) true} : \mathsf{bool} by T-Seq, from steps 6 and 9.
  11. ⊢\vdash the whole term :bool: \mathsf{bool} by T-Let', from steps 2 and 10.

Each step follows the rules. The error is at step 3: the two uses of r in steps 4 and 7 choose two instances, but they name the same cell. Evaluation, with the store on the right:

let r = ref (fun x -> x) in r := (fun x -> x + 1); (!r) true     | empty
-> let r = l in r := (fun x -> x + 1); (!r) true                  | l = fun x -> x
-> l := (fun x -> x + 1); (!l) true                               | l = fun x -> x
-> (); (!l) true                                                  | l = fun x -> x + 1
-> (!l) true                                                      | l = fun x -> x + 1
-> (fun x -> x + 1) true                                          | l = fun x -> x + 1
-> true + 1                                                       | l = fun x -> x + 1

The last term is not a value, and no rule applies to it. The program is stuck, so this type system is unsound. The copying model fails here: the copy (ref (fun x -> x)) := ...; (!(ref (fun x -> x))) true creates two cells and runs with no error, but the real program creates one cell.

The same program with the restriction. ref (fun x -> x) is not a value, so T-LetE binds r to (α→α) ref(\alpha \to \alpha)\ \mathsf{ref} with no quantifier. Step 4 now forces α=int\alpha = \mathsf{int}, and step 7 needs α=bool\alpha = \mathsf{bool}. W fails at the unification of int\mathsf{int} with bool\mathsf{bool}, and the program is rejected. The program let r = ref (fun x -> x) in r := (fun x -> x + 1); (!r) 2 uses the cell at one type and has the type int\mathsf{int}.

Values are still generalized. In let id = fun x -> x in ..., let n = 5 in ... and let k = fun x -> fun y -> x in ..., the right sides are values, and the schemes are as in plain HM. A variable is a value too, so in let g = id in if g true then g 1 else 0, the name g gets ∀α. α→α\forall \alpha.\, \alpha \to \alpha.

A safe program that the restriction rejects. In

let id = fun x -> x in
let f = id id in
if f true then f 1 else 0

the right side id id is an application, so f gets β→β\beta \to \beta with β\beta not quantified. The two uses need β=bool\beta = \mathsf{bool} and β=int\beta = \mathsf{int}, and the program is rejected, although plain HM gives it the type int\mathsf{int} and it runs without error. The usual repair is eta-expansion: let f = fun y -> id id y is a value and gets ∀β. β→β\forall \beta.\, \beta \to \beta. The same problem hits partial applications in real code, such as let ids = List.map (fun x -> x) in OCaml.

Weak type variables in OCaml. At the OCaml top level, let r = ref [] gets the type '_weak1 list ref. The variable '_weak1 is not quantified. After r := [1], the type of r becomes int list ref, and r := [true] is then a type error.

The relaxed restriction. OCaml generalizes a type variable of a non-value when the variable occurs only in covariant positions of τ1\tau_1, that is, never to the left of an arrow and never under ref or another mutable type (Garrigue 2004). So let l = List.rev [] gets 'a list, while let r = ref [] still gets a weak variable.

  • Let-polymorphism. The value restriction limits which let definitions get schemes. For pure programs, the copying model shows why every let is safe.
  • Hindley-Milner type system. The value restriction only changes T-Let', so each typable term still has a principal type and W still finds it. See the principal type theorem.
  • Imperative type variables (Tofte 1990). The approach of Standard ML in 1990. The type of ref uses imperative type variables, and a let may generalize them only when the right side is non-expansive. Other type variables are always generalized. The value restriction is simpler and replaced it in 1997.
  • Effect systems. An effect system can record in the type which regions a computation allocates or writes, and then generalize all variables that no effect mentions. This accepts more programs, at the cost of more complex types.
  • The Haskell view. Haskell needs no value restriction for references, because allocation is an IO action: in do r <- newIORef [], the name r is bound by a function argument and is monomorphic. Code that uses unsafePerformIO to allocate a top-level cell can break soundness in the same way as the program above. The monomorphism restriction of Haskell is a different rule, about type classes.
  • Type soundness. The theorem that the value restriction protects.

References

  1. Andrew K. Wright, Simple imperative polymorphism, LISP and Symbolic Computation 8(4), 1995, pages 343 to 355, the definition of the value restriction, its soundness proof for ML with references, and the study of how often it rejects existing programs
  2. Mads Tofte, Type inference for polymorphic references, Information and Computation 89(1), 1990, pages 1 to 34, the counterexample with a polymorphic reference cell, and imperative type variables with the non-expansive condition at let
  3. Jacques Garrigue, Relaxing the value restriction, Functional and Logic Programming (FLOPS 2004), Lecture Notes in Computer Science 2998, pages 196 to 213, the relaxed value restriction, which also generalizes type variables that occur only in covariant positions
  4. Benjamin C. Pierce, Types and Programming Languages, MIT Press, 2002, Chapter 13 (references, the rules T-Ref, T-Deref and T-Assign, and store typings) and Section 22.7 (the unsound polymorphic reference and the value restriction)

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)
WritingW4 complete
  • a review of the text: no review record reviews/W7DCCA/text.yaml