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.