Types II: Typing Formalism
We will continue our exploration of types. First, we will introduce
typing inference rules, which give us a concise and precise
way of describing type systems and how they behave.
We will use these inference rules to give type systems for
IfLang and the simply-typed lambda calculus.
Then, we will explore the consequences of simple types, and
see how it is not possible to give a typing derivation for
self-application. Finally, we will see that typing derivations are themselves
just data, and take our first steps toward proving properties of type systems.
import Lait
#lait
Typing Rules and Derivations for IfLang
Recall our IfLang type checker from the previous lecture:
type IfLang := | NumI (value : Int)
| BoolI (value : Bool)
| PlusI (e1 : IfLang) (e2 : IfLang)
| IfI (guard : IfLang) (thn : IfLang) (els : IfLang)
type IfType := | NumT | BoolT
def type_of (e : IfLang) : IfType :=
match e with
| NumI n => NumT
| BoolI b => BoolT
| PlusI e1 e2 =>
if type_of e1 == NumT && type_of e2 == NumT
then NumT
else error "type: expected Int"
| IfI g thn els =>
if type_of g == BoolT
then
let t_thn := type_of thn in
let t_els := type_of els in
if t_thn == t_els
then t_thn
else error "type: expected thn and els to have the same type"
else error "type: expected Bool"
end
Just as we used inference rules and derivation trees to concisely and precisely
describe the semantics of programs in the formalism lecture, it is
useful to use the same notation to describe type systems.
Here are the typing rules for IfLang that capture the above type checker:
\[ \dfrac{}{\vdash \verb|NumI | n : \texttt{Num}}\ \text{(T-Num)} \qquad \dfrac{}{\vdash \verb|BoolI | b : \texttt{Bool}}\ \text{(T-Bool)} \]
\[ \dfrac{\vdash e_1 : \texttt{Num} \quad \vdash e_2 : \texttt{Num}} {\vdash \verb|PlusI | e_1\ e_2 : \texttt{Num}}\ \text{(T-Plus)} \]
\[ \dfrac{\vdash g : \texttt{Bool} \quad \vdash e_1 : \tau \quad e_2 : \tau} {\vdash \verb|IfI | g\ e_1\ e_2 : \tau}\ \text{(T-If)} \]
We read the relation \(\vdash e : \tau\) as “term \(e\) has type \(\tau\)”. Here, the symbol ``\(\vdash\)’’ is called a “turnstile”, and is often used to denote when a proposition that we write using inference rules is defining a type system.
Thus, the (T-Num) rule says that any number \(\verb|NumI | n\) has type
Num. Here, \(\tau\) is a metavariable that stands for an arbitrary type;
so (T-If) says that an IfI has type \(\tau\) whenever its guard is a Boolean
and both of its branches have that same type \(\tau\).
Once again, to understand how these rules work, it’s helpful to look at an example derivation tree:
\[ \dfrac{\dfrac{\dfrac{}{\vdash \verb|NumI | 1 : \texttt{Num}}\ \text{(T-Num)} \quad \dfrac{}{\vdash \verb|NumI | 2 : \texttt{Num}}\ \text{(T-Num)}} {\vdash \verb|PlusI | (\verb|NumI | 1)\ (\verb|NumI | 2) : \texttt{Num}}\ \text{(T-Plus)} \quad \dfrac{}{\vdash \verb|NumI | 3 : \texttt{Num}}\ \text{(T-Num)}} {\vdash \verb|PlusI | (\verb|PlusI | (\verb|NumI | 1)\ (\verb|NumI | 2))\ (\verb|NumI | 3) : \texttt{Num}}\ \text{(T-Plus)} \]
What happens if we try to give a type to an ill-typed term? Then, we get stuck: there are no valid rules to apply. For instance:
\[ \dfrac{???}{\vdash \verb|PlusI | (\verb|NumI | 1)\ (\verb|BoolI | \texttt{true}) : \ ?} \]
The only rule whose conclusion mentions PlusI is (T-Plus), and it requires
the second argument to have type Num. But the only rule that applies to
\(\verb|BoolI | \texttt{true}\) is (T-Bool), which gives it type Bool.
So, no derivation tree exists, and we conclude that this term is
not well-typed according to our type system.
Typing Rules for STLC
Now let’s give typing rules for the simply-typed lambda calculus. Recall the
implementation of STLC.type_of from the previous lecture.
Notice that it has an extra argument, the environment env, that is necessary
for type checking lambda terms and variables. So, our typing
judgment needs to also include this environment as part of its definition.
We will call the typing environment (or typing context) \(\Gamma\).
You can think of \(\Gamma\) as the math version of a Map: it
maps variables to their types. We write \(\Gamma, x : \tau\) for the context
\(\Gamma\) extended with the variable \(x\) having type \(\tau\).
Using \(\Gamma\), we will define a typing judgment of the form \(\Gamma \vdash e : \tau\), which says “in context \(\Gamma\), the term \(e\) has type \(\tau\)”. Here are the typing rules for the simply-typed lambda calculus with numbers:
\[ \dfrac{}{\Gamma \vdash n : \texttt{Num}}\ \text{(T-Num)} \qquad \dfrac{x : \tau \in \Gamma}{\Gamma \vdash x : \tau}\ \text{(T-Var)} \]
\[ \dfrac{\Gamma \vdash e_1 : \texttt{Num} \quad \Gamma \vdash e_2 : \texttt{Num}} {\Gamma \vdash e_1 + e_2 : \texttt{Num}}\ \text{(T-Add)} \]
\[ \dfrac{\Gamma, x : \tau_1 \vdash e : \tau_2} {\Gamma \vdash \lambda x : \tau_1.\ e : \tau_1 \rightarrow \tau_2}\ \text{(T-Abs)} \]
\[ \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)} \]
Compare each rule to the corresponding case of STLC.type_of: (T-Var) is the
lookup in the environment, (T-Abs) is the Map.insert of the argument’s type
before checking the body, and (T-App) is the check that the function has type
\(\tau_1 \rightarrow \tau_2\) and the argument has type exactly \(\tau_1\).
At first these rules can look a bit scary, but they become comfortable with enough practice. First, let’s see how the typing context \(\Gamma\) is used when drawing a typing derivation.
The (T-Num) rule holds in any context, so the following is a valid derivation:
\[ \dfrac{}{x : \texttt{Num} \vdash 4 : \texttt{Num}}\ \text{(T-Num)} \]
This derivation says “in the typing context where \(x\) is a variable with type
Num, the term \(4\) has type Num”.
Of course, this rule also holds in the empty typing context where there are no variables in scope, which we write as follows:
\[ \dfrac{}{\vdash 4 : \texttt{Num}}\ \text{(T-Num)} \]
Next, the (T-Var) rule simply looks into the context to see which
type a variable has. For instance, the following derivation
tree shows that \(x\) has type Num in the context \(x : \texttt{Num}, y : \texttt{Num}\):
\[ \dfrac{\dfrac{}{x : \texttt{Num} \in x : \texttt{Num}, y : \texttt{Num}}} {x : \texttt{Num}, y : \texttt{Num} \vdash x : \texttt{Num}}\ \text{(T-Var)} \]
The key use of the typing context is that variables get moved into it during a derivation. Here is what that looks like:
\[ \dfrac{\dfrac{\dfrac{}{x : \texttt{Num} \in x : \texttt{Num}}} {x : \texttt{Num} \vdash x : \texttt{Num}}\ \text{(T-Var)}} {\vdash \lambda x : \texttt{Num}.\ x : \texttt{Num} \rightarrow \texttt{Num}}\ \text{(T-Abs)} \]
Notice how \(x : \texttt{Num}\) was added to the typing context in the premise. Finally, we can give a more complicated derivation involving a function call:
\[ \dfrac{\dfrac{\dfrac{\dfrac{}{x : \texttt{Num} \in x : \texttt{Num}}} {x : \texttt{Num} \vdash x : \texttt{Num}}\ \text{(T-Var)}} {\vdash \lambda x : \texttt{Num}.\ x : \texttt{Num} \rightarrow \texttt{Num}}\ \text{(T-Abs)} \quad \dfrac{}{\vdash 4 : \texttt{Num}}\ \text{(T-Num)}} {\vdash (\lambda x : \texttt{Num}.\ x)\ 4 : \texttt{Num}}\ \text{(T-App)} \]
Exercise. Write down at least 3 observationally inequivalent programs that are members of each of the following types:
- \(\texttt{Num} \rightarrow \texttt{Num}\)
- \(\texttt{Num} \rightarrow (\texttt{Num} \rightarrow \texttt{Num})\)
- \((\texttt{Num} \rightarrow \texttt{Num}) \rightarrow (\texttt{Num} \rightarrow \texttt{Num})\)
Exercise. Draw a typing derivation for the following STLC program, or explain why no valid tree exists:
- \(\lambda x : \texttt{Num}.\ (\lambda y : \texttt{Num} \rightarrow \texttt{Num}.\ y\ x)\)
- \(\lambda x : \texttt{Num}. x + x \)
- \(\lambda x : \texttt{Num} \rightarrow \texttt{Num}. x + x \)
Consequences of Simple Types
A question you might have about the simply-typed lambda calculus is: how expressive is it? Put differently: are there any lambda terms that we could run in the untyped lambda calculus that cannot be given a type?
The answer is yes! Consider the self-application function \(\omega = \lambda x.\ x\ x\) from the lambda calculus lecture. We would like to use this function in the simply-typed lambda calculus. To do this, we must annotate the argument \(x\) with some type. Which type should we choose?
Suppose we gave it type Num. Does the following term type check?
\[ \lambda x : \texttt{Num}.\ x\ x \]
No, it doesn’t, because we are trying to call \(x\) but it is not a function. Okay, let’s try a function type instead. Does this type check?
\[ \lambda x : \texttt{Num} \rightarrow \texttt{Num}.\ x\ x \]
It’s not immediately obvious, so let’s try to draw a derivation tree and see if we get stuck:
\[ \dfrac{\dfrac{???} {x : \texttt{Num} \rightarrow \texttt{Num} \vdash x\ x : \ ?}\ \text{(T-App)}} {\vdash \lambda x : \texttt{Num} \rightarrow \texttt{Num}.\ x\ x : \ ?}\ \text{(T-Abs)} \]
At the \(???\) point in the tree, we are stuck. We know that \(x\)
has type \(\texttt{Num} \rightarrow \texttt{Num}\), so (T-App) requires its
argument to have type Num. But the argument is \(x\) itself, which has
type \(\texttt{Num} \rightarrow \texttt{Num}\); this is an invalid function
call.
The same problem happens no matter which type we choose. For \(x\ x\) to type
check, \(x\) must have some function type \(\tau_1 \rightarrow \tau_2\), and
its argument (\(x\) again) must have type \(\tau_1\). So the type of the
argument of \(\omega\) must satisfy the equation
\(\tau \cong \tau \rightarrow \tau_2\) for some mystery type \(\tau\).
We have no such types in the simply-typed lambda calculus: every type is
either Num or a function type, and a type can never be equal to a strictly
larger type that contains it.
Since \(\omega\) is not typeable, neither is \(\Omega = \omega\ \omega\), the program that runs forever. This is no accident: it is a theorem that every well-typed STLC program terminates. Simple types rule out non-termination entirely!
A Typing Derivation Tree Datastructure
Now for a big idea: derivation trees are just data! We can think of typing derivation trees themselves as surface syntax. Then, we can give an abstract syntax datatype for representing them, with one constructor per typing rule:
type TyTree :=
-- contract: e = NumI n, t = NumT
| TyNum (e : IfLang) (t : IfType)
-- contract: e = BoolI b, t = BoolT
| TyBool (e : IfLang) (t : IfType)
-- contract:
-- e = PlusI e1 e2
-- d1 proves e1 has type NumT
-- d2 proves e2 has type NumT
-- t = NumT
| TyPlus (e : IfLang) (d1 : TyTree) (d2 : TyTree) (t : IfType)
-- contract:
-- e = IfI g thn els
-- dg proves g has type BoolT
-- dthn proves thn has type t
-- dels proves els has type t
| TyIf (e : IfLang) (dg : TyTree) (dthn : TyTree) (dels : TyTree) (t : IfType)
Each constructor of TyTree has a contract that specifies
when that typing derivation tree is valid. Lait does not have enough
language features to enforce these contracts, so we will need to be careful to
only construct valid derivation trees ourselves.
TyTree
places on its data. For instance, in Lean or Rocq it is possible to enforce
these contracts statically.
Let’s see how to manually construct the datastructure that corresponds to a typing derivation tree. For example, consider the following derivation:
\[ \dfrac{\dfrac{}{\vdash \verb|NumI | 1 : \texttt{Num}}\ \text{(T-Num)} \quad \dfrac{}{\vdash \verb|NumI | 2 : \texttt{Num}}\ \text{(T-Num)}} {\vdash \verb|PlusI | (\verb|NumI | 1)\ (\verb|NumI | 2) : \texttt{Num}}\ \text{(T-Plus)} \]
It corresponds to the following TyTree:
def ex_tree : TyTree :=
TyPlus (PlusI (NumI 1) (NumI 2))
(TyNum (NumI 1) NumT)
(TyNum (NumI 2) NumT)
NumT
Now, it’s natural to design a procedure for automatically building a typing
derivation tree for a particular IfLang term. This looks a lot
like the type_of function:
def get_type (d : TyTree) : IfType :=
match d with
| TyNum _ t => t
| TyBool _ t => t
| TyPlus _ _ _ t => t
| TyIf _ _ _ _ t => t
end
def build_ty_tree (e : IfLang) : TyTree :=
match e with
| NumI n => TyNum e NumT
| BoolI b => TyBool e BoolT
| PlusI e1 e2 =>
-- build derivations d1 and d2 for e1 and e2,
-- check that they both prove type NumT,
-- then combine them with (T-Plus)
let d1 := build_ty_tree e1 in
let d2 := build_ty_tree e2 in
if get_type d1 == NumT && get_type d2 == NumT
then TyPlus e d1 d2 NumT
else error "type: expected Int"
| IfI g thn els =>
-- build derivations for g, thn, and els,
-- check that g has type BoolT and that the
-- branches have the same type, then combine
-- them with (T-If)
let dg := build_ty_tree g in
let dthn := build_ty_tree thn in
let dels := build_ty_tree els in
if get_type dg == BoolT
then
if get_type dthn == get_type dels
then TyIf e dg dthn dels (get_type dthn)
else error "type: expected thn and els to have the same type"
else error "type: expected Bool"
end
#test build_ty_tree (PlusI (NumI 1) (NumI 2)) === ex_tree
#test get_type (build_ty_tree (IfI (BoolI true) (NumI 10) (NumI 20))) === NumT
#test_error build_ty_tree (PlusI (BoolI true) (NumI 2))
One way to understand build_ty_tree is that it builds a
proof that a term has a particular type, by applying the rules of our type
system. Whenever type_of e returns a type \(\tau\), build_ty_tree e
returns the evidence for why \(\vdash e : \tau\).
Properties of Type Systems
Now we can begin to explore properties of type systems themselves. For the rest
of this lecture we will study IfLang, since its structure is simpler.
Let’s start with a simple example: if an IfLang program is a value of type
Bool, then it must be either true or false.
How can we prove this fact?
Canonical Forms
First, let’s define a new judgment, \(\texttt{value}\ e\), that tells us whether or not a program is a value:
\[ \dfrac{}{\texttt{value}\ (\verb|BoolI | b)}\ \text{(V-Bool)} \qquad \dfrac{}{\texttt{value}\ (\verb|NumI | n)}\ \text{(V-Num)} \]
Now, we can formally state our first theorem about type systems:
Theorem (Boolean canonical forms). If \(\vdash e : \texttt{Bool}\) and \(\texttt{value}\ e\), then \(e = \verb|BoolI | b\) for some \(b\).
Proof. If \(\texttt{value}\ e\), then there are two possible derivations of this fact: one ending in (V-Bool), or one ending in (V-Num). We do case analysis on these two possibilities:
- (V-Bool). Then \(e = \verb|BoolI | b\), and we are done.
- (V-Num). Then \(e = \verb|NumI | n\). The only typing rule that applies to
\(\verb|NumI | n\) is (T-Num), so \(e\) has type
Num. This contradicts our assumption that \(e\) has typeBool.
Notice the reasoning principles we used in the above argument:
- Case analysis: we are allowed to reason case by case over the rules that could have been used to derive a judgment like \(\texttt{value}\ e\), a typing judgment, or a stepping judgment.
- Contradiction: if we can show that our assumptions contradict each other, then that case is impossible and we are done with it.
Note that we can prove a similar theorem for the simply-typed lambda calculus. What would that theorem look like?