Value restriction

In programming languages with Hindley-Milner type inference and imperative features, in particular the ML programming language family, the value restriction means that declarations are only polymorphically generalized if they are syntactic values (also called non-expansive). The value restriction prevents reference cells from holding values of different types and preserves type safety.

A Counter Example to Type Safety
In the Hindley–Milner type system, expressions can be given multiple types through parametric polymorphism. But naively giving multiple types to references breaks type safety. The following are typing rules for references and related operators in ML-like languages.

$$\begin{align} \mathtt{ref} &: \forall \alpha. \alpha \to (\alpha\ \mathtt{ref}) \\ \mathtt{!} &: \forall \alpha. (\alpha\ \mathtt{ref}) \to \alpha \\ \mathtt{:=} &: \forall \alpha. (\alpha\ \mathtt{ref}) \to \alpha \to \mathtt{unit} \end{align} $$

The operators have the following semantics: $\mathtt{ref}$ takes a value and creates a reference containing that value, $\mathtt{!}$  (dereference) takes a reference and reads the value in that reference, and $\mathtt{:=}$  (assignment) updates a reference to contain a new value and returns a value of the unit type. Given these, the following program unsoundly applies a function meant for integers to a Boolean value. The above program type checks using Hindley-Milner because  is given the type $\forall \alpha. (\alpha \to \alpha)\ \mathtt{ref}$, which is then instantiated to be of the type $(\mathtt{int} \to \mathtt{int})\ \mathtt{ref}$ when typing the assignment  , and $(\mathtt{bool} \to \mathtt{bool})\ \mathtt{ref}$  ref when typing the dereference.

The Value Restriction
Under the value restriction, the types of let bound expressions are only generalized if the expressions are syntactic values. In his paper, Wright considers the following to be syntactic values: constants, variables, $\lambda$ -expressions and constructors applied to values. The function and operator applications are not considered values. In particular, applications of the $$\mathtt{ref}$$ operator are not generalized. It is safe to generalize type variables of syntactic values because their evaluation cannot cause any side-effects such as writing to a reference.

The above example is rejected by the type checker under the value restriction as follows.

$, and the type checker rejects the program.
 * First  is given the type $(\alpha \to \alpha)\ \mathtt{ref}$ . This type is not generalized and $\alpha$  is a free variable in the typing context for the body of the let binding.
 * When the assignment is typed, the type of  is modified in the typing context to be of type $(\mathtt{int} \to \mathtt{int})\ \mathtt{ref}$  via unification.
 * The dereference  is typed as $$\mathtt{int} \to \mathtt{int}$$, but is applied to a value of type $\mathtt{bool}