In part 8, we wrote some pretty interesting programs in our little language.
We successfully expressed arithmetic and recursion. But there’s one thing
that we cannot express in our language without further changes: an if
statement.
Suppose we didn’t want to add a special if/else
expression into our language.
Thanks to lazy evaluation, we can express it using a function:
defn if c t e = {
case c of {
True -> { t }
False -> { e }
}
}
But an issue still remains: so far, our compiler remains monomorphic. That
is, a particular function can only have one possible type for each one of its
arguments. With our current setup, something like this
[note:
In a polymorphically typed language, the inner if
would just evaluate to
False
, and the whole expression to 3.
]
if (if True False True) 11 3
This is because, for this to work, both of the following would need to hold (borrowing some of our notation from the typechecking post):
But using our rules so far, such a thing is impossible, since there is no way for to be unified with . We need a more powerful set of rules to describe our program’s types.
Hindley-Milner Type System
One such powerful set of rules is the Hindley-Milner type system, which we have previously alluded to. In fact, the rules we came up with were already very close to Hindley-Milner, with the exception of two: generalization and instantiation. It’s been quite a while since the last time we worked on typechecking, so I’m going to present a table with these new rules, as well as all of the ones that we [note: The rules aren't quite the same as the ones we used earlier; note that is used in place of in the first rule, for instance. These changes are slight, and we'll talk about how the rules work together below. ] I will also give a quick summary of each of these rules.
Rule | Name and Description |
---|---|
Var: If the variable is known to have some polymorphic type then an expression consisting only of that variable is of that type. | |
App: If an expression , which is a function from monomorphic type to another monomorphic type , is applied to an argument of type , then the result is of type . | |
Case: This rule is not part of Hindley-Milner, and is specific to our language. If the expression being case-analyzed is of type and each branch is of the same type when the pattern works with type producing extra bindings , the whole case expression is of type . | |
Inst (New): If type is an instantiation (or specialization) of type then an expression of type is also an expression of type . | |
Gen (New): If an expression has a type with free variables, this rule allows us generalize it to allow all possible types to be used for these free variables. |
Here, there is a distinction between different forms of types. First, there are monomorphic types, or monotypes, , which are types such as , , and so on. These types are what we’ve been working with so far. Each of them represents one (hence, “mono-”), concrete type. This is obvious in the case of and , but for things are slightly less clear. Does it really represent a single type, if we can put an arbtirary thing for ? The answer is “yes”! Although is not currently known, it stands in place of another monotype, which is yet to be determined.
So, how do we represent polymorphic types, like that of ? We borrow some more notation from mathematics, and use the “forall” quantifier:
This basically says, “the type of is for all possible ”. This new expression using “forall” is what we call a type scheme, or a polytype . For simplicity, we only allow “forall” to be at the front of a polytype. That is, expressions like are not valid polytypes as far as we’re concerned.
It’s key to observe that only some of the typing rules in the above table use polytypes (). Whereas expressions consisting of a single variable can be polymorphically typed, this is not true for function applications and case expressions. In fact, according to our rules, there is no way to introduce a polytype anywhere into our system!
The reason for this is that we only allow polymorphism at certain locations. In the Hindley-Milner type system,
this is called Let-Polymorphism, which means that only in let
/in
expressions can variables or expressions
be given a polymorphic type. We, on the other hand, do not (yet) have let
/in
expressions, so our polymorphism
is further limited: only functions (and data type constructors) can be polymorphically typed.
Let’s talk about what Inst does, and what “” means. First, why don’t we go ahead and write the formal inference rule for :
In my opinion, this is one of the more confusing inference rules we have to deal with in Hindley-Milner. In principle, though, it’s not too hard to understand. says “ is more general than ”. Alternatively, we can interpret it as “ is an instance of ”.
What does it mean for one polytype to be more general than another? Intuitively, we might say that is more general than , because the former type can represent the latter, and more. Formally, we define this in terms of substitutions. A substitution replaces a variable with a monotype . If we can use a substitution to convert one type into another, then the first type (the one on which the substitution was performed) is more general than the resulting type. In our previous example, since we can apply the substitution to get from , the latter type is more general; using our notation, .
That’s pretty much all that the rule says, really. But what about the whole thing with and ? The reason for that part of the rule is that, in principle, we can substitute polytypes into polytypes. However, we can’t do this using . Consider, for example:
Hmm, this is not good. Didn’t we agree that we only want quantifiers at the front of our types? Instead, to make that substitution, we only substitute the monotype , and then add the at the front. But to do this, we must make sure that doesn’t occur anywhere in the original type (otherwise we can accidentally generalize too much). So then, our concrete inference rule is as follows:
In the above rule we:
- Replaced with , getting rid of in the quantifier.
- Observed that is not a free variable in the original type, and thus can be generalized.
- Added the generalization for to the front of the resulting type.
Now, Inst just allows us to perform specialization / substitution as many times as we need to get to the type we want.
A New Typechecking Algorithm
Alright, now we have all these rules. How does this change our typechecking algorithm? How about the following:
- To every declared function, assign the type , where [note: Of course, there can be more or less than 25 arguments to any function. This is just a generalization; we use as many input types as are needed. ] and is the function’s return type.
- We typecheck each declared function, using the Var, Case, App, and Inst rules.
- Whatever type variables we don’t fill in, we assume can be filled in with any type, and use the Gen rule to sprinkle polymorphism where it is needed.
Maybe this is enough. Let’s go through an example. Suppose we have three functions:
defn if c t e = {
case c of {
True -> { t }
False -> { e }
}
}
defn testOne = { if True False True }
defn testTwo = { if True 0 1 }
If we go through and typecheck them top-to-bottom, the following happens:
- We start by assuming , and .
- We look at
if
. We infer the type ofc
to be , and thus, . We also infer that , since they occur in two branches of the same case expression. Finally, we infer that , since whatever the case expression returns becomes the return value of the function. Thus, we come out knowing that . - Now, since we never figured out , we use Gen: . Like we’d want,
if
works with all types, as long as both its inputs are of the same type. - When we typecheck the body of
testOne
, we use Inst to turn the above type forif
into a single, monomorphic instance. Then, type inference proceeds as before, and all is well. - When we typecheck the body of
testTwo
, we use Inst again, instantiating a new monotype, and all is well again.
So far, so good. But what if we started from the bottom, and went to the top?
- We start by assuming , and .
- We look at
testTwo
. We infer that (since we pass inTrue
toif
). We also infer that , and that . Not yet sure of the return type ofif
, this is where we stop. We are left with the knowledge that (because the return type ofif
is the return type oftestTwo
), but that’s about it. Since is no longer free, we don’t generalize, and conclude that . - We look at
testOne
. We infer that (already known). We also infer that , and that . But wait a minute! This is not right. We are back to where we started, with a unification error!
What went wrong? I claim that we typechecked the functions that used if
before we typechecked if
itself,
which led us to infer a less-than-general type for if
. This less-than-general type was insufficient to
correctly check the whole program.
To address this, we enforce a particular order of type inference on our declaration, guided by dependencies between functions. Haskell, which has to deal with a similar issue, has a section in the 2010 report on this. In short:
- We find the [note: A transitive closure of a vertex in a graph is the list of all vertices reachable from that original vertex. Check out the Wikipedia page on this. ] of the function dependencies. We define a function to be dependent on another function if calls . The transitive closure will help us find functions that are related indirectly. For instance, if also depends on , then the transitive closure of will include , even if directly doesn’t use .
- We isolate groups of mutually dependent functions. If depends on and depends , they are placed in one group. We then construct a dependency graph of these groups.
- We compute a topological order of the group graph. This helps us typecheck the dependencies
of functions before checking the functions themselves. In our specific case, this would ensure
we check
if
first, and only then move on totestOne
andtestTwo
. The order of typechecking within a group does not matter, as long as we generalize only after typechecking all functions in a group. - We typecheck the function groups, and functions within them, following the above topological order.
To find the transitive closure of a graph, we can use Warshall’s Algorithm. This algorithm, with complexity , goes as follows:
In the above notation, is the th matrix , and is the adjacency matrix of the graph in question. All matrices in the algorithm are from , the set of by boolean matrices. Once this algorithm is complete, we get as output a transitive closure adjacency matrix . Mutually dependent functions will be pretty easy to isolate from this matrix. If and , then the functions represented by vertices and depend on each other.
Once we’ve identified the groups, and [note: This might seem like a "draw the rest of the owl" situation, but it really isn't. We'll follow a naive algorithm for findings groups, and for translating function dependencies into group dependencies. This algorithm, in C++, will be presented later on. ] it is time to compute the topological order. For this, we will use Kahn’s Algorithm. The algorithm goes as follows:
Note that since we’ve already isolated all mutually dependent functions into groups, our graph will never have cycles, and this algorithm will always succeed. Also note that since we start with nodes with no incoming edges, our list will begin with the groups that should be checked last. This is because a node with no incoming edges might (and probably does) still have outgoing edges, and thus depends on other functions / groups. Like in our successful example, we want to typecheck functions that are depended on first.
Implementation
Let’s start working on a C++ implementation of all of this now. First,
I think that we should create a C++ class that will represent our function
dependency graph. Let’s call it function_graph
. I propose the following
definition:
|
|
There’s a lot to unpack here. First of all, we create a type alias function
that
represents the label of a function in our graph. It is probably most convenient
to work with std::string
instances, so we settle for that. Next, we define
a struct that will represent a single group of mutually dependent functions.
Passing this struct by value seems wrong, so we’ll settle for a C++ unique_pt
to help carry instances around.
Finally, we arrive at the definition of function_graph
. Inside this class,
we define a helper struct, group_data
, which holds information
about an individual group as it is being constructed. This information
includes the group’s adjacency list and
indegree
(both used for Kahn’s topological sorting algorithm), as well as the set
of functions in the group (which we will eventually return).
The adjacency_lists
and edges
fields are the meat of the graph representation.
Both of the variables provide a different view of the same graph: adjacency_lists
associates with every function a list of functions it depends on, while
edges
holds a set of tuples describing edges in the graph. Having
more than one representation makes it more convenient for us to perform
different operations on our graphs.
Next up are some internal methods that perform the various steps we described above:
-
compute_transitive_edges
applies Warshall’s algorithm to find the graph’s transitive closure. -
create_groups
creates two mappings, one from functions to their respective groups’ IDs, and one from group IDs to information about the corresponding groups. This step is largely used to determine which functions belong to the same group, and as such, uses the set of transitive edges generated bycompute_transitive_edges
. -
create_edges
creates edges between groups. During this step, the indegrees of each group are computed, as well as their adjacency lists. -
generate_order
uses the indegrees and adjacency lists produced in the prior step to establish a topological order.
Following these, we have three public function definitions:
-
add_function
adds a vertex to the graph. Sometimes, a function does not reference any other functions, and would not appear in the list of edges. We will calladd_function
to make sure that the function graph is aware of such independent functions. For convenience,add_function
returns the adjacency list of the added function. -
add_edge
adds a new dependency between two functions. -
compute_order
method uses the internal methods described above to convert the function dependency graph into a properly ordered list of groups.
Let’s start by looking at how to implement the internal methods. compute_transitive_edges
is a very straightforward implementation of Warshall’s:
|
|
Next is create_groups
. For each function, we iterate over all other functions.
If the other function is mutually dependent with the first function, we add
it to the same group. In the outer loop, we skip over functions that have
already been added to the group. This is because
[note:
There is actually a slight difference between "mutual dependence"
the way we defined it and "being in the same group", and
it lies in the symmetric property of an equivalence relation.
We defined a function to depend on another function if it calls
that other function. Then, a recursive function depends on itself,
but a non-recursive function does not, and therefore does not
satisfy the symmetric property. However, as far as we're concerned,
a function should be in a group with itself even if it's not recursive. Thus, the
real equivalence relation we use is "in the same group as", and
consists of "mutual dependence" extended with symmetry.
]
is an equivalence relation,
which means that if we already added a function to a group, all its
group members were also already visited and added.
|
|
Once groups have been created, we use their functions’ edges
to create edges for the groups themselves, using create_edges
.
We avoid creating edges from a group to itself, to prevent
unnecessary cycles. While constructing the edges, we also
increment the relevant indegree counter.
|
|
Finally, we apply Kahn’s algorithm to create a topological order
in generate_order
:
|
|
These four steps are used in compute_order
:
|
|
Let’s now look at the remaining two public definitions.
First comes add_function
, which creates an adjacency list for the
function to be inserted (if one does not already exist),
and returns a reference to the resulting list:
|
|
We use this in add_edge
, which straightforwardly creates an edge
between two functions:
|
|
With this, we can now properly order our typechecking. However, we are just getting started: there are still numerous changes we need to make to get our compiler to behave as we desire.
The first change is the least relevant, but will help clean
up our code base in the presence of polymorphism: we will
get rid of resolve
, in both definitions and AST nodes.
The reasons for this are twofold. First,
[note:
Recall that ast_case
needs this information to properly
account for the changes to the stack from when data is unpacked.
]
This means that
all the rest of the infrastructure we’ve written around
preserving types is somewhat pointless. Second, when
we call resolve
, we’d now have to distinguish
between type variables captured by “forall” and actual,
undefined variables. That’s a lot of wasted work!
To replace the now-removed type
field,
we make ast_case
include a new member, input_type
,
which stores the type of the thing between case
and of
.
Since ast_case
requires its type to be a data type
at the time of typechecking, we no longer need to resolve anything.
Next, we need to work in a step geared towards finding function calls (to determine dependencies). As we have noted in part 6, it’s pretty easy to tell apart calls to global functions from “local” ones. If we see that a variable was previously bound (perhaps as a function argument, or by a pattern in a case expression), we know for sure that it is not a global function call. Otherwise, if the variable isn’t bound anywhere in the function definition (it’s a free variable), it must refer to a global function. Then, we can traverse the function body, storing variables that are bound (but only within their scope), and noting references to variables we haven’t yet seen. To implement this, we can use a linked list, where each node refers to a particular scope, points to the scope enclosing it, and contains a list of variables…
Wait a minute, this is identical to type_env
! There’s no reason to reimplement all
this. But then, another question arises: do we throw away the type_env
generated
by the dependency-searching step? It seems wasteful, since we will eventually
repeat this same work. Rather, we’ll re-use the same type_env
instances
in both this new step and typecheck
. To do this, we will now store a pointer
to a type_env
in every AST node, and set this pointer during our first traversal
of the tree. Indeed, this makes our type_env
more like a
symbol table. With this change,
our new dependency-finding step will be implemented by the find_free
function
with the following signature:
void ast::find_free(type_mgr& mgr, type_env_ptr& env, std::set<std::string>& into);
Let’s take a look at how this will be implemented. The simplest case (as usual)
is ast_int
:
|
|
In this case, we associate the type_env
with the node, but don’t do anything
else: a number is not a variable. A more interesting case is ast_lid
:
|
|
If a lowercase variable has not yet been bound to something, it’s free,
and we store it. Somewhat counterintuitively, ast_uid
behaves
differently:
|
|
We don’t allow uppercase variables to be bound to anything outside of data type
declarations, so we don’t care about uppercase free variables. Next up is
ast_binop
:
|
|
A binary operator can have free variables in the subexpressions on the left and on the right, and
the above implementation reflects that. This is identical to the implementation of
ast_app
:
|
|
Finally, ast_case
requires the most complicated function (as usual):
|
|
The type_scope
function replaces the type_env::scope
method,
which cannot (without significant effort) operate on smart pointers.
Importantly, we are using a new pattern
method here, insert_bindings
. This
is because we split “introducing variables” and “typechecking variables”
into two steps for patterns, as well. The implementation of insert_bindings
for pattern_var
is as follows:
|
|
A variable pattern always introduces the variable it is made up of.
On the other hand, the implementation for pattern_constr
is as follows:
|
|
All the variables of the pattern are placed into the environment. For now, we don’t worry about arity; this is the job of typechecking.
These changes are reflected in all instances of our typecheck
function. First of
all, typecheck
no longer needs to receive a type_env
parameter, since each
tree node has a type_env_ptr
. Furthermore, typecheck
should no longer call
bind
, since this was already done by find_free
. For example,
ast_lid::typecheck
will now use env::lookup
:
|
|
Don’t worry about instantiate
for now; that’s coming up. Similarly to
ast_lid
, ast_case::typecheck
will no longer introduce new bindings,
but unify existing types via the pattern
:
|
|
The above implementation uses another new pattern
method, typecheck
.
This method inherits the type checking functionality previously
contained in pattern::match
. Here’s the implementation for pattern_var
:
|
|
And here’s the implementation for pattern_constr
:
|
|
So far, so good. However, for all of this to reach the main typechecking
code, not only ast
subclasses need to be updated, but also
the definition
s. Here things get more complicated, because
definition_data
and definition_defn
are growing more and more apart.
Previously, we had two typechecking steps: typecheck_first
(which registered
function names into the environment) and typecheck_second
(which performed
the actual typechecking). However, not only are these names not informative,
but the algorithms for typechecking the two types of definition will soon
have different numbers of “major” steps.
Let’s take a look at how we would typecheck data types. I propose the following steps:
- Iterate all declared data types, storing them into some kind of “known” list.
- Iterate again, and for each constructor of a type, verify that it refers to “known” types. Add valid constructors to the global environment as functions.
We don’t currently verify that types are “known”; A user could declare a list of Floobs
,
and never say what a Floob
is.
[note:
Curiously, this flaw did lead to some valid programs being rejected. Since
we had no notion of a "known" type, whenever data type constructors
were created, every argument type was marked a "base" type;
see
this line if you're curious.
This would cause pattern matching to fail on the tail of a list, with
the "attempt to pattern match on non-data argument" error.
]
(good luck constructing
a value of a non-existent type), but a mature compiler should prevent this from happening.
On the other hand, here are the steps for function definitions:
- Find the free variables of each function to create the ordered list of groups as described above.
- Within each group, insert a general function type (like ) into the environment for each function.
- Within each group (in the same pass) run typechecking (including polymorphism, using the rules as described above).
The two types of definitions further diverge when generating LLVM and compiling to G-machine instructions:
data types immediately construct and insert their functions, and do not emit G-machine instructions,
while functions generate G-machine instructions, declare prototypes, and emit LLVM in three distinct phases.
Overall, there are virtually no similarities between the two data type declarations, and any inheritance
of common functions starts to appear somewhat forced. To address this, we remove the definition
class
altogether, and sever the relationship between definition_data
and definition_defn
. The
two now look as follows:
|
|
In definition_defn
, the functions are arranged as follows:
-
find_free
locates the free variables in the definition, populating thefree_variables
field and thereby finding edges for the function graph. -
insert_types
stores the type of the function into the global environment (a pointer to which is now stored as a field). -
typecheck
runs the standard typechecking steps. -
compile
generates G-machine instructions. -
declare_llvm
inserts LLVM function prototypes into thellvm_context
. -
generate_llvm
converts G-machine instructions into LLVM IR.
In definition_data
, the steps are significantly simpler:
-
insert_types
registers the type being declared as a “known” type. -
insert_constructors
inserts constructors (which are verified to refer to “known” types) into the global environment. -
generate_llvm
creates the LLVM functions (and their IR).
While the last three methods of definition_defn
remain unchanged save
for the name, the implementations of the first three see some updates.
First is find_free
:
|
|
First, to make sure we don’t pollute the global scope
with function parameters, find_free
creates a new environment
var_env
. Then, it stores into this new environment the function parameters,
ensuring that the parameters of a function aren’t marked “free”.
Concurrently, find_free
constructs the “general” function
type (used by insert_types
). Once all the arguments have been bound, definition_defn::find_free
makes a call to ast::find_free
, which does the work of actually
finding free variables.
Since the function type is created by find_free
, insert_types
has very little to do:
|
|
Finally, typecheck
, which no longer has to bind the function
arguments to new types, is also fairly simple:
|
|
Let’s move on to data types. In order to implement definition_data::insert_types
,
we need to store somewhere a list of all the valid type names. We do this
by adding a new type_names
field to type_env
, and implementing the
corresponding methods lookup_type
:
|
|
And bind_type
:
|
|
Note in the above snippets that we disallow redeclaring type names;
declaring two data types (or other types) with the same name in
our language will not be valid. In insert_types
, we create a new
data type and store it in the environment:
|
|
We then update insert_constructors
to query the environment
when creating constructor types, rather than blindly using new type_base(...)
like before:
|
|
The separation of data and function definitions must be reconciled with code
going back as far as the parser. While previously, we populated a single, global
vector of definitions called program
, we can no longer do that. Instead, we’ll
split our program into two maps, one for data types and one for functions. We
use maps for convenience: the groups generated by our function graph refer
to functions by name, and it would be nice to quickly look up the data
the names refer to. Rather than returning such maps, we change our semantic
actions to simply insert new data into one of two global maps. Below
is a snippet that includes all the changes:
|
|
Note that program
and definitions
no longer have a type, and that data
and defn
have been changed to return definition_data_ptr
and definition_defn_ptr
, respectively.
This necessitates changes to our main file. First of all, we declare the two new maps
we hope to receive from Bison:
|
|
We then change all affected functions, which in many cases amounts to splitting the program
parameter
into defs_data
and defs_defn
parameters. We also make other, largely mechanical changes: code iterating
over definitions now requires the use of second
to refer to the value stored in the map, and LLVM
generation now needs to separately process the two different types of definitions. The biggest change
occurs in typecheck_program
, which not only undergoes all the aforementioned modifications, but
is also updated to use topological ordering:
|
|
The above code uses the yet-unexplained generalize
method. What’s going on?
Observe that the Var rule of the Hindley-Milner type system says that a variable
can have a polytype in the environment . Our type_ptr
can only represent monotypes,
so we must change what type_env
associates with names to a new struct for representing polytypes,
which we will call type_scheme
. The type_scheme
struct, just like the formal definition of
a polytype, contains zero or more “forall”-quantified type variables, followed by a monotype which
may use these variables:
|
|
The type_scheme::instantiate
method is effectively an implementation of the special
case of the Inst rule, in which a polytype is specialized to a monotype. Since
the App and Case rules only use monotypes, we’ll be using this special case a lot.
We implement this method as follows:
|
|
In the above code, if the type scheme represents a monotype (i.e., it has no quantified variables),
we simply return that monotype. Otherwise, we must perform a substitution, replacing “forall”-quantified
variables with fresh type parameters to be determined (we will never determine a single type for any of
the quantified variables, since they are specifically meant to represent any type).
We build a substitution map, which assigns to each quantified type variable a corresponding
“fresh” type, and then create a new type with with the substitution applied using substitute
,
which is implemented as follows:
|
|
In principle, the function is fairly simple: if the current type is equivalent to a quantified type, we return the corresponding “fresh” type. If, on the other hand, the type represents a function, we perform a substitution in the function’s input and output types. This method avoids creating new types where possible; a new type is only created if a function’s input or output type is changed by a substitution (in which case, the function itself is changed by the substitution). In all other cases, substitution won’t do anything, so we just return the original type.
Now it is a bit more clear why we saw instantiate
in a code snippet some time ago;
to compute a monotype for a variable reference, we must take into account the
possibility that the variable has a polymorphic type, which needs to be specialized
(potentially differently in every occurrence of the variable).
When talking about our new typechecking algorithm, we mentioned using Gen to sprinkle
polymorphism into our program. If it can, Gen will add free variables
in a type to the “forall” quantifier at the front, making that type polymorphic.
We implement this using a new generalize
method added to the type_env
, which (as per
convention) generalizes the type of a given variable as much as possible:
|
|
For now, we disallow types to be generalized twice, and we naturally disallow generalizing
types of nonexistent variables. If neither of those things occurs, we find all the free
variables in the variable’s current type using a new method called type_mgr::find_free
,
and put them into the “forall” quantifier. type_mgr::find_free
is implemented as follows:
|
|
The above code is fairly straightforward; if a type is a variable that is not yet bound to anything, it is free; if the type is a function, we search for free variables in its input and output types; otherwise, the type has no free variables.
Finally, we have made the necessary changes. Let’s test it out with the example from the beginning:
data Bool = { True, False }
defn if c t e = {
case c of {
True -> { t }
False -> { e }
}
}
defn main = { if (if True False True) 11 3 }
Running it, we get the output:
3
Hooray!
While this is a major success, we are not yet done. Although our functions can now
have polymorphic types, the same cannot be said for our data types! We want to
have lists of integers and lists of booleans, without having to duplicate any code!
While this also falls into the category of polymorphism, this post has already gotten very long,
and we will return to it in part 11. Once we’re done with that, I still intend
to go over let/in
expressions, lambda functions, and Input/Output together with
strings.