Skip to content

Closures and Type Inference

This semester, I took a Compilers course where the problem sets involved incrementally implementing compiler features in OCaml. In this series, I’ll briefly summarize each piece. Taken together, I hope these posts provide a good foundation for understanding how compilers work.

The problem sets were fairly open-ended as long as the compiler produced correct results. My approaches won’t always match what a production compiler would do, but I’ve attempted to preserve the core ideas. Code is available in this repo.

Although the articles closely follow the problem sets, some also cover topics that weren’t directly tied to a specific problem set.


Until now, we have worked with a simple “C-ish” programming language (Cish). In previous assignments, we built a compiler that can compile simple Cish programs like the ones below to RISC-V.

// Cish example 1
main() {
return 12 + 4;
}
// Cish example 2
f(a) {
return a * a;
}
main() {
f(2);
}

In ps5, we move on to a richer programming language, Scish (“Scheme-ish”). Scish is a functional programming language. The main focus of ps5 is compiling closures.

// Scish example 1
((lambda (x) (+ x 3)) 4)
// Scish example 2
(((lambda (x) (lambda (y) (+ x y))) 42) 3)

Instead of compiling directly to RISC-V, we take a Scish AST and convert it into a Cish AST. Since we already implemented a Cish → RISC-V compiler in ps4, in theory, a Scish source program can be compiled in two steps: Scish → Cish → RISC-V.

In the ps5 starter code, Cish has been extended to include dynamic memory allocation (malloc). We don’t know how the Cish compiler compiles malloc to RISC-V; for the purposes of ps5, we simply assume that it exists and can be used by our Scish → Cish compiler.

Rather than focusing on the implementation details of constructing a Cish AST, let’s look at high-level strategies. The problem set recommended two different strategies for compiling closures. We’ll look at each one, but before we dive in, let’s review what closures are.

A closure is a function plus its environment. An environment is just a mapping from variable names to their values. In functional programming languages, functions are usually lexically scoped. This means that a function looks up its free variables in the environment where it was defined, rather than where it’s called.

In our second Scish example, we first apply 42 to the outer lambda, which gives us (lambda (y) (+ x y)) with x = 42. We need to preserve this binding so that when we later call the inner lambda with y = 3, we know that the value of x is 42.


Now, let’s return to our first Scish example.

((lambda (x) (+ x 3)) 4)

Here is the corresponding Cish code produced using Strategy A.

// We don't have to pass dynenv to main,
// it is shadowed right away, but we just do it
// so that every function has a uniform f(dynenv)
// signature.
main(dynenv) {
let result = 0; {
let dynenv = 0; {
let t1 = 0; {
let t2 = 0; {
let t3 = 0; {
result = malloc(8); // Allocate 8 bytes.
*result = t4; // First word points to function t4.
*(result + 4) = dynenv; // Second word points to main's env (which is just 0).
t1 = *result; // t4
t2 = *(result + 4); // main's env
result = 4; // Function argument x = 4.
t3 = malloc(8); // Allocate memory for new env frame.
*t3 = t2; // Pointer to main's env.
*(t3 + 4) = result; // Function argument x = 4.
result = t1(t3); // Call t4 with the new env frame.
}
}
}
}
return result;
}
}
t4(dynenv) {
let result = 0; {
result = *(dynenv + 4); // x = 4
let t5 = result; { // t5 is now 4
result = 3;
result = t5 + result;
}
return result;
}
}

The code was generated by a compiler and is not particularly readable, but the key idea is that we use malloc to store closures in memory.

In Strategy A, each function has a uniform f(dynenv) signature. Inside t4, we read *(dynenv + 4) to retrieve the function argument x = 4.

The interesting part happens right before we call t4. We allocate 8 bytes for a new environment frame. The first word points to the captured environment, forming a linked list of frames. The second word stores the function argument, 4. Each function takes only one argument; functions that take multiple arguments can be converted into nested unary functions.

t4's env main's env
[ - ] --------> [ 0 ]
[ x = 4 ]

Our example is simple, so the environment chain has only one real binding and main’s env is just 0. But if several lambdas were nested, we can imagine multiple linked frames, and variable lookup would require traversing that chain until the right binding is found.


Now, let’s look at the second Cish produced using Strategy B.

CLOSURE(tag, env, env_len) {
let p = malloc(12); {
*p = tag;
*(p + 4) = env;
*(p + 8) = env_len;
return p;
}
}
APPLY(closure, arg_val) {
let env = EXTEND_ENV(
arg_val,
*(closure + 4),
*(closure + 8)
); {
let tag = *closure; {
if (tag == 0) {
return lambda0(env);
} else {
0;
}
}
}
}
EXTEND_ENV(val, env, env_len) {
let new_env = malloc(4 + env_len * 4); {
*new_env = val;
let i = 0; {
for (i = 0; i < env_len; i = i + 1) {
*(new_env + i * 4 + 4) = *(env + i * 4);
}
}
return new_env;
}
}
main() {
let env = malloc(0); {
return APPLY(
CLOSURE(0, env, 0),
4
);
}
}
lambda0(env) {
return *(env + 0 * 4) + 3;
}

