Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Types

Well-typed programs can’t go wrong.

Milner, Robin. “A theory of type polymorphism in programming.” Journal of Computer and System Sciences 17.3 (1978): 348-375.

You’ve all programmed in a language with types before. In addition to Lait, a common example is C, where you declare the type of a variable alongside its name and assignment:

#include <stdio.h>
#include <stdint.h>

int main() {
    uint64_t my_num = 10;
    printf("Hello, World! %ld\n", my_num);
    return 0;
}

A type is a collection of values. In the above C program, the type uint64_t is the collection of all possible unsigned 64-bit integer values.

Types restrict the kinds of programs that you can write. For instance, in Lait, you cannot write this program:

import Lait
#lait

#eval 1 + true

If you try, you will get a type error. A type system is the set of rules that a program must follow in order to be well-typed. A type checker is a program that checks whether or not your program is well-typed.

Broadly, there are two motivations for wanting types in a programming language:

  • Physical reasons. In order to run programs we need to run them on a low-level CPU that doesn’t know about strings, Booleans, etc. Types tell the compiler what shape data has so it can map it into something the CPU understands. This can make writing compilers much easier.
  • Logical reasons. Types convey a lot of information about how programs behave to the compiler and to other programmers, beyond how data is represented physically on the computer. Types are used to (1) find and prevent certain kinds of bugs, (2) provide checked specifications for how programs behave, (3) aid in the creation of developer tools, and more.

Our goal in this module is to explore the design and implementation of type systems for various programming languages. This is a rich and deep topic within programming languages research and practice; we will only scratch the surface here.

In order to be useful, a type checker should satisfy the following key properties:

  • Soundness. If a program is well-typed, then it should be free of whatever kind of error the type system is trying to prevent.
  • Expressivity. It should be possible to write interesting well-typed programs.
  • Usability. A programmer should be able to write well-typed programs without too much trouble.
  • Efficiency. It should be faster to run the type checker than it is to run the program. This is partially motivated by the typical use case of type systems: we want to run our type-checking algorithm every time the user changes their code, and programs that users write might take a very long time to run. (Your type checker should not try to solve world peace or the Halting problem.)

As we design type checkers for our languages, we will seek to ensure that each one satisfies the above four properties.

Designing a Type System for IfLang

Let’s see an example of designing a type checker for the IfLang language. First, we recall the abstract syntax and definitional interpreter for IfLang:

type IfLang := | NumI (value : Int)
               | BoolI (value : Bool)
               | PlusI (e1 : IfLang) (e2 : IfLang)
               | IfI (guard : IfLang) (thn : IfLang) (els : IfLang)

type Value := | NumV (v : Int)
              | BoolV (v : Bool)

def Value.toInt (v : Value) : Int :=
  match v with
  | NumV i => i
  | _ => error "Value.toInt: not an Int"
  end

def Value.toBool (v : Value) : Bool :=
  match v with
  | BoolV b => b
  | _ => error "Value.toBool: not a Bool"
  end

def interp_if (e : IfLang) : Value :=
  match e with
  | NumI n => NumV n
  | BoolI b => BoolV b
  | PlusI e1 e2 =>
    let v1 := interp_if e1 in
    let v2 := interp_if e2 in
    NumV (Value.toInt v1 + Value.toInt v2)
  | IfI guard thn els =>
    if Value.toBool (interp_if guard) then interp_if thn else interp_if els
  end

Currently, it is possible for IfLang programs to cause runtime errors:

#eval interp_if (IfI (NumI 10) (NumI 15) (NumI 30))

The first step in designing a type checker is to establish the soundness guarantee of that type checker; i.e., which kinds of bugs ought to be prevented. Here, we will say that our IfLang type checker is sound if it rejects all IfLang programs that cause runtime errors in our definitional interpreter.

Let’s pause on this point: can’t a silly type checker just reject all programs? Such a type checker is surely sound, but it is not useful, because we still want to be able to write programs. So, a second requirement on type systems is that they are expressive: we can’t just reject all programs, including the valid ones.

Let’s write down some examples of the kinds of runtime errors our programs can have that we want our type system to prevent:

  • Using a number in a position where a Boolean is expected, like IfI (NumI 10) (NumI 15) (NumI 30).
  • Using a Boolean in a position where a number is expected, like PlusI (BoolI true) (NumI 10).

Now we are ready to make our type checker. Like our interpreters, our type checker will work by checking that each subprogram is itself well-typed. We can write a function called type_of that associates each IfLang program with its type. Its type in Lait will be IfLang -> IfType.

What is our “type of types”? In this instance, we have two possible types: numbers and Booleans.

type IfType := | NumT | BoolT

Now let’s start filling in type_of. The first few cases aren’t so bad:

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 => ???
  end

Notice how the PlusI case checks that both e1 and e2 have the correct type before returning NumT as the type of the whole expression.

Now, how do we typecheck IfI? Certainly we should ensure that the guard is a Boolean:

  | IfI g thn els =>
    if type_of g == BoolT
    then ???
    else error "type: expected Bool"

