CS4400
Welcome to the course webpage for the Fall 2026 edition of CS4400! Please check back to this page regularly for course updates.
- Place: East Village 024
- Time: Monday/Wednesday, 2:50pm-4:30pm
| Instructor | Office Hours | Photo | |
|---|---|---|---|
| Joshua Gancher | j.gancher@northeastern.edu | West Village H 332; Mondays, 1pm-2pm; and Tuesdays, 12:30pm-1:30pm; and by appointment | ![]() |
| TA | Office Hours | Photo | |
|---|---|---|---|
| Joseph Rotella | rotella.jo@northeastern.edu | West Village H 308; Tuesdays, 4pm-6pm | ![]() |
| Conrad Zimmerman (she/her) | zimmerman.co@northeastern.edu | West Village H 308; Fridays, 10am-12pm | ![]() |
Syllabus
This is the syllabus for CS4400, Fall 2026. Please read it in its entirety.
Logistics
- Course Communication: we will use Piazza. Please sign up here.
- Important messages will be sent as Piazza announcements; you are responsible for ensuring that you receive these messages. All graded work will be submitted to GradeScope. A course code for joining the GradeScope is on Canvas.
- This course is taught using Lait, a teaching-oriented language implemented in Lean.
- You are expected to attend all lectures in-person. Lectures consist of live programming, whiteboard work, and group discussion. Lecture notes will be posted online on this webpage before the lecture.
Course Description
Our goal in this course is to study the essentials of programming languages: their purpose, their design, and their implementation. You have all programmed before, probably in multiple programming languages. You may have noticed differences and similarities between the programming languages and wondered: why are there so many languages? Why are they different and similar in these particular ways? Why is programming in one language sometimes easier than others? How (and why) are new programming languages made? We will study these questions bottom-up: we will grow a tiny language and add features to it iteratively, along the way encountering many of the core ingredients that go into today’s modern programming languages. We will also see some of the core formal notions that have been so effective in designing many of today’s languages: in particular, we will see formal language semantics and type systems. Finally, we will go beyond our tiny language and explore some exotic languages that are radically different from ones you may have seen before. In the end, you should be equipped to learn new programming languages quickly, understand the key design decisions made by many of today’s languages, and be prepared for a world where new programming languages are being made all the time.
-
Module 1: Introduction. Our goal of this module is to introduce and motivate the topic of programming languages and become familiar programming in Lait. We will learn how to program in functional style, program with inductively defined datatypes, and become familiar with notation for describing induction.
-
Module 2: The λ-calculus. Our goal in this module is to grow a small but surprisingly rich programming language. We will add features slowly: first, we will add let-bindings and study scope and substitution. Then, we will introduce the λ-calculus, and become familiar with programming in it: we will see how to compile programs into the λ-calculus (Church encoding), how to program with recursion (Y-combinator), and how to implement the λ-calculus efficiently on a Von-Neumann architecture (environments and closures). Along the way, we will learn how to implement interpreters from big-step style inductive notation, and how to draw a derivation tree for an interpreter.
-
Module 3: Types. Our goal in this module is to implement and design type systems for practical programming languages. Many of today’s modern programming languages have types: it is important to understand what they are and how they are made. We will start by adding simple types to the λ-calculus and implementing a type-checker. We will see how to describe type systems using inductive notation, and how to draw a derivation tree for well-typed programs. Then we will slowly grow the underlying features of the language.
-
Module 4: Topics. Our goal in this module will be to study various topics within programming languages, subject to instructor and/or student interest. Possible topics will include imperative languages, control and effects, abstract machines, more expressive type systems, and memory safety.
-
Module 5: Proof Assistants. Our goal in this module is to explore proof assistants and how they can be used to proof properties of and reason about programming languages. We will use the Lean proof assistant to state and prove basic meta-theoretic properties of the languages we have developed so far in the course.
Reference Materials
The primary reference for this course will be the course notes, provided after each lecture and available on this website. You are strongly encouraged to review the course notes after each lecture. The following textbooks are good additional resources:
- Krishnamurthy, Shriram. Programming Languages: Application and Interpretation. Link
- Pierce, Benjamin C. Types and programming languages. MIT press, 2002.
- Friedman, Daniel P. and Mitchell Wand. Essentials of programming languages. Third edition. MIT press, 2008.
- Harper, Robert. Practical foundations for programming languages. Cambridge University Press, 2016.
Coursework and Grading Policies
The course will consist of the following graded material. It is subject to change during the first part of the semester; all changes will be announced in class and on Piazza, as well as reflected here.
-
Assignments (30% of total): About 7-8 in total. Posted on this webpage, turned in on GradeScope. You may discuss the problems with other students, but you must submit your own solutions.
-
Concept Check Quizzes (10% Of Total): Once a week. Each should take no more than 15 minutes. The lowest concept check quiz score will be dropped.
-
Exams (60% of Total): There will be a two in-class prelims (October 7 and November 9) as well as an in-person final exam during the final exam period. Each prelim and exam will be worth 20% each.
Grades are allocated by points, and the percentage is determined by the percentage of total points within each category.
Late Work
Assignments will be due at 11:59PM, and late work will be penalized according to the following scale:
- Less than 24 hours late: 5% penalty
- 24-48 hours late: 20% penalty
- More than 48 hours late: no longer accepted.
This timeline is in place to ensure timely return of grades. If you anticipate needing a special accomodation or grading extension, or an extenuating circumstance arises, please post a private Piazza question to me (or email me) well in advance (if possible) of the deadline. We are very willing to work with you to find a reasonable solution; if you have an anticipated need for a grading extension, reach out as early as possible.
Late work for exams and concept check quizzes will not be accepted. If you cannot come into class for an exam, please contact the instructor ahead of time.
Grading Thresholds
Letter grades will be assigned according to a standard grading threshold based on percentage of total points:
| Score Range | Letter Grade |
|---|---|
| > 93 | A |
| >= 90 | A- |
| >= 87 | B+ |
| >= 83 | B |
| >= 80 | B- |
| >= 77 | C+ |
| >= 73 | C |
| >= 70 | C- |
| >= 67 | D+ |
| >= 63 | D |
| >= 60 | D- |
| Less than 60 | D |
Academic Honesty
Cheating and other acts of academic dishonesty will be referred to Khoury College. There are very serious penalties here, so please do not take any chances by copying any material from the Internet or from other past or present students of this course or related courses. In particular, when completing the programming assignments, it is important that you do not refer to any completed solutions that you find on the Internet. When in doubt, ask the instructor or consult the Northeastern academic honesty page here.
AI Policy. You may use AI tools such as ChatGPT and Claude if they are helpful to you. However, you are still responsible for the content of all work submitted. Be warned that inappropriate use these tools can harm your learning. You will likely find yourself struggling in the course if you rely too heavily on AI tools to automatically produce code for your assignments, since many of the concepts are cumulative. You are strongly advised to first attempt all assignments yourself without the use of AI. In many ways, CS4400 is like a math class; you will not learn the material if you do not allow yourself to struggle with it!
Remote Policy. This class will be taught in person by default. If the class needs to be remote, it will be taught online using Zoom; a link will be available in Canvas under the Zoom tab. All course notes will be available online after the class. Please feel free to contact the instructor if you have any questions.
Title IX
Title IX of the Education Amendments of 1972 protects individuals from sex or gender-based discrimination, including discrimination based on gender-identity, in educational programs and activities that receive federal financial assistance.
Northeastern’s Title IX Policy prohibits Prohibited Offenses, which are defined as sexual harassment, sexual assault, relationship or domestic violence, and stalking. The Title IX Policy applies to the entire community, including male, female, transgender students, faculty and staff.
If you or someone you know has been a survivor of a Prohibited Offense, confidential support and guidance can be found through University Health and Counseling Services staff (https://www.northeastern.edu/uhcs/) and the Center for Spiritual Dialogue and Service clergy members (https://www.northeastern.edu/spirituallife/). By law, those employees are not required to report allegations of sex or gender-based discrimination to the University.
Alleged violations can be reported non-confidentially to the Title IX Coordinator within The Office for Gender Equity and Compliance at: titleix@northeastern.edu and/or through NUPD (Emergency 617.373.3333; Non-Emergency 617.373.2121). Reporting Prohibited Offenses to NUPD does NOT commit the victim/affected party to future legal action.
Faculty members are considered “responsible employees” at Northeastern University, meaning they are required to report all allegations of sex or gender-based discrimination to the Title IX Coordinator.
In case of an emergency, please call 911.
Please visit https://www.northeastern.edu/titleix for a complete list of reporting options and resources both on- and off-campus.
Students with Disabilities
Students who have disabilities who wish to receive academic services and/or accommodations should visit the Disability Access Services at 20 Dodge Hall or call (617) 373-2675. If you have already done so, please provide your letter from the DAS to me early in the semester so that I can arrange those accommodations. I cannot arrange formal accomodations without a letter from DAS.
Homeworks
HW1
Due Date: Friday, September 18 at 11:59 PM
- Upload your submission to Gradescope, starting from this starter file.
Each function in this file is filled in with
..., which throws an error about the code being unimplemented; your job is to fill in each function. (The Gradescope assignment will appear shortly.)
You should upload only a single Lean file beginning with the following two lines:
import Lait
#lait
-
Be sure to check that your submission is valid Lait code that type checks; if it is not, you will receive 0 points for that problem.
-
Your programs will be evaluated based on a number of tests. Gradescope will show you some tests when you submit, but not all of them. However, all of the tests we run will be testing the program’s specification, which will be unambiguous. You should test your code thoroughly before submitting.
-
For each problem, you should include at least 3 passing test cases different than the ones given below.
1. Min (10 points)
Implement a function min that takes as input two numbers and outputs which one is smaller.
def min (i : Int) (j : Int) : Int := ...
Example tests:
#test min 0 1 === 0
2. Sorted (10 points)
Implement a function sorted? of type List<Int> -> Bool which
returns true if and only if the list is sorted from least to greatest.
def sorted? (xs : List<Int>) : Bool := ...
Example tests:
#test sorted? [1, 2, 3] === true
#test sorted? [3, 2, 1] === false
3. Summing a Tree (10 points)
For this problem, we will use the following type for a binary tree:
type Tree := | Leaf (val : Int) | Node (left : Tree) (right : Tree)
Implement the function sum_tree of type Tree -> Int which returns the sum of all the integers in the tree.
def sum_tree (t : Tree) : Int := ...
Example test:
#test sum_tree (Node (Leaf 10) (Leaf 20)) === 30
4. Right Linear (10 points)
A binary tree is right linear iff, for every node in the tree, the left child is a leaf. For example, the following tree is right-linear:
/\
/ \
1 /\
2 3
The following tree is not:
/\
/\ \
1 2 \
3
Implement a function right_linear? of type Tree -> Bool
that returns true if and only if the tree is right linear.
def right_linear? (t : Tree) : Bool := ...
Example tests:
#test right_linear? (Node (Leaf 1) (Node (Leaf 2) (Leaf 3))) === true
5. DFS List (10 points)
A depth-first left-first traversal of a tree traverses the tree in depth-first order starting with the left child of each node. Consider this tree:
/\
/ 3
/\
1 2
For the above tree, a depth-first left-first traversal explores leaf 1, then 2, then 3.
Implement a function dfs_list of type Tree -> List<Int> that returns a
list of all the leaf values traversed according to depth-first left-first order.
def dfs_list (t : Tree) : List<Int> := ...
6. Subst (10 points)
Implement a function subst of type Tree -> Int -> Int -> Tree.
Given arguments subst t old n, it
takes a tree t and two numbers old and n and returns a tree that
results from substituting all leaves of value old with n. This is like a “find
and replace” for trees.
def subst (t : Tree) (old : Int) (n : Int) : Tree := ...
7. Multi-Subst (20 points)
Now we want to perform multiple substitutions at once. We will keep track of all the substitutions in a map.
The following definitions are built into Lait’s standard library:
- A type
Map<k, v>of maps with keys of typek, and values of typev. Map.lookup : Map<k, v> -> k -> Option<v>
You can find more information about maps in the Lait book.
Implement the function multi_subst of type Tree -> Map<Int,Int> -> Tree
which takes a tree t and a map m, and
returns a new tree that results from performing all the substitutions specified
by m. If a leaf’s value is not found in the map, leave that
leaf unchanged.
def multi_subst (t : Tree) (m : Map<Int,Int>) : Tree := ...
8. Filter_false (10 points)
Implement a function filter_false of type List<Int> -> (Int -> Bool) -> List<Int>
that takes a list of numbers xs and a function f as input, and returns a new list
that contains only those elements in xs for which f returns false.
def filter_false (xs : List<Int>) (f : Int -> Bool) : List<Int> := ...
Some example tests:
#test filter_false [1, 2, 2, 3] (fun x => x == 3) === [1, 2, 2]
#test filter_false [1, 2, 2, 3] (fun x => x == 2) === [1, 3]
HW2
Due Date: Wednesday, Sep 30, 11:59pm
- Upload your submission to Gradescope, starting from this starter code.
Each function in this file is filled in with
..., which throws an error about the code being unimplemented; your job is to fill in each function.
You should upload only a single Lean file beginning with the following two lines:
import Lait
#lait
-
Be sure to check that your submission is valid Lait code that type checks; if it is not, you will receive 0 points for that problem.
-
Your programs will be evaluated based on a number of tests. Gradescope will show you some tests when you submit, but not all of them. However, all of the tests we run will be testing the program’s specification, which will be unambiguous. You should test your code thoroughly before submitting.
-
For each problem, you should include at least 3 passing test cases different than the ones given below.
1. cond
Certain languages such as Racket have a construct called cond which functions as a multi-way conditional.
We will study a language that contains cond, given by the following grammar:
<expr> := | <int> | <bool> | <expr> > <expr> | <expr> + <expr> | cond { <list-of-arm> }
<int> := 0 | 1 | 2 | ...
<bool> := true | false
<list-of-arm> := | done | <arm>, <list-of-arm>
<arm> := | if <expr> then <expr>
For example, here is a valid program in our language, CondLang:
cond {
if 1 > 2 then 0,
if 10 > 9 then 1,
if 4 > 3 then 2,
done
}
Each cond has a list of arms, where each arm is an if-then without an else.
The semantics of cond is that we evaluate each arm in order, starting with the guard. If the condition of the arm’s guard evaluates to true, then we evaluate that arm’s body.
If the condition of the arm’s guard evaluates to false, then we forget about that arm and move onto the next one.
Hence, the above cond should evaluate to 1, since 10 = 9 is the first arm with a true condition.
The semantics of cond should throw an error if:
- We try to evaluate
>or+with non-integers; - We reach an arm of a
condand it reduces to a non-boolean; - All arms of a
condevaluate tofalseand thus reachdone, meaning that none of the conditions of thecondsucceeded.
Below are the relevant data types for your language:
type Value := | VInt (val : Int) | VBool (val : Bool)
type CondLang :=
| CVal (val : Value)
| CGreater (e1 : CondLang) (e2 : CondLang)
| CPlus (e1 : CondLang) (e2 : CondLang)
| CCond (arms : List<CondLang * CondLang>)
Above, the type CondLang * CondLang is a pair type. Pairs in Lait are constructed using tuple syntax (..., ...) and eliminated using fst and snd:
def myPair : Int * Bool := (3, true)
#eval fst myPair>> 3
#eval snd myPair>> true
(Note that fst and snd are keywords so must be put next to their arguments; fst on its own does not type check.)
Note that unlike the lecture notes, we don’t have separate constructors CBool and CInt for constants; instead, we inject the grammar of values into expressions. Thus, the expression 2 + 2 is represented as CPlus (CValue (VInt 2)) (CValue (VInt 2)).
1.1: Big-Step for CondLang
Implement a big-step definitional interpreter of type CondLang -> Value:
def interpCondLang (e : CondLang) : Value := ...
When you need to throw an error, you MUST use error "runtime error". For example, when converting a value to an integer:
def Value.toInt (v : Value) : Int :=
match v with
| VInt i => i
| VBool _ => error "runtime error"
end
1.2: Small-Step for CondLang
Now, you will implement a small-step interpreter for CondLang of the following type:
def stepCondLang (e : CondLang) : CondLang := ...
As before, values step to values; thus, CVal v steps to CVal v.
To step the binary operators CGreater and CPlus, you:
- step the left-hand side unless it’s a value; otherwise,
- step the right-hand side unless it’s a value; otherwise,
- both are values, so you step the expression into a suitable value for the result.
To step a CCond, you step each arm in sequence. First, step the guard of the first arm in the list. If the first guard is true, you move to evaluating the right-hand side of the arm. If the first guard is false, then you remove the first arm from the list.
Let’s see some examples of stepping CCond (written in concrete syntax):
cond { if 1 > 2 then 1 + 1, if 2 > 1 then 2 + 2, done }
--> // simplify first arm
cond { if false then 1 + 1, if 2 > 1 then 2 + 2, done }
--> // throw away first arm
cond { if 2 > 1 then 2 + 2, done }
--> // simplify first arm
cond { if true then 2 + 2, done }
--> // step to body of first arm
2 + 2
-->
4
As in the big-step semantics, if you need to step something like cond { if 3 then 2, done } then you must throw error "runtime error".
Similarly, if you need to step cond { done } you throw an error.
2. Uniquify
You are tired of dealing with shadowing, so instead you’ve decided to implement a function called uniquify that, when given an abstract syntax tree for LetLang, renames all shadowed variables to unique names (i.e., names that are guaranteed not to be bound anywhere else in the program). This way, you can tell a variable’s scope just by looking for its unique binding in the program!
We will use the following abstract syntax:
type Exp :=
| EInt (val : Int)
| EPlus (e1 : Exp) (e2 : Exp)
| EVar (var : String)
| ELet (var : String) (assignment : Exp) (body : Exp)
2.1: Rename
You run into a challenge almost immediately: even if we generate unique names,
we need a way to replace the existing name in your abstract syntax tree with
your newly generated unique one. Notice how our current subst function from
lecture does not do that.
Write a function updateNames:
def updateNames (e : Exp) (old : String) (new : String) : Exp := ...
which replaces all variables with name old in e with the name new, regardless of scoping rules (i.e., ignoring shadowing). You can safely assume that newname never appears in e.
Example behavior:
updateNames (ELet "x" (EInt 10) (EVar "x")) "x" "y" = ELet "y" (EInt 10) (EVar "y")
2.2: Uniquify
Now, we will implement uniquify : Exp -> Exp using updateNames. Your solution should
additionally use the following freshName function, which you can assume is
guaranteed to produce a unique name whenever it is called (don’t worry about
understanding how it works; we will cover mutation later):
def freshName : Unit -> String :=
let i := alloc 0 in
fun _ =>
let _ := set i (get i + 1) in
"a" ++ toString (get i)
See below for an example use:
def getTwoNames () :=
let x := freshName () in
let y := freshName () in
x ++ " " ++ y
#eval getTwoNames ()>> "a1 a2"
#eval getTwoNames ()>> "a3 a4"
The correctness requirement for uniquify is that it allows a simpler version of an interpreter for Exp to work, which does not take shadowing into account. Here is the simpler version:
def uniqSubst (var : String) (assignment : Exp) (body : Exp) : Exp :=
match body with
| EInt i => EInt i
| EPlus e1 e2 => EPlus (uniqSubst var assignment e1) (uniqSubst var assignment e2)
| EVar var' => if var == var' then assignment else (EVar var')
-- No shadowing logic for let.
| ELet var' e1 e2 => ELet var' (uniqSubst var assignment e1) (uniqSubst var assignment e2)
end
def uniqInterp (e : Exp) : Int :=
match e with
| EInt i => i
| EPlus e1 e2 => uniqInterp e1 + uniqInterp e2
| EVar _ => error "unbound variable"
| ELet var e1 e2 =>
let v1 := uniqInterp e1 in
let e2' := uniqSubst var (EInt v1) e2 in
uniqInterp e2'
end
Now, implement uniquify:
def uniquify (e : Exp) : Exp := ...
For example, the following test should pass:
#test uniqInterp (uniquify (ELet "x" (EInt 10) (ELet "x" (EInt 20) (EVar "x")))) === 20
The above should pass because we rename the variables in the above expression to unique names, so we never re-define a variable.
HW3
Due Date: Friday, Oct 23, 11:59pm
- Upload your submission to Gradescope, starting from this starter code.
You should upload only a single Lean file beginning with the following two lines:
import Lait
#lait
-
Be sure to check that your submission is valid Lait code that type checks; if it is not, you will receive 0 points for that problem.
-
Your programs will be evaluated based on a number of tests. Gradescope will show you some tests when you submit, but not all of them. However, all of the tests we run will be testing the program’s specification, which will be unambiguous. You should test your code thoroughly before submitting.
-
For each problem, you should include at least 3 passing test cases different than the ones given below.
1. Environments (40 points)
In Lecture 3, we gave a semantics to LetLang using substitution: to evaluate let x := e1 in e2, we evaluate e1 to a value v, and then substitute v for x everywhere in e2.
Substitution is an elegant way of describing semantics, but its implementation can be quite slow: every substitution has to scan over (and rebuild) the whole body of the let, which does not scale in practice.
Instead, most real interpreters use an environment: a map that records the value of every variable that is currently in scope. Rather than substituting, the interpreter carries the environment along as it runs:
- To evaluate a variable
x, look upxin the environment. - To evaluate
let x := e1 in e2, evaluatee1to a valuev, and then evaluatee2in the environment extended withx ↦ v.
For example, here is how let x := 10 in let y := x + 1 in x + y evaluates, starting from the empty environment {}:
evaluate let x := 10 in let y := x + 1 in x + y in {}
evaluate 10 in {} ==> 10
evaluate let y := x + 1 in x + y in {x ↦ 10}
evaluate x + 1 in {x ↦ 10} ==> 11
evaluate x + y in {x ↦ 10, y ↦ 11} ==> 21
We will use the following abstract syntax for LetLang:
type LetExpr :=
| NumL (n : Int)
| AddL (l : LetExpr) (r : LetExpr)
| MulL (l : LetExpr) (r : LetExpr)
| VarL (s : String)
| LetL (var : String) (assignment : LetExpr) (body : LetExpr)
We will represent environments using Lait’s built-in Map type, which supports Map.empty, Map.lookup, and Map.insert.
You can find more information about maps in the Lait book.
Implement a definitional interpreter interpLetEnv that uses a map to store the values of variables:
def interpLetEnv (env : Map<String, Int>) (e : LetExpr) : Int := ...
This function should not use substitution. Your interpreter should behave identically to the usual substitution semantics for LetLang, and in particular must respect lexical scope (including shadowing) as described in Lecture 3.
If you encounter a variable that is not in the environment, raise an error using error.
Example tests:
#test interpLetEnv Map.empty (LetL "x" (NumL 10)
(AddL (VarL "x") (VarL "x")))
=== 20
#test interpLetEnv (Map.insert Map.empty "y" 20) (LetL "x" (NumL 10)
(AddL (VarL "y") (VarL "x")))
=== 30
2. Working with Church Numerals (60 points)
In Lecture 5, we briefly discussed the Scott numerals, a way to encode natural numbers into the Lambda Calculus. In this problem, we will explore the other main way of encoding numbers: Church numerals.
For this problem, we will work with the following data structure for the lambda calculus:
type Lam :=
| VarE (id : String)
| LamE (arg : String) (body : Lam)
| AppE (e1 : Lam) (e2 : Lam)
The idea of the Church numerals is, like the Church booleans, to represent a number by its behavior. What is the behavior of a given number (say, 3)? We will say it is to repeat an action that many times.
Hence, the Church numeral for n is the function that takes a function f and a starting point x, and applies f to x, n times:
\[ \begin{aligned} 0 &:= \lambda f. \lambda x. x \\ 1 &:= \lambda f. \lambda x. f\ x \\ 2 &:= \lambda f. \lambda x. f\ (f\ x) \\ 3 &:= \lambda f. \lambda x. f\ (f\ (f\ x)) \\ &\ \ \vdots \end{aligned} \]
Instead of writing each number by hand, observe that we can use the following function, succ, to increment a Church numeral by one:
\[
\mathsf{succ} := \lambda n. \lambda f. \lambda x. f\ (n\ f\ x)
\]
Above, succ takes a Church numeral n and makes a new Church numeral by taking f and x, and applies f to the result of n f x. Hence, if n f x applies f to x N many times, then succ n will apply f to x N+1 many times.
Given succ, we can then write 1 := succ 0, 2 := succ 1, and so on.
Before working directly with the lambda calculus, let’s see that we can encode this in Lait.
def zero := fun f => fun x => x
def succ := fun n => fun f => fun x => f (n f x)
-- For technical Lait-only reasons, we need to unfold the definition
-- of `succ` above in the below two definitions.
-- one = succ zero
def one := fun f => fun x => f (zero f x)
-- two = succ one
def two := fun f => fun x => f (one f x)
#eval two (fun x => x ++ "!") "hi">> "hi!!"
Above, we get "hi!!" out, because we iterated fun x => x ++ "!" twice on the initial input, "hi".
In this problem, you will implement operations on the Church numerals in the lambda calculus. To help you out, we have given you in the starter code a function Church.decode : Lam -> Int, which can decode Church numerals into integers. The Church.decode function also runs the lambda term, so you can feel free to pass applications into it.
-- zero = λf. λx. x
def Church.zero : Lam := LamE "f" (LamE "x" (VarE "x"))
-- succ = λn. λf. λx. f (n f x)
def Church.succ : Lam :=
LamE "n" (LamE "f" (LamE "x"
(AppE (VarE "f") (AppE (AppE (VarE "n") (VarE "f")) (VarE "x")))))
def Church.one := AppE Church.succ Church.zero
def Church.two := AppE Church.succ Church.one
def Church.three := AppE Church.succ Church.two
-- Problem 2.1
def Church.ofInt (n : Int) : Lam :=
if n < 0 then error "Church.ofInt negative number"
else ...
First, given a non-negative number, implement a function Church.ofInt that turns that number into a Church numeral. The implementation should recurse on the given number, n,
using Church.zero in the base case, and using Church.succ in the recursive case.
Next, we are going to implement variants of addition and multiplication that work over Church numerals.
-- Problem 2.2
def Church.add : Lam := LamE "n" (LamE "m" ...)
-- Problem 2.3
def Church.mul : Lam := LamE "n" (LamE "m" ...)
Both solutions for Church.add and Church.mul will take in Church numerals for n and m, and output a new Church numeral.
To implement Church.add, we will follow the intuition of Church numerals: we take in a function f, an argument x, and apply f to x that numeral amount of times.
This gives us a straightforward way to implement addition: to add n to m, we can increment m by one (using Church.succ) n number of times.
That is, in symbols:
\[ n + m = m\ \underbrace{+\ 1 + 1 + \dots + 1}_{n \text{ times}} \]
Once you have Church.add, implementing Church.mul is similar, since n times m is the same as adding m to zero, n number of times:
\[ n \cdot m = 0\ \underbrace{+\ m + m + \dots + m}_{n \text{ times}} \]
Compiling LetExpr into the lambda calculus
Now, we are going to use Church numerals to compile LetExpr from the first problem into the lambda calculus:
-- Problem 2.4
def LetExpr.toLam (e : LetExpr) : Lam := ...
Your compiler must be correct, the following sense: if we have a closed LetExpr program p which does not contain negative numbers, then evaluating p under the ordinary semantics should be equivalent to running Church.decode on LetExpr.toLam p:
forall p, interpLetEnv Map.empty p = Church.decode (LetExpr.toLam p)
Hence, you may assume for this problem that all arguments to NumL inside of the LetExpr program e are nonnegative.
To implement LetExpr.toLam, note that LetExpr contains two language features: numbers, and let bindings. For numbers, you need to use Church numerals. For let bindings, you will need to find a way to encode let x = e1 in e2 using the (minimal) features of the lambda calculus.
To evaluate the correctness of your compiler, you should write a variety of tests, using #test, of the above property. For example:
def myProg : LetExpr := LetL "x" (NumL 10) (MulL (VarL "x") (NumL 2))
#test interpLetEnv Map.empty myProg === Church.decode (LetExpr.toLam myProg)
Note that Lait has a default step limit, and the implementation of Church.mul we guide you towards in this homework is quite inefficient; hence, multiplications of larger numbers (e.g., 5 * 8) will hit the step counter. Your tests can be over small numbers, as long as they are correct.
(There is a faster implementation of Church.mul that allows you to evaluate larger multiplications, such as 10 * 8, without hitting the step limit. Feel free to look for the faster verison as well!)
HW4
Due Date: Friday, Nov 6, 11:59pm
- Upload your submission to Gradescope, starting from this starter code.
You should upload only a single Lean file beginning with the following two lines:
import Lait
#lait
-
Be sure to check that your submission is valid Lait code that type checks; if it is not, you will receive 0 points for that problem.
-
Your programs will be evaluated based on a number of tests. Gradescope will show you some tests when you submit, but not all of them. However, all of the tests we run will be testing the program’s specification, which will be unambiguous. You should test your code thoroughly before submitting.
-
For each problem, you should include at least 3 passing test cases.
1. Type Checking Products, Sums, and Let (50 points)
In this problem, you will write a type checker for a small language with numbers, let bindings, product types, and sum types. Below is the syntax of the language (both the types and expressions):
\[ \begin{aligned} \tau &::= \texttt{Num} \mid \tau \times \tau \mid \tau + \tau \\ e &::= n \mid x \mid e + e \mid (e, e) \mid \mathsf{fst}\ e \mid \mathsf{snd}\ e \mid \mathsf{let}\ x = e\ \mathsf{in}\ e \\ &\ \ \ \ \ \ \ \mid\ \texttt{inl}[\tau]\ e \mid \texttt{inr}[\tau]\ e \mid \mathsf{case}\ e\ \mathsf{of}\ \{\texttt{inl}\ x \Rightarrow e;\ \texttt{inr}\ y \Rightarrow e\} \end{aligned} \]
And implemented in Lait:
type Ty :=
| NumT
| ProdT (l : Ty) (r : Ty)
| SumT (l : Ty) (r : Ty)
type Expr :=
| NumE (n : Int)
| VarE (x : String)
| LetE (x : String) (e1 : Expr) (e2 : Expr)
| AddE (l : Expr) (r : Expr)
| PairE (l : Expr) (r : Expr)
| FstE (e : Expr)
| SndE (e : Expr)
| InlE (other : Ty) (e : Expr)
| InrE (other : Ty) (e : Expr)
| CaseE (e : Expr) (x : String) (e1 : Expr) (y : String) (e2 : Expr)
The starter code defines a definitional interpreter, interp : Expr -> Value, for an appropriate type of Value, which you should not change.
(interp is implemented in terms of another function, interp_inner, that passes around an environment for let bindings.)
Note that the interpreter ignores the type annotations on InlE and InrE; these are only important for type checking. As usual, interp will raise an error if it reaches a stuck term.
Your task is to design a type checker for this language that:
- Is sound: it rejects as ill-typed all syntactically well-formed programs that cause Lait runtime errors.
- Is expressive: we can use numbers, product and sum types as expected without getting type errors.
- Is efficient: your type checker should not evaluate the program using
interpor perform other expensive computations.
To this end, implement the function
def typeOf (e : Expr) : Ty := ...
This function returns the type of the expression, or throws an error using error if ill-typed.
Your implementation will be evaluated against the three criteria above.
Some notes:
Sum Types. We saw these in Lecture 12. The difference is that here, inl and inr are annotated with the type of the other side of the sum. Hence, the typing rule for inl looks like this:
\[ \dfrac{\Gamma \vdash e : \tau_1}{\Gamma \vdash \texttt{inl}[\tau_2]\ e : \tau_1 + \tau_2}\ \text{(T-Inl)} \]
This change makes typeOf easier to implement, since now the output type of inl[t] e is uniquely determined from t and the type of e.
Product Types. We haven’t seen these yet, but the idea is similar to product types in Lait. If \(\Gamma \vdash e_1 : \tau_1\) and \(\Gamma \vdash e_2 : \tau_2\), then we can pair them together to receive \(\Gamma \vdash (e_1, e_2) : \tau_1 \times \tau_2\). Conversely, if we have a pair \(\Gamma \vdash p : \tau_1 \times \tau_2\), we have that \(\Gamma \vdash \mathsf{fst}\ p : \tau_1\) and \(\Gamma \vdash \mathsf{snd}\ p : \tau_2\).
2. Correct-by-Construction Random Access Vectors (50 points)
Many programming languages have support for arrays (also called vectors), which are lists of a fixed length. For instance, Python supports arrays with the following syntax:
>>> myarr = [1, 2, 3]
>>> myarr[1]
2
Unfortunately, it is easy to make Python arrays crash: for instance, we can look up an array index that is greater than the length of the array, which causes a runtime error:
>>> myarr[4]
IndexError: list index out of range
Let’s make a tiny language for manipulating vectors that prevents this kind of error using a type system. Here is its syntax:
e ::= x | n | () | e + e | let x = e in e | [e_1, ..., e_n] | e[n] | alloc e | get e | set e e | L
n ::= 0 | 1 | 2 | ... // integer constants
L ::= 0 | 1 | 2 | ... // heap locations
Here is the same syntax in Lait:
type VecLang :=
| NumL (n : Int)
| VarL (x : String)
| UnitL
| AddL (e1 : VecLang) (e2 : VecLang)
| LetL (x : String) (e1 : VecLang) (e2 : VecLang)
| VecL (elems : List<Int>)
| NthL (e : VecLang) (i : Int)
| AllocL (e : VecLang)
| GetL (e : VecLang)
| SetL (r : VecLang) (e : VecLang)
| LocL (i : Int)
Our language has numbers, let bindings, the unit value (), addition, vector literals (VecL), indexing into a vector (NthL), and support for mutable references (via alloc, get, and set, which behave the same as in Lecture 11.)
The constructor LocL is used for heap locations during runtime, and doesn’t show up in user-written programs.
As is usual, our vectors will be zero-indexed. Hence, the following program:
NthL (VecL [0, 1]) 1
should interpret to 1, not 0.
2.1: A Definitional Interpreter (20 points)
First, in this problem you will implement a definitional interpreter for this language.
The final result of a VecLang program is either a number, the unit value, a vector, or a heap location:
type VecValue :=
| VInt (n : Int)
| VUnit
| VVec (ls : List<Int>)
| VRef (i : Int)
Implement the function
def interpVec (e : VecLang) : VecValue := ...
You will need to implement interpVec in terms of a helper function which keeps track of the heap; interpVec itself will begin with an empty heap.
It should raise an error on an unbound variable, when NthL is used on
a non-vector or an out-of-bounds index, if AddL is used on non-numbers, or when GetL / SetL is misused (either via passing in a non-heap location value, or via an out-of-bounds heap location).
Your implementation will be tested for correctness. Since heap locations don’t
make sense outside of the context of a particular heap, we will not evaluate
whether heap locations returned through VRef are in bounds.
However, we will test to ensure that AllocL/GetL/SetL work correctly inside a closed program!
To implement interpVec, you will need to keep track of a heap as the program evaluates. At the very least, the heap needs to map integers to values. However, since AllocL needs to return a fresh memory location — one that hasn’t been used before — you also need to keep track of enough information to enforce this as well. Your code should NOT use Lait’s Ref<T> type; you need to actually implement the heap in your interpreter.
To implement NthL, the
starter code includes a function List.nth : List<a> -> Int -> Option<a> that you may find useful: List.nth xs i returns None whenever i is out of bounds (including when it is negative).
Because our programs have side effects via references, evaluation order now matters. Your interpreter should evaluate arguments left-to-right.
2.2: A Type Checker (30 points)
Now, you will implement a type checker for VecLang. Since we are not giving you the types, you will need to define your own grammar of types:
type VecTy := ...
Then, you will need to implement a function checkVec : VecLang -> VecTy that computes the type of a closed VecLang program. (As in interpVec, this type checker will need a helper function that keeps track of extra information.) If there is a type error, you raise an error through error.
At the top level, your type checker will implement the following function:
def ensureWellTyped (e : VecLang) : Unit := ...
which simply calls your checkVec function and throws away the type.
A well-typed program should not cause ensureWellTyped to throw an error, while an ill-typed program should cause ensureWellTyped to error.
Your type checker should be efficient, expressive, and sound: we will test your type checker to make sure that
(1) a variety of “reasonable” programs that do not cause runtime errors type check, and (2) any program that would cause a runtime error will fail to type check.
We will evaluate (1) and (2) via #test and #test_error, respectively.
You may assume references work as they do in Lecture 11; that is, we do not store an integer into a reference that was holding a vector. Moreover, you may assume that if a reference holds a vector of size N, we will only want to store other vectors of size N into it.
Finally, since LocL only appears at runtime but not on surface programs, you should reject LocL as ill-typed.
Course Notes
All course content will be collected into notes. They will typically be posted after the corresponding class.
- Introduction
- Interpreting Programs
- Adding Booleans; Scope and Substitution
- The Lambda Calculus
- Programming and Compiling to the Lambda Calculus
- Formalism
- Formalism of the Lambda Calculus
Introduction
import Lait
#lait
Course Overview: Why Study Programming Languages?
You have all programmed in a programming language, but so far, you’ve most likely only interacted with the language as an oracle: you have written programs, and you have learned the meaning of various programs by running them and seeing what happens. This is like how a baby learns to speak: you have learned about programming languages observationally, sometimes also called by immersion.
This course is all about the active study of programming languages. It’s a bit like an English class: we will break programming languages into their tiny gruesome pieces to learn about how they work. It’s also a bit like a math class: we will give precise definitions for what programs do, and study the consequences of those choices. And of course, it’s a programming class: you will write a lot of code and implement a host of different programming languages throughout the course.
In this course, we will actively engage in the study of programming languages. Programming languages have many facets:
- Social: A programming language is a means of communication between programmers, and exists in a social environment with its own customs.
- Mathematical: Programs written in a programming language have an abstract notion of “meaning”, given as a definition.
- Implementation: A programming language can be realized as a program (a compiler, interpreter, etc.) that can be run by a computer and programmed in.
We will study these aspects in turn and implement many programming languages ourselves. Along the way, we will understand more about today’s programming languages, and understand where programming languages may be going in the future.
Consequences of Programming Language Design
Programming languages should not make you laugh at something that they do, but many are unfortunately hilarious. What do you think this C program does?
#include <iostream>
int main() {
while(true) {}
}
void go_home_c_plus_plus_you_are_drunk() {
std::cout << "lol" << std::endl;
}
If you answered “loop forever”, you would be wrong for the latest version of C running on Clang, see for yourself by running it here. In fact, this program prints “lol” to the console. The reason why it does this isn’t so important. The fact that it does this at all is what matters. It turns out that this behavior is mathematically legal; the C specification permits this “optimization”.
Note: This video is recommended viewing.
What do you think this JavaScript program that adds two empty arrays evaluates to?
[] + []
If you answered “empty string”, you know a lot of JavaScript and you are right!
Why does this evaluate to the empty string? Well, + becomes string
append, so it coerces its arguments into strings, and the empty array is coerced
into the empty string. Of course!
What’s the point? Aren’t programming languages just funny complicated things that sometimes have weird behavior, just like how English sometimes has strange oddities that we simply accept?
Yes, and no. Languages are synthetic creatures: we made them! Every oddity in a language was someone’s idea that they thought was a really cool idea that would help them, or someone else, program. Sometimes, it is only in hindsight – after programming in a language for many years and writing lots of code – that we realize a cool-seeming idea wasn’t so cool after all.
An important example is Tony Hoare’s billion dollar mistake: null pointers. Consider the following Java program:
public class Example {
public static void main(String[] args) {
Object obj = null;
obj.hashCode();
}
}
This program causes a runtime error. The design question is: should Java’s typechecker permit this program? Today, it does: you can compile this program, and running it will yield a runtime error. The problem with null values is that they can happen anywhere; programs can surprisingly fail due to a mystery null appearing and not being handled properly, leading to very expensive debugging to track down where the null value originated. Over time, due to this cost, programming languages have slowly moved away from this model: languages like Rust or Kotlin do not permit arbitrary null values, and by and large this is accepted and no one complains about missing their null values.
The moral of the story is: language design is important and can impact generations of programmers. Many of today’s programming languages were developed in a very ad-hoc way; they have small mistakes and big mistakes, and programmers just learn to live with them. As a society, we are beginning to grapple with the enormous technical debt of programming in languages with poor design decisions: for instance, the federal government has, in the past, advocated for programming in memory-safe languages. The main aim of this class is to study the systematic design of programming languages: what are the choices one can make in making a programming language, and how are those choices implemented. It might even make you a better programmer.
Tips for Success in the Course
- Read the syllabus carefully and ask questions if anything is unclear.
- Attend lectures and take your own notes. It might be useful for you to follow along with the code yourself.
- Read the course notes and give feedback on them if you see any typos.
- Make use of your resources. Go to office hours if you need help, ask questions on Piazza.
- Communicate with the instructor if you are struggling or need accomodations.
- Start assignments early; they can be quite tricky and you might need help. Test your code!
Lait
One lesson we will see in this class is that the smaller a programming language is, the harder it is to mess up. Lait is a programming lanugage designed for teaching programming languages courses. It is small, so it has less opportunities for mistakes. It has a simple syntax and type system inspired by ML. See here for more information about Lait. We won’t cover every feature you need from Lait in this lecture; you are expected to learn some on your own.
A Lait program is a collection of definitions. The following is a Lait program:
def myNumber := 2 + 2
If you hover over the myNumber definition, you will see that it has type Int.
You can also hover over commands, such as def and #eval below, to see documentation for them.
You can then evaluate the definition by using the #eval command:
#eval myNumber>> 4
Note: In these notes, definitions of important terms are written in bold. Important ideas are written with emphasis.
Lait has a number of built-in types, such as Int, Bool, and String, and supports
ordinary the arithmetic and boolean operations:
#eval true>> true
#eval false>> false
#eval true && false>> false
#eval if true then 1 else 2>> 1
#eval 1 * (2 - 3) + 4>> 3
#eval "hello">> "hello"
#eval "hello" ++ " " ++ "world" -- String concatenation is written using ++>> "hello world"
#eval 1 == 2>> false
#eval 1 != 2>> true
#eval 1 >= 2>> false
#eval 1 <= 2>> true
#eval 1 < 2>> true
#eval 1 > 2>> false
Lait Functions
Lait is a higher-order language, meaning that functions are values. Let’s take a look at one:
def myFun := fun x => x + 1
If we hover over it, we can see that it has type Int -> Int.
We can then apply it to an argument by using the #eval command:
#eval myFun 1>> 2
Instead of writing functions using fun, we can also make them using definitions that take arguments:
def myFun' x := x + 1
This style of function can also take multiple arguments:
def myAdd x y := x + y
Type Annotations
Definitions in Lait can be annotated with types, which ensures that the type Lait assigns to the definition is what you intended. It’s good style to do so.
You can annotate the type of a definition like so:
def myNumber' : Int := 2 + 2
def myBool : Bool := true && false
def myAdd' x y : Int := x + y
Note that for functions, the type annotation is for the output of the function; not the function as a whole. Let’s see what happens if we get the type annotation wrong:
def badNumber : String := 2 + 2
As you can see, this will cause a type error.
For functions, you can annotate the type of the arguments like so:
def myAdd_annotated_args (x : Int) (y : Int) : Int := x + y
Note that you don’t need to annotate every argument:
def myAdd'' x (y : Int) := x + y
Local Variables
When writing the body of a definition, you can introduce local variables by using the let keyword:
def myNum :=
let x := 2 in
let y := 3 in
x + y
Lists
Lists are an important datatype. A list is one of two things: an empty list Nil, or a
cons node Cons hd tl where hd is the head of the list and tl is the tail of the list.
Let’s see some lists:
#eval Nil>> Nil
#eval Cons 1 Nil>> Cons 1 Nil
#eval Cons 1 (Cons 2 Nil)>> Cons 1 (Cons 2 Nil)
It’s tedious to declare lists this way, so we have several short-hand notations.
First, Nil and Cons can be abbreviated to [] and :: respectively:
#eval []>> Nil
#eval 1 :: []>> Cons 1 Nil
#eval 1 :: (2 :: [])>> Cons 1 (Cons 2 Nil)
Next, we can use the following notation to build lists more easily:
#eval [1, 2, 3]>> Cons 1 (Cons 2 (Cons 3 Nil))
We will use all of these notations throughout the course.
Now that we’ve seen how to build lists, let’s see how to use them. We must analyze them using pattern matching.
def myList := [1, 2, 3]
def addList xs :=
match xs with
| Nil => 0
| Cons hd tl => hd + addList tl
end
#eval addList myList>> 6
Pattern matching in Lait must begin with match ... with, have a number of cases — for lists, two for head and cons — and must end with end.
We often use xs to denote a list (think of it as the plural of x).
For lists in particular, the [] and :: notations work for pattern matching as well:
def addList' xs :=
match xs with
| [] => 0
| hd :: tl => hd + addList' tl
end
#eval addList' [1, 2, 3]>> 6
Testing and Errors
Lait has some built-in commands for testing and error handling.
The most important one is #test, which ensures that a given expression evaluates to an expected value:
#test (addList' [1, 2, 3]) === 6
Note that #test requires three equal signs === to separate the given expression from the expected value.
One equal sign, =, is used for definitions; two equal signs, ==, is used for checking equality; and three equal signs, ===, is used for testing.
A successful test will report nothing, while a failed test will show an error:
#test (addList' [1, 2, 3]) === 7
Syntax: Programs Are Data
Our study of programming languages begins with understanding how programs are represented to the computer. Surface syntax is the textual representation of a program: it’s what you type into your editor.
Consider the following surface syntax for a calculator expression:
1 + 2
This represents the program “add 1 and 2”. The first important lesson is that this choice of syntax is not a given. The following other choices could also work:
| Syntax Style | Example | Description |
|---|---|---|
| S-Expressions | (+ 1 2) | As seen in Lisp-style languages, such as Racket |
| Postfix | 1 2 + | Used in some programming languages and calculators |
Syntax is merely a matter of convention. To understand a programming language more deeply, we need to abstract away the details of the surface syntax and work with a more uniform representation. This is called abstract syntax, which can be represented as the following data structure in Lait:
type CalcLang := | NumE (val : Int) | AddE (left : CalcLang) (right : CalcLang)
Then, the program “add 1 and 2” can be represented as:
def add1to2 := AddE (NumE 1) (NumE 2)
This same abstract syntax can represent a variety of different surface syntax. The process of translating surface syntax into abstract syntax is called parsing; we will discuss this a bit more next lecture.
Semantics: Giving a Programming Language Meaning
Semantics associates a meaning with abstract syntax.
What does the
program add1to2 do? Intuitively, this program should “evaluate to 3”
by performing the addition 1+2.
We define the semantics of programs compositionally by giving a meaning to each part. Let’s start by giving a specification for the semantics of calculator programs using English:
NumE vshould evaluate tovAddE l rshould evaluate by evaluatinglandrindividually, and then adding the results.
We are using one language, English, to describe the behavior of another language,
CalcLang. It’s helpful to give these two languages names to denote their
roles. We call CalcLang the object language: it’s the language
we are trying to describe. We call English the meta-language: it’s the language
we’re using to describe another one.
While one can use English to describe the semantics of a programming language
— and very important langauges are specified in this way —
we will opt for a different approach, and specify programming languages by using another programming language (namely, Lait).
Doing this has a number of advantages.
First, our Lait specifications will be executable, meaning that we can actually run CalcLang programs via Lait. Second, by using Lait, we are forced to be formal and precise. Indeed, our specification for the semantics of AddE is not quite precise enough. For example: what if l or r do not evaluate to numbers? what order should we evaluate l and r in? are we using “real” numbers, integers, or something else?
By using Lait as our meta-language, we are forced to have an answer to all of these questions.
Lait as a Meta-Language
We can use Lait as a meta-language for describing the meaning of
CalcLang programs. To do this, we can write an interpreter:
a Lait program that runs CalcLang programs.
Here is an example of such a program:
def interpCalc (e : CalcLang) : Int :=
match e with
| NumE v => v
| AddE l r => interpCalc l + interpCalc r
end
#test (interpCalc (AddE (NumE 1) (NumE 2))) === 3
#test (interpCalc (AddE (AddE (NumE 1) (NumE 2)) (NumE 3))) === 6
Here, we delegate the problem of defining the meaning of the values 3 and
6 to Lait: these are Lait integers. We also delegate the meaning of +
to Lait: this is Lait addition.
This is our first programming language. We will see many more.
Interpreting Programs
Last time, we saw CalcLang, syntax trees, and an interpreter
for a calculator program. In this lecture we will break these ideas down further
and more methodically explore them.
import Lait
#lait
Parsing and Grammars
Recall our CalcLang abstract syntax datastructure from last lecture.
For this class, we’ll add a few other operations: subtraction and multiplication.
type CalcLang := | NumE (val : Int)
| AddE (left : CalcLang) (right : CalcLang)
| MulE (left : CalcLang) (right : CalcLang)
| SubtractE (left : CalcLang) (right : CalcLang)
We can draw a CalcLang data structure as a tree. For instance,
we can draw AddE (AddE (NumE 1) (NumE 2)) (NumE 3) as the
following parse tree:
+
/ \
+ 3
/ \
1 2
Elements of the AST that have children are called non-terminal;
for example, AddE, MulE, and SubtractE are non-terminal.
Conversely, elements of the AST that have no children are called terminal;
NumE is the only terminal. By convention, children of non-terminals
are drawn left-to-right: so, the left child of the tree node for
AddE (AddE (NumE 1) (NumE 2)) (NumE 3)
is the tree node for AddE (NumE 1) (NumE 2).
Grammars
To translate surface syntax into abstract syntax, we parse it using a grammar.
This is what takes the sequence of characters 1 + 2 * 3 into the abstract syntax tree AddE (NumE 1) (MulE (NumE 2) (NumE 3)).
You learn early on that multiplication “happens before” addition; which means that we should parse it as 1 + (2 * 3), and not as (1 + 2) * 3.
The technical term for this is that multiplication binds more tightly than addition, and thus results in this parse tree for 1 + 2 * 3:
+
/ \
1 *
/ \
2 3
If we were to parse it as (1 + 2) * 3, we would get this parse tree:
*
/ \
+ 3
/ \
1 2
As languages get more complicated, there will be lots of rules about how to translate various surface syntax into abstract syntax. These rules are summarized by a grammar.
Before showing the grammar for infix notation, let’s see a simpler grammar for s-expressions.
Recall that using s-expressions, we can write CalcLang programs as follows:
// S-Expression for: 1 + 2 * 3
(+ 1 (* 2 3))
// S-Expression for: (1 + 2) * 3
(* (+ 1 2) 3)
Now, below is the grammar for s-expressions:
<expr> ::= <number>
| (+ <expr> <expr>)
| (* <expr> <expr>)
| (- <expr> <expr>)
<number> ::= 1 | 2 | 3 | ...
This grammar defines the non-terminal <expr>, which is an expression in CalcLang.
Each vertical bar denotes one possible way of forming expression; we call these production rules.
Every character inside a production rule NOT contained in angle brackets is a lexeme; that is,
a string from the surface syntax. (In our language, the lexemes are (, ), +, *, and -, along with the numbers 1, 2, 3, etc.)
Note
The above syntax for a grammar is inspired by BNF, or Backus-Naur Form. BNF specifications of grammars are used pervasively in computer science.
Now we can learn the algorithm for using grammars to parse strings by example. The first thing we need to do is convert syntax strings to a sequence of lexemes. Then, we have each production rule “consume” the lexemes in order to parse the string.
Consider the following surface syntax string: “10”.
This is a single lexeme consisting of a number, so only
matches one production rule: the one for <number>; hence, this parses to NumE 10.
Next, consider the string (+ 1 2).
There are five lexemes here: (, +, 1, 2, and ).
The first lexeme is (, so this cannot be a number; it must be one of the other productions.
The other productions contain ( as the first lexeme, so we then move to the second one, +.
The only production rule that applies here is the one for addition.
Recursively, we then need to parse two sub-expressions. The next lexeme in the sequence is 1 — which only matches the production rule for <number> — so
we consume that 1 and set the first sub-expression to NumE 1.
The next lexeme is 2, and similarly we consume it and set the next sub-expression to NumE 2.
Now that we have built the two sub-expressions and consumed the first four lexemes, the next lexeme we expect to see following the rule for addition is ).
Fortunately, we have that in our sequence, so we consume it. We are now out of lexemes and the top-level production rule has finished, so we output AddE (NumE 1) (NumE 2).
Finally, consider the string (+ (+ 1 2) 3).
This will proceed as before, with nine lexemes: (, +, (, +, 1, 2, ), 3, and ).
The same recursive strategy will apply, except that when we reach the first sub-expression,
we don’t see a number, but instead see the lexemes ( and +. This matches the rule for addition (as we saw above).
Hence, the parser will return AddE (AddE (NumE 1) (NumE 2)) (NumE 3).
Infix Grammar for CalcLang
Now that we’ve seen how to parse s-expressions, let’s see how to parse infix notation. This is similarly given by a grammar:
<expr> ::= <number>
| ( <expr> <expr> )
| <expr> * <expr>
| <expr> + <expr>
| <expr> - <expr>
<number> ::= 1 | 2 | 3 | ...
Above, <expr> now has four production rules: in addition to the rules for numbers and infix operators, we have a production rule for parenthesized expressions.
By convention, we assume rules are applied in the order that they appear in the
grammar; this gives parenthesis and multiplication priority over addition
and subtraction, which we expect from PEMDAS.
This grammar seems reasonable, but it is tricky: what does the surface syntax 1 + 2 + 3 parse to?
This is an example of ambiguity. From the above grammar, there are two
valid parse trees for this expresion:
+
/ \
1 +
/ \
2 3
and
+
/ \
+ 3
/ \
1 2
To resolve this ambiguity, we will specify the binding order of our operations. We say binary operations bind to the left, meaning that we prefer the second tree to the first. Sometimes it makes sense to bind to the right; then, we would prefer the first tree.
In general, there are many tools for generating parsers these days from specifications like the grammars we showed you here. We won’t spend much of this class focusing on the implementation of parsers themselves. Instead, we will focus with manipulating abstract syntax trees directly.
Note
There are a lot of different ways people think about parsing. Examples include Pratt parsing, Earley parsing, Parser combinators, LR/LL parsing, and more. Some projects prefer to implement their own parser, while other projects prefer to use a parsing library.
The Stepper: Simplifying Calculator Programs
We saw last time how to give a semantics to calculator programs using Lait as a metalanguage. Let’s extend our interpreter from last time to handle the new operations:
def interp_calc (c : CalcLang) : Int :=
match c with
| NumE v => v
| AddE e1 e2 => interp_calc e1 + interp_calc e2
| MulE e1 e2 => interp_calc e1 * interp_calc e2
| SubtractE e1 e2 => interp_calc e1 - interp_calc e2
end
#test (interp_calc (AddE (NumE 1) (NumE 2))) === 3
#test (interp_calc (SubtractE (AddE (NumE 1) (NumE 2)) (NumE 3))) === 0
The above interpreter is called a
definitional interpreter for CalcLang: it defines the semantics of CalcLang
via an interpreter that recursively evaluates sub-programs.
One of the themes we’ll see in this class is that there are many
ways to run programs that have uses in different contexts.
Here we’ll see another way to interpret CalcLang programs that
is more like how you learned to calculate in high school: by simplification.
If you are given a big expression like 1 + ((2 * 3) + 7), the way that
you usually approach solving it is by simplifying it in pieces, like:
1 + ((2 * 3) + 7)
--> 1 + (6 + 7)
--> 1 + 13
--> 14
Each line of the above computation is a step of simplification. We can
design an alternative interpreter for CalcLang that works more like this
style of reasoning that progressively simplifies programs until there is no work
left to do.
Let’s start by making a step function that takes one step
of simplification. There are of course many different orders in which
simplification can occur; let’s pick one and see the consequences, focusing
only on addition for now:
def step (e : CalcLang) : CalcLang :=
match e with
| NumE v => NumE v
| AddE e1 e2 =>
match e1 with
| NumE v1 =>
match e2 with
| NumE v2 => NumE (v1 + v2)
| _ => AddE (NumE v1) (step e2)
end
| _ => AddE (step e1) e2
end
| MulE e1 e2 =>
match e1 with
| NumE v1 =>
match e2 with
| NumE v2 => NumE (v1 * v2)
| _ => MulE (NumE v1) (step e2)
end
| _ => MulE (step e1) e2
end
| SubtractE e1 e2 =>
match e1 with
| NumE v1 =>
match e2 with
| NumE v2 => NumE (v1 - v2)
| _ => SubtractE (NumE v1) (step e2)
end
| _ => SubtractE (step e1) e2
end
end
#eval step (AddE (AddE (NumE 1) (NumE 2)) (AddE (NumE 3) (NumE 4)))>> AddE (NumE 3) (AddE (NumE 3) (NumE 4))
#eval step (AddE (NumE 3) (AddE (NumE 3) (NumE 4)))>> AddE (NumE 3) (NumE 7)
Notice how with each step a particular part of the program is simplified. We arbitrarily chose to simplify the left expression first, and then the right expression.
Now we can define a function run that steps a program until it reaches a
fixed point (i.e., it does not change):
def run (e : CalcLang) : CalcLang :=
let stepped_e := step e in
if stepped_e == e then
e
else
run stepped_e
#test (run (AddE (AddE (NumE 1) (NumE 2)) (AddE (NumE 3) (NumE 4))))
=== NumE 10
#test (run (AddE (AddE (NumE 1) (NumE 2)) (NumE 3)))
=== NumE 6
#test (run (AddE (AddE (NumE 1) (NumE 2)) (AddE (NumE 3) (NumE 4))))
=== NumE 10
#test (run (SubtractE (AddE (NumE 1) (NumE 2)) (NumE 3)))
=== NumE 0
We call the above interpreter a small-step interpreter. The key is that the small-step and definitional interpreters always agree on the value that all programs run to. We will see more of the small step interpreter as we progress through the course, but for now, the key takeaway is that there is more than one way of evaluating a program. The small step interpreter makes each step of computation very explicit, and seems to correspond closely to how a computer might execute the above program. The definitional interpreter seems to be the most straightforward implementation strategy.
IfLang: Adding Conditionals
Now, let’s grow our little language by adding conditionals; we will call this
langauge IfLang. We will use the following abstract syntax:
type IfLang := | NumI (value : Int)
| AddI (e1 : IfLang) (e2 : IfLang)
| IfI (guard : IfLang) (thn : IfLang) (els : IfLang)
Notice, IfLang does not have any Booleans. This doesn’t stop
us from giving a semantics for IfI, though. Let’s
choose a meaning: if guard evaluates to a non-zero value,
then evaluate the then branch; otherwise, evaluate the else
branch. We can implement this semantics in a definitional interpreter:
def interp_if (e : IfLang) : Int :=
match e with
| NumI v => v
| AddI e1 e2 => interp_if e1 + interp_if e2
| IfI guard thn els => if interp_if guard != 0 then interp_if thn else interp_if els
end
#test (interp_if (IfI (NumI 0) (NumI 10) (NumI 20))) === 20
Notice here that our object language (IfLang) has a different semantics for
conditionals than our meta language (Lait), even though we make use of Lait’s
if construct to give a semantics to IfLang’s. This is often the case
when making interpreters, and we’ll see more examples of this.
Adding Booleans; Scope and Substitution
This lecture we will continue to grow our language. Last time, we ended with a language for if-then-else and numbers. Today, we will add a new type of values (Booleans) as well as local variables.
import Lait
#lait
IfLang with Booleans
Recall the IfLang language from last time:
type IfLang := | NumI (value : Int)
| PlusI (e1 : IfLang) (e2 : IfLang)
| IfI (guard : IfLang) (thn : IfLang) (els : IfLang)
(We only need to consider addition here; multiplication will behave similarly.) Last time, we gave this language a semantics via a definitional interpreter with the following type:
def interp_if_old (e : IfLang) : Int := ...
In other words, we made the choice that every value in IfLangOld was a Lait Int. Thus, to interpret a guard for an if/then/else, we had to make a decision about how to think of an integer as an if-condition.
Let’s think of another semantics that matches our intuition better: numbers will be interpreted as Int, and guards will be interpreted as Bool. Thus, let’s change our language to support booleans.
type IfLang := | NumI (value : Int)
| BoolI (value : Bool)
| PlusI (e1 : IfLang) (e2 : IfLang)
| AndI (e1 : IfLang) (e2 : IfLang)
| IfI (guard : IfLang) (thn : IfLang) (els : IfLang)
Above, we only made two changes: we have a way to construct Boolean constants (via BoolI); and we have a way to join two Booleans together (via AndI). (Adding disjunction via OrI will be the same.)
Before writing our interpreter, let’s think about a few examples and how they should evaluate. First, ordinary numberic expressions should evaluate as before:
PlusI (NumI 1) (NumI 2) ===> NumI 3
Next, Boolean expressions should evaluate as expected:
AndI (BoolI true) (BoolI false) ==> BoolI false
Similarly for IfI:
IfI (AndI (BoolI true) (BoolI false)) (NumI 1) (NumI 2) ==> NumI 2
Now, what should happen if we add a number to a Boolean? We should get that this raises an error in the Lait code:
AndI (BoolI true) (NumI 3) ==> ERROR
Similarly, evaluating IfI where the guard is a number should give us an error.
The Interpreter
How should we define an interpreter for IfLang, now that we have multiple kinds of values (numbers and booleans)?
We will define a type of value, for a number-or-boolean value:
type Value := | NumV (v : Int)
| BoolV (v : Bool)
Then, we will have the type of our interprer return a value:
def interp_if (e : IfLang) : Value := ...
Let’s now think of how to write this function by cases.
If we are interpreting NumI or BoolI, we just take the inner value and call the appropriate constructor in Value:
def interp_if (e : IfLang) : Value :=
match e with
| NumI v => NumV v
| BoolI v => BoolV v
| _ => ...
end
Now, let’s think of how to interpret PlusI e1 e2. Recursively, we will obtain
values v1 := interp_if e1, and v2 := interp_if e2. However, we cannot add these values together yet, as
they are not guaranteed to be numbers. Indeed, this won’t be the case if e1 is a boolean. In this case, we want to throw an error. We will do this by defining two helper functions which will cast Values to numbers or booleans, and throw an error
if it isn’t of the desired form:
def Value.toInt (v : Value) : Int :=
match v with
| NumV i => i
| _ => error "Value.toInt: not an Int"
end
and similarly for Booleans:
def Value.toBool (v : Value) : Bool :=
match v with
| BoolV b => b
| _ => error "Value.toBool: not a Bool"
end
Given these definitions, we can now define our interpreter.
def interp_if (e : IfLang) : Value :=
match e with
| NumI v => NumV v
| BoolI v => BoolV v
| PlusI e1 e2 =>
let v1 := interp_if e1 in
let v2 := interp_if e2 in
NumV (Value.toInt v1 + Value.toInt v2)
| AndI e1 e2 =>
let v1 := interp_if e1 in
let v2 := interp_if e2 in
BoolV (Value.toBool v1 && Value.toBool v2)
| IfI e1 e2 e3 =>
let v := interp_if e1 in
let b := Value.toBool v in
if b then interp_if e2 else interp_if e3
end
-- Runs successfully
#eval interp_if (IfI (BoolI true) (NumI 1) (NumI 2)))>> NumV 1
-- Errors
#eval interp_if (IfI (NumI 0) (NumI 1) (NumI 2)))
-- Errors
#eval interp_if (PlusI (BoolI true) (NumI 24))
Static vs Dynamic languages
Of course, you don’t want to write programs that crash. There are multiple kinds of ways of preventing crashes. One way is using static types, which means you have a type system that catches these kinds of errors before trying to run the program. Lait is a statically typed language:
#eval true + 24
Another point in the design space are dynamic languages, which keep track of typing information at runtime. For example, see the below interaction with Racket:
> (+ 3 2)
5
> (+ #t 3)
; +: contract violation
; expected: number?
; given: #t
; [,bt for context]
Above we raise a contract violation, which is a concept that appears during runtime, rather than during a static type checking phase.
One difference between Lait and Racket is that certain expressions that happen to run fine but only due to their runtime semantics will work fine in Racket, but won’t work in Lait. For example, consider if true then (1 + 2) else true + false. If we try to run this in Lait, we will get a type error:
#eval if true then (1 + 2) else (true + false)
But if we run it in Racket:
> (if #t (+ 1 2) (+ #t #f))
3
The choice to use a static or dynamic language requires a tradeoff. Statically-typed languages help programmers find unintentional crashes before the program runs, while dynamic languages provide more flexibility, at the cost of preventing fewer crashes ahead of time.
As it stands, IfLang currently behaves like a dynamic language, using Lait-level errors to catch type mismatches at runtime.
#eval interp_if (IfI (BoolI true) (PlusI (NumI 1) (NumI 2)) (PlusI (BoolI true) (BoolI false))))>> NumV 3
Later on in this course, we will study type systems, which will allow our languages to be statically typed.
Question: Lazy vs Eager.
Currently interp_if allows you to run if/then/else expressions where one of the two sides is guaranteed to crash.
What would happen if we changed our interpreter to evaluate both sides before running a Lait-level if, rather than evaluating only the relevant side?
Question: Checking the types for if/then/else.
Currently interp_if allows the “then” branch to return a number, while the “else” branch returns a Boolean. How might we
prevent this behavior in the interpreter, if we wanted to?
Adding Variables
Now, let’s move onto adding local variables. Our goal is to have local variables behave as in Lait, so let’s first see how they behave.
In Lait, local variables (i.e., variables inside of expressions) are introduced using the syntax let .. := .. in ..:
#eval let myvar := 10 in myvar + 1>> 11
Let’s make the terminology more precise here. The name myvar is an identifier, which is bound to the result of the expression 10. The body of the let is what happens after the if; in the above, myvar + 10 is the body.
What makes a local variable local is that it is not visible outside of the body of the let expression. For example, the second #eval below will raise an error:
#eval let myvar := 10 in myvar + 1>> 11
#eval myvar + 20
Above, the second #eval raises the error that “myvar is not found”.
The way to make this precise is with a notion of scope. The scope of an identifier in a let expression is the body of the let expression. Thus, myvar is out of scope for the second #eval.
Shadowing
What happens if you try to redefine a local variable? Let’s see:
#eval let myvar := 10 in let myvar := 20 in myvar>> 20
What happens here is that we prefer the inner-most binding in the syntax tree: the most recent variable binding is the one we use. This is called lexical scope, because the scope of the binding depends on its position in the syntax tree.
If we use the same identifier twice, we say that the inner binding code let myvar := 20 in myvar shadows the outer binding let myvar := 10 in .... Hence, the first binding goes out of scope, and can no longer be accessed. Most languages you’ve used use lexical scope.
Under lexical scope, the above example is exactly equivalent to just using a new identifier:
#eval let myvar := 10 in let myvar' := 20 in myvar'>> 20
Substitution
Now, let’s move on to understanding how we might go about implementing local variables. First, let’s define an abstract syntax tree for LetLang, a small language with let expressions:
type LetLang := | NumE (n : Int)
| PlusE (l : LetLang) (r : LetLang)
| VarE (var : String)
| LetE (var : String) (assignment : LetLang)
(body : LetLang)
There are a few different ways to implement a semantics for LetLang. The one we will tackle here is a substitution-based semantics. It is like a “find-and-replace” for expressions. Let’s first see how LetLang steps intuitively before defining its semantics.
-- In a surface syntax: let x := 10 in x + x
LetE "x" (NumE 10) (PlusE (VarE "x") (VarE "x"))
==>
-- Substitute (VarE "x") with (NumE 10) in the body
PlusE (NumE 10) (NumE 10)
-- Finally, simplify the addition as before
(NumE 20)
To evaluate a LetE, you evaluate the body, but first substitute the value of "x" in.
However, there is a choice for how to do this. Consider the following example:
LetE "x" (PlusE (NumE 10) (NumE 10)) (PlusE (VarE "x") (VarE "x"))
There are two possible things we can do:
- First simplify
PlusE (NumE 10) (NumE 10)to a value (NumE 20), and then substituteNumE 20in for"x"; - Substitute the entire expression
PlusE (NumE 10) (NumE 10)in for"x", giving us the expression(PlusE (PlusE (NumE 10) (NumE 10) (PlusE (NumE 10) (NumE 10)))).
The first strategy is called eager evaluation while the second is called lazy. Most languages are eager languages, but there are some exceptions; for example, Haskell is a call-by-need language that does not use eager evaluation. We will discuss this in the future. We will use eager evaluation today.
Implementing Substitution
To implement substitution, we will need to be very careful to not violate how shadowing should work. For example, our semantics should do something roughly like this:
LetE "x" (NumE 10) (LetE "x" (NumE 20) (VarE "x"))
==>
LetE "x" (NumE 20) (VarE "x")
==>
NumE 20
After we evaluate NumE 10, we will eventually “throw away” the result, because we are going to shadow the binding to a new one with the same name.
We will do this with a helper function called subst:
def subst (var : String) (assignment : LetLang) (body : LetLang) : LetLang :=
match body with
| NumE i => NumE i
| PlusE e1 e2 => PlusE (subst var assignment e1) (subst var assignment e2)
| VarE var' => if var == var' then assignment else VarE var'
| LetE var' e1 e2 =>
let e1' := subst var assignment e1 in
let e2' :=
if var == var' then e2
else subst var assignment e2 in
LetE var' e1' e2'
end
The idea of subst var assignment body is that we replace all instances of VarE var with assignment.
If we find another let expression that defines var, then we stop recursing.
Let’s see some unit tests:
#test subst "x" (NumE 10) (PlusE (VarE "x") (VarE "x"))
===
PlusE (NumE 10) (NumE 10)
#test subst "x" (NumE 10) (LetE "x" (NumE 20) (VarE "x"))
===
(LetE "x" (NumE 20) (VarE "x"))
Interpreting LetLang
Now that we have defined substitution, let’s implement an interpreter.
def interp_let (e : LetLang) : Int :=
match e with
| NumE v => v
| PlusE e1 e2 => interp_let e1 + interp_let e2
| VarE v => error "interp_let: got a variable"
| LetE x e1 e2 =>
let v := interp_let e1 in
let e2' := subst x (NumE v) e2 in
interp_let e2'
end
#eval interp_let (LetE "x" (NumE 10) (PlusE (VarE "x") (VarE "x")))>> 20
#eval interp_let (LetE "x" (NumE 10) (LetE "y" (NumE 20) (PlusE (VarE "x") (VarE "y")))))>> 30
#eval interp_let (LetE "x" (NumE 10) (LetE "x" (NumE 20) (PlusE (VarE "x") (VarE "x")))))>> 40
Open and Closed Expressions
Note that interp_let throws an error if we hit a variable. This is because we assume that the only expressions we
interpret are closed: every variable is defined by an enclosing let. Hence, the below are closed expressions:
LetE "x" (NumE 10) (VarE "x")
LetE "x" (LetE "y" (NumE 1) (VarE "y")) (VarE "x")
However, the below are not. They are open: there exists a variable that is not defined by a prior let.
VarE "x"
LetE "x" (NumE 1) (VarE "y")
LetE "x" (VarE "x") (VarE "x")
Note that for the third example above, the scope of the let is the body, but not the assigned value of the expression.
Hence, "x" is out of scope for the first VarE "x", but in scope for the second one.
Dynamic Scope
A key property of our scoping rules so far is that they are static, meaning
that the scope of an identifier does not depend on the runtime behavior of a
program. This might seem like an obvious requirement – most languages you have
used satisfy this requirement – but there are examples of languages where which
variables are in-scope can depend on the runtime behavior of a program. This is
an actual common Lisp program that prints out 5 5:
(defvar x 100)
(defmethod fun1 (x)
(print x)
(fun2))
(defmethod fun2 ()
(print x))
(fun1 5)
Why don’t we print 100?
The defvar function introduces a special global variable x. Then, when fun1 is called, it introduces a variable x into scope, and binds it to the value 5. Then, it prints x, which has value 5, so the first 5 gets printed.
But now, fun1 will call fun2, which takese no arguments. It also prints x, which outputs 5, but we surely expect 100 to be printed!
This is because the scoping rules in Common Lisp are dynamic: once introduced, a variable never leaves scope, and hence variables always refers to the most recently declared identifier encountered while running the program. (Note: Common Lisp also has a local-like facility that supports lexical scope.) Because of this unintuitive behavior, dynamic scope by default is less popular for modern languages. For more reading on scope, see this blog post.
The Lambda Calculus
So far, the languages we’ve seen – LetLang, IteLang, CalcLang – are tiny, and seem unrepresentative of the kinds of languages that we would actually prgram in. We will change that today by seeing the smallest interesting programming language: the lambda calculus. Despite its simplicity — barely more complicated than LetLang — we will see it is Turing-complete: it is capable (more or less) of representing any program your computer can run. This combination of expressiveness and simplicity has made it the historical and intellectual starting point for much of programming languages.
Syntax
Written as a grammar, the lambda calculus is as follows:
<expr> := <ident>
| λ <ident>. <expr>
| <expr> <expr>
| ( <expr> )
<ident> := x | y | ...
That is, expressions in the lambda calculus are only composed of only three forms:
- Variables;
- Abstraction, written as
λ x. e, wherexis an identifier andeis an expression; and - Application, written as
e e', whereeande'are both expressions.
The lambda calculus is, in essence, the theory of functions. Abstraction creates functions, while application calls them. Let’s see some terms in the lambda calculus:
- \( \lambda x. x \): this represents the identity function, since it returns whatever it is called with.
- \( (\lambda x. x) (\lambda x. x) \): calling the identity function on itself.
- \( \lambda x. \lambda y. x \): a function which, given \( x \), returns another function that, when given \( y \), returns \( x \); and
- \( \lambda x. \lambda y. y \): a function which, given \( x \), returns another function that, when given \( y \), returns \( y \).
You might have noticed by now that the lambda calculus is quite similar to how anonymous functions work in real languages. This is not an accident: the lambda calculus — which goes back to Alonzo Church in the 30s — is the historical predecessor of many modern programming languages. We can see this in anonymous functions in Lait:
import Lait
#lait
-- In Lait, we use "fun" instead of a lambda symbol, and use "=>" instead of a dot.
#check (fun x => x) (fun x => x)>> a -> a
As well as in Python:
>>> id = lambda x: x
>>> id(id)
<function <lambda> at 0x100b48f70>
>>> id(id)(32)
32
The beauty of the lambda calculus is its combination of simplicity and expressiveness. As we will see soon, the lambda calculus is Turing-complete, meaning that it can define any computable function. At the same time, it is extremely simple, and can be embedded in Lait as follows:
type Exp := | EVar (var : String)
| ELam (var : String) (body : Exp)
| EApp (e1 : Exp) (e2 : Exp)
Reading Lambda Calculus on Paper
It is extremely important that you understand intuitively how to read lambda calculus terms on paper, so we will spend some time on that now. Going back to our grammar, see that the case for application — given by putting lambda terms side by side — is ambiguous. (This is the same problem as we had for addition in the second lecture.) We resolve this ambiguity by making application be left-associative, which means that \( e_1\ e_2\ e_3 \) is always parsed as \( (e_1\ e_2)\ e_3 \), rather than \( e_1\ (e_2\ e_3) \). This allows us to think of nested functions as multi-argument ones: for example, \( (\lambda x. \lambda y. x\ y)\ z\ w \) is the same as \( ((\lambda x. \lambda y. x\ y)\ z)\ w \), which means that we will run the body \( x\ y \), where the argument \( z \) stands for \( x \) and \( w \) stands for \( y \). This is the same as what happens in Lait:
#eval (fun x => fun y => x + y) 2 3
The other important rule is that the scope of the argument to a function is as far as it will go. Thus, \( \lambda x. x\ x\ x \) is the same as \( \lambda x. (x\ x\ x) \), rather than (say) \( (\lambda x. x\ x)\ x \).
The grammar of the lambda calculus is probably unfamiliar, so let’s see some concrete examples:
| Surface Syntax | Abstract Syntax (in Lait) |
|---|---|
| \( x \) | EVar "x" |
| \( \lambda x. x \) | ELam "x" (EVar "x") |
| \( \lambda x. \lambda y. y \) | ELam "x" (ELam "y" (EVar "y")) |
| \( x\ y \) | EApp (EVar "x") (EVar "y") |
| \( x\ y\ z \) | EApp (EApp (EVar "x") (EVar "y")) (EVar "z") |
| \( (x\ y)\ z \) | EApp (EApp (EVar "x") (EVar "y")) (EVar "z") |
| \( x\ (y\ z) \) | EApp (EVar "x") (EApp (EVar "y") (EVar "z")) |
Open and Closed Terms
A very important idea in the lambda calculus (and every other language that has variables) is the distinction between closed and open terms. A term in the lambda calculus is closed if every variable \( x \) in the program is bound by a corresponding abstraction \( \lambda x.\ \), and open if there is a variable that does not have a corresponding abstraction. Let’s see some examples:
| Expression | Closed or Open? |
|---|---|
| \( x \) | Open |
| \( \lambda x. x \) | Closed |
| \( \lambda x. y \) | Open |
| \( \lambda x. \lambda y. y \) | Closed |
| \( (\lambda x. x) x \) | Open! |
| \( \lambda x. \lambda x. x \) | Closed |
Throughout the class, we will almost entirely be focused on closed terms. Thus, we will give a semantics below to \( (\lambda x. x)\ (\lambda y. y) \), since it is closed, but won’t need to give a semantics to \( (\lambda x. y) (\lambda y. x) \), since it is an open program.
Semantics of the Lambda Calculus
Now that we have seen how to write lambda calculus terms, let’s see how to evaluate them. We will do so by first presenting a small-step semantics for lambda terms: that is, one where one step of evaluation happens at a time. This will be easier to understand by example on paper. Then, we will move to implementing a big-step interpreter for the lambda calculus.
Note
We will be presenting one of multiple different choices of semantics for the lambda calculus, called (weak) call-by-value. While other choices are possible, this is the only semantics we will need to consider.
There are two important cases to consider: abstraction and application. For abstraction, the important idea is that functions are values. Hence, lambda terms step to themselves:
\[ \lambda x. x \to \lambda x. x \]
Calling a function: \(\beta\)-reduction
Next, we need to consider application (i.e., function calls). The important case to consider is when both sides of the application \( e_1 e_2 \) are values (i.e., abstractions). In this case, we are in a situation where we want to step \( (\lambda x.\ e) v \), where \(v\) itself is an abstraction. To step this program, just as we did for LetLang, we will use substitution.
Whenever we have \( (\lambda x. e)\ v \), we step to \( e \) with the the value \(v\) substituted for the variable \(x\).
\[ (\lambda x. x)\ (\lambda y. \lambda z. y) \xrightarrow{\text{substitute $x := (\lambda y. \lambda z. y)$ in the body $x$}} (\lambda y. \lambda z. y) \]
Let’s break this down step by step:
- We first saw we are applying a function to another function. The first function here is \( \lambda x. x\).
- We then open up the first function to get a variable and a body. The variable is the identifier \( x \), while the body is the expression \( x \).
- We finally took that body, and substituted the second function, \( \lambda y. \lambda z. y \), in for the variable \( x \).
Let’s see another example: \[ (\lambda x. \lambda y. x)\ (\lambda z. z) \to \lambda y. \lambda z.\ z \]
- The first function is \( (\lambda x. \lambda y. x) \), whose variable is \( x \) and whose body is \( \lambda y. x \).
- We substituted \( \lambda z. z \) into the body for \( x \).
One more: \[ (\lambda x. \lambda y. y)\ (\lambda z. z) \to \lambda y. y \] In this case, the variable \(x\) is unused in the function’s body; hence, we substitute \(\lambda z.\ z\) in for \(x\) to receive \(\lambda y. y\).
This reduction step is called \(\beta\)-reduction.
A critical property of substitution is that it respects lexical scope with respect to shadowing. Thus, if we have a lambda term \( \lambda x. \lambda x. x \), the inner body \( x \) refers to the inner-most binding (i.e., the second one). Lait works the same way:
#eval (fun x => fun x => x + 1) 10 20>> 21
Stepping general expressions
Recall that for CalcLang, our small-step semantics for addition first
simplified the left-hand side, then the right-hand side. For example: ((1 + 2) + (3 + 4)) makes the following sequence of steps:
((1 + 2) + (3 + 4))
-->
(3 + (3 + 4))
-->
(3 + 7)
-->
10
Our stepping rules for the lambda calculus will behave the same way:
- If we are stepping a value \(v = \lambda x.\ e\), we return \(v\) itself.
- If we are stepping \((\lambda x.\ e)\ v\), we \(\beta\)-reduce: return \(e\) with \(v\) substituted for \(x\).
- If we are stepping \(e_1 e_2\), we step \(e_1\) until it is a value; then, step \(e_2\) until it is a value; then, the \(\beta\)-reduction rule applies.
As an example:
\[ \begin{aligned} & ((\lambda f. \lambda x. f\ x)\ (\lambda a. a))\ ((\lambda g. g)\ (\lambda b. \lambda c. c)) \xrightarrow{\text{Step $(\lambda f. \lambda x. f\ x)\ (\lambda a. a)$}} \\ & (\lambda x. (\lambda a. a)\ x)\ ((\lambda g. g)\ (\lambda b. \lambda c. c)) \xrightarrow{\text{Step $((\lambda g. g)\ (\lambda b. \lambda c. c))$}} \\ & (\lambda x. (\lambda a. a)\ x)\ (\lambda b. \lambda c. c) \xrightarrow{\text{Step outer application}} \\ & (\lambda a. a)\ (\lambda b. \lambda c. c) \xrightarrow{\text{Step outer application}} \\ & \lambda b. \lambda c. c. \end{aligned} \]
Note the order of events: we first stepped the left-hand side until it was a value, then the right-hand side, and only then did we \(\beta\)-reduce. Note also that \(\beta\)-reduction handed us back a term that was not yet a value, so we had to keep stepping.
A Big-Step Evaluator
Now that we see how the lambda calculus evaluates on paper, let’s turn this into a definitional interpreter (i.e., a big-step interpreter). As we saw for CalcLang, the difference between small-step and big-step is that big-step interpreters directly reduce to values (i.e., for us, abstractions) rather than intermediate computations.
We first need to define a substitution function for lambda expressions:
type Value := | VLam (var : String) (body : Exp)
def Value.toExp (v : Value) : Exp :=
match v with
| VLam var body => ELam var body
end
def subst (var : String) (assignment : Value) (body : Exp) : Exp :=
match body with
| EVar var' => if var == var' then Value.toExp assignment else EVar var'
| EApp e1 e2 => EApp (subst var assignment e1) (subst var assignment e2)
| ELam var' body' =>
if var == var' then
ELam var' body' -- Shadowing: no substitution
else
ELam var' (subst var assignment body')
end
def interp (e : Exp) : Value :=
match e with
| EVar _ => error "interp: got a variable"
| ELam var body => VLam var body
| EApp e1 e2 =>
let v1 := interp e1 in
let v2 := interp e2 in
let v1_substituted := match v1 with
| VLam var body => subst var v2 body
end
in
interp v1_substituted
end
Now, let’s see a few examples, before our big one from before:
#eval ELam "x" (EVar "x")>> ELam "x" (EVar "x")
#eval (EApp (ELam "x" (EVar "x")) (ELam "y" (EVar "y")))>> EApp (ELam "x" (EVar "x")) (ELam "y" (EVar "y"))
-- Breaking up the big terms into sub-pieces...
def Lf_Lx_fx := ELam "f" (ELam "x" (EApp (EVar "f") (EVar "x")))
def La_a := ELam "a" (EVar "a")
def Lg_g := ELam "g" (EVar "g")
def Lb_Lc_c := ELam "b" (ELam "c" (EVar "c"))
#eval interp (EApp (EApp Lf_Lx_fx La_a) (EApp Lg_g Lb_Lc_c))>> VLam "b" (ELam "c" (EVar "c"))
Some Features of the Lambda Calculus
It might not seem like the lambda calculus is a very expressive language, because of how small it is. So, let’s see how we can encode seemingly-richer features into the lambda calculus.
Multi-argument Functions
Lait lets us define functions like so
def callf f x := f x
Doing this in the lambda calculus is easy enough: we just write a function that defines another function: \[ \lambda f. \lambda x. f\ x \]
The process of transforming a multi-argument into nested functions of single arguments is called currying. In Lait, multi-argument functions are secretly just “curried” single-argument functions in disguise!
We can see this in the type of callf:
#check callf>> (a -> b) -> a -> b
Other languages have multi-argument functions baked more deeply into the language, like Python. However, you can reconstruct the curried function by using lambdas:
>>> def f(x, y):
... return x + y
...
>>> f(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() missing 1 required positional argument: 'y'
>>> f_curried = lambda x: lambda y: f(x,y)
>>> f_curried(3)
<function <lambda>.<locals>.<lambda> at 0x100b600d0>
>>> f_curried(3)(5)
8
Non-termination
One thing the lambda calculus seems to lack is any loop or way to recurse. However, even though the lambda calculus does not have an explicit looping construct, it is nevertheless possible to express loops!
Let’s do this by making a program that runs forever. To do this, we define a lambda calculus term \(\omega\) that takes a function as an argument and calls that function with itself:
\[ \omega := \lambda x. x\ x \]
Now, let’s see when we consider \(\omega\)’s big brother, \(\Omega\):
\[ \Omega ::= \omega\ \omega \]
Let’s try to run \(\Omega\). \(\Omega\) consists of an application between two values, so the \(\beta\)-reduction rule applies.
\[ (\lambda x. x\ x) (\lambda x. x\ x) \to (\lambda x. x\ x) (\lambda x. x\ x) \]
We get exactly back to where we started! Thus, \(\Omega\) is the while (true) { } of the lambda calculus.
Let’s see our Lait interpreter explode on it:
def omega := ELam "x" (EApp (EVar "x") (EVar "x"))
#eval interp (EApp omega omega)
Programming in, and Compiling To, the Lambda Calculus
As mentioned before, the lambda calculus is an expressive enough calculus for (theoretically) arbitrary computations. Today we’re going to see this play out in two different ways: via compiling into the lambda calculus, and via programming recursive functions in the lambda calculus. We will also learn about how lambda calculus terms can be considered equivalent to each other.
import Lait
#lait
BoolLang
First, we will see how a language with seemingly no relation to the lambda calculus can be compiled into it. Below, we have BoolLang:
type BoolLang :=
| BTrue
| BFalse
| BNot (e1 : BoolLang)
| BAnd (e1 : BoolLang) (e2 : BoolLang)
def BoolLang.interp (b : BoolLang) : Bool :=
match b with
| BTrue => true
| BFalse => false
| BNot e => not (BoolLang.interp e)
| BAnd e1 e2 => (BoolLang.interp e1) && (BoolLang.interp e2)
end
Let’s recall our lambda calculus definitions from last time:
type Exp := | EVar (var : String)
| ELam (var : String) (body : Exp)
| EApp (e1 : Exp) (e2 : Exp)
type Value := | VLam (var : String) (body : Exp)
def Value.toExp (v : Value) : Exp :=
match v with
| VLam var body => ELam var body
end
def subst (var : String) (assignment : Value) (body : Exp) : Exp :=
match body with
| EVar var' => if var == var' then Value.toExp assignment else EVar var'
| EApp e1 e2 => EApp (subst var assignment e1) (subst var assignment e2)
| ELam var' body' =>
if var == var' then
ELam var' body' -- Shadowing: no substitution
else
ELam var' (subst var assignment body')
end
def interp (e : Exp) : Value :=
match e with
| EVar _ => error "interp: got a variable"
| ELam var body => VLam var body
| EApp e1 e2 =>
let v1 := interp e1 in
let v2 := interp e2 in
let v1_substituted := match v1 with
| VLam var body => subst var v2 body
end
in
interp v1_substituted
end
Compilers
Our goal is to show that the lambda calculus is expressive enough to encode BoolLang via a compiler. First, let’s discuss what this means: a compiler is a semantics-preserving translation from one language to another one. Compilers are one of the pillars of programming languages, so understanding them is important to understand programming languages in general.
Our compiler will be a function encode : BoolLang -> Exp.
Here, BoolLang is our source language, while the lambda calculus is our target language.
What does it mean for our compiler to be correct?
We will say that our compiler is correct if, for any BoolLang program e, if we compile e and run it as a lambda-calculus term, then we will get the same thing back
as if we run e in the BoolLang language, and encode the final result as a lambda-calculus term.
We can show this as the following diagram:
BoolCalc prog --------------------> lambda calc prog
| encode |
| |
| interp-bool | interp-lam
| |
| |
\/ encode \/
BoolCalc value -------------------> lambda calc value
When we draw a diagram like this, we mean that the square commutes: encoding and then interpreting in the lambda calculus is the same as interpreting in BoolLang and then encoding the final result.
Booleans in the Lambda Calculus
To write our function encode, we will need to choose a representation for the various BoolLang constructs, such as BTrue and BFalse.
We much pick lambda terms for these values. There are multiple possible encodings; we will study the following encodings for booleans introduced by Alonzo Church:
\[ \begin{aligned} \mathsf{Ltrue} &:= \lambda x. \lambda y. x \\ \mathsf{Lfalse} &:= \lambda x. \lambda y. y \end{aligned} \]
Hence, we are representing Ltrue and Lfalse as functions!
The central idea here is that Church booleans represent a choice. What is “true”? It is the decision that, when given two things, return the first.
Similarly, “false” is the decision that, when given two things, we return the second. To gain some intuition on this, think about how Booleans can be used in other languages, such as Lait:
#eval if true then 1 else 2>> 1
#eval if false then 1 else 2>> 2
The purpose of a boolean is to be used, and we use a boolean by doing a case split on it, via if/then/else. Hence, in the lambda calculus, we can represent a boolean by its behavior: a boolean is a two-argument function that behaves as its corresponding if/then/else. Hence, Ltrue X Y should evaluate to X, while Lfalse X Y should evaluate to Y, for any other lambda calculus terms X and Y.
Now that we have encoded BTrue and BFalse, we need to interpet the rest of BoolLang: BNot and BAnd.
Let’s first consider BNot. To encode BNot in the lambda calculus, we want a unary function: a term LNot in the lambda calculus so that LNot LTrue evaluates to LFalse, and LNot LFalse evaluates to LTrue. Let’s go back to our if/then/else intuition: how would we use if/then/else to compute not?
def myNot (b : Bool) : Bool :=
if b then false else true
#eval myNot true>> false
#eval myNot false>> true
Hence, we can take LNot to be the term which uses its argument to perform an if/then/else, and return LFalse on the true branch, and LTrue on the false branch:
\[ \mathsf{LNot} := \lambda b. b\ \mathsf{LFalse}\ \mathsf{LTrue} = \lambda b. b\ (\lambda x.\ \lambda y.\ y)\ (\lambda x. \lambda y. x) \]
Finally, let’s consider BAnd. Similarly, we want to encode it using if/then/else:
def myAnd (b1 : Bool) (b2 : Bool) : Bool :=
if b1 then b2 else false
#eval myAnd true true>> true
#eval myAnd true false>> false
#eval myAnd false true>> false
#eval myAnd false false>> false
This means we want the following definition: \[ \mathsf{LAnd} := \lambda b_1. \lambda b_2. b_1\ b_2\ \mathsf{LFalse}\ = \lambda b_1. \lambda b_2. b_1\ b_2\ (\lambda x. \lambda y. y) \]
Let’s now embed these into Lait, and see that they compute as expected:
def LTrue := ELam "x" (ELam "y" (EVar "x"))
def LFalse := ELam "x" (ELam "y" (EVar "y"))
def LNot := ELam "b" (EApp (EApp (EVar "b") LFalse) LTrue)
def LAnd := ELam "b1" (ELam "b2" (EApp (EApp (EVar "b1") (EVar "b2")) LFalse))
#eval interp (EApp LNot LTrue)>> VLam "x" (ELam "y" (EVar "y"))
#eval interp (EApp LNot LFalse)>> VLam "x" (ELam "y" (EVar "x"))
#eval interp (EApp (EApp LAnd LTrue) LTrue)>> VLam "x" (ELam "y" (EVar "x"))
#eval interp (EApp (EApp LAnd LTrue) LFalse)>> VLam "x" (ELam "y" (EVar "y"))
#eval interp (EApp (EApp LAnd LFalse) LTrue)>> VLam "x" (ELam "y" (EVar "y"))
#eval interp (EApp (EApp LAnd LFalse) LFalse)>> VLam "x" (ELam "y" (EVar "y"))
Now that we have our encoding in place, we can implement the compiler:
def encode (b : BoolLang) : Exp :=
match b with
| BTrue => LTrue
| BFalse => LFalse
| BNot b' =>
let e := encode b' in
EApp LNot e
| BAnd b1 b2 =>
let e1 := encode b1 in
let e2 := encode b2 in
EApp (EApp LAnd e1) e2
end
Let’s see that it works for arbitrary BoolLang programs:
def myProgram :=
BAnd
(BAnd
(BNot (BNot (BAnd BTrue (BNot BFalse))))
BTrue)
(BNot BFalse)
#eval BoolLang.interp myProgram>> true
#eval interp (encode myProgram)>> VLam "x" (ELam "y" (EVar "x"))
Equivalences of Lambda Calculus Terms
As you use our interpreter for lambda calculus terms, you will see that sometimes you might output one term while you expected another “equivalent” one. For example, consider the following program:
def id := ELam "x" (EVar "x")
def id_id := EApp id (ELam "y" (EVar "y"))
#eval interp id_id>> VLam "y" (EVar "y")
When we apply the identity function to the identity function, we get back the identity function. However, these programs are not equal from the perspective of Lait:
#eval id == (Value.toExp (interp id_id))>> false
Indeed, id uses the variable "x", while id_id ends up using the variable "y". While they are not literally the same code, they are of course the same in some way.
There are two ways in which we talk about equivalences of lambda terms, other than direct syntactic equality.
Alpha-Equivalence
The first is alpha equivalence. Put simply, two expressions are alpha equivalent if we can rename bound variables (those created by \(\lambda\)) to arise at the same term. For example, \(\lambda x. x\) and \(\lambda y. y\) are alpha equivalent. Below are some more terms, and whether they are alpha equivalent:
| Terms | Alpha Equivalent? |
|---|---|
| \( \lambda x. x\) and \( \lambda y. y\) | Yes |
| \( \lambda x. x \) and \( (\lambda x. x)\ (\lambda y. y) \) | No |
| \( \lambda x. \lambda y. x\) and \( \lambda y. \lambda x. y\) | Yes |
| \( \lambda x. \lambda y. x\) and \( \lambda y. \lambda x. x\) | No |
| \( \lambda x. \lambda y. x \) and \( \lambda x. \lambda x. x \) | No |
The first pair is alpha equivalent by renaming y to x. The second pair is not alpha equivalent because the two terms have a different structure; while the second evaluates to an alpha equivalent term to the first one, the two terms are not themselves alpha equivalent.
The third pair is alpha equivalent, because the second function is the same as the first by just permuting the variable names x and y.
However, if we change the structure of the lambda term, and return the second argument in the second term, but the first argument in the first term, they will not be alpha-equivalent.
Observational Equivalence
The second way we can think of lambda calculus terms as equivalent is observational equivalence, which states whether two lambda calculus terms behave the same. In this sense, \( \lambda x. x \) and \( (\lambda x. x)\ (\lambda y. y) \) are observationally equivalent: the left evaluates to an identity function, while the right also evaluates to an identity function.
In general, “observational equivalence” means that the two programs make the same observations; that is, behave exactly identically. For example, in C, two programs would be observationally equivalent if they write to the same memory addresses, return the same values, and print the same results (among other things). In the lambda calculus, however, we only have one notion of observation: whether a given term terminates. Recall from last lecture that the term \( \Omega := (\lambda x. x\ x)\ (\lambda x. x\ x) \) loops forever. Thus, we can craft a term, called poisonPill, that loops forever whenever it is called:
\[ \mathsf{poisonPill} := \lambda z. \Omega \]
Then, to know whether two terms are observationally equivalent, we can ask if they terminate the exact same when given the same arguments. For example, \( \lambda x. x \) and \( (\lambda x. x)\ (\lambda y. y) \) will, both when given A, just return A, even if A loops forever when it is called; thus, they will both always behave the same in all contexts. However, \(\mathsf{LTrue}\) and \(\mathsf{LFalse}\) don’t have the same termination behavior when given the following arguments (abbreviated \( \mathsf{id}\) for \(\lambda x. x\)):
\[ \begin{align*} &(\mathsf{Ltrue}\ \mathsf{poisonPill}\ \mathsf{id})\ \mathsf{id} \\ &(\mathsf{Lfalse}\ \mathsf{poisonPill}\ \mathsf{id})\ \mathsf{id} \end{align*} \]
A more interesting observational equivalence the following one: \(\mathsf{Ltrue}\) is observationally equivalent to \( \lambda z. \mathsf{Ltrue}\ z \). Since everything in the lambda calculus is a function, any function value is equivalent to a function that calls that value on its argument.
However, \( \Omega \) is definitely not observationally equivalent to \( \lambda z. \Omega\ z \)!
Natural Numbers
In addition to Booleans, the lambda calculus can actually represent any inductive datatype that we would want to represent in Lait. As another example, let’s consider the natural numbers. As an inductive datatype, we can represent the natural numbers like so:
type Nat := | NZero | NSucc (val : Nat)
Hence, 0 is represented with NZero, 2 as NSucc (NSucc NZero), and so on.
There are multiple ways of representing these in the lambda calculus.
For our purposes, we will use the Scott encoding. (The other popular encoding is the Church encoding.)
The basic idea of the Scott encoding is that we represent each element of the type Nat above as a function of its constructors. First, let’s see what that looks like in Lait.
def zero := fun z => fun s => z
def succ n := fun z => fun s => s n
Hence, zero, when given arguments for zero and successor, just returns the zero argument. Similarly succ, on a number n, when given arguments for zero and successor,
returns the successor argument applied to n.
Similar to if/then/else, we can think of the arguments to Scott numerals not only as constructors, but also case analysis. Given a Scott number n and two other terms
A and B, the term n A B can be thought of as follows: if n is 0, return A; otherwise, if n is m + 1, return B applied to m.
For example, we can see if a number is positive via case analysis:
def isPos n := n false (fun _ => true)
#eval isPos zero>> false
#eval isPos (succ zero)>> true
Let’s now convert Scott numerals to lambda calculus:
\[ \begin{align*} \mathsf{LZero} :=\ &\lambda z. \lambda s. z \\ \mathsf{LSucc} := \lambda n. &\lambda z. \lambda s. s\ n \end{align*} \]
Hence, we have that 2 = LSucc (LSucc LZero) is represented as \(\lambda z. \lambda s. s (\lambda z. \lambda s. s (\lambda z. \lambda s. z))\).
Addition via Recursion
Note
This is a special topic for the interested reader. The point is that the lambda calculus can embed arbitrary programs.
Now, let’s see how we can define mathematical operations on Scott numerals. We will consider addition. To see how it works, let’s first see how it works on our datatype from earlier:
def add_nat (n1 : Nat) (n2 : Nat) : Nat :=
match n1 with
| NZero => n2
| NSucc n1' => NSucc (add_nat n1' n2)
end
We define addition by recursion on the first number: if n1 is zero, then we return n2; otherwise, n1 = n1' + 1, so we return the successor of n1' + n2.
Thus, there are actually two ingredients that make addition work: case analysis on n1, and recursion.
To make recursion work, one can write a fixpoint combinator in the lambda calculus that lets you write recursive functions.
The idea of a fixpoint combinator is that we can turn a non-recursive function into a recursive one, by having the non-recursive function take an explicit “self” argument.
For example, add_nat could instead be represented as:
fix (fun self n1 n2 =>
match n1 with
| NZero => n2
| NSucc n1' => NSucc (self n1' n2)
end
)
As there are multiple choices of numbers in the lambda calculus, there are also multiple choices of fixpoint combinators. Let’s choose one, called the Z combinator: \[ \mathsf{fix} := \lambda f. (\lambda x. f (\lambda v. x\ x\ v)) (\lambda x. f (\lambda v. x\ x\ v)) \]
We can then define addition as we did in Lait: \[ \mathsf{add} := \mathsf{fix} (\lambda \mathsf{self}. \lambda n_1. \lambda n_2. n_1\ n_2\ (\lambda n_1’. \mathsf{LSucc} (\mathsf{self}\ n_1’\ n_2)) ) \]
Let’s embed these terms into Lait to see that they work:
-- Scott numeral: 0
def Z := ELam "z" (ELam "s" (EVar "z"))
-- Scott numeral: S
def S := ELam "n" (ELam "z" (ELam "s" (EApp (EVar "s") (EVar "n"))))
def One := EApp S Z
def Two := EApp S (EApp S Z)
#eval interp Two>> VLam "z" (ELam "s" (EApp (EVar "s") (ELam "z" (ELam "s" (EApp (EVar "s") (ELam "z" (ELam "s" (EVar "z"))))))))
-- Z combinator
def Fix := ELam "f" (
EApp (
ELam "x" (
EApp (EVar "f") (ELam "v" (EApp (EApp (EVar "x") (EVar "x")) (EVar "v")))
)
)
(
ELam "x" (
EApp (EVar "f") (ELam "v" (EApp (EApp (EVar "x") (EVar "x")) (EVar "v")))
)
)
)
def Add := EApp Fix (ELam "self" (ELam "x" (ELam "y"
(EApp (EApp (EVar "y") (EVar "x")) (ELam "n" (EApp S (EApp (EApp (EVar "self") (EVar "n")) (EVar "x"))))))))
#eval interp (EApp (EApp Add Two) Two)>> VLam "z" (ELam "s" (EApp (EVar "s") (ELam "z" (ELam "s" (EApp (EVar "s") (ELam "z" (ELam "s" (EApp (EVar "s") (ELam "z" (ELam "s" (EApp (EVar "s") (ELam "z" (ELam "s" (EVar "z"))))))))))))))
Real-World Experiments with the Lambda Calculus
The above section shows how the lambda calculus can embed natural numbers. Indeed, by extending these methods, it can actually represent arbitrary computations via simply recursion and “pattern matching” over datatypes, represented through encodings like the Scott numerals. Taken to its logical extreme, one can implement arbitrary programs as lambda calculus terms. For example, here is an entire C compiler written as one gigantic lambda calculus term. This compiler can turn arbitrary C code into lambda calculus terms, and then evaluate them using an interpreter for the lambda calculus (much like what we have in Lait).
Formalism
We have reached a point now where we have quite a complicated little garden of languages, each with their own syntax and semantics. It is time to bring order to this situation by introducing a concise and powerful system of notation for describing a program’s behavior. This new notation will empower us to quickly and precisely write down a description of a program’s semantics. As we move through the course, you will see more of this notation as we use it to describe type systems and other facets of how programs operate.
This lecture is heavily based on Chapter 3 of Pierce, B. C. (2002). Types and Programming Languages. MIT Press.import Lait
#lait
Inference Rules and Derivation Trees
Let’s go back to the CalcLang example we’ve been studying since
the first lecture:
type CalcLang := | NumE (val : Int) | AddE (left : CalcLang) (right : CalcLang)
We’ve seen two ways of giving semantics to CalcLang: big-step (via a
definitional interpreter) and small-step (via a stepper). Let’s start with the small-step semantics.
In Lecture 2, our stepper behaved as follows:
NumE vis a value, so there is nothing left to do.- To step
AddE e1 e2:- if
e1ande2are both valuesNumE v1andNumE v2, step to their sum,NumE (v1 + v2); - if
e1is a value (bute2is not), stepe2; - if
e1isn’t a value, stepe1.
- if
This is quite a mouthful, and it is a bit awkward to describe these rules in English. So, we will introduce the following notation to summarize these rules:
\[ \dfrac{}{\verb|AddE | (\verb|NumE | n_1)\ (\verb|NumE |n_2) \rightarrow \verb|NumE |(n_1 + n_2)}\ \text{E-Add1} \]
\[ \dfrac{e_1 \rightarrow e_1^{\prime}}{\verb|AddE | e_1\ e_2 \rightarrow \verb|AddE | e_1^{\prime}\ e_2}\ \text{E-Add2} \qquad \dfrac{e_2 \rightarrow e_2^{\prime}}{\verb|AddE | (\verb|NumE | n)\ e_2 \rightarrow \verb|AddE | (\verb|NumE | n)\ e_2^{\prime}}\ \text{E-Add3} \]
Note
Inference rules can be tricky the first time you see them! It’s good to get some practice using them.
This notation is probably unfamiliar, so let’s define what it means. An inference rule is a collection of premises followed by a conclusion, separated by a horizontal line. For example, the following is a simple inference rule that says that if it is raining and you have no umbrella, then you are wet:
\[ \dfrac{\text{It is raining.} \quad \text{You have no umbrella.}}{\text{You are wet.}} \]
If an inference rule has no premises, then it is called an axiom. Axioms are always true. The following is an example of an axiom:
\[ \dfrac{}{\text{The sun is hot.}} \]
Using inference rules for programming languages. To use inference rules to describe the semantics of programs, we have \(\rightarrow\) be interpreted as a relation between two programs. Thus, for any programs \(e_1\) and \(e_2\), it makes sense to write down the proposition \(e_1 \rightarrow e_2\). What inference rules do is tell us which propositions of the form \(e_1 \rightarrow e_2\) are true.
Note that there are infinitely many programs \(e_1\) and \(e_2\) such that \(e_1 \rightarrow e_2\). For example, we have that \(\verb|AddE | (\verb|NumE | 1)\ (\verb|NumE | 2) \rightarrow \verb|NumE | 3\), and \(\verb|AddE | (\verb|NumE | 1)\ (\verb|NumE | 3) \rightarrow \verb|NumE | 4\), and so on. Thus, to make the rules easier to write, we use metavariables, like \(n\) and \(e_1\), which are place holders that stand in for concrete syntax. The field of programming languages often uses certain conventions when using metavariables: for example, \(n\), \(n_1\), \(n’\) and so on stand for numbers, while \(e\) and \(e’\) stand for arbitrary expressions. Going through each rule one at a time:
- (E-Add1) handles the case when both arguments are numbers.
It is an axiom: it says that the program
AddE (NumE n1) (NumE n2)steps toNumE (n1 + n2). Be careful here: the \(+\) in the conclusion is Lait-level addition of actual numbers, whileAddEis our abstract syntax for addition inCalcLang. - (E-Add2) says that if
e1to some other expressione1', thenAddE e1 e2steps toAddE e1' e2. - (E-Add3) says that if
e2can take a step toe2', thenAddE (NumE n) e2can take a step toAddE (NumE n) e2'.
Note that, unlike our stepper in Lecture 2, there is no rule whose conclusion is \(\verb|NumE | n_1 \rightarrow \dots\): here, values do not step at all. Also note that these rules are deterministic: at most one inference rule can apply at a time.
Derivation Trees and Running Programs by Hand
To apply an inference rule to a concrete program, we match the program against the rule’s
conclusion, finding a piece of concrete syntax for each metavariable. This process is called unification.
For example, suppose we want to determine what the following CalcLang
program steps to: AddE (NumE 10) (NumE 20).
To do this, we need to determine which of the above inference rules apply to this program. We do this by process of elimination:
- The (E-Add1) rule applies: the syntax
AddE (NumE 10) (NumE 20)matches the left-hand side of the \(\rightarrow\) in its conclusion. Concretely, the number10unifies with the mtavariablen1, and20unifies with the metavariablen2. - The (E-Add2) rule does not apply: to use it, we would need as a hypothesis
that
NumE 10can take a step, butNumE ncannot take a step for anyn. - The (E-Add3) rule does not apply, for the same reason: we would need
NumE 20to take a step.
So, we can draw the following derivation that shows how to apply the (E-Add1) rule to take a step:
\[ \dfrac{}{\verb|AddE | (\verb|NumE | 10)\ (\verb|NumE | 20) \rightarrow \verb|NumE | 30}\ \text{(E-Add1)} \]
It is typical to write the name of the applied inference rule whenever it is used, but it may sometimes be left out for brevity, especially in the case of axioms.
One of the key properties of inference rules is that they can be chained together, with the conclusions of one rule feeding into the premises of the next rule. For instance, we can chain together the (E-Add1) and (E-Add2) rules to establish a more complicated fact:
\[
\dfrac{\dfrac{}{\verb|AddE | (\verb|NumE | 1)\ (\verb|NumE | 2) \rightarrow \verb|NumE | 3}\ \text{(E-Add1)}}
{
\verb|AddE | (\verb|AddE | (\verb|NumE | 1)\ (\verb|NumE | 2))
(\verb|NumE | 2) \rightarrow \verb|AddE | (\verb|NumE | 3)\ (\verb|NumE |
2) }\ \text{(E-Add2)}
\]
This structure is called a derivation tree. At the bottom of the
tree is the final conclusion. A derivation tree is valid if
all of the leaves of the tree are axioms,
i.e., statements that hold without premises.
Notice how in the above derivation tree, the metavariable \(e_1\) of the
(E-Add2) rule unifies with the syntax AddE (NumE 1) (NumE 2), and the
metavariable \(e_2\) unifies with the syntax NumE 2.
From Inference Rules to Implementation
Inference rules are a specification language: they are an improvement over English for describing the semantics of programs. So, it is important to know how to translate inference rules into implementations.
Because our rules for CalcLang are deterministic, they describe a partial function: if we have an expression \(e_1\), then
there is at most one \(e_2\) such that \(e_1 \rightarrow e_2\). Hence, in this case, we can implement the small-step rules in Lait as a function
from expressions to expressions, with one case for each inference rule:
def step (e : CalcLang) : CalcLang :=
match e with
| NumE _ => error "step: numbers do not step"
| AddE e1 e2 =>
match e1 with
| NumE n1 =>
match e2 with
| NumE n2 =>
-- ------------------ (E-Add1) where n = n1 + n2
-- n1 + n2 --> n
NumE (n1 + n2)
| _ =>
-- e2 --> e2'
-- ------------------------ (E-Add3)
-- n1 + e2 --> n1 + e2'
let e2' := step e2 in
AddE (NumE n1) e2'
end
| _ =>
-- e1 --> e1'
-- ------------------------ (E-Add2)
-- e1 + e2 --> e1' + e2
let e1' := step e1 in
AddE e1' e2
end
end
We implement step (as usual) by pattern matching on the expression.
Notice, however, that each arm of the match corresponds to a particular inference rule,
and how each premise of the form \(e \rightarrow e^{\prime}\) turns into a recursive call to step.
Since no rule applies to numbers,
we raise an error in that case.
Let’s check that step agrees with the derivations we drew by hand:
#test step (AddE (NumE 10) (NumE 20)) === NumE 30
#test step (AddE (AddE (NumE 1) (NumE 2)) (NumE 2)) === AddE (NumE 3) (NumE 2)
#eval step (NumE 3)
Big-Step Semantics
Recall our definitional interpreter for CalcLang:
def interpCalc (e : CalcLang) : Int :=
match e with
| NumE n => n
| AddE e1 e2 => interpCalc e1 + interpCalc e2
end
A big-step semantics relates programs to the values that they run to. We can use our inference rule notation to describe this relation in a manner similar to the small-step semantics. We write \(e \Downarrow v\) to mean that program \(e\) runs to value \(v\):
\[ \dfrac{}{\verb|NumE | n \Downarrow n}\ \text{(B-Num)} \qquad \dfrac{e_1 \Downarrow v_1 \quad e_2 \Downarrow v_2}{\verb|AddE | e_1\ e_2 \Downarrow (v_1 + v_2)}\ \text{(B-Add)} \]
Note that while the small-step semantics $\to$ is a relation between programs
and programs, big-step $\Downarrow$ is a relation between programs and values.
(For CalcLang, we take values to just be mathematical integers).
Now we can use these inference rules to draw derivation trees that
describe running CalcLang programs to values:
\[ \dfrac{\dfrac{}{\verb|NumE | 1 \Downarrow 1}\ \text{(B-Num)} \qquad \dfrac{}{\verb|NumE | 2 \Downarrow 2}\ \text{(B-Num)}} {\verb|AddE | (\verb|NumE | 1)\ (\verb|NumE | 2) \Downarrow 3}\ \text{(B-Add)} \]
Another example:
\[ \dfrac{ \dfrac{ \dfrac{}{\verb|NumE | 1 \Downarrow 1}\ \text{(B-Num)} \quad \dfrac{}{\verb|NumE | 2 \Downarrow 2}\ \text{(B-Num)} } {\verb|AddE | (\verb|NumE | 1)\ (\verb|NumE | 2) \Downarrow 3}\ \text{(B-Add)} \quad \dfrac{}{\verb|NumE | 3 \Downarrow 3}\ \text{(B-Num)}} {\verb|AddE | (\verb|AddE | (\verb|NumE | 1)\ (\verb|NumE | 2))\ (\verb|NumE | 3) \Downarrow 6}\ \text{(B-Add)} \]
Observe: this derivation tree looks exactly like a trace of running
interpCalc. Each use of (B-Add) corresponds to a call to interpCalc on an AddE,
whose two premises correspond to the two recursive calls. In this way, one can
think of the big-step semantics as a concise shorthand for describing
how definitional interpreters behave.
#test interpCalc (AddE (AddE (NumE 1) (NumE 2)) (NumE 3)) === 6
Structural Induction
Inference rules give us the scaffolding to argue carefully about what programs
do. Suppose we want to establish the following seemingly obvious fact: all
CalcLang programs terminate. This seems quite obviously true (as long as
the abstract syntax trees of programs we consider are finite in size, which is
an assumption we always make). How might we go about proving such a thing?
First, we want to translate this statement into something mathematically rigorous.
For a program \(e\) to terminate means that there exists an integer \(n\) such that \(e \Downarrow n\).
Theorem. For every CalcLang program \(e\), \(e \Downarrow n\) for some \(n\).
We will prove this by structural induction on program syntax. To use structural induction on programs, you do the following:
- Prove the theorem for the base cases, which are the programs which do not syntactically contain other sub-programs. For
CalcLang, the only base case isNumE. - Then, prove each inductive case, which are the programs that do have sub-programs. For
CalcLang, the only inductive case isAddE. When we prove an inductive case, we get to assume the theorem already holds for the sub-programs; these assumptions are called inductive hypotheses.
Note
You may notice here a subtle difference between this notion of induction and the one you may have seen in your math classes. In math class, you typically make inductive arguments using the natural numbers, like “first, show the theorem holds for objects of size 1. Then, assuming the theorem holds for objects of size \(n\), show that the theorem holds for objects of size \(n+1\). Then, we can conclude that the theorem holds for all objects of size at least 1.” Here, we are not inducting on the naturals; we are instead inducting on our abstract syntax tree.
Now, let’s prove the theorem.
- Case \( \verb|NumE | n \): this is a base case. Thus, we must show that \( \verb|NumE | n \Downarrow n’ \) for some \(n’\). By applying rule (B-Num), we can set \(n’ := n\) and the result follows.
- Case \(\verb|AddE | e_1\ e_2\): this is an inductive case. Thus, we already know that \(e_1 \Downarrow n_1\) and \(e_2 \Downarrow n_2\) for some integers \(n_1\) and \(n_2\), and we need to show that \(\verb|AddE | e_1\ e_2 \Downarrow n_3\) for some \(n_3\). We can set \(n_3 := n_1 + n_2\), and apply rule (B-Add).
We have proven each base case and inductive case, so the result follows.
Notice that this proof has the same shape as interpCalc itself: interpCalc only ever
calls itself recursively on sub-terms of its input. This kind of recursion is called
structural recursion, and structural induction is how we reason about it.
Note
The following statements are also provable by structural induction:
- Determinism: If \(e \Downarrow n\) and \(e \Downarrow n’\), then \(n = n’\).
- Safety against negative numbers: If \(e\) does not contain any subterms of the form \(\verb|NumE | m\) where \(m < 0\), then if \(e \Downarrow m\), we have that \(m \geq 0\).
Extensions to CalcLang
Let’s now see how our inference rules look like when we extend the CalcLang language.
For simplicity, we will write them using big-step semantics.
If0
First, let’s consider an extension with a construct for if0/then/else:
e ::= NumE n | AddE e1 e2 | If0 e1 e2 e3
Informally, the semantics of If0 e1 e2 e3 is:
- Evaluate
e1to a valuev. - If
v = 0, evaluatee2. - Otherwise, evaluate
e3.
Before today, we would only specify If0 via a definitional interpreter in Lait. However, now we can specify it much easier, by the following pair of rules:
\[ \dfrac{e_1 \Downarrow v_1 \quad v_1 = 0 \quad e_2 \Downarrow v}{\verb|If0 | e_1\ e_2\ e_3 \Downarrow v} \qquad \dfrac{e_1 \Downarrow v_1 \quad v_1 \neq 0 \quad e_3 \Downarrow v}{\verb|If0 | e_1\ e_2\ e_3 \Downarrow v} \]
In English first rule states that If0 e1 e2 e3 evaluates to v whenever e1 evaluates to v1, v1 = 0, and e2 evaluates to v.
Similarly, the second rule states that If0 e1 e2 e3 evaluates to v whenever e1 evaluates to v1, v1 != 0, and e3 evaluates to v.
Arbitrary
Because inference rules are used to define arbitrary relations, they can define the semantics of programs that don’t nicely correspond to an interpreter in Lait.
For example, let’s extend CalcLang again with a construct for “give me an arbitrary number”:
e ::= ... | Arb
The semantics is that Arb could evaluate to anything. While making this precise in Lait is very difficult, let’s see how we can specify such an idea using an inference rule:
\[ \dfrac{}{\verb|Arb| \Downarrow v} \]
That’s it! This gives us a nondeterministic semantics.
Question. What do the derivation trees for \(\verb|AddE | (\verb|NumE |42)\ \verb|Arb| \Downarrow v\) look like? What can they evaluate to?
Question. Even though Arb seems like anything is possible and thus all
understanding about our programs is lost, this is not necessarily the case.
Suppose we also had MulE. Then what is a program that uses Arb but nevertheless has a deterministic semantics?
Formalizing the Lambda Calculus
This is a continuation of last lecture on how to formalize programming languages mathematically.
import Lait
#lait
Small-Step Semantics for the Lambda Calculus
Now we can write down the small-step semantics for the lambda calculus.
To do this smoothly, we will take one more leap of faith: instead of writing inference rules with abstract syntax (such as with EAdd, or ELam for the lambda calculus), we will use concrete syntax.
For this, we need just a bit more notation.
If \(e\) is a lambda calculus program, then we write \(e[x \mapsto v]\) for
the result of substituting \(v\) for the variable \(x\) in \(e\).
We will use the metavariable \(v\) to stand for values; in the case of the
lambda calculus, all values are abstractions.
Then, we can write the small-step semantics for the call-by-value
lambda calculus:
\[ \dfrac{e_1 \rightarrow e_1^{\prime}}{e_1\ e_2 \rightarrow e_1^{\prime}\ e_2}\ \text{(E-App1)} \qquad \dfrac{e_2 \rightarrow e_2^{\prime}}{v_1\ e_2 \rightarrow v_1\ e_2^{\prime}}\ \text{(E-App2)} \qquad \dfrac{}{(\lambda x. e)\ v_2 \rightarrow e[x \mapsto v_2]}\ \text{(E-Beta)} \]
The type of the small-step relation \(\rightarrow\) is that it relates lambda-calculus expressions with lambda-calculus expressions.
These three rules are exactly the informal stepping rules from Lecture 4: step the function until
it is a value, then step the argument until it is a value, then \(\beta\)-reduce.
Just as with CalcLang, there is no rule for stepping an abstraction: values do not step.
Let’s see some examples of stepping specific lambda terms:
\[ \dfrac{}{(\lambda x. x)\ (\lambda y. y) \rightarrow \lambda y. y}\ \text{(E-Beta)} \]
Another one:
\[ \dfrac{\dfrac{}{(\lambda x. x)\ (\lambda y. y) \rightarrow \lambda y. y}\ \text{(E-Beta)}} {((\lambda x. x)\ (\lambda y. y))\ (\lambda z. z) \rightarrow (\lambda y. y)\ (\lambda z. z)}\ \text{(E-App1)} \]
Another one:
\[ \dfrac{\dfrac{}{(\lambda x. x)\ (\lambda y. y) \rightarrow \lambda y. y}\ \text{(E-Beta)}} {(\lambda z. z)\ ((\lambda x. x)\ (\lambda y. y)) \rightarrow (\lambda z. z)\ (\lambda y. y)}\ \text{(E-App2)} \]
As we did for CalcLang, we can translate these rules into a Lait function. Let’s recall our
definitions from before, changing them slightly to make our small-steps more ergonomic:
type Exp := | EVar (var : String)
| ELam (var : String) (body : Exp)
| EApp (e1 : Exp) (e2 : Exp)
def Exp.isValue (e : Exp) : Bool :=
match e with
| ELam _ _ => true
| _ => false
end
def subst (var : String) (assignment : Exp) (body : Exp) : Exp :=
match body with
| EVar var' => if var == var' then assignment else EVar var'
| EApp e1 e2 => EApp (subst var assignment e1) (subst var assignment e2)
| ELam var' body' =>
if var == var' then
ELam var' body' -- Shadowing: no substitution
else
ELam var' (subst var assignment body')
end
Now, each rule becomes one arm of a match (again, not stepping values now).
Let’s also have our stepper print out the rule that it is using:
def stepLam (e : Exp) : Exp :=
match e with
| EVar _ => error "stepLam: got a variable"
| ELam _ _ => error "stepLam: values do not step"
| EApp e1 e2 =>
match e1 with
| ELam x body =>
if Exp.isValue e2 then
-- ------------------------------- (E-Beta)
-- (\x. body) v --> body[x |-> v]
let _ := print "E-Beta" in
subst x e2 body
else
-- e2 --> e2'
-- --------------------- (E-App2)
-- v1 e2 --> v1 e2'
let _ := print "E-App2" in
EApp e1 (stepLam e2)
| _ =>
-- e1 --> e1'
-- --------------------- (E-App1)
-- e1 e2 --> e1' e2
let _ := print "E-App1" in
EApp (stepLam e1) e2
end
end
Let’s check it now against the three derivations above.
(Remember that you can hover/click on #eval results if they have more than one line to show.)
def Lx_x := ELam "x" (EVar "x")
def Ly_y := ELam "y" (EVar "y")
def Lz_z := ELam "z" (EVar "z")
#eval stepLam (EApp Lx_x Ly_y)>> E-Beta
-- Another example: repeatedly stepping a term..
#eval stepLam (EApp (EApp Lx_x Ly_y) Lz_z)>> E-App1
#eval stepLam (stepLam (EApp (EApp Lx_x Ly_y) Lz_z))>> E-App1
#eval stepLam (stepLam (stepLam (EApp (EApp Lx_x Ly_y) Lz_z)))
-- Another example:
#eval stepLam (EApp Lz_z (EApp Lx_x Ly_y))>> E-App2
Big-Step Semantics for the Lambda Calculus
Now that we have seen the small-step semantics, let’s turn to the big-step semantics. Here is is below:
\[ \dfrac{}{(\lambda x. e) \Downarrow (\lambda x. e)}\ \text{B-Lam} \qquad \dfrac{e_1 \Downarrow (\lambda x. e) \quad e_2 \Downarrow v_2 \quad e[x \mapsto v_2] \Downarrow v}{e_1\ e_2 \Downarrow v}\ \text{B-App} \]
The type of the big-step relation \(\Downarrow\) is that it relates lambda-calculus expressions with values of the form \(\lambda x. e\). As we saw in lecture 6, values big-step to values; this gives us the first rule. For the second rule, we think of how we would write the interpreter for applications. To interpret \(e_1\ e_2\), we:
- Interpret \(e_1\) down to a value, \(\lambda x. e\);
- Interpret \(e_2\) down to a value, \(v_2\);
- And continue interpreting \(e[x \mapsto v_2]\).
In essence, the big-step rule “chains together” multiple evaluations to give a single rule for application, rather than a collection of rules (E-App1, E-App2, E-Beta).
Relating the Big and Small-Step Semantics
So far, we’ve seen the big-step and the small-step semantics as two separate ways of defining the semantics of programs. But, intuitively, these two semantics ought to agree. The formal relationship we want is that if one repeatedly performs small steps until a term is fully simplified, then this fully simplified value is equal to the value given by the big-step semantics.
Let’s make this relationship precise by defining an additional relation \(\rightarrow^{\ast}\) (called the multi-step relation, sometimes also called “star step”) that repeatedly performs small steps. We can define this using the small-step semantics as:
\[ \dfrac{e \rightarrow e^{\prime} \quad e^{\prime} \rightarrow^{\ast} e^{\prime\prime}}{e \rightarrow^{\ast} e^{\prime\prime}}\ \text{(E-Trans)} \qquad \dfrac{}{v \rightarrow^{\ast} v}\ \text{(E-Refl)} \]
The (E-Trans) rule, short for transitivity, says that \(e\) multi-steps to \(e^{\prime\prime}\) if there is some intermediate \(e^{\prime}\) such that \(e\) steps to \(e^{\prime}\), and \(e^{\prime}\) multi-steps to \(e^{\prime\prime}\). The (E-Refl) rule, short for reflexivity, says that a value multi-steps to itself. (Since (E-Refl) only applies to values, \(e \rightarrow^{\ast} e^{\prime\prime}\) means that \(e\) runs all the way to the value \(e^{\prime\prime}\).) Let’s see an example:
\[ \dfrac{ \dfrac{\dfrac{}{\verb|AddE | (\verb|NumE | 1)\ (\verb|NumE | 2) \rightarrow \verb|NumE | 3}\ \text{(E-Add1)}} {\verb|AddE | (\verb|AddE | (\verb|NumE | 1)\ (\verb|NumE | 2))\ (\verb|NumE | 3) \rightarrow \verb|AddE | (\verb|NumE | 3)\ (\verb|NumE | 3)}\ \text{(E-Add2)} \quad \dfrac{ \dfrac{}{\verb|AddE | (\verb|NumE | 3)\ (\verb|NumE | 3) \rightarrow \verb|NumE | 6}\ \text{(E-Add1)} \quad \dfrac{}{\verb|NumE | 6 \rightarrow^{\ast} \verb|NumE | 6}\ \text{(E-Refl)} } {\verb|AddE | (\verb|NumE | 3)\ (\verb|NumE | 3) \rightarrow^{\ast} \verb|NumE | 6}\ \text{(E-Trans)} } {\verb|AddE | (\verb|AddE | (\verb|NumE | 1)\ (\verb|NumE | 2))\ (\verb|NumE | 3) \rightarrow^{\ast} \verb|NumE | 6}\ \text{(E-Trans)} \]
We implemented this relation as the run function in lecture 2.
Using our new step function, which only applies to non-values, it looks like this:
def multistep (e : CalcLang) : CalcLang :=
match e with
| NumE n => NumE n -- (E-Refl)
| AddE _ _ => multistep (step e) -- (E-Trans)
end
Then, we can state the following theorem that formally relates the two semantics:
Theorem. For any CalcLang program \(e\), \(e \rightarrow^{\ast} n\) if and only if
\(e \Downarrow n\).
We won’t prove this theorem right now, but the proof is a structural inductive argument
not unlike the one we did for showing that all CalcLang programs terminate.
It’s not too difficult, but it is quite tedious, since it requires handling many
cases.
An analogous theorem holds for the lambda calculus: its small-step rules agree with the
big-step interp function from lecture 4. This justifies our giving only a small-step semantics for the
lambda calculus above: if we want a big-step semantics, we can define \(e \Downarrow v\) to mean \(e \rightarrow^{\ast} v\).
Differences between Big-Step and Small-Step
One might wonder why we consider both big-step and small-step semantics, since they can seem redundant. There are a lot of different reasons, but we will focus on two:
- Simplicity. Small-step semantics typically have more rules, but each rule is simpler. On the other hand, big-step semantics has less rules, but each rule is more complicated. This is a tradeoff.
- Nontermination. Big-step semantics has a different view on programs that run forever than small step. Consider our nonterminating lambda calculus term \(\Omega := (\lambda x. x\ x)\ (\lambda x. x\ x)\). Under a small-step semantics, we have the infinite chain of steps \(\Omega \rightarrow \Omega \rightarrow \Omega \rightarrow \dots \). Under a big-step semantics, we can’t talk about \(\Omega\): indeed, there is no value \(v\) such that \(\Omega \Downarrow v\) (under an appropriate big-step semantics for the lambda calculus).
Errors and Being Stuck
Finally, we will conclude this discussion by revisiting IfLang from lecture 3, which
adds Booleans and conditionals to our calculator language. (We leave out and for brevity.)
<expr> ::= <number>
| true
| false
| <expr> + <expr>
| if <expr> then <expr> else <expr>
| ( <expr> )
Let’s define our semantics so that the guards of if-expressions are expected to be Booleans.
Here is what the rules look like for this. Below, we are making one more step towards brevity, by writing IfLang as well in concrete syntax. Note that this makes the rule (E-Add1) a little subtle: the addition + in the conclusion of the rule is addition at the level of the AST, while the side condition is using + in the metalanguage.
\[ \dfrac{}{n_1 + n_2 \rightarrow n}\ \text{(E-Add1)} \quad \text{where } n = n_1 + n_2 \]
\[ \dfrac{e_1 \rightarrow e_1^{\prime}}{e_1 + e_2 \rightarrow e_1^{\prime} + e_2}\ \text{(E-Add2)} \qquad \dfrac{e_2 \rightarrow e_2^{\prime}}{n + e_2 \rightarrow n + e_2^{\prime}}\ \text{(E-Add3)} \]
\[ \dfrac{}{\mathsf{if}\ \mathsf{true}\ \mathsf{then}\ e_1\ \mathsf{else}\ e_2 \rightarrow e_1}\ \text{(E-IfT)} \qquad \dfrac{}{\mathsf{if}\ \mathsf{false}\ \mathsf{then}\ e_1\ \mathsf{else}\ e_2 \rightarrow e_2}\ \text{(E-IfF)} \]
\[ \dfrac{e_1 \rightarrow e_1^{\prime}}{\mathsf{if}\ e_1\ \mathsf{then}\ e_2\ \mathsf{else}\ e_3 \rightarrow \mathsf{if}\ e_1^{\prime}\ \mathsf{then}\ e_2\ \mathsf{else}\ e_3}\ \text{(E-IfStep)} \]
Note what happens if we try to step the program if 10 then true else false: there is no
rule that applies to this program! The guard 10 is not true or false, so neither (E-IfT) nor (E-IfF) applies,
and 10 cannot take a step, so (E-IfStep) does not apply either. Similarly, no rule applies to true + 1.
Formally, a term is stuck if (1)
there is no small-step rule that applies to it, and (2) it is not a value.
Stuck terms are exactly the ones that cause runtime errors in interpreters. In lecture 3, our interpreter for IfLang
raised an error when this happened (via Value.toInt and Value.toBool).
Open terms in the lambda calculus are another example: a variable \(x\) on its own is not a value,
and no rule applies to it, so it is stuck. This is why both interp and stepLam raise an error when they reach a variable:
#eval stepLam (EVar "x")
Since we don’t want our interpreters to crash, we also don’t want our semantics to get stuck. Thus, we will now turn to talking about types, which allow us to ensure that we never get stuck terms.
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?
- 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.
- 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.
- We can give up on efficiency and run
<very complex expression>to a value. Depending on whether that value istrueorfalse, 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:
- Create examples that demonstrate all the soundness bugs that you want your type checker to prevent.
- 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.
- Create a function
type_ofthat 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. - Test your
type_offunction 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 Syntax | Abstract 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:
Numis the type of numbers; an example program with this type is \( 5 + 2 \).Num -> Numis 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 -> Numis 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) -> Numis 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) -> Numtakes 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
xhaving 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 givexwhile 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.
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?
Types III: Type Soundness
In this lecture we will (1) more deeply explore the consequences and properties of types and (2) grow our type system. First, we will make precise what it means for a type system to be sound, and see the standard technique for proving soundness. Then, we will put all of our formal tools together to quickly prototype a new language with mutable state, and see how mutable state changes what our type system guarantees.
import Lait
#lait
Type Soundness
One of our key properties of type systems is that they are sound: a sound type checker will reject programs that cause runtime errors in our interpreters. This property is best summarized by the famous quote from Robin Milner that “well-typed programs don’t go wrong”.
How can we establish that a type checker is sound? Well, one way is to very thoroughly test our type checker implementation with lots of example programs. This can work, especially for fairly small programming languages, but as our languages get increasingly complex it starts to become very challenging to design sufficiently comprehensive test suites to cover all possible programs.
An alternative to exhaustive testing of our type checkers is to formally prove that our type checker eliminates all bad programs. This technique of proving type checkers formally sound is a pillar of type system design.
What does it mean to “formally prove a type system sound”? Well, consider
IfLang. Recall its small-step semantics from
the formalism lecture:
\[ \dfrac{}{n_1 + n_2 \rightarrow n}\ \text{(E-Add1)} \quad \text{where } n = n_1 + n_2 \]
\[ \dfrac{e_1 \rightarrow e_1^{\prime}}{e_1 + e_2 \rightarrow e_1^{\prime} + e_2}\ \text{(E-Add2)} \qquad \dfrac{e_2 \rightarrow e_2^{\prime}}{n + e_2 \rightarrow n + e_2^{\prime}}\ \text{(E-Add3)} \]
\[ \dfrac{}{\mathsf{if}\ \mathsf{true}\ \mathsf{then}\ e_1\ \mathsf{else}\ e_2 \rightarrow e_1}\ \text{(E-IfT)} \qquad \dfrac{}{\mathsf{if}\ \mathsf{false}\ \mathsf{then}\ e_1\ \mathsf{else}\ e_2 \rightarrow e_2}\ \text{(E-IfF)} \]
\[ \dfrac{e_1 \rightarrow e_1^{\prime}}{\mathsf{if}\ e_1\ \mathsf{then}\ e_2\ \mathsf{else}\ e_3 \rightarrow \mathsf{if}\ e_1^{\prime}\ \mathsf{then}\ e_2\ \mathsf{else}\ e_3}\ \text{(E-IfStep)} \]
and its typing rules from the previous lecture, which we now write using the same concrete syntax:
\[ \dfrac{}{\vdash n : \texttt{Num}}\ \text{(T-Num)} \qquad \dfrac{}{\vdash b : \texttt{Bool}}\ \text{(T-Bool)} \qquad \dfrac{\vdash e_1 : \texttt{Num} \quad \vdash e_2 : \texttt{Num}} {\vdash e_1 + e_2 : \texttt{Num}}\ \text{(T-Plus)} \]
\[ \dfrac{\vdash g : \texttt{Bool} \quad \vdash e_1 : \tau \quad \vdash e_2 : \tau} {\vdash \mathsf{if}\ g\ \mathsf{then}\ e_1\ \mathsf{else}\ e_2 : \tau}\ \text{(T-If)} \]
Suppose \(e\) is a well-typed IfLang program. It might take many steps
before it reaches a value, \(e \rightarrow e_1 \rightarrow e_2 \rightarrow \cdots \rightarrow v\).
Recall that the way that we encode errors in our formal semantics is
by getting stuck, meaning that there is a term that is not a value
but has no applicable small-step rule.
Our goal is that no matter how many steps a well-typed program takes, it
never reaches a stuck term. This leads to our notion of formal type soundness:
Theorem (Type Soundness of IfLang). Let \(e\) be an IfLang
program with \(\vdash e : \tau\). Then, for any sequence of steps
\(e \rightarrow e_1 \rightarrow \cdots \rightarrow e_n\) (with \(n \geq 0\)),
\(e_n\) is not stuck.
Up until now, we have just given you many definitions relating to programming languages. The above theorem shows us the true power of programming languages: we can prove theorems that universally quantify over programs. Thus, no matter how large or complex the program is — it could be a million lines of code — as long as it’s well typed, it can’t get stuck.
Proving Type Soundness Syntactically
This technique for proving type soundness was introduced in: Wright, Andrew K., and Matthias Felleisen. "A syntactic approach to type soundness." Information and Computation 115.1 (1994): 38-94. If you want more details on this proof technique, see Chapters 8 and 9 of Types and Programming Languages.Establishing the type soundness of type systems is one of the core themes of programming languages research and development, and has animated much of the formal development of languages. To prove type soundness, we will follow a particular recipe, called progress and preservation.
First, this recipe requires us to prove a progress lemma, which states that every well-typed program can step, unless it’s a value:
Lemma (Progress). For any well-typed IfLang program \(e\),
either (1) \(e\) can take a single step, or (2) \(e\) is a value.
Next, we need to separately prove preservation, which says that if we step from a well-typed expression, the result is well typed:
Lemma (Preservation). If \(\vdash e : \tau\) and \(e \rightarrow e^{\prime}\), then \(\vdash e^{\prime} : \tau\).
Progress says that well-typed terms are not stuck right now. Preservation says that being well-typed is maintained by taking a step, so that we can apply progress again after taking a step. Together, these two lemmas imply type soundness, and hence establish that our small-step interpreter never encounters runtime errors.
Proof of Type Soundness. Using Progress and Preservation, we can prove our Type Soundness theorem.
- Suppose \(\vdash e : \tau\) and \(e \rightarrow e_1 \rightarrow \cdots \rightarrow e_n\). Our job is to show that \(e_n\) is not stuck.
- First, show that \(\vdash e_n : \tau\) — that is, \(e_n\) is well-typed. This is by induction on \(n\).
- Base case (\(n = 0\)): No steps were taken, so \(e_n = e\). By assumption, \(\vdash e : \tau\).
- Inductive case (\(n = k + 1\)): Our inductive hypothesis says that \(\vdash e_k : \tau\). Since \(e_k \rightarrow e_{k+1}\), preservation tells us that \(\vdash e_{k+1} : \tau\).
- Now, Progress tells us immediately that \(e_n\) is either a value or can take a step; thus, it is not stuck by definition.
Proof of the Progress Lemma
Type soundness isn't everything. There are many widely-used type systems in the wild today that are not type sound, including TypeScript and Java. Nonetheless, type soundness has proven to be a useful "north star" for type systems and has been influential in designing practical type systems. There are also richer notions of type safety than the syntactic notion of type safety that we discuss here: see this blog post.Let’s see an example of why one of these two lemmas is true: we will prove the progress lemma. Our argument will be by induction on the typing derivation tree of \(\vdash e : \tau\). We do case analysis on the last rule used in the derivation; in each case, our inductive hypothesis says that the progress lemma holds for every premise of that rule. Our goal is to show that in every case \(e\) is either a value or it can take a step:
- (T-Num). In this case, \(e\) must be a number, which is a value.
- (T-Bool). In this case, \(e\) must be a Boolean, which is a value.
- (T-If). In this case, \(e = \mathsf{if}\ g\ \mathsf{then}\ e_1\ \mathsf{else}\ e_2\),
and \(\vdash g : \texttt{Bool}\). Our inductive hypothesis says that \(g\)
is either a value or can take a step. We do case analysis on these two possibilities:
- Case 1: \(g\) is a value. By the Boolean canonical forms theorem, since \(\vdash g : \texttt{Bool}\), \(g\) is either \(\mathsf{true}\) or \(\mathsf{false}\). If it is \(\mathsf{true}\), \(e\) steps using the (E-IfT) rule; if it is \(\mathsf{false}\), \(e\) steps using the (E-IfF) rule.
- Case 2: \(g\) can step, \(g \rightarrow g^{\prime}\). In this case, \(e\) steps using the (E-IfStep) rule.
Notice that we never needed the inductive hypotheses for the branches
\(e_1\) and \(e_2\): the semantics of if never evaluates the branches until
the guard has been evaluated.
The proof for (T-Plus) is very similar to the case for (T-If), so we leave it as an exercise.
Proof of Preservation
While we won’t fully prove preservation in class, we can at least see how the proof would go. Recall that preservation says that if \(\vdash e : \tau\) and \(e \rightarrow e’\), then \(\vdash e’ : \tau\).
The proof is also by induction on the typing derivation for \(\vdash e : \tau\). In each case, we then additionally have the information that \(e \rightarrow e’\). Since we are inducting on the typing judgment, this will tell what \(e\) is, and hence what \(e’\) can be.
Preservation: T-Plus
Let’s look at the case for addition (T-Plus); thus, we have that \(\vdash e_1 + e_2 : \texttt{Num}\), and thus that \(\vdash e_1 : \texttt{Num}\) and separately \(\vdash e_2 : \texttt{Num}\). By induction, we also have the progress lemma for \(e_1\) and \(e_2\). Thus, we also have:
- If \(e_1 \rightarrow e_1’\), then \(\vdash e_1’ : \texttt{Num}\); and
- If \(e_2 \rightarrow e_2’\), then \(\vdash e_2’ : \texttt{Num}\).
We then need to proceed by all of the possible ways that \(e = e_1 + e_2\) can step.
- Case (E-Add1): We learn that \(e_1 = n_1\) and \(e_2 = n_2\), and \(e’ = n_3\) where \(n_3 = n_1 + n_2\). We have that \(\vdash e’ : \texttt{Num}\) by (T-Num).
- Case (E-Add2): We learn that \(e_1 \rightarrow e_1’\), and \(e’ = e_1’ + e_2\). We have that \(\vdash e_1’ : \texttt{Num}\) by our inductive hypothesis, and \(\vdash e_2 : \texttt{Num}\) by assumption. Thus, by (T-Add), we have that \(\vdash e’ : \texttt{Num}\).
- Case (E-Add3): We learn that \(e_1 = n\) and \(e_2 \rightarrow e_2’\), and \(e’ = n + e_2’\). We have that \(\vdash n : : \texttt{Num}\) by (T-Num) and \(\vdash e_2 : \texttt{Num}\) by our inductive hypothesis; thus, \(\vdash e’ : \texttt{Num}\) by (T-Add).
Exercise. Prove the preservation lemma for the case where \(e = \mathsf{if}\ g\ \mathsf{then}\ e_1\ \mathsf{else}\ e_2\). (Hint: do case analysis on which step rule was used to derive \(e \rightarrow e^{\prime}\).)
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.
Extensions to the Simply-Typed Lambda Calculus: Subtyping; Sum Types and Product Types
import Lait
#lait
\[ \newcommand{\Int}{\texttt{Int}} \newcommand{\Nat}{\texttt{Nat}} \newcommand{\Pos}{\texttt{Pos}} \]
Prelude: Correctly Handling Division
Let’s begin with an STLC.
\[ \begin{align*} e &::= x \mid n \mid e \oplus e \mid \lambda x : \tau. e \mid e\ e \\ \oplus &::= + \mid \times \mid / \\ n &::= 0 \mid 1 \mid 2 \mid \dots \end{align*} \]
Above, we write \(e \oplus e\) to make reference to a binary operator: for now, we will have addition, multiplication, and division. Here, division refers to integer division: thus 7 / 3 = 2. Crucially, if we divide by zero, this should raise a runtime error.
We will not fully specify the semantics of this language, since by now you can see how it would go. For example, multiplication would similarly need three rules: the “main” rule states what happens when we multiply two integer values \(n_1 \times n_2\), while two “helper” rules state what happens when we step \(e_1 \times e_2\) and \(n \times e\).
Division will work the same way; however, once we actually reach the rule for values, we will not let it step if the second argument is zero:
\[ \dfrac{}{n_1\ /\ n_2 \rightarrow n}\ \text{(E-Div)} \quad \text{where } n_2 \neq 0 \text{ and } n = \lfloor n_1 \div n_2 \rfloor \]
Division causes unsoundness with a naive type system. First, let’s observe that if our types are just like before: \[ \tau ::= \Nat \mid \tau \to \tau \] we can easily give types to addition and multiplication, as we have seen before. (Here, \(\Nat\) refers to the natural numbers.) Division is going to break things, though. If we had the below typing rule: \[ \dfrac{\Gamma \vdash e_1 : \Nat \quad \Gamma \vdash e_2 : \Nat} {\Gamma \vdash e_1\ /\ e_2 : \Nat}\ \text{(T-Div-Unsound)} \] Then we would now have an unsound type system. (Why?)
For the rest of today, we are going to study two solutions to this: one using subtyping, where we can prove statically that we never divide by zero; and another using sum types, where we can instead implement a “checked” division operator that enforces dynamically that division-by-zero never happens.
Subtyping
One possible response to the issue about T-Div-Unsound is that our types are too coarse: Nat is simply not informative enough to use division.
To solve this, we can throw in a new type for positive integers:
\[ \tau ::= \Nat \mid \Pos \mid \tau \to \tau \]
The idea now is that a given integer expression (e.g., \(1 + 2\ /\ 3\)) can actually be of one of two types: either Nat, if we don’t know that it is nonzero, or Pos, if we know that it must be nonzero.
This can solve our problem, because we can say that division requires a Pos for the second argument.
However, we now have a quite different-looking type system, as we now have two numeric types to cover integers, with one (Nat) a strict superset of the other (Pos). Thus, we want that every Pos is a Nat, but not vice versa.
Then, we can specify division as follows:
\[ \dfrac{\Gamma \vdash e_1 : \Nat \quad \Gamma \vdash e_2 : \Pos} {\Gamma \vdash e_1\ /\ e_2 : \Nat}\ \text{(T-Div)} \] Thus, T-Div states that given a natural number (possibly zero), and given a positive number, we can divide the first by the second. To make this work with the rest of our language, we need to answer two questions:
- How should we type addition and multiplication?
- How should subtyping work?
Typing Rules for Addition and Multiplication
First, let’s think about addition. When typing \(e_1 + e_2\), there are two possible types for each expression (either Nat or Pos); and thus four possible configurations of types for both. We can list out these possibilities:
- If \(e_1\) and \(e_2\) are both
Nat, we have no guarantee that the sum will be positive; thus, the result must have typeNat. - If either \(e_1\) or \(e_2\) have type
Pos, then we know that \(e_1 + e_2\) must bePosas well!. Indeed, since if \(n_1 > 0\) and \(n_2 \geq 0\), we have that \(n_1 + n_2 > 0\).
We can think of these two possibilities as two typing rules for addition. The first one will say that if we add Nat and Nat together, we get Nat; however, the second one will say that if we add Nat and Pos together, we get Pos.
Let’s implement these:
\[ \dfrac{\Gamma \vdash e_1 : \Nat \quad \Gamma \vdash e_2 : \Nat} {\Gamma \vdash e_1 + e_2 : \Nat}\ \text{(T-Add1)} \]
\[ \dfrac{\Gamma \vdash e_1 : \tau_1 \quad \Gamma \vdash e_2 : \tau_2 \quad \tau_1, \tau_2 \in \{\Nat, \Pos\} \quad (\tau_1 = \Pos \lor \tau_2 = \Pos)} {\Gamma \vdash e_1 + e_2 : \Pos}\ \text{(T-Add2)} \]
The first rule is what we had before for addition.
The second rule is new: it states that, if we are adding two integer types together, and one is a Pos, the result is a Pos.
We can now play the same game with multiplication:
- If both arguments are
Pos, multiplication should return aPos. - If either is a
Nat, multiplication should return aNat.
Exercise: Write down our new formal typing rules for multiplication.
Typing Constants, and Using Subtyping
Now, let’s see how we should introduce numeric types; that is, how to give types to constant integers. For hardcoded program constants, we can just return the most informative type:
\[ \dfrac{\tau = \begin{cases} \Nat & n = 0 \\ \Pos & n > 0 \end{cases}} {\Gamma \vdash n : \tau}\ \text{(T-Num)} \]
However, this alone is not enough. While we can how say that \(\Gamma \vdash 5 : \Pos\), we might also want to treat \(5\) as a Nat. For example, we cannot yet type check this function: \[ (\lambda x : \Nat. x + 1)\ 5\] since Nat and Pos are not the same. To make this work, we introduce a judgment for subtyping, \( \tau_1 <: \tau_2 \),
which says that \(\tau_1\) is a subtype of \(\tau_2\). Intuitively, this states that every value inside of \(\tau_1\) is also inside of \(\tau_2\). Thus, whenever we have a variable of type \(\tau_1\), it is also sound to treat it like a \(\tau_2\).
Let’s see the rules for numeric types, and the way we can use subtyping to make our example program type check:
\[ \dfrac{}{\tau <: \tau}\ \text{(Sub-Refl)} \qquad \dfrac{}{\Pos <: \Nat}\ \text{(Sub-Pos)} \qquad \dfrac{\Gamma \vdash e : \tau_1 \quad \tau_1 <: \tau_2} {\Gamma \vdash e : \tau_2}\ \text{(T-Sub)} \]
Above, (Sub-Refl) says that every type is a subtype of itself, (Sub-Pos) says that Pos is a subtype of Nat, while (T-Sub) says that expressions typed at subtypes can be reinterpreted at supertypes. Using these rules, we can now give a derivation tree to show our example is well-typed:
First, we type the body of the function:
\[ \dfrac{\dfrac{x : \Nat \in x : \Nat} {x : \Nat \vdash x : \Nat}\ \text{(T-Var)} \quad \dfrac{}{x : \Nat \vdash 1 : \Pos}\ \text{(T-Num)}} {x : \Nat \vdash x + 1 : \Pos}\ \text{(T-Add2)} \]
Then, we use this to type the whole program:
\[ \dfrac{\dfrac{x : \Nat \vdash x + 1 : \Pos} {\vdash \lambda x : \Nat.\ x + 1 : \Nat \to \Pos}\ \text{(T-Abs)} \quad \dfrac{\dfrac{}{\vdash 5 : \Pos}\ \text{(T-Num)} \quad \dfrac{}{\Pos <: \Nat}\ \text{(Sub-Pos)}} {\vdash 5 : \Nat}\ \text{(T-Sub)}} {\vdash (\lambda x : \Nat.\ x + 1)\ 5 : \Pos}\ \text{(T-App)} \]
The key step is (T-Sub): the argument \(5\) has type \(\Pos\), but the function expects a \(\Nat\), so we use subtyping to forget that \(5\) is positive.
Subtyping Functions
This is bonus material. While our subtyping judgment right now only relates numeric types, we can extend it to handle function types as well. For example, the below should type check:
\[ (\lambda f : \Nat \to \Nat.\ f\ 5)\ (\lambda x : \Nat.\ x + 1) \] Currently, this does not type check under our current rules. Why is this? Because while the first argument expects a function of type \(\Nat \to \Nat\), the right-hand side type checks under \(\Nat \to \Pos\), which is not the same. While we could force the second function to have type \(\Nat \to \Nat\), by using (T-Sub) inside of the function’s body, doing so is non-compositional; indeed, we are now changing the second function’s type just to make it work with the first one. Instead, we can make subtyping work for functions:
\[ \dfrac{\tau’_i <: \tau_i \quad \tau_o <: \tau’_o} {(\tau_i \to \tau_o) <: (\tau’_i \to \tau’_o)}\ \text{(Sub-Fun)} \]
This typing rule deserves some explanation. Recall that if \(\tau_i \to \tau_o\) is a subtype of \(\tau’_i \to \tau’_o\), then every variable of the first function type should work in the place where the second one is required. Let’s see some examples:
- \((\Nat \to \Pos) <: (\Nat \to \Nat)\). This makes sense, because every \(\Pos\) is a \(\Nat\), and thus the function’s output can be coerced to the bigger type.
- \((\Pos \to \Nat) <: (\Nat \to \Nat)\)? This does not make sense! Let’s see an example why. Consider the function \(\lambda y : \Pos.\ 10\ /\ y\), which has type \(\Pos \to \Nat\). If this subtyping held, then (T-Sub) would let the following program type check: \[ (\lambda g : \Nat \to \Nat.\ g\ 0)\ (\lambda y : \Pos.\ 10\ /\ y) \] But this program steps to \((\lambda y : \Pos.\ 10\ /\ y)\ 0\), and then to \(10\ /\ 0\), which is stuck. So our type system would be unsound.
- However, \((\Nat \to \Nat) <: (\Pos \to \Nat)\) does make sense. For example, consider: \[ (\lambda g : \Pos \to \Nat.\ g\ 3)\ (\lambda x : \Nat.\ x + x) \] Any context expecting a \(\Pos \to \Nat\) function will only ever pass it \(\Pos\) arguments. Since every \(\Pos\) is a \(\Nat\), a function accepting any \(\Nat\) can handle them.
Thus, we see that when subtyping functions, we have that the output types need to subtype left-to-right, while the input types need to subtype right-to-left.
Sum Types
Let’s back up to STLC again:
\[ \tau ::= \Nat \mid \tau \to \tau \]
We will now investigate a different solution to our problem with division. Instead of using the type system to prove that division is safe, we will instead add extra types to allow division to become checked: if we try to divide, we will get an error that we can recover from. In particular, we will implement option types, making division now look like this:
divide : Nat -> Nat -> Option Nat
When we use division, we need to explicitly case split on whether division succeeded or not. For example, suppose we want to try to divide two numbers, and return 1234 if division fails. We can do it like this:
fun (x : Nat) (y : Nat) =>
case divide x y of
| Some v => v
| None => 1234
To actually implement option types in the STLC, we will implement a more fundamental concept: sum types, which look like \( \tau_1 + \tau_2\). The basic idea is that a value of type \(\tau_1 + \tau_2\) is a tagged value of the form \(\texttt{inl}\ v\), where \(v \in \tau_1\), or \(\texttt{inr}\ v\), where \(v \in \tau_2\).
We can implement option types using sum types, because we can also have a type for Unit (whose value is written ()), which stands for “no information”. Hence, we can then define
\[ \texttt{Option}\ \tau \mathrel{\overset{\text{def}}{=}} \tau + \texttt{Unit} \]
Then, the calculus will allow us to case split on if the value is inl (in which case it is Some), or inr (in which case it is None).
Sum Types in Lait
Whenever you use a type declaration with multiple constructors, you are using a sum type. For example: the type
type IntOrBool := | CInt (val : Int) | CBool (val : Bool)
can be represented using the sum type \(\texttt{Int} + \texttt{Bool}\). If we have three cases, it can be interpreted as a nested sum:
type OneOfThree := | First (val : Int) | Second (val : Int) | Third (val : Int)
desugars to \(\texttt{Int} + \texttt{Int} + \texttt{Int}\). Now, if we have a simple enumerated type, such as
type Color := | Red | Green | Blue
this would be represented as a nested sum of units: \(\texttt{Unit} + \texttt{Unit} + \texttt{Unit}\).
However, note that sum types are not enough to reconstruct type defintions in Lait. If we have a recursive type, such as
type MyList := | MNil | MCons (val : Int) (res : MyList)
then we cannot represent this with a sum type alone; however, we can using a recursive type, which we may cover later.
Sum Types, Formally
Let’s now make it formal. Our types will now look like so:
\[ \tau ::= \Nat \mid \tau \to \tau \mid \tau + \tau \mid \texttt{Unit} \] while our expressions are going to include new ways of: introducing and eliminating sum types, via pattern matching; and introducing the Unit type:
\[ e ::= x \mid n \mid () \mid \lambda x : \tau.\ e \mid e\ e \mid e + e \mid e\ /\ e \mid \texttt{inl}\ e \mid \texttt{inr}\ e \mid \mathsf{case}\ e\ \mathsf{of}\ \{\texttt{inl}\ x \Rightarrow e;\ \texttt{inr}\ y \Rightarrow e\} \]
Let’s now see the new typing rules needed for Unit and sum types, before seeing how we can model checked division.
First, the unit value \(()\) always has type \(\texttt{Unit}\):
\[ \dfrac{}{\Gamma \vdash () : \texttt{Unit}}\ \text{(T-Unit)} \]
Next, we introduce sum types by tagging a value with \(\texttt{inl}\) or \(\texttt{inr}\):
\[ \dfrac{\Gamma \vdash e : \tau_1}{\Gamma \vdash \texttt{inl}\ e : \tau_1 + \tau_2}\ \text{(T-Inl)} \qquad \dfrac{\Gamma \vdash e : \tau_2}{\Gamma \vdash \texttt{inr}\ e : \tau_1 + \tau_2}\ \text{(T-Inr)} \]
Note that in (T-Inl), the type \(\tau_2\) does not appear in the premise: we are free to pick any \(\tau_2\) we like. (Similarly for \(\tau_1\) in (T-Inr).) This means that these rules are not syntax-directed; real type checkers fix this either by asking for a type annotation, or by inferring \(\tau_2\) from how the expression is used.
Finally, we eliminate sum types by case splitting. Both branches must have the same type \(\tau\), since we don’t know statically which branch will run:
\[ \dfrac{\Gamma \vdash e : \tau_1 + \tau_2 \quad \Gamma, x : \tau_1 \vdash e_1 : \tau \quad \Gamma, y : \tau_2 \vdash e_2 : \tau} {\Gamma \vdash \mathsf{case}\ e\ \mathsf{of}\ \{\texttt{inl}\ x \Rightarrow e_1;\ \texttt{inr}\ y \Rightarrow e_2\} : \tau}\ \text{(T-Case)} \]
Now, let’s see the rule for a checked division:
\[ \dfrac{\Gamma \vdash e_1 : \Nat \quad \Gamma \vdash e_2 : \Nat} {\Gamma \vdash e_1\ /\ e_2 : \Nat + \texttt{Unit}}\ \text{(T-Div-Checked)} \]
Correspondingly, division now never gets stuck at runtime. Instead, it returns \(\texttt{inl}\) of the result on success, and \(\texttt{inr}\ ()\) on division by zero:
\[ \dfrac{}{n_1\ /\ n_2 \rightarrow \texttt{inl}\ n}\ \text{(E-Div-Ok)} \quad \text{where } n_2 \neq 0 \text{ and } n = \lfloor n_1 \div n_2 \rfloor \qquad \dfrac{}{n_1\ /\ 0 \rightarrow \texttt{inr}\ ()}\ \text{(E-Div-Zero)} \]
And now we can see our example function from before, implemented in our calculus:
\[
\lambda x : \Nat.\ \lambda y : \Nat.
\mathsf{case}\ x\ /\ y\ \mathsf{of}\ \{\texttt{inl}\ v \Rightarrow v;\ \texttt{inr}\ z \Rightarrow 1234\}
\]
This has type \(\Nat \to \Nat \to \Nat\): in the \(\texttt{inl}\) branch we have \(v : \Nat\), while in the \(\texttt{inr}\) branch we have \(z : \texttt{Unit}\), which we ignore.
Dynamic Semantics of Sum Types
Now, we need to give stepping rules to sum types.
First, we need to let values step through inl and inr:
\[ \dfrac{e \rightarrow e’}{\texttt{inl}\ e \rightarrow \texttt{inl}\ e’}\ \text{(E-Inl)} \qquad \dfrac{e \rightarrow e’}{\texttt{inr}\ e \rightarrow \texttt{inr}\ e’}\ \text{(E-Inr)} \]
Now, when giving semantics to case, we have it behave like an if/then/else, with the exception that we also need to
substitute in a new value when we pattern match.
\[ \begin{gathered} \dfrac{e \rightarrow e’} {\mathsf{case}\ e\ \mathsf{of}\ \{\texttt{inl}\ x \Rightarrow e_1;\ \texttt{inr}\ y \Rightarrow e_2\} \rightarrow \mathsf{case}\ e’\ \mathsf{of}\ \{\texttt{inl}\ x \Rightarrow e_1;\ \texttt{inr}\ y \Rightarrow e_2\}}\ \text{(E-Case)} \\[1.5em] \dfrac{} {\mathsf{case}\ (\texttt{inl}\ v)\ \mathsf{of}\ \{\texttt{inl}\ x \Rightarrow e_1;\ \texttt{inr}\ y \Rightarrow e_2\} \rightarrow e_1[x \mapsto v]}\ \text{(E-Case-Inl)} \\[1.5em] \dfrac{} {\mathsf{case}\ (\texttt{inr}\ v)\ \mathsf{of}\ \{\texttt{inl}\ x \Rightarrow e_1;\ \texttt{inr}\ y \Rightarrow e_2\} \rightarrow e_2[y \mapsto v]}\ \text{(E-Case-Inr)} \end{gathered} \]
Note that values of sum types are now \(\texttt{inl}\ v\) and \(\texttt{inr}\ v\), where \(v\) is itself a value.
Encoding Booleans via Sum Types
A central theme of this course is that many programming concepts can be implemented in more expressive concepts.
Here, we will see that once we have a Unit type and sum types, we can implement booleans. To do this requires: defining the Bool type; defining expressions for true/false, and ensuring they have the correct types; as well as implementing if/then/else.
Observe that values of type Bool encode a single choice: either true or false. We can encode the same using a sum type, where both sides are Unit:
\[ \texttt{Bool} \mathrel{\overset{\text{def}}{=}} \texttt{Unit} + \texttt{Unit} \]
We can then define true and false accordingly:
\[ \texttt{true} \mathrel{\overset{\text{def}}{=}} \texttt{inl}\ () \qquad \texttt{false} \mathrel{\overset{\text{def}}{=}} \texttt{inr}\ () \]
Observe that, by unfolding definitions, we have that \(\vdash \texttt{true} : \texttt{Bool}\) by (T-Unit) and (T-Inl); similarly, \(\vdash \texttt{false} : \texttt{Bool}\). Finally, we can define if/then/else as follows:
\[ (\mathsf{if}\ e\ \mathsf{then}\ e_1\ \mathsf{else}\ e_2) \mathrel{\overset{\text{def}}{=}} (\mathsf{case}\ e\ \mathsf{of}\ \{\texttt{inl}\ \_ \Rightarrow e_1;\ \texttt{inr}\ \_ \Rightarrow e_2\}) \]
Observe that \((\mathsf{if}\ \texttt{true}\ \mathsf{then}\ e_1\ \mathsf{else}\ e_2) \to e_1\) by (E-Case-Inl).
By unfolding definitions, we can prove a derived typing rule for our version of if/then/else: \[ \dfrac{\Gamma \vdash e : \texttt{Bool} \quad \Gamma \vdash e_1 : \tau \quad \Gamma \vdash e_2 : \tau} {\Gamma \vdash \mathsf{if}\ e\ \mathsf{then}\ e_1\ \mathsf{else}\ e_2 : \tau}\ \text{(T-If)} \]
Product Types
Dual to sum types are product types, which let you put two pieces of information together into a single value. Given two types \(\tau_1\) and \(\tau_2\), the product type \(\tau_1 \times \tau_2\) contains all tuples of the form \( (v_1, v_2) \) where \(v_1\) is in \(\tau_1\) and \(v_2\) is in \(\tau_2\).
Product Types in Lait Observe that Lait has product types, as do most functional programming languages:
def p := (true, 3)
#eval fst p>> true
#eval snd p>> 3
Product types are the simplest way to model compound data. For example, if we have the following struct in C:
struct User {
int id;
char username[50];
float balance;
}
We can think of this as being modeled (roughly) by a nested product type \(\texttt{Int} \times (\texttt{char[50]} \times \texttt{float}) \).
Product Types, Formally Hence, we will again extend our type grammar:
\[ \tau ::= \Nat \mid \tau \to \tau \mid \tau + \tau \mid \tau \times \tau \mid \texttt{Unit} \]
Then we will extend our expressions to have tuples, along with a way of reading from the first or second component of a tuple:
\[ e ::= \dots \mid (e, e) \mid \mathsf{fst}\ e \mid \mathsf{snd}\ e \]
Below are the relevant typing rules:
\[ \dfrac{\Gamma \vdash e_1 : \tau_1 \quad \Gamma \vdash e_2 : \tau_2} {\Gamma \vdash (e_1, e_2) : \tau_1 \times \tau_2}\ \text{(T-Pair)} \]
\[ \dfrac{\Gamma \vdash e : \tau_1 \times \tau_2} {\Gamma \vdash \mathsf{fst}\ e : \tau_1}\ \text{(T-Fst)} \qquad \dfrac{\Gamma \vdash e : \tau_1 \times \tau_2} {\Gamma \vdash \mathsf{snd}\ e : \tau_2}\ \text{(T-Snd)} \]
The dynamic semantics of products will encode that \( (v_1, v_2) \) is a value whenever \( v_1\) and \(v_2\) are both values. Below are the most important rules for products:
\[ \dfrac{}{\mathsf{fst}\ (v_1, v_2) \rightarrow v_1}\ \text{(E-Fst)} \qquad \dfrac{}{\mathsf{snd}\ (v_1, v_2) \rightarrow v_2}\ \text{(E-Snd)} \]
The rest of the stepping rules (e.g., what happens if we have a general \((e_1, e_2)\) follow our recipe from before.
Exercise. Write down the rest of the stepping rules for products. We will get two extra rules for stepping tuples, and one extra rule each for \(\mathsf{fst}\) and \(\mathsf{snd}\).
The Algebra of Algebraic Types
Put together, sum types and product types form a very simple model of algebraic data types, which is the way that Lait models data types. For example, let’s now consider the following type in Lait:
type Shape := | Rect (width : Int) (height : Int) | Circle (radius : Int)
This can be modeled via the following type: \[ (\texttt{Int} \times \texttt{Int}) + (\texttt{Int}) \]
You might be wondering: why are they called sum and product types? There is a very fun correspondence between sum and product types and ordinary sums and products on numbers. Let’s have a very minimal type grammar:
\[ \tau ::= \texttt{Unit} \mid \tau \to \tau \mid \tau + \tau \mid \tau \times \tau \]
We will consider an ordinary STLC that has unit, sums, products, and functions:
\[ e ::= x \mid () \mid \lambda x:\tau. e \mid e\ e \mid (e, e) \mid \mathsf{fst}\ e \mid \mathsf{snd}\ e \mid \mathsf{inl}\ e \mid \mathsf{inr}\ e \mid \mathsf{case}\ e\ \mathsf{of}\ \{\texttt{inl}\ x \Rightarrow e;\ \texttt{inr}\ y \Rightarrow e\} \]
Now, let’s think about the possible closed programs \(e\) that inhabit each type; that is, given a type \(\tau\), which programs \(e\) are such that \(\vdash e : \tau\)? A remarkable fact is that, up to observational equivalence (discussed in Lecture 5), there are only finitely many closed terms of each type! Moreover, we can count them: for each type \(\tau\), we can compute its cardinality \(|\tau|\).
First, consider Unit. Up to the number of steps the program takes, there is really only one program, (), that inhabits Unit. Other programs, such as (fun x : Int => ()) 5 also have type Unit, but they are observationally equivalent: meaning that the only observable difference between them is the number of steps they take to reach a value.
Put another way, in our calculus the cardinality of the Unit type is just 1:
\[ |\texttt{Unit}| = 1 \]
Now, consider \(\tau_1 \times \tau_2\). How many programs inhabit \(\tau_1 \times \tau_2\)? Well, values of this type are pairs of programs that inhabit \(\tau_1\) and \(\tau_2\), respectively. This means that the cardinality of the product type is the product of the cardinalities:
\[ |\tau_1 \times \tau_2| = |\tau_1| \times |\tau_2|\]
Next, consider \(\tau_1 + \tau_2\). This is where we can think about nontrivial cardinalities.
Consider Unit + (Unit + Unit). How many values are there here? There are three: inl (), inr (inl ()), and inr (inr ()). This means that the cardinality of the sum is the sum of the cardinalities:
\[ |\tau_1 + \tau_2| = |\tau_1| + |\tau_2|\]
Exercise. Remember that we can define Bool = Unit + Unit. What is the cardinality of Bool?
Exercise. What is the cardinality of (Bool + Bool) * Bool? Can you write down all of the values of this type?
Finally, consider function types. It turns out that, in our minimal calculus with finite types, the cardinality of the function type is the exponent of the cardinalities:
\[ |\tau_1 \to \tau_2| = |\tau_2|^{|\tau_1|} \]
To gain intuition for this, consider enumerating all of the possible functions from Bool + Unit to Bool.
For each value in the domain, we can either assign it false or true. Hence, there are \(2^3 = 8\) possible functions total.
Exercise. What is the cardinality of (Bool -> Bool) -> Bool?
Polymorphism and System F
So far, we have only studied simple types, such as Int -> Int, Nat + Bool, or Ref (Int -> Int). What makes these types simple is that they do not support polymorphism, which we will now discuss.
import Lait
#lait
\[ \newcommand{\Nat}{\texttt{Nat}} \newcommand{\List}{\texttt{List}} \]
Polymorphism in Programming Languages
Simply put, polymorphism allows you to write functions that work at multiple types. Already in the lambda calculus, you have been working with a simple example of this: the identity function \(\lambda x. x\). While this function should be able to take in a value of any type, embedding it into STLC requires you to pick a particular type for \(x\), while a polymorphic calculus allows the caller itself to pick the type.
This kind of polymorphism exists in many languages. In Java:
public static <T> T identity(T x) {
return x;
}
In OCaml:
let id (x : 'a) : 'a = x;;
And in Lait:
def id (x : a) : a := x
Parametric vs Ad-Hoc Polymorphism
This style of polymorphism, which we will study, is called parametric polymorphism. This means that we have a single piece of code that works at multiple types. This is essential for code reuse; for example,
allowing you to map over a list of type List<Nat> as well as a list of type List<Bool>.
Parametric polymorphism is in contrast to ad-hoc polymorphism, where the type itself also specifies code that we should run. Typically, ad-hoc polymorphism means that a type is equipped with a record that specifies the operations the type allows you to do. An example would be interfaces in Java:
public interface Printable {
void print();
}
class Text implements Printable {
private String content;
public Text(String content) {
this.content = content;
}
@Override
public void print() {
System.out.println("Printing: " + content);
}
}
public class Main {
public static void printItem(Printable item) {
item.print();
}
public static void Main(String[] args) {
Printable o = new Text("Hello");
printItem(o);
}
}
Traits and type classes in Rust and Haskell are other examples of ad-hoc polymorphism. Today, while we will study parametric polymorphism, we will see how ad-hoc polymorphism can be encoded.
System F
To study parametric polymorphism, we will design, implement, and study a small language. This language is called System F.
The idea of System F is to extend the simply-typed lambda calculus with the following features:
-
Type Abstraction. We need a way for functions to take in types, as well as values, like the polymorphisc identity function in Java. In our syntax, we will write the polymorphic identity function as follows: \[ \texttt{Id} := \Lambda X. (\lambda x : X.\ x) \] Here, we introduce a new kind of lambda abstraction, \(\Lambda X\), that abstracts over type variables, in constrast to \(\lambda x\), which abstracts over term variables. Thus, the function says “take in a type
X; then, take in a valuexof typeX; then, returnX.” This is almost 1-1 with the Java identity example. -
Type Application. Now that we have a polymorphic identity function, we need to use it. Just like how type abstraction parallels ordinary abstraction over values, type application will behave the same way. We use the following notation for type application: \[ \texttt{id-nat} := \texttt{Id} [\texttt{Nat}] = (\Lambda X. (\lambda x : X.\ x)) [\texttt{Nat}] \] Above, we will have that
id-nathas the type we expect:Nat -> Nat. We write type application in square brackets to distinguish it from ordinary application. -
Universal Types. For this all to work out, we need our polymorphic identity \(\texttt{Id}\) to have a type as well. To do this, we introduce a new kind of type: universal types, written \(\forall X. t\) (read “for all X, t”), where
Xis a type identifier andtis a type that can make reference toX. This allows us to give the following type to \(\texttt{Id}\): \[ \texttt{Id} =\Lambda X. (\lambda x : X.\ x) : \forall X. X \to X\] You should think of \(\forall X. X \to X\) as like a “type-level lambda”: it is a type that, once given a type for X, gives you back a new type. For example, feeding it \(\texttt{Nat}\) gives you back \(\texttt{Nat} \to \texttt{Nat}\).
We can now specify the surface syntax of System F. For the purpose of having interesting examples, we will also throw in numbers and addition:
\[ \begin{align*} \text{Expressions}\ e ::=\ &x \mid n \mid \lambda x : \tau. e \mid e\ e\ \ \ \ &&\text{Inherited from STLC} \\ &\mid \Lambda X. e &&\text{Type abstraction} \\ &\mid e\ [\tau] &&\text{Type application} \\ \text{Types}\ \tau ::=\ &\texttt{Nat} \mid \tau \to \tau \ \ \ &&\text{Inherited from STLC} \\ & \mid \forall X. \tau &&\text{Forall-types} \\ & \mid X &&\text{Type variables} \end{align*} \]
System F Semantics
The semantics of System F is very similar to STLC. The main difference is that type abstraction and type application interact via beta reduction, similar to ordinary functions. Let’s see how \(\texttt{id-nat}\) from above evaluates, when we apply it to an argument: \[ ((\Lambda X. (\lambda x : X.\ x)) [\texttt{Nat}]) 10 \xrightarrow{\text{Substitute Nat}} (\lambda x : \texttt{Nat}. x) 10 \xrightarrow{\text{Substitute 10}} 10 \]
A more interesting example is a “call-twice” function which takes a type variable X, a function f : X -> X, a value x : X and returns f (f x):
\[
\texttt{calltwice} = \Lambda X. \lambda f : X \to X. \lambda x : X. f (f x)
\]
Let’s see it evaluate on numbers:
\[ \begin{align*} \texttt{calltwice}\ [\texttt{Nat}]\ (\lambda x : \texttt{Nat}. x + 1)\ 5 &= (((\Lambda X. \lambda f : X \to X. \lambda x : X. f (f x))\ [\texttt{Nat}])\ (\lambda x : \texttt{Nat}. x + 1))\ 5 \\ &\to ((\lambda f : \Nat \to \Nat. \lambda x : \Nat. f (f x))\ (\lambda x : \texttt{Nat}. x + 1))\ 5 \\ &\to (\lambda x : \Nat. (\lambda x : \Nat. x + 1) ((\lambda x : \Nat. x + 1)\ x))\ 5 \\ &\to (\lambda x : \Nat. x + 1) ((\lambda x : \Nat. x + 1)\ 5) \\ &\to \dots \\ &\to 7 \end{align*} \]
System F Types
The ruels for the type system of System F are quite similar to STLC. The difference is that we need to keep track of type variables as well as term variables. To that end, we will have the typing judgment of System F have two contexts: one for type variables, and one for term variables. The judgment looks like this: \[ \Delta; \Gamma \vdash e : \tau \]
Above, the context \(\Gamma\) is just like before: it maps term variables to types. The new context \(\Delta\) is a set of type variables, and only exists to ensure that each type variable is in scope. The types inside of \(\Gamma\) can make reference to the type variables in \(\Delta\).
Let’s now see the rules:
\[ \dfrac{}{\Delta; \Gamma \vdash n : \Nat}\ \text{(T-Num)} \qquad \dfrac{\Delta; \Gamma \vdash e_1 : \Nat \quad \Delta; \Gamma \vdash e_2 : \Nat} {\Delta; \Gamma \vdash e_1 + e_2 : \Nat}\ \text{(T-Add)} \]
\[ \dfrac{(x : \tau) \in \Gamma} {\Delta; \Gamma \vdash x : \tau}\ \text{(T-Var)} \]
\[ \dfrac{\Delta; \Gamma, x : \tau_1 \vdash e : \tau_2} {\Delta; \Gamma \vdash \lambda x : \tau_1.\ e : \tau_1 \to \tau_2}\ \text{(T-Lam)} \qquad \dfrac{\Delta; \Gamma \vdash e_1 : \tau_1 \to \tau_2 \quad \Delta; \Gamma \vdash e_2 : \tau_1} {\Delta; \Gamma \vdash e_1\ e_2 : \tau_2}\ \text{(T-App)} \]
\[ \dfrac{\Delta; X; \Gamma \vdash e : \tau} {\Delta; \Gamma \vdash \Lambda X.\ e : \forall X.\ \tau}\ \text{(T-TLam)} \qquad \dfrac{\Delta; \Gamma \vdash e : \forall X.\ \tau_1 \quad \Delta \vdash \tau_2\ \text{ok}} {\Delta; \Gamma \vdash e\ [\tau_2] : \tau_1[X := \tau_2]}\ \text{(T-TApp)} \]
All of the rules except for (T-TLam) and (T-TApp) are the same as STLC, except for the added context. The rule for \(\Lambda X. e\), (T-TLam), states that we type check \(e\), and then bind the free type variable \(X\) under a \(\forall\). This rule is directly analogous to (T-Lam).
The rule for type application, (T-TApp), states that if \(e\) has type \(\forall X.\ \tau_1\), then \(e[\tau_2]\) has the inner type \(\tau_1\), but with \(\tau_2\) substituted for \(X\). (Note here that we are using square brackets for substitution as well as type application.) This rule requires an auxiliary judgment, \(\Delta \vdash \tau\ \text{ok}\), which enforces that all free type variables are in scope according to Delta.
\[ \dfrac{}{\Delta \vdash \Nat\ \text{ok}}\ \text{(Ok-Nat)} \qquad \dfrac{\Delta \vdash \tau_1\ \text{ok} \quad \Delta \vdash \tau_2\ \text{ok}} {\Delta \vdash \tau_1 \to \tau_2\ \text{ok}}\ \text{(Ok-Arrow)} \]
\[ \dfrac{X \in \Delta} {\Delta \vdash X\ \text{ok}}\ \text{(Ok-Var)} \qquad \dfrac{\Delta, X \vdash \tau\ \text{ok}} {\Delta \vdash \forall X.\ \tau\ \text{ok}}\ \text{(Ok-Forall)} \]
Example typing judgment. Let’s now see how our example \(\texttt{calltwice}\) is well-typed. First, let’s see the typing derivation for \(\texttt{calltwice}\) itself. First, let’s type the body of calltwice under the type abstraction, with the free type variable \(X\) in scope:
\[ X; \emptyset \vdash \lambda f : X \to X.\ \lambda x : X.\ f\ (f\ x) : (X \to X) \to X \to X \]
Now, we can type check calltwice by closing off the inner body under a type abstraction, which removes the free type variable from our context:
\[ \dfrac{\rlap{X}\hphantom{\emptyset}; \emptyset \vdash \hphantom{\Lambda X.\ }\lambda f : X \to X.\ \lambda x : X.\ f\ (f\ x) : \hphantom{\forall X.\ }(X \to X) \to X \to X} {\emptyset; \emptyset \vdash \Lambda X.\ \lambda f : X \to X.\ \lambda x : X.\ f\ (f\ x) : \forall X.\ (X \to X) \to X \to X}\ \text{(T-TLam)} \]
Now, we can apply calltwice to the type Nat:
\[ \dfrac{\emptyset; \emptyset \vdash \texttt{calltwice} : \forall X.\ (X \to X) \to X \to X \quad \emptyset \vdash \Nat\ \text{ok}} {\emptyset; \emptyset \vdash \texttt{calltwice}\ [\Nat] : ((X \to X) \to X \to X)[X := \Nat] = (\Nat \to \Nat) \to \Nat \to \Nat}\ \text{(T-TApp)} \]
System F Types Constrain Implementations
A remarkable fact about System F is that we can infer a lot about terms just based on their types. For example, consider the polymorphic identity function:
\[ \begin{align*} \vdash \texttt{Id} &: \forall X.\ X \to X \\ \texttt{Id} &:= \Lambda X.\ \lambda x : X.\ x \end{align*} \]
Now, here is the cool part: are there any other implementations of \(\forall X. X \to X\) (up to observational equivalence)? It turns out there are not! There is only one. This is due to the fact that \(X\) is an abstract type variable. The implementation must return and \(X\), and it is only given an \(X\); hence, the only thing it can do is return the one it is given.
Following the same logic, let’s now implement Booleans in System F:
\[
\begin{align*}
\texttt{Bool} &:= \forall X. X \to X \to X \\
\texttt{false} &:= \Lambda X.\ \lambda x : X.\ \lambda y : X.\ y \
\texttt{true} &:= \Lambda X.\ \lambda x : X.\ \lambda y : X.\ x
\end{align*}
\]
By the same logic as above, we can see that the two Church booleans are the only possible implementations of the type \(\texttt{Bool}\).
Exercise. What are the possible implementations (if any) of \(\forall X.\ X\)?
Church Numerals in System F
You might have noticed something interesting about our \(\texttt{calltwice}\) example: if you look at the implementation of \(\texttt{calltwice}\), it looks suspiciously similar to the Church numeral for two: \(\lambda f. \lambda x. f\ (f x)\). This is not an accident! Indeed, unlike STLC, the Church numerals can be encoded into System F.
Let’s now derive typed Church numerals in general.
The basic idea is that we want to think of a number as how it behaves under iteration: given a function f and an argument x, the numeral for N will apply f to x N times. Since the type of x is arbitrary, we abstract over it. Hence, Church numerals in System F are values of the following type:
\[ \forall X.\ (X \to X) \to X \to X \]
Let’s see some examples:
\[ \begin{align*} \text{zero} &:= \Lambda X. \lambda f : X \to X. \lambda x : X. x \\ \text{one} &:= \Lambda X. \lambda f : X \to X. \lambda x : X. f x \\ \text{two} &:= \Lambda X. \lambda f : X \to X. \lambda x : X. f (f x) \\ & \dots \end{align*} \]
Values of this type are in one-to-one correspondence with actual natural numbers. Let’s see this:
From natural numbers to Church. Suppose we have a natural number N (say, 5). Then, we can create a term that applies f to x that many times:
\[ \text{five} := \Lambda X. \lambda f : X \to X. \lambda x : X. f\ (f\ (f\ (f\ (f\ x)))) \]
From Church to natural numbers. Suppose we have a value \(n : \forall X.\ (X \to X) \to X \to X\). Because we can choose any type for \(X\), we can choose \(Nat.\) This allows us to then plug in \((\lambda x: Nat. x + 1)\) for the first argument, and \(0\) for the second argument. This gives us back a closed term of type \(\Nat\) which will evaluate to the corresponding natural number.
Programming with Lists
It turns out that System F is excellent at representing all kinds of data types, and not just Church numerals. Let’s now see how lists work in System F. Similar to Church numerals, the way we represent lists is through their behavior. For natural numbers, the canonical behavior is iterating a functions; for lists, it will be a fold. First, let’s see how folds work in Lait:
def fold(xs : List<t>) (nilCase : r) (consCase : t -> r -> r) : r :=
match xs with
| [] => nilCase
| x :: xs' => consCase x (fold xs' nilCase consCase)
You can think of fold as a generic form of pattern match, where we abstract the body of the pattern match by functions.
This, for example, allows us to sum a list, by setting t = Int and r = Int:
def sumList (xs : List<Int>) := fold xs 0 (fun x => fun acc => x + acc)
#eval sumList [1, 2, 3]>> 6
Now, here’s the magic trick: every list xs : List<t> is in one-to-one correspondence with its fold, of type forall r. r -> (t -> r -> r) -> r. We get xs’s fold by partially applying xs to the fold function. We can see this correspondence play out in Lait.
From lists to a folding function. This direction is trivial: take a list xs : List<t>, and output fold xs:
def list_to_fold (xs : List<t>) := fold xs
#check list_to_fold [1, 2, 3]>> a -> (Int -> a -> a) -> a
See that list_to_fold [1, 2, 3] has type a -> (Int -> a -> a) -> a. In Lait, type variables are implicitly universally quantified; thus, this type corresponds to the System F type \(\forall R.\ R \to (\texttt{Int} \to R to R) \to R\).
From folding functions to lists. This is the trick that is analogous with going back from Church numerals to numbers. We have a function of type r -> (Int -> r -> r) -> r, and we want to turn it back into a list of type List<Int>. How to do so? By setting r := List<Int>, and supplying nil and cons to the folding function:
def recovered_list :=
(list_to_fold [1, 2, 3]) [] (fun x => fun acc => x :: acc)
#eval recovered_list>> Cons 1 (Cons 2 (Cons 3 Nil))
Lists in System F. Now that we have a bijection between lists and an appropriate polymorphic function, we can define lists in System F by this function:
\[ \texttt{List}\ \tau := \forall R.\ R \to (\tau \to R \to R) \to R. \]
Pattern matching over the list just becomes applying the “list” to an appropriate return type, nil case, and cons case.
To actually build up a list requires inventing a folding function. First, let’s do nil:
\[ \begin{align*} \vdash \texttt{nil}_\tau &: \List\ \tau \\ \texttt{nil}_\tau &:= \Lambda R.\ \lambda n : R.\ \lambda c : (\tau \to R \to R). n \end{align*} \]
The nil value simply returns the “nil” case of the folding function. Now, let’s do cons:
\[ \begin{align*} \vdash \texttt{cons}_\tau &: \tau \to \List\ \tau \to \List\ \tau \\ \texttt{cons}_\tau &:= \lambda x : \tau.\ \lambda xs : \List\ \tau. \\ &\qquad \Lambda R.\ \lambda n : R.\ \lambda c : (\tau \to R \to R). \\ &\qquad\qquad c\ x\ (xs\ [R]\ n\ c) \end{align*} \]
The implementation of cons x xs creates a folding function that first calls the folding function for xs, and then applies the cons case to it.
Product and Sum Types in System F
Now that we’ve seen Church numerals and lists, we can see how the technique generalizes to product and sum types.
Product Types in System F
A pair p : t1 * t2 is in bijection with all of the ways we can pattern match on it. Hence, we can define pairs via their pattern matches.
A pattern match on a pair has one arm which takes both values.
In Lait, it looks like this:
type MyProd<a, b> := | MkMyProd (x : a) (y : b)
def matchMyProd(p : MyProd<a, b>) (f : a -> b -> r) : r :=
match p with
| MkMyProd x y => f x y
end
Which means that it looks as follows in System F:
\[ \texttt{Prod}_{\tau_1, \tau_2} := \forall R.\ (\tau_1 \to \tau_2 \to R) \to R \]
We can then construst pairs by implementing the pattern match.
\[ \begin{align*} \vdash \texttt{pair}_{\tau_1, \tau_2} &: \tau_1 \to \tau_2 \to \texttt{Prod}_{\tau_1, \tau_2} \\ \texttt{pair}_{\tau_1, \tau_2} &:= \lambda x : \tau_1.\ \lambda y : \tau_2.\ \Lambda R.\ \lambda f : (\tau_1 \to \tau_2 \to R). f\ x\ y \end{align*} \]
Sum Types in System F
A sum type v : t1 + t2 can be pattern matched on by two arms, each of which takes one value. In Lait, that looks like this:
type Sum<a, b> := | Inl (x : a) | Inr (y : b)
def matchSum(p : Sum<a, b>) (f : a -> r) (g : b -> r) : r :=
match p with
| Inl x => f x
| Inr y => g y
end
Which means that sums have the following type in System F:
\[ \texttt{Sum}_{\tau_1, \tau_2} := \forall R.\ (\tau_1 \to R) \to (\tau_2 \to R) \to R\]
We can then construct elements of a sum type by calling the appropriate functions:
\[ \begin{align*} \vdash \texttt{inl}_{\tau_1, \tau_2} &: \tau_1 \to \texttt{Sum}_{\tau_1, \tau_2} \\ \texttt{inl}_{\tau_1, \tau_2} &:= \lambda x : \tau_1.\ \Lambda R.\ \lambda f : (\tau_1 \to R).\ \lambda g : (\tau_2 \to R). f\ x \\ \\ \vdash \texttt{inr}_{\tau_1, \tau_2} &: \tau_2 \to \texttt{Sum}_{\tau_1, \tau_2} \\ \texttt{inr}_{\tau_1, \tau_2} &:= \lambda y : \tau_2.\ \Lambda R.\ \lambda f : (\tau_1 \to R).\ \lambda g : (\tau_2 \to R). g\ y \end{align*} \]
Enabling Ad-Hoc Polymorphism
Let’s consider an interface in Java called Show:
interface Show {
String show();
}
class Main {
public static String WithBraces(Show t) {
String x = t.show();
return "{" + x + "}";
}
}
We can think of WithBraces as a polymorphic function that takes in an arbitrary value t of an arbitrary type T, so long as T implements the Show interface. We can implement this in a language with parametric polymorphism by passing around a field that holds the stuff that T needs to implement:
\[ \texttt{Show}_\tau := \tau \to \texttt{String} \]
(If Show had multiple fields, we could put them together by using a product type.)
Then, we can implement WithBraces by taking in the type T and a value t : T, along with the \(\texttt{Show}\) field:
\[ \begin{align*} \vdash \texttt{WithBraces} &: \forall T.\ \texttt{Show}_T \to T \to \texttt{String} \\ \texttt{WithBraces} &:= \Lambda T.\ \lambda f : \texttt{Show}_T.\ \lambda x : T. \\ &\qquad \texttt{"\{"} \mathbin{\texttt{++}} f\ x \mathbin{\texttt{++}} \texttt{"\}"} \end{align*} \]
More about System F
import Lait
#lait
System F and Other Polymorphic Languages
Now, we have seen System F, and we have also been working with Lait, another polymorphic language. How do they relate?
One big difference is the lack of needing to explicitly annotate types. In Lait, we can do the following:
def calltwice f x := f (f x)
#eval calltwice (fun x => x + 1) 5>> 7
Lait then correctly infer that this function has type (a -> a) -> a -> a, which in System F would translate to \(\forall X. (X \to X) \to X \to X\).
Comparing this version of calltwice to our version in System F, we see that Lait doesn’t require explicit type variable quantification or application.
What is going on here? We can see that Lait is performing type inference: the
act of assigning a type to code which does not have all type information in the
source. To model this formally, one can imagine a variant of System F where explicit type abstraction and application isn’t present in surface terms, but instead needs to be guessed in the type checker. Thus, under this calculus, we would instead see a judgment for calltwice like so:
\[
\vdash \lambda f.\ \lambda x.\ f\ (f x) : \forall X. (X \to X) \to X \to X
\]
Unfortunately, J.B. Wells in 1996 proved that type inference and type checking for un-annotated System F is undecidable.. Hence, no adequate algorithm can exist!
Why, then, can Lait infer a polymorphic type for calltwice?
It’s because Lait, and other polymorphic languages like OCaml, support a more restricted form of polymorphism. Thus, they are not actually implementing all of System F, but a subset of System F that balances expressivity with the ability to do type checking efficiently.
To a very rough degree of approximation, the main restriction that makes type inference tractable is the restriction to rank-1 polymorphism. This means that while functions can be polymorphic, their arguments cannot: every function type has to have the form \(\forall \overrightarrow{X}, \tau\), where \(\overrightarrow{X}\) is a sequence of type variables, and \(\tau\) is a simple type (one that does not have a \(\forall\)).
Hence, the following type is not expressible in Lait: \[ (\forall A, A \to A) \to (\texttt{Int} \times \texttt{Bool}) \] because we have type quantification inside an arrow type. (This would be called rank-2 polymorphism since we are nesting a \(\forall\) “one layer deep” inside of a type.) First, let’s see that we can come up with a System F program with this type easily: \[ \lambda f : (\forall A, A \to A). (f\ [\texttt{Int}]\ 3, f\ [\texttt{Bool}]\ \texttt{false}) \]
This function takes in a polymorphic identity function and applies it twice: once at type Int, and once at type Bool. Let’s now try to do this in Lait:
def rank2 f := (f 3, f false)
What’s going on? Lait first reads f 3, and knows that f must have a type type of the form Int -> .... This then doesn’t line up with applying f at false.
Why Int -> ?? and not a more complicated type, like (forall A, ...) -> ...?
Because Lait assumes rank-1 polymorphism, which means that functions taken as input to a function cannot have quantified types.
However, Lait does allow a program similar to rank2 to work:
def poly_id x := x
def apply_poly_id := (poly_id 3, poly_id false)
This program now does type check, because we don’t take a function as input to another function, but rather define a function at the top-level, and then use it later on in multiple ways.
There is a very rich history of algorithms designed for type inference in the presence of polymorphism. The classic algorithm is called Hindley-Milner inference, which sets up a constraint system of types that needs to be solved. Another complementary approach is Bidirectional Typing, which can be throught of as a clever way of mixing type checking with type inference.
Logical Aspects of System F
Finally, let’s touch upon some of the more deep theoretical aspects of System F. In particular, the connection between type systems and logic. For more information, you can read Phil Wadler’s paper Propositions as types.
To motivate this connection, let’s look at the following logical inference rule, called modus ponens:
For all A and B, if I know that “A implies B”, and I know A, then I know B.
This can be written as an inference rule like so:
\[ \dfrac{A \implies B \quad A}{B} \]
But now, let’s think about the following System F type:
\[ \forall A, \forall B, (A \to B) \to A \to B \]
As you can see, once we have a typed programming language, then we can map logical statements onto types. That gives us the first correspondence: propositions are types.
But, if propositions are types, what are programs? For example, we can actually implement a program of the above System F type:
\[ \Lambda A. \Lambda B. \lambda f : (A \to B). \lambda x : A. f\ x \]
Under this correspondence, proofs are programs. Thus, the above is actually a proof of modus ponens!
Let’s now see how the rest of propositional logic works under this correspondence.
First, since we think of inference rules as implications, then we can see already that we are “implementing” implication using function types. Hence, implication is given by function types.
Additionally, from last class, we saw that System F can encode product and sum types. Under this correspondence, these types correspond to the conjunction and disjunction of propositions.
Let’s see a table that captures all of this, using our notation from last time:
| Proposition | Type |
|---|---|
| Propositional variable | Type variable |
| Conjunction \(A \land B\) | Product type \(A \times B = \texttt{Prod}_{A, B}\) |
| Disjunction \(A \lor B\) | Sum type \(A + B = \texttt{Sum}_{A, B}\) |
| Implication \(A \implies B\) | Function type \(A \to B\) |
We can now prove a simple propositional logic theorem simply by programming. Let’s prove the following theorem:
\[ \dfrac{(((A \lor B) \land C) \implies D) \land A \land C}{D} \]
This corresponds to the following type in System F:
\[ \forall A.\ \forall B.\ \forall C.\ \forall D.\ (((A + B) \times C) \to D) \to A \to C \to D \]
We can then implement a program with this type:
\[
\Lambda A, B, C, D.\
\lambda f : ((A + B) \times C) \to D.\ \lambda a : A.\ \lambda c : C.\
f\ (\texttt{inl}\ a, c)
\]
In words: we prove \(D\) by taking in a function for the proof of the implication, and two additional arguments for a proof of \(A\) and a proof of \(C\). Then, \(\texttt{inl}\ a\) is a proof of \(A \lor B\). We pass that proof, and the proof of \(c\) into \(f\) to receive the proof of \(D\).
Imperative Languages
So far, we hae mostly looked at functional languages, which are descendents of the lambda calculus. For the rest of the semester, we will instead look at imperative languages. We will see that the same tools we have been using all along can equally analyze them as well. After introducing our imperative language of choice (called IMP), we will then study various techniques for analyzing IMP programs, such as noninterference (for security properties), and program logic (for correctness properties).
IMP
We now turn to analyzing a simple imperative language, called IMP, meant to model languages such as Python, Java, or C. What these languages have in common is a distinction between statements and expressions. For example, it makes sense to do the following in Python:
x = 2 + 2
But it does not make sense to do the following:
x = (x = 2 + 2)
The program x = 2 + 2 above is a statement — a thing that runs for the purpose of modifying state — while the sub-program 2 + 2 is an expression, which is only meant to compute values.
We model this abstractly by having a grammar of both statements and expressions.
\[ \begin{aligned} \text{Statements}\ s &::= x := e \mid s_1; s_2 \mid \mathsf{if}\ e\ \mathsf{then}\ s_1\ \mathsf{else}\ s_2 \mid \mathsf{while}\ e\ \mathsf{do}\ s \mid \mathsf{skip} \\ \text{Expressions}\ e &::= x \mid n \mid e_1 + e_2 \mid e_1 \times e_2 \mid e_1 - e_2 \mid e_1 / e_2 \mid e_1 \leq e_2 \\ \text{Numeric Constants}\ n &::= 0 \mid 1 \mid 2 \mid -1 \mid -2 \mid \dots \end{aligned} \]
Our statements, given by the metavariable \(s\), can either be assignment (\(x :=
e\)), sequencing (\(s_1 ; s_2\)), an if-then-else (\(\mathsf{if}\ e\ \mathsf{then}\ s_1\ \mathsf{else}\ s_2\)), a
while loop \(\mathsf{while}\ e\ \mathsf{do}\ s\), or \(\mathsf{skip}\), which does nothing (similar to pass in Python). Our expressions, given by the variable \(e\), represent
computations on integers.
For our version of IMP, we do not have Booleans explicitly, but instead encode Booleans via integers: 0 is false, and 1 is true. Hence, the control-flow statements via \(\mathsf{if}\) and \(\mathsf{while}\), by testing if the guard is \(0\) or not. The semantics of \(e_1 \leq e_2\) will return \(1\) if the value of \(e_1\) is at most the value of \(e_2\), and \(0\) otherwise.
Note that, while the rest of the operators concerning Booleans are not explicitly defined, they can be encoded:
\[ \begin{aligned} \neg e &::= 1 - e \\ e_1 \land e_2 &::= e_1 \times e_2 \\ e_1 \lor e_2 &::= \neg (\neg e_1 \land \neg e_2) \\ e_1 < e_2 &::= \neg (e_2 \leq e_1) \\ e_1 \geq e_2 &::= e_2 \leq e_1 \end{aligned} \]
For example, the following IMP program computes the \(n\)th Fibonacci number, storing the result in \(a\):
\[ \begin{aligned} &a := 0; \\ &b := 1; \\ &i := 0; \\ &\mathsf{while}\ i < n\ \mathsf{do} \\ &\quad t := a + b; \\ &\quad a := b; \\ &\quad b := t; \\ &\quad i := i + 1 \end{aligned} \]
For \(n \geq 0\), this program will terminate with the desired value stored in \(a\).
Semantics of IMP
Now, how should we specify the semantics of IMP?
We will use an operational (stepping) semantics, as we have been doing before. But how to model variable assignment?
We’ve seen this already: variable assignment is mutability, which we have studied for MutLang in Lecture 11! Thus, we will use the idea of a store (or a heap) which will map variables to values:
\[ \sigma : \mathsf{Var} \to \mathbb{Z} \]
To give semantics to IMP, we are going to give semantics to expressions and statements separately. Recall that for giving an operational semantics, we have two choices: a big step semantics \(\Downarrow\), which maps programs to result values, and a small step semantics \(\to\), which maps programs to other programs. It turns out that IMP can best be specified with a combination: we will use a big-step semantics for expressions, and a small-step semantics for statements.
Semantics for Expressions
First, let’s see expressions. Since expressions depend on the store, but do not change the store, the shape of our judgment will look like the following:
\[ \langle \sigma, e \rangle \Downarrow n. \]
Let’s see these rules:
\[ \dfrac{}{\langle \sigma, n \rangle \Downarrow n}\ \text{(E-Num)} \qquad \dfrac{}{\langle \sigma, x \rangle \Downarrow \sigma(x)}\ \text{(E-Var)} \]
\[ \dfrac{\langle \sigma, e_1 \rangle \Downarrow n_1 \quad \langle \sigma, e_2 \rangle \Downarrow n_2}{\langle \sigma, e_1 + e_2 \rangle \Downarrow n}\ \text{(E-Add)} \quad \text{where } n = n_1 + n_2 \]
\[ \dfrac{\langle \sigma, e_1 \rangle \Downarrow n_1 \quad \langle \sigma, e_2 \rangle \Downarrow n_2}{\langle \sigma, e_1 \times e_2 \rangle \Downarrow n}\ \text{(E-Mul)} \quad \text{where } n = n_1 \times n_2 \]
\[ \dfrac{\langle \sigma, e_1 \rangle \Downarrow n_1 \quad \langle \sigma, e_2 \rangle \Downarrow n_2}{\langle \sigma, e_1 - e_2 \rangle \Downarrow n}\ \text{(E-Sub)} \quad \text{where } n = n_1 - n_2 \]
\[ \dfrac{\langle \sigma, e_1 \rangle \Downarrow n_1 \quad \langle \sigma, e_2 \rangle \Downarrow n_2 \quad n_2 \neq 0}{\langle \sigma, e_1 / e_2 \rangle \Downarrow n}\ \text{(E-Div)} \quad \text{where } n = n_1 / n_2 \]
\[ \dfrac{\langle \sigma, e_1 \rangle \Downarrow n_1 \quad \langle \sigma, e_2 \rangle \Downarrow n_2 \quad n_1 \leq n_2}{\langle \sigma, e_1 \leq e_2 \rangle \Downarrow 1}\ \text{(E-LeqT)} \qquad \dfrac{\langle \sigma, e_1 \rangle \Downarrow n_1 \quad \langle \sigma, e_2 \rangle \Downarrow n_2 \quad n_1 > n_2}{\langle \sigma, e_1 \leq e_2 \rangle \Downarrow 0}\ \text{(E-LeqF)} \]
Note that we give a partial semantics to division: the program becomes stuck if we try to divide an expression by zero.
Semantics for Statements
Now we do statements. Since statements do modify the store, we have the small-step relation map stores and statements to stores and statements:
\[ \langle \sigma, s \rangle \to \langle \sigma’, s’ \rangle. \]
Here are the rules:
\[ \dfrac{\langle \sigma, e \rangle \Downarrow n}{\langle \sigma, x := e \rangle \to \langle \sigma[x \mapsto n], \mathsf{skip} \rangle}\ \text{(S-Assign)} \]
\[ \dfrac{\langle \sigma, s_1 \rangle \to \langle \sigma’, s_1’ \rangle}{\langle \sigma, s_1; s_2 \rangle \to \langle \sigma’, s_1’; s_2 \rangle}\ \text{(S-Seq1)} \qquad \dfrac{}{\langle \sigma, \mathsf{skip}; s_2 \rangle \to \langle \sigma, s_2 \rangle}\ \text{(S-Seq2)} \]
\[ \dfrac{\langle \sigma, e \rangle \Downarrow n \quad n \neq 0}{\langle \sigma, \mathsf{if}\ e\ \mathsf{then}\ s_1\ \mathsf{else}\ s_2 \rangle \to \langle \sigma, s_1 \rangle}\ \text{(S-IfT)} \qquad \dfrac{\langle \sigma, e \rangle \Downarrow 0}{\langle \sigma, \mathsf{if}\ e\ \mathsf{then}\ s_1\ \mathsf{else}\ s_2 \rangle \to \langle \sigma, s_2 \rangle}\ \text{(S-IfF)} \]
\[ \dfrac{}{\langle \sigma, \mathsf{while}\ e\ \mathsf{do}\ s \rangle \to \langle \sigma, \mathsf{if}\ e\ \mathsf{then}\ (s; \mathsf{while}\ e\ \mathsf{do}\ s)\ \mathsf{else}\ \mathsf{skip} \rangle}\ \text{(S-While)} \]
These rules merit some explanation. First, let’s look at (S-Assign). To evaluate \(x := e\), we first evaluate \(e\) under the big-step semantics, to get a value \(n\). We then update the store to set \(x\) equal to \(n\), and change update the statement to \(\mathsf{skip}\), which means “we are done executing”.
Now, let’s look at the sequence rules. The rule (S-Seq1) for \(s_1; s_2\) is reminiscent of the small-step rules for MutLang: we step the inner program and update the heap accordingly. The second rule (S-Seq2) says that if we are done executing on the left-hand side of a sequence, then we are done on the right-hand side. Let’s see an example, starting with the map sending every variable to zero. Below, we write \(\{x_1 \mapsto n_1, \dots, x_k \mapsto n_k\}\) for the store sending each \(x_i\) to \(n_i\) and every other variable to \(0\):
\[ \begin{aligned} \langle \{\}, x := 1; y := 2 \rangle &\to \langle \{x \mapsto 1\}, \mathsf{skip}; y := 2 \rangle && \text{(S-Seq1, S-Assign)} \\ &\to \langle \{x \mapsto 1\}, y := 2 \rangle && \text{(S-Seq2)} \\ &\to \langle \{x \mapsto 1, y \mapsto 2\}, \mathsf{skip} \rangle && \text{(S-Assign)} \end{aligned} \]
The last subtle rule is (S-While). Instead of trying to step the inner program and doing the test on the guard itself, (S-While) instead makes the observation that a while loop is equivalent to an if/then/else, where in the “then” case, we run the body once, and then recurse, and in the “else” case, we do nothing: \[ \mathsf{while}\ e\ \mathsf{do}\ s = \mathsf{if}\ e\ \mathsf{then}\ (s; \mathsf{while}\ e\ \mathsf{do}\ s)\ \mathsf{else}\ \mathsf{skip}. \]
IMP is Turing Complete (?!)
While IMP is a very simple language, in some respects — certainly conceptually simpler than System F! — a remarkable fact about IMP is that it is Turing complete. Thus, any lambda-calculus term, or C program, can be translated to an IMP program. While we won’t go into the details why exactly the essential properties that make IMP turing complete is a combination of unbounded data via integers, control flow, and loops.
Hence, even for a language as simple as IMP, there exists no algorithm that can determine basic properties for arbitrary IMP programs: for example, whether the program will terminate, or what the final value of a given variable \(x\) will be.
Adding Arrays
To make IMP more interesting, we are going to add arrays to the language. Arrays will be denoted with upper-case variables (e.g., \(T\)), and will be modeled as having an infinite size (so we don’t need to think about array access being in bounds). Like variables, we won’t have a way to create new arrays, but instead will assume the arrays we use will be held in the state. Thus, we will modify our language like so:
\[ \begin{aligned} \text{Statements}\ s &::= \dots \mid T[e] := e \\ \text{Expressions}\ e &::= \dots \mid T[e] \end{aligned} \]
To model arrays in the semantics, we need to augment our state to keep track of them. Thus, our state will now be composed of two mappings:
\[ \begin{aligned} &\sigma_\mathsf{Var} : \mathsf{Var} \to \mathbb{Z} \\ &\sigma_\mathsf{Arr} : \mathsf{Arr} \to (\mathbb{Z} \to \mathbb{Z}) \end{aligned} \]
By convention, lower-case variables (e.g., \(x\)) will be ordinary integer variables, while upper-case variables will be array variables. In the semantics, each array is mapped to an infinite array from integers to integers.
Semantics for Arrays
To extend our semantics to handle arrays, we will keep our configurations of the form \(\langle \sigma, e\rangle\) and \(\langle \sigma, s\rangle\), but will interpret \(\sigma\) here as holding two mappings internally for \(\sigma_\mathsf{Var}\) and \(\sigma_\mathsf{Arr}\). Under this notation, the original rules for IMP still apply, since we can interpret \(\sigma(x)\) to mean \(\sigma_\mathsf{Var}(x)\).
Thus, we only need two new rules for array access and array assignment. First, array access: \[ \dfrac{\langle \sigma, e\rangle \Downarrow n}{\langle \sigma, T[e] \rangle \Downarrow \sigma_\mathsf{Arr}(T)(n)} \text{(E-ArrayGet)} \]
Next, array assignment: \[ \dfrac{\langle \sigma, e_1\rangle \Downarrow n_1 \quad \langle \sigma, e_2 \rangle \Downarrow n_2} {\langle \sigma, T[e_1] := e_2 \rangle \to \langle \sigma[T[n_1] := n_2], \mathsf{skip} \rangle } \]
For array assignment, we use the notation \(\sigma[T[n_1] := n_2]\) to mean the store \(\sigma\), but modify \(\sigma_\mathsf{Arr}(T)\) so that \(T[n_1] = n_2\).
Example: Insertion Sort
Now that we have arrays, we can start to model some interesting programs. First, let’s recall the sorting algorithm insertion sort: the idea is we repeatedly process bigger and bigger prefixes of the array. For each prefix, we iterate backwards starting from the end, and repeatedly swap array elements if they are out of order. Here is insertion sort in Python:
def swap(arr, i, j):
arr[i], arr[j] = arr[j], arr[i]
def insertion_sort(arr):
for i in range(1, len(arr)):
j = i
while j > 0 and arr[j - 1] > arr[j]:
swap(arr, j - 1, j)
j -= 1
return arr
To write this in IMP, we will first define \(\mathsf{swap}\) as an abbreviation for the following program:
\[ \begin{aligned} \mathsf{swap}(A, e_1, e_2) \stackrel{\mathsf{def}}{=}\ &\mathit{tmp} := A[e_1]; \\ &A[e_1] := A[e_2]; \\ &A[e_2] := \mathit{tmp} \end{aligned} \]
With this abbreviation, insertion sort is:
\[ \begin{aligned} &i := 1; \\ &\mathsf{while}\ i < n\ \mathsf{do} \\ &\quad j := i; \\ &\quad \mathsf{while}\ (0 < j) \land (A[j] < A[j - 1])\ \mathsf{do} \\ &\quad\quad \mathsf{swap}(A, j - 1, j); \\ &\quad\quad j := j - 1 \\ &\quad i := i + 1 \end{aligned} \]
In this course, we have been mostly focused on the design of functional programming languages and their type systems. In the remainder of this course, we will focus on verification: the use of concepts from PL to formally prove that programs are not only well-behaved in a generic sense (e.g., they do not get stuck), but that they are actually correct. For example, formally proving that the above program actually implements a sorting algorithm correctly.
Program Logics
Last class, we introduced IMP; this class, we will discuss how we can use a formal logic to formally verify IMP programs correct on all possible inputs.
Array Maximum
Let’s consider the following program, using our extension to arrays:
i := 0;
max := -1;
while i < n do
if a[i] > max then
max := a[i]
else skip;
i := i + 1
The above program computes a maximum over an array. But how do we know that this program is correct? What does “correct” mean? For our purposes, we can define correctness by “what should be true after the program finishes.”
Logical Specifications
To define correctness, we need to invent a specification: a formal definition for what it means for the above program to be correct. Even for the above program, there are many kinds of specifications you can write. In this class, we will explore logical specifications: the ability to assign pre- and post-conditions to code which describes the desired behavior of the code. A precondition is what we assume to be true before the code runs, and a postcondition is what we want to be true after the code runs.
Spec for Array Maximum.
For our array maximum, what should the pre- and post-conditions be? Well, we assume that n is the length of the array, so let’s ensure that is positive. In addition, let’s assume the array only holds nonnegative elements, so that we can let \(-1\) be the correct initial value.
\[ n > 0 \wedge (\forall i, a[i] \geq 0) \]
Now, let’s think about a good postcondition.
We should ensure that the maximum actually is a maximum, if n is bigger than 0:
\[ \forall i, \text{max} \geq a[i] \] Additionally, we want to ensure the maximum is actually in the array. Thus, our postcondition becomes the following: \[ (\exists i. \text{max} = a[i]) \wedge (\forall i, \text{max} \geq a[i]) \]
The above formulae form a valid specification of our program. If we call our program MAX, then we can say that the following Hoare triple (named after Tony Hoare) is valid:
\[ \{ n > 0 \wedge (\forall i, a[i] \geq 0)\}\ \text{MAX}\ \{ (\exists i. \text{max} = a[i]) \wedge (\forall i, \text{max} \geq a[i])\} \]
A Hoare triple is of the form \( \{P\}\ s\ \{Q\} \), where \(P\) is our precondition, \(s\) is our program, and \(Q\) is our postcondition. Intuitively, validity of a Hoare triple states the following: if our initial state satisfies the precondition, then the final state must satisfy the postcondition.
What is a pre/postcondition? What, formally, are these \(P\)’s and \(Q\)’s? We are writing them as logical formulae, so one could imagine specifying them using formal grammar of logical formulae. However, we instead will think of them more abstractly: a precondition or postcondition is simply a set of states:
\[ P, Q \subseteq \mathsf{States}. \] Above, \(\mathsf{States}\) is the set of all possible program states. We can interpret logical formulas as sets by considering the sets that satisfy the formula.
\[ “n \geq 0” := \{ \sigma \mid \sigma(n) \geq 0 \} \] \[ “x = 4 \land y = 3” := \{ \sigma \mid \sigma(x) = 4 \land y = 3 \} \]
Thus, free variable names in formula, except when otherwise specified, stand for variables in the state. Crucially however, everything else in the logical formula is “just math”. Thus, the greater-than symbol \(\geq\) in the formula is just the greater-than relation on integers, while the greater-than symbol in a program is a formal expression.
Example: Assignment
Before diving into formal properties, let’s take a look at some Hoare triples. First, assignment: \[ \{ x = 3 \land y = 4 \}\ x := y\ \{ x = 4 \land y = 4 \} \] The above states that if \(x\) is equal to \(3\) and \(y\) is equal to \(4\), then after running \(x := y\), we get that \(x\) is equal to \(4\) and \(y\) is still equal to \(4\). Note that if we remove the precondition on \(x\), the triple is still valid: \[ \{ y = 4 \}\ x := y\ \{ x = 4 \land y = 4 \} \] However, if we remove the precondition on \(y\), then it is not valid: \[ \text{INVALID:}\ \{ x = 3 \}\ x := y\ \{ x = 4 \land y = 4 \} \] When we remove conjunctions from the precondition, we are weakening it, meaning that more initial states can apply to it.
On the other hand, if we remove things from the postcondition, that is fine, since it’s a proof obligation, and thus if we make it weaker, we are just proving less: \[ \{ x = 3 \land y = 4 \}\ x := y\ \{ \text{True} \} \]
Example: Swap
Let’s now think about a piece of code that swaps two variables:
\[ \text{Swap}(x, y) := (\text{tmp} := x; x := y; y := \text{tmp}) \]
Let’s think about a good specification for that function. First, if \(x\) is \(6\) and \(y\) is \(7\), then we should get that \(y\) is \(6\) and \(x\) is \(7\):
\[ \{x = 6 \land y = 7\}\ \text{Swap}(x, y)\ \{x = 7 \land y = 6\} \]
More generally, for any \(\mathbf{v}_1\) and \(\mathbf{v}_2\), the corresponding triple should hold:
\[ \forall \mathbf{v}_1, \mathbf{v}_2. \{x = \mathbf{v}_1 \land y = \mathbf{v}_2\}\ \text{Swap}(x, y)\ \{x = \mathbf{v}_2 \land y = \mathbf{v}_1 \} \]
Above, we write \(\mathbf{v}_1/\mathbf{v}_2\) in bold to indicate that they are not variables in the program, but instead logical variables standing in for mathematical integers.
Curiously, there is another implementation of Swap that doesn’t need a temporary variable: \[ \text{Swap2}(x, y) := (x := x + y; y := x - y; x := x - y). \] Can you convince yourself that the same pre and postconditions hold for Swap2 that hold for Swap?
Example: Minimum
Let’s do one more before we dig deeper into the semantics of the program logic: \[ \text{Min}(x, y, m) := (\mathsf{if}\ x <= y\ \mathsf{then}\ m := x\ \mathsf{else}\ m := y) \]
This program won’t need a precondition, so its Hoare triple will look like so:
\[ \{\text{True}\}\ \text{Min}(x, y, m)\ \{Q\} \]
Now, what do we want to be true at the end of the program? Suppose we just required that \(m\) was smaller than \(x\) and \(y\):
\[ Q = (m \leq x) \land (m \leq y). \]
This postcondition is sound, but it is not precise. An imprecise spec is one that can be fulfilled by another program that we did not intend. For example, if we let
\[ \text{FakeMin}(x, y, m) := (m := 0 - (x \times x) - (y \times y)), \] then we will also have that \(m\) is at most \(x\) and \(y\):
\[ \{\text{True}\}\ \text{FakeMin}(x, y, m)\ \{m \leq x \land m \leq y\} \ \]
Whether this spec is good enough depends on our use case. If we are trying to find a lower bound in an array of values, then this version of \(Q\) is sufficient, and we could equally use Min or FakeMin. However, if we need to actually return an element in that array, then this spec is not enough. Thus, we will update the spec to also require that \(m\) is equal to one of the two values:
\[ Q = m \leq x \land m \leq y \land (m = x \lor m = y). \]
We then will be able to derive the following:
\[ \{\text{True}\}\ \text{Min}(x, y, m)\ \{m \leq x \land m \leq y \land (m = x \lor m = y)\} \]
while the below is invalid:
\[ \text{INVALID:}\ \{\text{True}\}\ \text{FakeMin}(x, y, m)\ \{m \leq x \land m \leq y \land (m = x \lor m = y)\} \]
Validity of Hoare Triples
Now, we can investigate what it means to have a valid Hoare triple \( \{P\}\ s\ \{Q\}\). Our earlier intuition was that “if our initial state satisfies the precondition, then the final state must satisfy the postcondition.” Since \(P\) and \(Q\) are just sets of states, a state \(\sigma\) satifies the pre/postcondition exactly when it is in the set: \(\sigma \in P\). Thus, we only need to be able to talk about initial and final states. We can appeal to the stepping semantics of IMP, covered last time. Thus, the triple \( \{P\}\ s\ \{Q\}\) is valid if the following holds:
\[ \forall \sigma, \sigma’. \sigma \in P \wedge \langle \sigma, s \rangle \to^* \langle \sigma’, \mathsf{skip} \rangle \implies \sigma’ \in Q. \]
We write \(\vDash \{P\}\ s\ \{Q\} \) if the Hoare triple is valid.
Unwinding the definition for Swap. Let’s now see if it’s the case directly if Swap is correct. By uwinding the definitions for Swap:
\[ \{x = 6 \land y = 7\}\ \text{Swap}(x, y)\ \{x = 7 \land y = 6\} \]
We can see that validity is asking the following:
\[ \forall \sigma, \sigma’. \sigma(x) = 6 \land \sigma(y) = 7 \wedge \langle \sigma, \text{Swap}(x, y) \rangle \to^* \langle \sigma’, \mathsf{skip} \rangle \implies \sigma’(x) = 7 \land \sigma’(y) = 6. \]
By the definition of how Swap, we can see that whenever \(Swap(x, y)\) terminates under \(\sigma\) to obtain \(\sigma’\), we have that
\[ \sigma’(z) = \begin{cases} \sigma(x) & z = \text{tmp} \\ \sigma(y) & z = x \\ \sigma(x) & z = y \\ \sigma(z) & \text{otherwise.} \end{cases} \]
Thus, if \(\sigma(x) = 6\) and \(\sigma(y) = 7\), then \(\sigma’(x) = \sigma(y) = 7\) and \(\sigma’(y) = \sigma(x) = 6\), as required.
How to Validate Hoare Triples?
Now that we know how to specify programs, let’s now show how to prove programs correct against these specifications. How might we show that a Hoare triple \( \{P\}\ s\ \{Q\} \) is valid?
First, we could consider testing: try to run \(s\) on many different, randomly sampled states that satisfy \{P\}, and see if the final states satisfy \{Q\}. This technique is very powerful since it is quite automated, but it has the following limitations:
- Soundness. While we check that \(s\) is correct on many possible initial states, we don’t get a proof that it is correct on all infinitely many possible states.
- Completeness. This technique only works if we can efficiently check \{P\} and \{Q\}, but they might have universal quantifiers in them, which we can’t automatically check in general.
- Performance. This technique requires running the command \(s\) many times, which might have significant performance issues (for example, if \(s\) runs in time exponential in a given input, \(n\).)
In this lecture, we will investigate a different method: program logic (or Hoare logic), which instead provides a collection of inference rules that we can prove sound.
Assumptions about Expressions. For the purpose of this lecture, we will assume that expressions are all total and deterministic, meaning that for every state \(\sigma\), there is a unique value \(n\) such that \(\langle \sigma, e \rangle \Downarrow n.\). Hence, we will not worry about division in this lecture.
Skip, Consequence, and Assignment
First, let’s think about the simple programs.
Program Logic Rule: Skip
Since \(\mathsf{skip}\) doesn’t do anything, the output state is exactly equal to the input state. Thus, for any \(P\), the following inference rule is sound:
\[ \dfrac{}{\{P\}\ \mathsf{skip}\ \{P\}} \text{(R-Skip)} \]
Here, soundness means that the Hoare triple is valid. Let’s prove this rule sound. Unrolling the definition for validity means we want to prove the following:
\[ \forall \sigma, \sigma’. \sigma \in P \land \langle \sigma, \mathsf{skip} \rangle \to^* \langle \sigma’, \mathsf{skip} \rangle \implies \sigma’ \in P. \]
Since skip does not step, if we have \( \langle \sigma, \mathsf{skip} \rangle \to^* \langle \sigma’, \mathsf{skip} \rangle\) then we have that zero steps have been taken, and thus \(\sigma’ = \sigma\). Hence the above simplifies to this:
\[ \forall \sigma, \sigma’. \sigma \in P \land \sigma’ = \sigma \implies \sigma’ \in P \]
which is of course true.
Program Logic Rule: Consequence
From our examples above, we can see that it is sound to strengthen a precondition — assuming more things — as well as weaken a postcondition — trying to prove fewer things. We can formalize this via the rule of consequence:
\[ \dfrac{P’ \implies P \quad \{P\}\ s\ \{Q\} \quad Q \implies Q’}{\{P’\}\ s\ \{Q’\}} \text{(R-Conseq)} \]
Since \(P\) and \(P’\) are sets of states, the use of implication in the hypothesis (\(P’ \implies P\)) means the same thing as subset: \(P’ \subseteq P\). That is, every state in \(P’\) must also be in \(P\).
For example, if we have
\[ \{ x = 1 \land y = 2 \}\ s\ \{x = 3 \land y = 4\}\] then we can do the following:
- Weaken the postcondition to just \(x = 3\) (which is a larger set of states). Since we know the final states of \(s\) always satisfy \(x = 3\) and \(y = 4\), it is sound to only require \(x = 3\).
- Strengthen the precondition to \(x = 1 \land y = 2 \land z = 5\) (which is a smaller set of states). Since we know the initial states of \(s\) want \(x = 1\) and \(y = 2\), also assuming \(z = 5\) does not hurt.
Proof of consequence. We can prove this rule formally. To prove it, we assume the hypotheses and must prove the consequence. Thus, we know:
- (1) \(P’ \implies P\)
- (2) \(Q \implies Q’\)
- (3) \(\forall \sigma, \sigma’. \sigma \in P \land \langle \sigma, s \rangle \to^* \langle \sigma’, \mathsf{skip} \rangle \implies \sigma’ \in Q\)
And we need to show:
- \(\forall \sigma, \sigma’. \sigma \in P’ \land \langle \sigma, s \rangle \to^* \langle \sigma’, \mathsf{skip} \rangle \implies \sigma’ \in Q’\)
Thus, since what we need to show is an implication, we additionally assume a \(\sigma\) and \(\sigma’\), and that:
- (4) \(\sigma \in P’\)
- (5) \(\langle \sigma, s \rangle \to^* \langle \sigma’, \mathsf{skip} \rangle \)
And need to show finally that:
- \(\sigma’ \in Q’\)
To show that \(\sigma’ \in Q’\), it is enough to show that \(\sigma’ \in Q\), by assumption (2). But then we can use assumption (3), which can prove that, as long as: (a) the program runs from \(\sigma\) to \(\sigma’\); and (b) that \(\sigma \in P\). But then, (a) is proven by assumption (5), while (b) is proven by assumption (1) and (4).
Program Logic Rule: Assignment
Now, let’s think about \(x := e\), which steps in one step to skip with an updated state. Below is the rule for assignment:
\[ \dfrac{}{\{P[e/x]\}\ x := e\ \{P\}} \text{(R-Assign)} \]
Above, we write \(P[e/x]\) for the syntactic substitution of \(e\) for \(x\) in \(P\). Here, we are identifying \(e\) with its mathematical meaning, in addition to its meaning as an IMP expression.
This rule merits a little bit of discussion, as it looks a little backwards. First, let’s see some examples:
\[ \{x = 1\}\ y := x + x\ \{ x = 1 \land y = 2 \} \]
This triple follows from (R-Assign) and (R-Conseq). First, we need the precondition to line up with the postcondition, but with \(e\) substituted for \(y\). Thus, since the postcondition is \[P := x = 1 \land y = 2\], we know that our desired precondition is \[P[e/y] := x = 1 \land (x + x = 2). \] Our desired precondition is a logical consequence of our actual precondition (\(x = 1\)), so we can first use (R-Conseq) to instead prove the following triple:
\[ \{x = 1 \land (x + x = 2)\}\ y := x + x\ \{ x = 1 \land y = 2 \} \]
And now we can use (R-Assign) to finish the proof.
We can write this proof as a derivation tree:
\[ \dfrac{ \dfrac{}{x = 1 \implies x = 1 \land (x + x = 2)} \qquad \dfrac{}{\{x = 1 \land (x + x = 2)\}\ y := x + x\ \{ x = 1 \land y = 2 \}} \text{(R-Assign)} \qquad \dfrac{}{x = 1 \land y = 2 \implies x = 1 \land y = 2} }{ \{x = 1\}\ y := x + x\ \{ x = 1 \land y = 2 \} } \text{(R-Conseq)} \]
While the assignment rule (R-Assign) seems a bit obtuse, we can conceptualize it better as coming up with the best precondition to prove the postcondition. When is it the case that, after we do \(x := e\), we get \(P\)? Well, it’s exactly when \(P\) holds before the assignment, by thinking of the assignment as happening in the precondition instead. In practice, we always use (R-Conseq) to implicitly change our actual precondition to the right shape so that we can call (R-Assign).
Here are some more valid triples:
\[ \{ x = 42\} y := x + 1 \{ y = 43 \} \]
The above holds because we can transform the above precondition, by (R-Conseq), to \( x + 1 = 43 \) (which is logically equivalent). Then, (R-Assign) holds.
\[ \{ x \leq N \} y := x + 2 \{ y \leq N + 2 \} \]
Similarly, we transform the precondition to \( x + 2 \leq N + 2\), and then (R-Assign) applies.
Program Logic Rule: If/then/else
To prove an if/then/else is correct, we need to analyze both sides of the branches. Additionally, we get to assume the branch is equal (or not equal) to zero:
\[ \dfrac{\{P \land e \neq 0\}\ s_1\ \{Q\} \quad \{P \land e = 0\}\ s_2\ \{Q\}}{\{P\}\ \mathsf{if}\ e\ \mathsf{then}\ s_1\ \mathsf{else}\ s_2\ \{Q\}} \text{(R-If)} \]
This matches the stepping rules from last time.
To show this rule is sound, you can prove the following lemma:
Lemma. If \(\langle \sigma, \mathsf{if}\ e\ \mathsf{then}\ s_1\ \mathsf{else}\ s_2 \rangle \to^* \langle \sigma’, \mathsf{skip} \rangle\), then either:
- \(\sigma(e) \neq 0\) and \(\langle \sigma, s_1 \rangle \to^* \langle \sigma’, \mathsf{skip}\rangle\); or
- \(\sigma(e) = 0\) and \(\langle \sigma, s_2 \rangle \to^* \langle \sigma’, \mathsf{skip}\rangle\).
This lemma is true because an if/then/else statement can only step in one possible way given a particular state.
Program Logic Rule: Sequencing
Now, how would we prove that Swap is correct? Since Swap only uses assignment and sequencing (\(;\)), we need a rule for sequencing. Here it is:
\[ \dfrac{\{P\}\ s_1\ \{R\} \quad \{R\}\ s_2\ \{Q\}}{\{P\}\ s_1; s_2\ \{Q\}} \text{(R-Seq)} \]
Here, \(R\) is an intermediate condition: it describes the states after \(s_1\) finishes but before \(s_2\) begins. Note that \(R\) does not appear in the conclusion, so when we use (R-Seq), we get to pick \(R\) ourselves.
To show this rule is sound, you can prove the following lemma:
Lemma. If \(\langle \sigma, s_1; s_2 \rangle \to^* \langle \sigma’, \mathsf{skip} \rangle\), then there exists some \(\sigma’’\) such that:
- \(\langle \sigma, s_1 \rangle \to^* \langle \sigma’’, \mathsf{skip}\rangle\); and
- \(\langle \sigma’‘, s_2 \rangle \to^* \langle \sigma’, \mathsf{skip}\rangle\).
This lemma states that for \(s_1; s_2\) to step to \(\mathsf{skip}\), we need to first run \(s_1\) all the way down to \(\mathsf{skip}\) before we run \(s_2\). Soundness follows directly from this lemma.
Program Logic Rule: While
Now, let’s think about while loops. These are the most subtle, and where the challenge of program logic proofs comes from. First, let’s see the rule:
\[ \dfrac{P \implies I \quad \{I \land e \neq 0\}\ s\ \{I\} \quad I \land e = 0 \implies Q}{\{P\}\ \mathsf{while}\ e\ \mathsf{do}\ s\ \{Q\}} \text{(R-While)} \]
To prove that \(\{P\}\ \mathsf{while}\ e\ \mathsf{do}\ s \{Q\}\) is valid, we need to come up with an appropriate loop invariant, \(I\). This loop invariant need to have the following properties:
- It is implied by the precondition, \(P\), which means that it holds before the loop runs;
- Whenever we have \(I\) and \(e \neq 0\), then \(s\) enforces that the loop invariant still holds after termination; and
- Whenever we have \(I\) and \(e = 0\), we have that the desired postcondition \(Q\) holds. Thus, when the loop is done, the postcondition holds.
Let’s see an example, where we count up to \(n\) by one each time:
i := 0;
while i < n do
i := i + 1
We want to show that, whenever \(n \geq 0\), we have that \(i = n\) at the end of the program. That is, the following Hoare triple should be valid:
\[ \{n \geq 0\}\ i := 0;\ \mathsf{while}\ i < n\ \mathsf{do}\ i := i + 1\ \{i = n\} \]
Now, let’s prove it. First, let’s use (R-Seq), (R-Assign), and (R-Conseq) to get rid of the assignment, and enforce that \(i = 0\) before the loop runs. Using (R-Seq) with intermediate condition \(n \geq 0 \land i = 0\), we need to prove two triples. The first is
\[ \{n \geq 0\}\ i := 0\ \{n \geq 0 \land i = 0\}, \]
which holds since (R-Assign) gives us the precondition \(n \geq 0 \land 0 = 0\), and \(n \geq 0\) implies this by (R-Conseq). The second is the triple for just the while loop:
\[ \{n \geq 0 \land i = 0\}\ \mathsf{while}\ i < n\ \mathsf{do}\ i := i + 1\ \{i = n\} \]
Now, we need to come up with a good loop invariant. It needs to hold on initialization, be maintained by the loop, and imply that \(i = n\) at the end. It turns out that a good loop invariant is that \(i \leq n\). Let’s see why by using (R-While):
\[ \dfrac{ n \geq 0 \land i = 0 \implies i \leq n \quad \{i \leq n \land i < n\}\ i := i + 1\ \{i \leq n\} \quad i \leq n \land \neg(i < n) \implies i = n }{ \{n \geq 0 \land i = 0\}\ \mathsf{while}\ i < n\ \mathsf{do}\ i := i + 1\ \{i = n\} } \text{(R-While)} \]
Above, recall that the guard \(i < n\) is an IMP expression that evaluates to \(1\) or \(0\); thus, \(e \neq 0\) becomes \(i < n\), and \(e = 0\) becomes \(\neg(i < n)\), i.e., \(i \geq n\). Now, we just need to show that our use of (R-While) is valid; that is, the three hypotheses hold.
- Initialization. If \(i = 0\) and \(n \geq 0\), then \(i \leq n\). Note that this is exactly where we need the precondition \(n \geq 0\): if \(n\) were negative, the loop would never run, and we would end with \(i = 0 \neq n\).
- Preservation. By (R-Assign), it is enough to show the precondition \((i \leq n)[i + 1/i] = (i + 1 \leq n)\). Since we are working with integers, \(i < n\) implies \(i + 1 \leq n\), so (R-Conseq) finishes the proof.
- Exit. If \(i \leq n\) and \(i \geq n\), then \(i = n\).
It is worth seeing why other choices of invariant fail. The invariant \(\text{True}\) holds initially and is trivially preserved, but it is too weak: at exit, \(i \geq n\) alone does not give \(i = n\). On the other hand, the invariant \(i = n\) is strong enough at exit, but it does not hold initially (unless \(n = 0\)), nor is it preserved by the loop body. A good loop invariant must be weak enough to hold initially and be preserved, but strong enough to imply the postcondition.
Program Logics, Continued
Last lecture, we saw the rules for a program logic for IMP. This class, we will see some more examples, and then turn to a concrete implementation of program logic using Dafny.
\[ \newcommand{\assert}[1]{{\color{blue}{\{#1\}}}} \newcommand{\comment}[1]{\qquad {\color{gray}{\textit{// #1}}}} \]
Proof Outlines
To describe program logic proofs, one thing we can do is to write down the whole derivation tree. For example, one possible derivation tree for \(\assert{\text{True}}\ x := 1; y := x + 2\ \assert{y \geq 3}\) is:
\[ \dfrac{ \dfrac{}{\text{True} \implies \text{True}} \quad \dfrac{ \mathcal{D}_1 \qquad \mathcal{D}_2 }{ \{\text{True}\}\ x := 1; y := x + 2\ \{x = 1 \land y = 3\} } \text{(R-Seq)} \quad \dfrac{}{x = 1 \land y = 3 \implies y \geq 3} }{ \{\text{True}\}\ x := 1; y := x + 2\ \{y \geq 3\} } \text{(R-Conseq)} \]
At the bottom, (R-Conseq) weakens the postcondition \(x = 1 \land y = 3\) to \(y \geq 3\). Above that, we use (R-Seq) with the intermediate condition \(x = 1\), which leaves two subderivations. The first, \(\mathcal{D}_1\), proves \(\{\text{True}\}\ x := 1\ \{x = 1\}\):
\[ \mathcal{D}_1 = \dfrac{ \dfrac{}{\text{True} \implies 1 = 1} \quad \dfrac{}{\{1 = 1\}\ x := 1\ \{x = 1\}} \text{(R-Assign)} \quad \dfrac{}{x = 1 \implies x = 1} }{ \{\text{True}\}\ x := 1\ \{x = 1\} } \text{(R-Conseq)} \]
Here, (R-Assign) gives us the precondition \((x = 1)[1/x] = (1 = 1)\), which is implied by \(\text{True}\). The second, \(\mathcal{D}_2\), proves \(\{x = 1\}\ y := x + 2\ \{x = 1 \land y = 3\}\):
\[ \mathcal{D}_2 = \dfrac{ \dfrac{}{x = 1 \implies x = 1 \land x + 2 = 3} \quad \dfrac{}{\{x = 1 \land x + 2 = 3\}\ y := x + 2\ \{x = 1 \land y = 3\}} \text{(R-Assign)} \quad \dfrac{}{x = 1 \land y = 3 \implies x = 1 \land y = 3} }{ \{x = 1\}\ y := x + 2\ \{x = 1 \land y = 3\} } \text{(R-Conseq)} \]
Here, (R-Assign) gives us the precondition \((x = 1 \land y = 3)[x + 2/y] = (x = 1 \land x + 2 = 3)\), which is implied by \(x = 1\).
This is a very difficult way to understand a proof. Instead, we will present proof outlines, which sequence pre- and postconditions in between commands:
\[ \begin{array}{l} \assert{\text{True}} \\ x := 1; \\ \assert{x = 1} \\ y := x + 2 \\ \assert{x = 1 \land y = 3} \\ \assert{y \geq 3} \end{array} \]
The basic idea of a proof outline is that we interleave assertions between program fragments. We will write all assertions in blue. The assertion at the top is the precondition for the whole code block, while the assertion at the bottom is a the postcondition. An intermediate assertion, such as \(\assert{x = 1},\) serves as both a postcondition for the statement above the assertion (\(x := 1\)) as well as a precondition for the statement below it (\(y := x + 2\)). If we write two assertions side-by-side, such as \(\assert{x = 1 \land y = 3}\) and \(\assert{y \geq 3}\), then the latter one is a logical consequence of the former one. A proof outline is valid if every triple \(\assert{P}\ c\ \assert{Q}\) in the outline is a valid Hoare triple.
Note that strictly speaking, the above is only a proof outline, since certain low-level steps aren’t being shown. For example, a fully formal proof of \(\assert{x = 1}\ y := x + 2\ \assert{x = 1 \land y = 3}\) requires using the rule of consequence, as in \(\mathcal{D}_2\). However, we can justifiably “bottom out” here in the proof, as it is usually clear by inspection whether a Hoare triple of the form \(\assert{P}\ x := e\ \assert{Q}\) is true.
For the rest of this course, we will primarily work with proof outlines. However, understanding how the underlying rules of Hoare logic work from last time are necessary to understand how to work with the proof outlines.
If/Then/Else. To handle an if-then-else in a proof outline, you need to precede the entire if/then/else block with a precondition, and ensure the same postcondition holds on both branches. However, when you descend into each branch, you get to learn whether the condition is true or not.
\[ \begin{array}{l} \assert{\text{True}} \\ \textbf{if}\ x \geq y\ \textbf{then} \\ \quad \assert{\text{True} \land x \geq y} \comment{Precondition and guard is true} \\ \quad \mathit{max} := x \\ \quad \assert{\mathit{max} = x \land x \geq y} \\ \quad \assert{\mathit{max} \geq x \land \mathit{max} \geq y} \\ \textbf{else} \\ \quad \assert{\text{True} \land x < y} \comment{Precondition and guard is false} \\ \quad \mathit{max} := y \\ \quad \assert{\mathit{max} = y \land x < y} \\ \quad \assert{\mathit{max} \geq x \land \mathit{max} \geq y} \\ \assert{\mathit{max} \geq x \land \mathit{max} \geq y} \end{array} \]
While Loops. To handle while loops in a proof outline, you need to identiy a loop invariant which holds upon loop entry, is preserved by the loop when the loop condition is true, and implies the desired postcondition when the loop condition is false. To make the proof clear, we will notate loop invariants explicitly in the program: our while loops will now look like
while e do
invariant P
s
where P is the loop invariant.
For example, here is a complete proof outline for a loop counting up to the value of \(x\):
\[ \begin{array}{ll} \assert{x \geq 0} & \\ y := 0; & \\ \assert{x \geq 0 \land y = 0} & \\ \textbf{while}\ y < x\ \textbf{do} & \\ \quad \textbf{invariant}\ \assert{y \leq x} & \\ \quad \assert{y < x \land y \leq x} & \comment{Loop condition and loop invariant} \\ \quad y := y + 1; & \\ \quad \assert{y \leq x} & \comment{Why is this true?} \\ \assert{\lnot (y < x) \land y \leq x} & \comment{Negated loop condition and loop invariant} \\ \assert{y = x} & \comment{By simplification} \end{array} \]
Let’s do another one, for computing the factorial function:
\[ \begin{array}{ll} \assert{n \geq 0} & \\ i := 0; & \\ \mathit{result} := 1; & \\ \assert{n \geq 0 \land i = 0 \land \mathit{result} = 1} & \\ \textbf{while}\ i < n\ \textbf{do} & \\ \quad \textbf{invariant}\ \assert{i \leq n \land \mathit{result} = i!} & \\ \quad \assert{i < n \land i \leq n \land \mathit{result} = i!} & \\ \quad i := i + 1; & \\ \quad \assert{i \leq n \land \mathit{result} = (i-1)!} & \\ \quad \mathit{result} := \mathit{result} * i; & \\ \quad \assert{i \leq n \land \mathit{result} = i!} & \\ \assert{\lnot (i < n) \land i \leq n \land \mathit{result} = i!} & \\ \assert{\mathit{result} = n!} & \end{array} \]
Implementations of Program Logics
In practice, researchers and programmers don’t sit down and write program logic proof outlines on paper; instead, they use formal verification tools which can automatically validate that a given proof is correct.
There are lots of tools in this space, which broadly fall into two categories:
- Tools which are libraries embedded in general-purpose theorem provers, such as Iris, VST, or vcgen; and
- Standalone tools, which use constraint solvers to check program logic proofs. Two popular tools here are Dafny, which is its own programming language, and Verus, a program logic for Rust.
Today, we will look into Dafny. The easiest way to install Danfy is using its VSCode extension. The rest of today’s lecture will will be following along the Dafny tutorial, which covers the subset of Dafny that overlaps with what we have learned in class.
How Dafny Works. Dafny is a semi-automated tool for performing program logic proofs. The user writes a piece of code (called a method) along with pre and postconditions, and Dafny will either return that the method is verified, or that it cannot complete the proof. Crucially, if Dafny cannot complete the proof, that does not mean that the statement is wrong! It can also mean that the user needs to supply more proof annotations for Dafny to check the proof.
The fragment of Dafny we are considering today is quite similar to IMP, but with the addition of methods. Since verification of IMP with integers is undecidable, Dafny requires you to annotate each loop with an invariant; without loop invariants, Dafny won’t be able to reason about the postcondition of a loop.
The real power of tools like Dafny comes from its powerful proof automation. For example, the following piece of code is valid Dafny (i.e., it verifies successfully):
method MakeUpperBound(x : int, y : int) returns (z : int)
ensures z >= x && z >= y
{
z := (x * x) + (y * y);
}
From vanilla Hoare logic alone, we get this triple:
\[ \assert{True}\ z := (x * x) + (y * y)\ \assert{z = x^2 + y^2} \] However, moving from this triple to the actual postcondition requires the following logical deduction (using the rule of consequence):
\[ (z = x^2 + y^2) \implies (z \geq x \land z \geq y). \] This requires a nontrivial mathematical argument, based on the properties of multiplication and \(\geq\). Fortunately, Dafny can decide certain simple mathematical properties like these automatically. It does so by using constraint solvers, which are lower-level programs which allow you to encode a collection of mathematical constraints, and decide whether or not it’s satisfiable. These constraint solvers can then be used to check whether a particular mathematical implication is correct. (Note: When reasoning about nonlinear arithmetic (such as multiplication) and quantifiers, automatic constraint solvers quickly become incomplete. In practice, you often have to help them out by stating extra intermediate assertions.)
Secrecy and Noninterference
These notes are in part adapted from Security Foundations, as well as the survey paper Language-Based Information-Flow Security.
Using the program logic we have seen in class, you can prove that a given program can compute the right answer for all possible inputs. However, just because a program can compute the right answer does not mean that it doesn’t have any bugs!
Let’s see an example in C-looking pseudocode.
string PlaceOrder(string item, string address, string card) {
string receipt = FormatReceipt(item, address);
Charge(card, Price(item));
WriteFile(card, "~/orders.log");
return receipt;
}
The above piece of code takes in an item item, a shipping address address, and a credit card number card,
charges the card for the item, and returns a receipt for the order.
However, it also writes the credit card number to disk in a place where any other person (or concurrently running process) could read it. While PlaceOrder returns what it should, it should not count as a correct ordering function!
First, let’s see that Hoare logic on its own cannot prevent this issue.
Let’s think of a specification for PlaceOrder, just focusing on the return value.
\[ \{\mathsf{True}\}\ \mathsf{PlaceOrder}(\mathsf{item}, \mathsf{address}, \mathsf{card})\ \{\mathsf{return} = \mathsf{FormatReceipt}(\mathsf{item}, \mathsf{address})\} \]
This specification
of the return value
is correct from a functional perspective, but not from a security perspective.
OK, we could try to fix it. Let’s try one fix, which prevents ~/orders.log from being written, by ensuring that the disk content at ~/orders.log remains unchanged:
\[ \forall v.\ \{\mathsf{Disk}(\mathtt{\sim/orders.log}) = v\}\ \mathsf{PlaceOrder}(\mathsf{item}, \mathsf{address}, \mathsf{card})\ \{\mathsf{return} = \mathsf{FormatReceipt}(\mathsf{item}, \mathsf{address}) \land \mathsf{Disk}(\mathtt{\sim/orders.log}) = v\} \]
However, of course, this does not prevent PlaceOrder from just writing to some other location on the disk. So maybe we should instead ban all writes to the disk:
\[ \forall D.\ \{\mathsf{Disk} = D\}\ \mathsf{PlaceOrder}(\mathsf{item}, \mathsf{address}, \mathsf{card})\ \{\mathsf{return} = \mathsf{FormatReceipt}(\mathsf{item}, \mathsf{address}) \land \mathsf{Disk} = D\} \]
But this precludes any legitimate write to the disk; for example, we might want PlaceOrder to write the receipt to a file on the disk:
string PlaceOrder(string item, string address, string card) {
string receipt = FormatReceipt(item, address);
Charge(card, Price(item));
WriteFile(receipt, "~/receipt.txt");
return receipt;
}
How do we allow “good” writes to happen while preventing “bad” writes? The answer, which we will discuss today, is to track dependencies.
Security for IMP
Let’s think of this problem for our simple imperative language, IMP. Below is an abstracted version of our function from before: \[ \begin{array}{l} \mathit{receipt} := \mathit{item} + \mathit{address}; \\ \mathit{file} := \mathit{card}; \end{array} \] For us to analyze this example, we need to name which variables should be secret and which should be public. For this example, let’s say that \(\mathit{item}\), \(\mathit{address}\), \(\mathit{receipt}\), and \(\mathit{file}\) are public, but \(\mathit{card}\) is secret. This program is insecure because there is an information flow from the secret variable \(\mathit{card}\) to the public variable \(\mathit{file}\). That is, reading \(\mathit{file}\) will tell us what \(\mathit{card}\) is. We will now investigate what it means to prevent insecure information flows in programs.
We need a condition on programs which tells us that you can’t deduce the values of secret variables from the values of public variables. First, let’s consider the following requirement: no public variables can be equal to a secret variable. This requirement isn’t quite good enough, due to the following program: \[ \begin{array}{l} \mathit{receipt} := \mathit{item} + \mathit{address}; \\ \mathit{file} := \mathit{card} + 1; \end{array} \] While \(\mathit{file}\) is never equal to \(\mathit{card}\), an attacker can deduce the value of \(\mathit{card}\) by subtracting 1 from \(\mathit{file}\).
Instead, we need to capture the idea that no public variable can depend on a secret variable. We capture dependency by considering two executions of the program, which the same public inputs but different secret inputs. If the public outputs change in the two executions, then we know there is a dependency from the secret inputs to the public outputs.
Let’s see this in action with our example program. Let’s take two states: \[ \sigma_1 = \{\mathit{item} \mapsto 1, \mathit{address} \mapsto 2, \mathit{receipt} \mapsto 3, \mathit{file} \mapsto 4, \mathit{card} \mapsto 5\} \] Now, since the public inputs have to be the same in both executions, we set the second state as: \[ \sigma_2 = \{\mathit{item} \mapsto 1, \mathit{address} \mapsto 2, \mathit{receipt} \mapsto 3, \mathit{file} \mapsto 4, \mathit{card} \mapsto 6\} \]
Now, we can run the program to receive two final states: \[ \sigma_1’ = \{\mathit{item} \mapsto 1, \mathit{address} \mapsto 2, \mathit{receipt} \mapsto 3, \mathit{file} \mapsto 5, \mathit{card} \mapsto 5\} \] \[ \sigma_2’ = \{\mathit{item} \mapsto 1, \mathit{address} \mapsto 2, \mathit{receipt} \mapsto 3, \mathit{file} \mapsto 7, \mathit{card} \mapsto 6\} \]
Since the value of \(\mathit{file}\) changed at the end, we know that \(\mathit{file}\) depended on a secret input. If we instead changed the second line to \(\mathit{file} := \mathit{item};\), however, then the final states would be: \[ \sigma_1’ = \{\mathit{item} \mapsto 1, \mathit{address} \mapsto 2, \mathit{receipt} \mapsto 3, \mathit{file} \mapsto 1, \mathit{card} \mapsto 5\} \] \[ \sigma_2’ = \{\mathit{item} \mapsto 1, \mathit{address} \mapsto 2, \mathit{receipt} \mapsto 3, \mathit{file} \mapsto 1, \mathit{card} \mapsto 6\} \] Since the value of \(\mathit{file}\) did not change, we know that \(\mathit{file}\) does not depend on a secret input.
Defining Security.
This brings us to our definition of security, which is called noninterference.
To define noninterference for general programs, we need a notion of a labeling, \(\Gamma\), which assigns a security level to each variable in the program. For now, we will have two security levels: public and secret. Hence, \(\Gamma\) will have type \(\mathsf{Var} \to \{public, secret\}\).
Now, we need to know how to talk about the two parallel states, \(\sigma_1\) and \(\sigma_2\). We need them to agree on public outputs, but (possibly) differ on secret outputs. To that end, we introduce the following definition: \[ \sigma_1 \approx_\Gamma \sigma_2 := \forall x. \Gamma(x) = public \implies \sigma_1(x) = \sigma_2(x). \] \[ \sigma_1 \approx_L \sigma_2 := \forall x. \Gamma(x) = public \implies \sigma_1(x) = \sigma_2(x). \] We say that \(\sigma_1\) and \(\sigma_2\) are indistinguishable under \(\Gamma\) if \(\sigma_1 \approx_\Gamma \sigma_2\). Two states are indistinguishable if they agree on all public variables. Now that we have defined indistinguishability, we can define noninterference:
Definition (Noninterference). Let \(\Gamma\) be a labeling. An IMP statement \(s\) is noninterferent if, for all \(\sigma_1\) and \(\sigma_2\) such that \(\sigma_1 \approx_\Gamma \sigma_2\), if \(\langle \sigma_1, s \rangle \to^* \langle \sigma_1’, \mathsf{skip} \rangle\) and \(\langle \sigma_2, s \rangle \to^* \langle \sigma_2’, \mathsf{skip} \rangle\), then \(\sigma_1’ \approx_\Gamma \sigma_2’\).
You can think of noninterference as a property on two parallel executions of the program, where they begin from two indistinguishable states. If both executions finish, then the two final states must also be indistinguishable. This intuition shows why Hoare logic on its own is not enough: Hoare logic (as we have seen in class) only reasons about one execution at a time, whereas noninterference requires two.
Examples: Assignment
Throughout the below examples, we will write \(x_P\) for a public variable \(x\), and \(y_S\) for a secret variable \(y\).
Is the following program noninterferent? \[ \begin{array}{l} x_P := a_P + b_P; \\ y_S := z_S + 1; \end{array} \]
Yes, because, while we assign to a secret variable, we only use secrets to do so.
What about this one? \[ \begin{array}{l} x_P := a_P + b_P; \\ y_S := x_P + 1; \end{array} \] Still yes! You are allowed to move public values into secret variables; just not the other way around.
What about this? \[ \begin{array}{l} x_S := y_S + z_P; \\ a_S := x_S + 1; \\ b_P := 2 \cdot a_S; \end{array} \] No, because there is a dependency between \(x_S\) and \(b_P\).
This all seems to imply a rule: assignments can flow from public to secret, but not vice versa.
Examples: Control Flow
So far, we have only seen how noninterference works for simple programs consisting of assignments. Now, let’s see what noninterference means for control flow statements, such as conditionals and loops.
First, let’s consider the following program: \[ \begin{array}{l} \mathsf{if}\ x_P > 0\ \mathsf{then} \\ \quad y_S := 1 \\ \mathsf{else} \\ \quad y_S := 2 \end{array} \] Is this program noninterferent? Yes, because the condition is based on a public variable. Thus, the two parallel runs of the program will follow the same control flow, and either both assign \(y_S := 1\) or both assign \(y_S := 2\).
For the same reason, the following programs is also noninterferent: \[ \begin{array}{l} x_P := 0; \\ \mathsf{while}\ x_P < y_P\ \mathsf{do} \\ \quad z_S := z_S + 1; \end{array} \] We are performing a loop, but the loop condition is based on public variables.
OK, so does that mean we can only branch on a public expression? Not so! This is also fine: \[ \begin{array}{l} y_P := z_P \cdot 2; \\ \mathsf{if}\ y_S > 0\ \mathsf{then} \\ \quad x_S := y_S \\ \mathsf{else} \\ \quad x_S := -y_S \\ y_P := y_P + 1 \end{array} \] Thus, we can branch on secret variables as well; however, the below program is not noninterferent: \[ \begin{array}{l} \mathsf{if}\ y_S > 0\ \mathsf{then} \\ \quad x_P := 1 \\ \mathsf{else} \\ \quad x_P := 2 \end{array} \] Why is this? Because there is an indirect control-flow dependency from the secret variable \(y_S\) to the public variable \(x_P\). Considering booleans as integers still, the above program is equivalent to: \[ \begin{array}{l} x_P := 1 \cdot (y_S > 0) + 2 \cdot (y_S \leq 0); \end{array} \] which is not allowed by our rule about assignment.
This brings us to our second rule: you cannot assign to public variables inside of a secret branch.
Defending Noninterference
Now that we have a definition of noninterference, we can now define a type system for statements which can guarantee noninterference. What does this mean for the real world? It means that, given an untrusted piece of code (even one written by a coding agent), we can statically check and hence trust that it won’t misuse our secret data. This is a very powerful idea! The type system we are presenting is an information flow type system, because it tracks information flows throughout the program.
Since we are defining a type system, we first need to define our types. We want to track public and secret data, so our types are going to be security labels:
\[ L ::= \mathsf{public} \mid \mathsf{secret} \]
Now, we need to define our type system. Let’s recap the grammar of IMP we wish to capture:
\[ \begin{array}{rcl} e & ::= & n \mid x \mid e_1 \oplus e_2 \mid \ominus e \\ s & ::= & x := e \mid s_1; s_2 \mid \mathsf{if}\ e\ \mathsf{then}\ s_1\ \mathsf{else}\ s_2 \mid \mathsf{while}\ e\ \mathsf{do}\ s \end{array} \] Above, \(e_1 \oplus e_2\) and \(\ominus e\) represent arbitrary binary and unary operations, respectively.
Because our grammar has two subgrammars for expressions and statements, we will define separate typing judgments for each.
Typing Expressions. Expressions will be typed in a manner similar to how we typed arithmetic expressions earlier in the class. The judgment will look like \(\Gamma \vdash e : L\), where \(\Gamma : \mathsf{Var} \to \{ \mathsf{public}, \mathsf{secret} \}\) is a labeling.
To define the typing rules, we will introduce one more piece of notation: the join \(L_1 \sqcup L_2\), which represents the least upper bound of the two labels \(L_1\) and \(L_2\). For our simple set of labels \({\mathsf{public}, \mathsf{secret}}\), the join is defined as follows: \[ L_1 \sqcup L_2 := \begin{cases} \mathsf{public} & \text{if } L_1 = \mathsf{public} \text{ and } L_2 = \mathsf{public} \\ \mathsf{secret} & \text{otherwise} \end{cases} \]
We can now define the typing rules for expressions: \[ \dfrac{}{\Gamma \vdash n : \tau}\ \text{(T-Const)} \qquad \dfrac{}{\Gamma \vdash x : \Gamma(x)}\ \text{(T-Var)} \]
\[ \dfrac{\Gamma \vdash e_1 : L_1 \qquad \Gamma \vdash e_2 : L_2}{\Gamma \vdash e_1 \oplus e_2 : L_1 \sqcup L_2}\ \text{(T-BinOp)} \qquad \dfrac{\Gamma \vdash e : L}{\Gamma \vdash \ominus e : L}\ \text{(T-UnOp)} \]
Typing Statements. We are now ready to type statements. Since statements only are run for their side effects but do not themselves output values, our judgment for statements does not have an output type. Furthermore, because we need to track control-flow dependencies (since you can’t assign to public variables in a secret branch), our judgment also needs to include a program counter label which represents the current security level of control flow. Putting these ideas together, our judgment will look like \(\Gamma; \mathsf{pc} \vdash s\), where \(\mathsf{pc}\) is the current program counter label. Initially \(\mathsf{pc}\) will begin at \(\mathsf{public}\), but can grow when we branch on secrets.
To define the typing rules for statements, we need one extra ingredient: a notion of flows-to, written \(L_1 \sqsubseteq L_2\), which represents that information is allowed to flow from label \(L_1\) to label \(L_2\). For our simple set of labels \({\mathsf{public}, \mathsf{secret}}\), the flows-to relation is defined as follows: \[ L_1 \sqsubseteq L_2 := \begin{cases} \mathsf{false} & \text{if } L_1 = \mathsf{secret} \text{ and } L_2 = \mathsf{public} \\ \mathsf{true} & \text{otherwise} \end{cases} \]
We now can define the typing rules for statements:
\[ \dfrac{}{\Gamma; \mathsf{pc} \vdash \mathsf{skip}}\ \text{(T-Skip)} \qquad \dfrac{\Gamma \vdash e : L \qquad \mathsf{pc} \sqsubseteq \Gamma(x) \qquad L \sqsubseteq \Gamma(x)}{\Gamma; \mathsf{pc} \vdash x := e}\ \text{(T-Assign)} \]
\[ \dfrac{\Gamma; \mathsf{pc} \vdash s_1 \qquad \Gamma; \mathsf{pc} \vdash s_2}{\Gamma; \mathsf{pc} \vdash s_1; s_2}\ \text{(T-Seq)} \]
\[ \dfrac{\Gamma \vdash e : L \qquad \Gamma; \mathsf{pc} \sqcup L \vdash s_1 \qquad \Gamma; \mathsf{pc} \sqcup L \vdash s_2}{\Gamma; \mathsf{pc} \vdash \mathsf{if}\ e\ \mathsf{then}\ s_1\ \mathsf{else}\ s_2}\ \text{(T-If)} \]
\[ \dfrac{\Gamma \vdash e : L \qquad \Gamma; \mathsf{pc} \sqcup L \vdash s}{\Gamma; \mathsf{pc} \vdash \mathsf{while}\ e\ \mathsf{do}\ s}\ \text{(T-While)} \]
The rules for \(\mathsf{skip}\) and sequencing are straightforward. For assignment, we need to perform two checks: one, that the label of the expression can flow to the label of the variable being assigned (to rule out direct flows from secret to public), and two, that the current program counter label also flows to the label of the variable being assigned (to rule out implicit flows from the control flow to the variable). The rules for control flow statements grow the program counter label by the label of the guard.
Soundness. While we will formally prove soundness of the type system, we can state it:
Theorem. If \(\Gamma; \mathsf{public} \vdash s\), then \(s\) satisfies noninterference under \(\Gamma\).
Incompleteness of Information Flow Type Systems
It is worth mentioning that there are some programs which are semantically noninterferent but are not accepted by the type system. Indeed, since IMP is Turing-complete, it is undecidable to automatically check whether a given program is noninterferent. Consider this program: \[ \begin{array}{l} s; \\ \mathsf{if}\ e\ \mathsf{then}\ x_P := y_S\ \mathsf{else}\ \mathsf{skip} \end{array} \] where the variable \(y_S\) is not used in the program \(s\). This program is noninterferent if and only if, after running \(s\), the value of \(e\) is equal to zero, which is undecidable.
While this might be a contrived example, there are some more interesting (and realistic) programs which are noninterferent but do not pass our type system. Here is an example: \[ \begin{array}{l} x_P := y_S; \\ z_S := x_P; \\ x_P := 0; \end{array} \] Here, we temporarily make use of the public variable \(x_P\) to store the value of the secret variable \(y_S\) before copying it to the secret variable \(z_S\). The above program is equivalent to the program \[ \begin{array}{l} z_S := y_S; \\ x_P := 0; \end{array} \] which is noninterferent, so our first program must be as well. While this example might seem a bit contrived, it stands in for a real use-case: shared memory usage. Suppose we have a high-security process which needs to use memory that is shared between multiple threads. Naively, this is insecure, since another thread can read the contents of the shared memory, which might contain secrets. However, if the high-security process makes sure to zeroize the memory after releasing access to the shared resource, then the shared resource can safely hold secret data temporarily.