In the second approach, we invoke a function by calling APPLY on a CLOSURE. Each lambda is assigned a unique ID called a tag. During compilation, we generate a fresh tag for each lambda and give it a name like lambda0. Inside APPLY, we use the tag to invoke the right lambda.

CLOSURE(tag, env, env_len) allocates 12 bytes. The first word stores the tag, the second word points to the captured environment, and the third word stores its length. This information is used by EXTEND_ENV, which is called inside APPLY.

EXTEND_ENV copies the captured environment and prepends the new argument. We need to know the environment’s length so that we can allocate the right number of bytes. While copying the environment is more expensive, variable lookup becomes simpler. Instead of chasing pointers through linked environments, we can access variables within one contiguous block of memory. In practice, the compiler can use a scheme like De Bruijn indices to determine each variable’s index directly, rather than scanning for it at runtime. EXTEND_ENV returns new_env, which we then pass to lambda0(new_env).

Of the two strategies, I implemented Strategy B.


In ps6, we implement a compiler for an ML-ish programming language. As in ps5, instead of targeting RISC-V, we compile to a higher-level representation (Scish).

MLish is fairly similar to Scish, but we add another layer of complexity. In addition to compilation, we also type-check and type-infer the given ML program. For example:

(fun a b -> a + b) 1 2

Notice that the types are not annotated, so we have to infer them as we type-check the program. In this example, the program is valid because + is applied to two integers. If a program is not well-typed, we raise a TypeError.

We can have polymorphic types. For example, the identity function has a polymorphic type: it can be used as an int -> int, bool -> bool, and so on. In the example below, the same function is used once on an integer and once on an empty list.

let x = (fun x -> x) in
(x 1, x [])

To implement type inference, we first need to implement a set of core operations. We will look at each operation, and at the end, zoom out to see how everything fits together in one traversal of the AST.

If the programmer annotated every type, type-checking would mostly amount to traversing the AST and checking that two subtrees have matching types. With type inference, however, we often don’t know a variable’s type right away, and may only figure it out later as we see more of the program.

In this problem set, we handle this uncertainty using an OCaml ref, which is a mutable box. In the code, unknown types are represented as Guess_t of tipe option ref (tipe instead of the reserved type keyword). That means a guess is a box that either holds None if the type is yet unknown, or Some t once we have figured out what the type must be. So we can start with Guess_t (ref None) as a placeholder and fill it in later as more information becomes available.

Informally, we can think of type inference as solving a system of equations, where Guess_ts are the unknown variables that we are trying to solve for.

Unification checks whether two types, t1 and t2, can be made compatible. The tricky part is that t1 and t2 may contain unconstrained guesses.

During unification, some of these guesses may be resolved. For example, a guess in t1 can become constrained once we compare it against t2. It is also possible to learn that two guesses must stand for the same type, even if we still don’t know what that type is. In this case, we can link the two guesses to mark that they should be equal, and resolve them later once more information becomes available.

A subtle issue is that linked guesses may not be resolved immediately. Suppose we already know that r1 and r2 should represent the same type, and later we learn that r2 is an integer:

r1 -> r2
r2 -> int

r1 should also resolve to an int, but we may have to follow the chain of links before we see that. In my implementation, this step is handled by prune. Before unifying t1 and t2, I first prune each one so that linked guesses are reduced to their current final type.

Another subtlety is that unification fails if it creates a cycle. Suppose that, while recursively unifying t1 and t2, we need to unify a guess r with some type t. Before binding r to t, we check whether t already contains r. If it does, unification fails.

Consider the following example:

Lambda ("x", App (Var "x", Var "x"))

This corresponds to the expression fun x -> (x x). In (x x), the left x is a function, while the right x is passed to it as an argument. In other words, x is called with itself as the argument.

Suppose x is assigned a fresh guess r1. Since the right x is the argument, it has type r1. The left x must therefore have type r1 -> r2 for some result type r2. However, the left x is the same variable and also has type r1, so we are forced to unify r1 with r1 -> r2.

We are left with a weird recursive state where:

r1 = r1 -> r2

This is impossible to unify, because r1 contains itself. If we keep expanding the equation, we get:

r1 = r1 -> r2
r1 = (r1 -> r2) -> r2
r1 = ((r1 -> r2) -> r2) -> r2
...

For this reason, unification should fail when a guess appears inside the type it is being unified with. In my implementation, this is checked by occur. When this happens, we treat the program as ill-typed and raise a TypeError.

