Extensions to the Simply-Typed Lambda Calculus: Mutability
So far, we have investigated a relatively simple calculus: the simply-typed lambda calculus, which for us has numbers, addition, and functions.
Today, we’re going to see how the tools we have gained allow us to quickly add new language features.
import Lait
#lait
\[ \newcommand{\Int}{\texttt{Int}} \newcommand{\Nat}{\texttt{Nat}} \newcommand{\Pos}{\texttt{Pos}} \]
Mutable State: MutLang
We will study MutLang: an extension of STLC that also covers mutable cells.
This will model how mutability works in many functional programming languages, such as Lait or OCaml:
def mkCell () : Ref<Int> :=
alloc 42
def test1 :=
let c := mkCell () in
let _ := set c 2 in
let _ := set c (get c + 4) in
get c
#eval test1>> 6
We will model mutability with a new type, Ref t, which stands for “mutable cells holding a t”.
This type will have three operations:
alloc e, which, given ane : t, will create a fresh mutable cell location holding that value;get ewhich, given ane : Ref t, will dereference the heap at the locationeto obtain at; andset e1 e2which, givene1 : Ref tande2 : t, will update the heap at locatione1to now holde2. It will return the unit value(), of typeUnit, since there is no meaningful result.
The syntax of MutLang is given below:
\[ e ::= x \mid n \mid () \mid e + e \mid \lambda x : \tau. e \mid e\ e \mid \mathsf{alloc}\ e \mid \mathsf{get}\ e \mid \mathsf{set}\ e\ e \]
Example Program
In the call-by-value lambda calculus, we don’t have let bindings in the syntax; however, we can always emulate them via the following:
\[ (\mathsf{let}\ x : \tau = e_1\ \mathsf{in}\ e_2) \mathrel{\overset{\text{def}}{=}} (\lambda x : \tau. e_2)\ e_1 \]
Given the above definition, we can then implement our program test1 from above as follows:
\[ \begin{array}{l} \mathsf{let}\ c : \texttt{Ref}\ \texttt{Num} = \mathsf{alloc}\ 42\ \mathsf{in} \\ \mathsf{let}\ \_ : \texttt{Unit} = \mathsf{set}\ c\ 2\ \mathsf{in} \\ \mathsf{let}\ \_ : \texttt{Unit} = \mathsf{set}\ c\ (\mathsf{get}\ c + 4)\ \mathsf{in} \\ \mathsf{get}\ c \end{array} \]
(Here we have inlined mkCell.)
Small-Step Semantics for MutLang
We now give a small-step semantics for MutLang.
The basic idea is that we keep the semantics for all of the STLC-inherited features basically the same (e.g., lambda abstraction), but also thread through a notion of a “heap”, which keeps track of the values inside of mutable memory cells.
Additionally, we need to extend our expressions with a runtime-only value for a heap location:
\[ e ::= \dots \mid \ell \in \mathbb{N} \]
To give a small-step semantics, we will generalize our stepping relation a bit. Previously, the stepping relation was of the form \(e \to e’\), where \(e\) and \(e’\) are expressions. Now, we will have the stepping relation take the form \(\langle \sigma, e \rangle \to \langle \sigma’, e’ \rangle\). Here, \(\sigma : \mathbb{N} \to \texttt{Val}\) is a heap, which maps memory locations to values.
The stepping rules for MutLang will be given in two parts.
The first part are all of the rules for the “old” features (e.g., addition, or application). In these rules, we don’t use the heap \(\sigma\), but merely thread it through:
\[ \begin{gathered} \dfrac{}{\langle \sigma, n_1 + n_2 \rangle \rightarrow \langle \sigma, n \rangle}\ \text{(E-Add1)} \quad \text{where } n = n_1 + n_2 \\[1.5em] \dfrac{\langle \sigma, e_1 \rangle \rightarrow \langle \sigma^{\prime}, e_1^{\prime} \rangle} {\langle \sigma, e_1 + e_2 \rangle \rightarrow \langle \sigma^{\prime}, e_1^{\prime} + e_2 \rangle}\ \text{(E-Add2)} \qquad \dfrac{\langle \sigma, e_2 \rangle \rightarrow \langle \sigma^{\prime}, e_2^{\prime} \rangle} {\langle \sigma, n + e_2 \rangle \rightarrow \langle \sigma^{\prime}, n + e_2^{\prime} \rangle}\ \text{(E-Add3)} \\[1.5em] \dfrac{\langle \sigma, e_1 \rangle \rightarrow \langle \sigma^{\prime}, e_1^{\prime} \rangle} {\langle \sigma, e_1\ e_2 \rangle \rightarrow \langle \sigma^{\prime}, e_1^{\prime}\ e_2 \rangle}\ \text{(E-App1)} \qquad \dfrac{\langle \sigma, e_2 \rangle \rightarrow \langle \sigma^{\prime}, e_2^{\prime} \rangle} {\langle \sigma, v\ e_2 \rangle \rightarrow \langle \sigma^{\prime}, v\ e_2^{\prime} \rangle}\ \text{(E-App2)} \\[1.5em] \dfrac{} {\langle \sigma, (\lambda x : \tau. e)\ v \rangle \rightarrow \langle \sigma, e[x \mapsto v] \rangle}\ \text{(E-Beta)} \end{gathered} \] Note that while we don’t use the heap in a nontrivial way, it is still updated: for example, (E-Add2) says that when stepping \(e_1 + e_2\), the side effects of \(e_1\)’s stepping on the heap will affect how the overall term steps.
The next rules are related to mutation.
First, allocation: when we allocate an expression, we first run it to a value, then we update the heap to hold that new value, using a fresh memory location \(\ell\). The return value of alloc is that fresh memory location.
\[ \begin{gathered} \\[1.5em] \dfrac{\langle \sigma, e \rangle \rightarrow \langle \sigma^{\prime}, e^{\prime} \rangle} {\langle \sigma, \mathsf{alloc}\ e \rangle \rightarrow \langle \sigma^{\prime}, \mathsf{alloc}\ e^{\prime} \rangle}\ \text{(E-Alloc1)} \qquad \dfrac{} {\langle \sigma, \mathsf{alloc}\ v \rangle \rightarrow \langle \sigma[\ell \mapsto v], \ell \rangle}\ \text{(E-Alloc2)} \quad \text{where } \ell \notin \text{dom}(\sigma) \end{gathered} \]
Now, get. When we call get e, we need to reduce e down to a memory location. Then, we look up that memory location in the heap.
\[ \begin{gathered} \dfrac{\langle \sigma, e \rangle \rightarrow \langle \sigma^{\prime}, e^{\prime} \rangle} {\langle \sigma, \mathsf{get}\ e \rangle \rightarrow \langle \sigma^{\prime}, \mathsf{get}\ e^{\prime} \rangle}\ \text{(E-Get1)} \qquad \dfrac{} {\langle \sigma, \mathsf{get}\ \ell \rangle \rightarrow \langle \sigma, \sigma(\ell) \rangle}\ \text{(E-Get2)} \quad \text{where } \ell \in \text{dom}(\sigma) \end{gathered} \]
Finally, set. set e1 e2 should now be unsurprising: we run e1 and e2 down to values (left-to-right); and then we update the heap. The return value of set will be the unit value \(()\).
\[ \begin{gathered} \\[1.5em] \dfrac{\langle \sigma, e_1 \rangle \rightarrow \langle \sigma^{\prime}, e_1^{\prime} \rangle} {\langle \sigma, \mathsf{set}\ e_1\ e_2 \rangle \rightarrow \langle \sigma^{\prime}, \mathsf{set}\ e_1^{\prime}\ e_2 \rangle}\ \text{(E-Set1)} \qquad \dfrac{\langle \sigma, e_2 \rangle \rightarrow \langle \sigma^{\prime}, e_2^{\prime} \rangle} {\langle \sigma, \mathsf{set}\ \ell\ e_2 \rangle \rightarrow \langle \sigma^{\prime}, \mathsf{set}\ \ell\ e_2^{\prime} \rangle}\ \text{(E-Set2)} \\[1.5em] \dfrac{} {\langle \sigma, \mathsf{set}\ \ell\ v \rangle \rightarrow \langle \sigma[\ell \mapsto v], () \rangle}\ \text{(E-Set3)} \quad \text{where } \ell \in \text{dom}(\sigma) \end{gathered} \]
Typechecking MutLang
To rule out these stuck terms, we need a new type former. The type \(\texttt{Ref}\ \tau\) is the type of mutable cells whose contents have type \(\tau\):
\[ \tau ::= \texttt{Num} \mid \texttt{Unit} \mid \tau \rightarrow \tau \mid \texttt{Ref}\ \tau \]
Here are the typing rules for MutLang. The first group is inherited from STLC:
\[ \dfrac{}{\Gamma \vdash n : \texttt{Num}}\ \text{(T-Num)} \qquad \dfrac{}{\Gamma \vdash () : \texttt{Unit}}\ \text{(T-Unit)} \qquad \dfrac{x : \tau \in \Gamma}{\Gamma \vdash x : \tau}\ \text{(T-Var)} \qquad \dfrac{\Gamma \vdash e_1 : \texttt{Num} \quad \Gamma \vdash e_2 : \texttt{Num}} {\Gamma \vdash e_1 + e_2 : \texttt{Num}}\ \text{(T-Plus)} \]
\[ \dfrac{\Gamma, x : \tau_1 \vdash e : \tau_2} {\Gamma \vdash \lambda x : \tau_1.\ e : \tau_1 \rightarrow \tau_2}\ \text{(T-Abs)} \qquad \dfrac{\Gamma \vdash e_1 : \tau_1 \rightarrow \tau_2 \quad \Gamma \vdash e_2 : \tau_1} {\Gamma \vdash e_1\ e_2 : \tau_2}\ \text{(T-App)} \]
The second group covers mutable cells:
\[ \dfrac{\Gamma \vdash e : \tau}{\Gamma \vdash \mathsf{alloc}\ e : \texttt{Ref}\ \tau}\ \text{(T-Alloc)} \qquad \dfrac{\Gamma \vdash e : \texttt{Ref}\ \tau}{\Gamma \vdash \mathsf{get}\ e : \tau}\ \text{(T-Get)} \qquad \dfrac{\Gamma \vdash e_1 : \texttt{Ref}\ \tau \quad \Gamma \vdash e_2 : \tau} {\Gamma \vdash \mathsf{set}\ e_1\ e_2 : \texttt{Unit}}\ \text{(T-Set)} \]
The key rule is (T-Set): we may only overwrite a cell with a value of the
same type as its current contents. This guarantees that the type of a cell’s
contents never changes, so that every get of that cell returns a value of the
type we expect.
Exercise: Implement a type checker for MutLang, which will have type Map<String, MutType> -> MutLang -> MutType.
Now we can state type soundness for MutLang. Since programs now run with a
store, the theorem talks about configurations:
Theorem (Type Soundness for MutLang). Let \(e\) be a MutLang program
with \(\vdash e : \tau\). Then, for any sequence of steps
\(\langle \emptyset, e \rangle \rightarrow \langle \sigma_1, e_1 \rangle \rightarrow \cdots \rightarrow \langle \sigma_n, e_n \rangle\),
the configuration \(\langle \sigma_n, e_n \rangle\) is not stuck: either
\(e_n\) is a value, or \(\langle \sigma_n, e_n \rangle\) can take a step.
This theorem can be proven using progress and preservation, but we will not cover it now.
Consequences of Mutable State
It turns out that every STLC program terminates: it is impossible to write an infinite loop using STLC.
Remarkably, even though MutLang doesn’t explicitly model recursion, we can implement recursion in MutLang.
Let’s see how this works in Lait:
def fact_box : Ref<Int -> Int> := alloc (fun n => 0)
-- fact is not recursive: it calls whatever function is in fact_box
def fact (n : Int) : Int :=
if n == 0 then 1 else n * (get fact_box) (n - 1)
-- "tie the knot": put fact inside its own box
def _ := set fact_box fact
#test fact 5 === 120
The function fact does not call itself, but it does call whatever function is
currently stored in fact_box. Initially that is some arbitrary function, but then we
overwrite the box with fact itself. From then on, fact calls fact.
This trick is called backpatching, or “Landin’s knot”.
This also means we can use mutable state to loop forever:
def my_fun : Ref<Int -> Int> := alloc (fun x => x + 1)
def loopy (x : Int) : Int := (get my_fun) x
def _ := set my_fun loopy
-- loopy 0 now runs forever:
-- loopy 0 -> (get my_fun) 0 -> loopy 0 -> (get my_fun) 0 -> ...
Note that this all does not contradict type soundness. Type soundness just says that “well-typed programs can’t get stuck”. However, it does not say that all well-typed programs must terminate.