Now, what do we do for the ???? Here we encounter a conundrum, because we can have a program like this:

IfI <very complex expression> (BoolI true) (NumI 10)

Depending on what <very complex expression> evaluates to, this program could have type BoolT or NumT. How do we resolve this?

  1. We can give up some expressivity in the name of efficiency: we can reject some programs that do not cause runtime errors, for the sake of a faster type checker.
  2. We can expand our set of types to include types like “unknown” or “bool+int”. This may compromise soundness, depending on how we deal with these new types in our type checker.
  3. We can give up on efficiency and run <very complex expression> to a value. Depending on whether that value is true or false, we can output the type of the corresponding branch.

We choose the first option. This is a design decision because it involves tradeoffs between design objectives. Most languages with type checkers make this decision, including Lait, which requires that both branches of an if have the same type:

#eval if true then 1 else false

We will make the same compromise and require that both branches of an if return the same type:

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

Finally, we can test our type checker. We will have two kinds of tests: soundness tests that check that ill-typed programs are rejected, and expressivity tests that ensure that valid programs do not raise type errors.

First, some expressivity tests:

#test type_of (PlusI (NumI 1) (NumI 2)) === NumT
#test type_of (PlusI (PlusI (NumI 1) (NumI 3)) (NumI 2)) === NumT
#test type_of (IfI (BoolI true) (NumI 10) (NumI 20)) === NumT

Next, some soundness tests:

#test_error type_of (PlusI (BoolI true) (NumI 2))
#test_error type_of (IfI (BoolI false) (NumI 10) (BoolI true))

The Type Checker Design Recipe

We can summarize the above design process into a design recipe that explains step by step how to approach designing a type system for any programming language:

  1. Create examples that demonstrate all the soundness bugs that you want your type checker to prevent.
  2. Create a datatype for representing the kinds of types your programs have. You can build this datatype by thinking about what kinds of values your program has and how you may need to sort them into buckets; think of each type like a bucket of values.
  3. Create a function type_of that associates each term of your language with its type. This function should raise a type error if no type for a term exists, and be efficient to run on programs.
  4. Test your type_of function for expressivity by making sure well-typed programs pass, and test it for soundness by making sure ill-typed programs fail.

The Simply-Typed Lambda Calculus (STLC)

Let’s take our new recipe and apply it to a more interesting language: the simply-typed lambda calculus extended with numbers.

type LType := | TNum
              | TFun (arg : LType) (body : LType)

type STLC := | VarE (s : String)
             | NumE (n : Int)
             | AddE (e1 : STLC) (e2 : STLC)
             | LamE (arg : String) (typ : LType) (body : STLC)
             | AppE (e : STLC) (arg : STLC)

Note that, unlike the untyped lambda calculus, each abstraction now carries a type annotation for its argument. (The name “simply-typed” refers to a lambda calculus type system that does not support polymorphism; we will discuss polymorphism later.) We can give the following surface syntax for this abstract syntax:

<expr> := ( <expr> )
        | λ <ident> : <t>. <expr>
        | <expr> <expr>
        | <expr> + <expr>
        | <ident>

<t> := ( <t> )
     | Num
     | <t> -> <t>

Some examples of parsing terms:

Surface SyntaxAbstract Syntax
\( \lambda x : \texttt{Num}. x \)LamE "x" NumT (VarE "x")
\( \lambda x : \texttt{Num -> Num}. (x\ 5) \)LamE "x" (FunT NumT NumT) (AppE (VarE "x") (NumE 5))

Let’s look at some examples of types in this system:

  • Num is the type of numbers; an example program with this type is \( 5 + 2 \).
  • Num -> Num is the type of functions taking a number, and returning a number; an example program with this type is \( \lambda x : \texttt{Num}.\ x + 1 \).
  • Num -> Num -> Num is the type of functions that take in a number, and return another function which takes in a number and returns a number; an example program with this type is \( \lambda x : \texttt{Num}.\ \lambda y : \texttt{Num}.\ x + y \).
  • (Num -> Num) -> Num is the type of function that, given a function which takes in a number and returns a number, returns a number; an example program with this type is \( \lambda f : \texttt{Num -> Num}.\ f\ 5 \).
  • ((Num -> Num) -> Num) -> Num takes in one of the above things, and returns a number; an example program with this type is \( \lambda g : \texttt{(Num -> Num) -> Num}.\ g\ (\lambda x : \texttt{Num}.\ x + 1) \).

We consider the usual substitution-based interpreter for a lambda calculus (as in the lambda calculus lecture):

-- subst x v e performs e[x |-> v]
def subst (x : String) (v : STLC) (e : STLC) : STLC :=
  match e with
  | VarE s => if s == x then v else VarE s
  | NumE n => NumE n
  | AddE e1 e2 => AddE (subst x v e1) (subst x v e2)
  | LamE id typ body =>
    if x == id
    then LamE id typ body                       -- shadowing case
    else LamE id typ (subst x v body)
  | AppE e1 e2 => AppE (subst x v e1) (subst x v e2)
  end