Now, let’s start thinking about polymorphic types. To make our lives easier, we only assume let-polymorphism. This means that only let-bound expressions contain polymorphic types.

let x = (fun x -> x) in
(x 1, x [])

In this example, x can be polymorphic because it is introduced in (fun x -> x). Here, the let-bound expression (fun x -> x) happens to be an identity function that works uniformly across many types.

Suppose we encounter let while traversing the AST. We first infer the type of the let-bound expression. Fresh guesses are generated in the process, so the inferred type could be something like r1 -> r1.

But we have a problem. Since this is an identity function, it should work across different types. If we constrained r1 -> r1 directly, then seeing x 1 would constrain r1 to int. When we later encounter x [], r1 would already be fixed to int, so the second use would fail.

To avoid this, we generalize r1 -> r1 into a polymorphic type such as tvar0 -> tvar0 and store the “type scheme” in an environment. Later, whenever we actually use x, we retrieve the type scheme and instantiate it by replacing tvar0 with a fresh guess.

For example, the first use of x might give us r2 -> r2, which can then be constrained to int -> int when we see x 1.

When we later encounter x [], we instantiate the type scheme again with a different fresh guess, say r3 -> r3. Since this guess is independent of r2, it can be constrained to a list without conflicting with the earlier use.

Before we call unify, polymorphic variables should already have been instantiated.

Let’s see how type schemes are implemented.

type tipe_scheme = Forall of (tvar list) * tipe
type env = (var * tipe_scheme) list

Here, a tvar such as tvar0, tvar1, … represents a polymorphic type variable. For the fun x -> x example, the type scheme of x is something like:

Forall (["tvar0"], Fn_t (Tvar_t "tvar0", Tvar_t "tvar0"))

This loosely translates to: “all tvars listed here are polymorphic variables that may be instantiated with fresh guesses when this type scheme is used.”

Here is my implementation for generalization and instantiation. While I won’t discuss the details, we can see that both rely on several helper functions.

let generalize (env : env) (t : tipe) : tipe_scheme =
let t_gs = guesses_of_type t in
let env_gs = guesses_of_env env in
let gs = diff t_gs env_gs in
let fresh_tvs = List.map (fun r -> (r, fresh_tvar ())) gs in
let new_tipe = substitute_guesses fresh_tvs t in
Forall (List.map snd fresh_tvs, new_tipe)
let instantiate (Forall (tvars, t) : tipe_scheme) : tipe =
let fresh_guesses =
List.map (fun tvar -> (tvar, guess ())) tvars
in
substitute fresh_guesses t

One subtle point in generalization is that we cannot generalize every unresolved guess in the inferred type. Some guesses may be connected to variables in the outside environment. For example, consider:

fun y ->
let x = (fun z -> y) in
...

Here, let’s say y already has some unknown type r1, and we introduce a fresh guess r2 for z. The let-bound expression fun z -> y therefore has the type r2 -> r1. Here, it is safe to generalize r2, but not r1, because r1 must remain connected to the outer variable y. This is why generalization excludes guesses that already appear in the surrounding environment.

We have covered the core set of operations, but it is still very confusing to see how they all fit together. So let’s return to the example from above one last time. The identity function example’s AST would look something like this.

Let
├── bound variable: x
├── bound expression:
│ └── Fn
│ ├── parameter: x
│ └── body:
│ └── Var x
└── body:
└── Pair
├── left:
│ └── App
│ ├── function: Var x
│ └── argument: Int 1
└── right:
└── App
├── function: Var x
└── argument: Nil

As discussed earlier, we first infer the type of the let-bound expression, which is then generalized and stored in the environment as a type scheme. After that, we continue type-checking the body. When we see a pair, we type-check the left component first, and then the right component.

let rec tc (env : env) (e : Mlish_ast.exp) : tipe =
match e with
...
| Pair, [e1; e2] ->
let t1 = tc env e1 in
let t2 = tc env e2 in
Pair_t (t1, t2)

As we type-check t1, we encounter x. At this point, we look up x in the environment and retrieve its type scheme. We then instantiate that type scheme with fresh guesses.

Those fresh guesses are later resolved when we unify at App.

let rec tc (env : env) (e : Mlish_ast.exp) : tipe =
match e with
...
(App (e1, e2), _) ->
let t1 = tc env e1 in
let t2 = tc env e2 in
let tr = guess () in (* a fresh guess for return type *)
unify t1 (Fn_t (t2, tr));
tr

At this point, the application tells us more about the type of x. In the left branch, x is applied to 1, so the fresh instantiated type of x is forced to become int -> int. In the right branch, the same process happens again, but with a new instantiation of x, which is why the two uses do not interfere with each other.