iTranslated by AI
Type Inference in LunarML and Ideas for the Future
This article is for day 25 of the Language Implementation Advent Calendar 2023.
In this article, I will discuss the evolution of the type inference process in the Standard ML compiler LunarML, which I am developing, and present ideas for type-related features that may be introduced in the future.
Evolution
The initial type checker I wrote was quite textbook-style. Variables used for unification were managed by numbers, and substitutions were managed by a table. The signature of the function for type checking expressions looked like this:
val typeCheckExp : Context * Env * S.Exp -> T.Ty * T.Exp
It was straightforward, returning the type of the given expression and the expression after adding type annotations.
In February 2022, it was discovered that type checking had become a bottleneck in the compilation process. At that time, I addressed the issue by "reducing the number of generated type variables by propagating the expected type." Here is the article from that time:
The type of the function for type checking became as follows. If there is an "expected type," it is passed. This is merely a hint, and the receiver is free to ignore it.
val typeCheckExp : InferenceContext * Env * S.Exp * (* type hint *) T.Ty option -> T.Ty * T.Exp
In June, since type checking was still slow, I switched to using destructive updates for unification. I also introduced levels according to the following article:
The background of that time is described in this article:
Recently (December 2023), I was inspired by bidirectional typing. It involves splitting typing rules into "those that synthesize a type" and "those that receive an expected type and check against it." Since I was already propagating an "expected type," it already had a bidirectional typing flavor, but I have further strengthened that approach. The functions for type checking expressions became as follows:
val synthTypeOfExp : InferenceContext * Env * S.Exp -> T.Ty * T.Exp
and checkTypeOfExp : InferenceContext * Env * S.Exp * T.Ty -> T.Exp
Pattern type checking has also been split into "synthesizing" and "checking against an expected type".
Applying bidirectional typing to Standard ML requires several considerations. These have not been implemented yet.
-
Record projection: In bidirectional typing, function application
f xis usually handled by first synthesizing the type offand then checkingxagainst the argument type. However, for record projection#label record, this would require synthesizing the type of#labelfirst. In SML's projection expression#label, the type cannot be determined without unification, so this is not very desirable. If the function part of a function application is a projection, it seems better to add an ad-hoc rule to first synthesize the type of the argument and, if it is a record type, return the type of the field. -
Binary operations: SML has several polymorphic functions like
=and+that take the same type on both sides. Furthermore, literals like42can take multiple types (not limited toint). Consequently, in a binary operation likex + 42, even if the type ofxis known, unification is necessary to determine the type of the literal. Since this is inefficient, if the type of the function being applied is of the form'a * 'a -> ..., it would be better to synthesize the type of the first argument and then check the remaining arguments against it. -
valdeclarations with type annotations: Inval pat = exp, should we synthesize the type ofexpfirst and checkpatagainst it, or synthesize the type ofpatfirst and checkexp? Given that manyvaldeclarations likeval x = explikely won't have type annotations on the pattern, the former seems better. However, that would mean the "expected type from context" cannot be used for checkingexpin cases likeval pat : ty = exp. In such cases, it would be better to use an ad-hoc rule: if there is a type annotation at the top level of the left-hand pattern, check both the inner pattern and the right-hand expression against it.
Future
Standard ML type checking doesn't inherently require the power of bidirectional typing, though it might help make error messages clearer. However, LunarML may benefit from bidirectional typing if extensions are implemented in the future. Here are some ideas for such extensions.
Type-dependent names
In common object-oriented languages, types possess their own namespaces, and methods can be called through them. Furthermore, in Swift, constructors and other members (such as .init or .some) can be called without a type name when the expected type is known from the context. Regardless of the pros and cons of object-oriented programming, linking a namespace to a type is a compelling idea that might be worth incorporating into LunarML.
(Actually, Standard ML does link value constructor namespaces to types, which is utilized in datatype replication, though it is not typically used for everyday tasks.)
SML implementations for Java or .NET reportedly supported method calls using syntax like obj.#method, but I am considering a different approach here.
First, what if we allowed omitting the module name for a constructor when there is an expected type from the context? For example, if the expected type is StringCvt.radix, one could write .HEX instead of StringCvt.HEX.
Regarding methods, the functional programming community already knows techniques to write the "argument first, function second." This is the pipeline operator |> : 'a * ('a -> 'b) -> 'b. Let's consider whether this can be utilized.
We can treat the first argument of the pipeline operator as an object and the second argument as a method. By extending the rules we considered for binary operations, we can perform type checking while knowing part of the type of the second argument based on the type of the first argument—specifically, the 'a in 'a -> 'b. If a "type-dependent name" appears when 'a -> 'b is expected, we will search the namespace linked to the type of 'a. For instance, x |> .toString would search for the toString function based on the type of x.
Let's also allow applying some arguments to a "type-dependent name." This would mean writing xs |> .map (fn y => y + 1) would result in the map function being searched based on the type of xs.
Combining the constructor and method-like features, for example, Word.fmt StringCvt.DEC w could be written as w |> .fmt .DEC. ...At least, that's the hope.
With this approach, when creating bindings for object-oriented libraries, the recommended argument order would be:
val method : arg1 * ... * argN -> self -> result
Since automatically linking namespaces to types seems difficult (as a single type can be exported from multiple modules), it would be explicitly declared. For example:
(* Associate the Int module with the int type *)
_associate int = Int
GADTs
GADTs would also be nice to have. I haven't investigated them thoroughly yet, but I'll list them here for now.
Subtyping
I want LunarML to interface well with existing languages like Lua and JavaScript. If we want to interact with existing statically-typed object-oriented languages like Java or .NET in the future, there is a good chance that having subtyping in LunarML would be useful.
Bidirectional typing seems helpful for making subtyping coexist with ML-style type inference.
Now, should we introduce union types? While it's unclear if union types are useful for interfacing with Java or .NET, they might be desirable for JavaScript. Introducing union types in the usual way would allow expressions that previously didn't have a type to be typed. For example:
if b then 42 else "foo"
This expression was previously a type error, but with union types, it could be assigned a type like union[int, string]. Is this desirable, or would it be a surprise?
For union types, it might be better to allow them only when the expected type from the context is a union type. In other words, reject cases like:
val x = if b then 42 else "foo"
But allow cases like:
val x = (if b then 42 else "foo") : union[int, string]
Speaking of subtyping, there is also bounded quantification. I'd like to consider what the syntax should be.
Interaction with Unification
In the current LunarML type inference algorithm, unification variables are modified destructively. Consequently, whether advanced type features compile or not might depend on the order in which constraints are generated. For example:
val fst : 'a * 'b -> 'a = fn (x, _) => x
fun foo r = fst (Word.fmt r 0w0, r = .DEC)
Should this compile successfully? If the type checking of Word.fmt r 0w0 is performed first, it would likely succeed. On the other hand:
val fst : 'a * 'b -> 'a = fn (x, _) => x
fun foo r = fst { 2 = r = .DEC, 1 = Word.fmt r 0w0 }
This would likely fail.
Approaches that depend on such compiler implementation details can surprise users, so I want to be cautious.
Discussion