def STLC.getNum (e : STLC) : Int :=
  match e with 
  | NumE i => i
  | _ => error "STLC: not a number"
  end

def STLC.interp (e : STLC) : STLC :=
  match e with
  | VarE s => error "runtime: unbound symbol"
  | NumE n => NumE n
  | AddE e1 e2 => 
    let v1 := STLC.interp e1 in 
    let v2 := STLC.interp e2 in 
    NumE (STLC.getNum v1 + STLC.getNum v2)
  | LamE id typ body => LamE id typ body
  | AppE e1 e2 =>
    -- run e1 to get (lambda id. body)
    -- run e2 to get a value argV
    -- run body[id |-> argV]
    match STLC.interp e1 with
    | LamE id typ body => STLC.interp (subst id (STLC.interp e2) body)
    | _ => error "runtime: calling a non-function"
    end
  end

Following our type design recipe, our goal is to design our type system to eliminate runtime errors. We can identify the following kinds of runtime errors we would like to eliminate:

  • Calling a non-function, with programs like \( (10\ 20) \).
  • Calling a function with the wrong argument type, like \( (\lambda x : \texttt{Num}\ {\to}\ \texttt{Num}.\ x\ 5)\ 10 \). (Here the function expects an argument that is itself a function, but is given a number.)

Now we can design a type checker to eliminate these errors. Because the body of a function can mention its argument, we need to keep track of the types of the variables in scope; we do so with a type environment mapping identifiers to their types.

def lookup (env : Map<String, LType>) (s : String) : LType :=
  match Map.lookup env s with
  | None => error "type-error: unrecognized symbol"
  | Some t => t
  end

def STLC.type_of (env : Map<String, LType>) (e : STLC) : LType :=
  match e with
  | VarE s => lookup env s
  | NumE n => TNum
  | AddE e1 e2 => 
    let t_e1 := STLC.type_of env e1 in 
    let t_e2 := STLC.type_of env e2 in 
    if t_e1 == TNum && t_e2 == TNum then 
      TNum
    else error "type error: invalid addition"
  | LamE arg typ body =>
    TFun typ (STLC.type_of (Map.insert env arg typ) body)
  | AppE e1 e2 =>
    let t_e1 := STLC.type_of env e1 in
    let t_e2 := STLC.type_of env e2 in
    match t_e1 with
    | TFun tau1 tau2 =>
      if tau1 == t_e2
      then tau2
      else error "type error: invalid function call"
    | _ => error "type error: invalid function call"
    end
  end

Let’s walk through the cases:

  • A variable has whatever type the environment says it has; if it isn’t in the environment, the program is open and we reject it.
  • A number has type NumT.
  • For an addition \( e_1 + e_2 \), we type check each argument separately and ensure they are both numbers. If they are, we return TNum; otherwise, we return an error.
  • For a lambda \( \lambda x : \tau. e \), we type check the body in an environment extended with x having type \( \tau \). If the body has type \( \tau’ \), the lambda has the function type \( \tau \to \tau’ \). This is exactly why the annotation is required: without it, we wouldn’t know what type to give x while checking the body.
  • For an application, the function must have a function type \( \tau_1 \to \tau_2 \), and the argument must have type exactly \( \tau_1 \). The result then has type \( \tau_2 \).

Now some tests. First, expressivity:

#test STLC.interp (AppE (LamE "x" TNum (VarE "x")) (NumE 10)) === NumE 10

#test STLC.type_of Map.empty (AppE (LamE "x" TNum (VarE "x")) (NumE 10)) === TNum

#test STLC.type_of Map.empty (LamE "x" TNum (VarE "x")) === TFun TNum TNum

-- Higher-order: a function that applies its argument to 5
#test STLC.type_of Map.empty
  (LamE "f" (TFun TNum TNum) (AppE (VarE "f") (NumE 5)))
  === TFun (TFun TNum TNum) TNum

-- The body of a lambda can use its variable
#test STLC.type_of Map.empty (AppE (LamE "x" TNum (AddE (VarE "x") (NumE 1))) (NumE 2)) === TNum

-- Addition
#test STLC.interp (AddE (NumE 1) (NumE 2)) === NumE 3

#test STLC.type_of Map.empty (AddE (NumE 1) (NumE 2)) === TNum

And soundness:

-- Calling a non-function
#test_error STLC.type_of Map.empty (AppE (NumE 10) (NumE 20))

-- Calling a function with the wrong argument type
#test_error STLC.type_of Map.empty
  (AppE (LamE "x" (TFun TNum TNum) (AppE (VarE "x") (NumE 5))) (NumE 10))

-- Open term
#test_error STLC.type_of Map.empty (VarE "y")

-- Adding a function to a number
#test_error STLC.type_of Map.empty (AddE (NumE 1) (LamE "x" TNum (VarE "x")))

-- Adding the result of a bad call
#test_error STLC.type_of Map.empty (AddE (NumE 1) (AppE (NumE 10) (NumE 20)))

In the next few lectures, we will learn how to think about type systems more rigorously and mathematically — in particular, how to prove that a given type system is sound.