13.3. Type system

Morloc checks a program against general types, which name no language, and only later gives each value a concrete type in the language that holds it. This section specifies the checker: bidirectional inference with an ordered context, how polymorphism is resolved before anything runs, typeclass instance selection, kinds and the side solvers for type-level naturals, strings, lists, sets and rows, aliases and newtypes, and type equality. It ends with how a general type becomes a concrete one. Effects are in Effects; choosing the language of each call is Realization.
Two layers of types. A signature such as `sum

[Int] → Int` is general: it says what the function means, in every language at once. A native form (type L ⇒ …​) says how one language spells a general type. The checker reasons only about general types. Concrete types are derived after realization has placed every call in a language, by translating the general type through that language’s native forms.

Diagram
Diagram

Bidirectional checking. The checker follows the ordered-context design of Dunfield and Krishnaswami. Each term is either checked against a type it is expected to have (an argument, an annotated body, a definition with a signature) or has its type synthesized from its parts (a variable, an application). The context is an ordered list of universally bound variables, unsolved existential variables, solved existentials and scope markers; order fixes which existential may mention which variable, so a solution can never escape the scope of a variable it uses. Instantiating a polymorphic type creates fresh existentials, and checking against one binds its variables in the context. Where an expected type meets a synthesized one, the checker requires the synthesized type to be a subtype. An unsolved existential can already carry partial knowledge, such as the record fields or tuple positions read from it, and that knowledge is checked when it is solved.

Subtyping is narrow. It does three things and nothing else: it relates a polymorphic type to its instances; it lets T flow into ?T, the only value coercion in the language (Optional types); and it lets a type with a known dimension flow into the same type with that dimension omitted, so Vector 3 Real is accepted where Vector Real is expected. Int is not a subtype of Real. Dimensions in the same slot must be equal after reduction.

Polymorphism. A lowercase variable in a signature is universally quantified over the whole signature, and each use of the term instantiates it afresh. Every polymorphic use is resolved to concrete types at compile time: no value crosses a language boundary at a type that still holds a variable. To get there, a definition is typed at each type it is used at: either a copy of its body is checked at each use or, when it has a signature, the body is checked once against the signature and elaborated once per distinct type of use. Recursion at a different type than the one being elaborated (polymorphic recursion) has no finite set of elaborations and is rejected. A variable that nothing determines, where a native representation needs it, is an error at the term where it occurs and names the variable; a variable no representation needs, such as a phantom parameter, is not.

Typeclasses. A class declares method signatures; each method name belongs to one class. A method used at type T runs an implementation of the instance for T, and that instance’s implementations are all those given for it, in any language and any module: they are alternatives, like the several definitions of one term (Parsing and module loading). Selection works on general types. The candidates are the instances whose head the use-site type is an instance of; the most specific one is kept. If the candidates have no unique most specific head (two heads overlap and neither specializes the other), the use is rejected as ambiguous. An instance on a transparent type alias is rejected, since an alias is the same type as its expansion and would collide with its expansion’s instance. Instances never type a record literal: a literal whose type would come only from the instance a method resolves to is an error at the literal. See Overload terms with typeclasses.

Kinds. A type parameter has kind Type unless declared otherwise ((n :: Nat)). The other kinds are Nat, Str, Rec, List and Set; values of these kinds exist only in the type system and are erased before anything runs. An alias parameter that fills only slots of one non-Type kind takes that kind. In a signature, a binder on an argument ties the argument’s value to a type-level variable: n@Int binds a Nat, x@Str a Str, xs@[Str] a List. See The kind system and Tensors.

Side solvers. Equations between type-level expressions of a non-Type kind are handed to a solver for that kind. An equation a solver cannot decide yet is deferred and retried as variables are solved.

Kind What the solver decides

Nat

+, -, * and / (integer division) reduce when the operands are ground; expressions with variables are kept in a sum-of-products normal form. Two dimensions that reduce to different numbers are a type error. An equation still open when inference ends, such as n + m = 4, is accepted when it has a solution in the naturals, since dimensions are erased and the variables need no value; one with no solution is an error at the term that produced it.

Rec

Rows: labeled fields with row variables standing for unknown blocks of fields. Fields are matched by label, a row variable takes what is left, and a match with more than one solution is deferred.

Str

Literals only: two literals, or concatenations folding to literals, are compared. A free variable is solved by ordinary assignment, never by solving a word equation.

List

Ordered lists of strings. Ground prefixes and suffixes are stripped; a single variable against a ground remainder is solved; two variables defer.

Set

Unordered sets of strings, compared in a canonical sorted form. Union, intersection and difference reduce on ground operands.

Aliases. A type alias is the same type as its expansion, in every position. Two aliases with one expansion are the same type. The checker keeps alias names in the types it reports, so diagnostics name the alias, but it unfolds an alias head wherever two types are compared or decomposed, so no judgment depends on whether an alias was written. An alias must be applied to all of its Type parameters, every parameter must appear in its body, and its body may name a type of any kind. A recursive alias is legal only when it is regular (the alias recurs at its own parameters) and every recursive occurrence sits under ? or [ ], as in type T a = (a, ?(T a)). An alias owns no instances and no native forms; it shares those of its expansion.

Newtypes. newtype N = T makes a new type that is never equal to T and crosses language boundaries in the form of T. It owns its instances and native forms. Values move between N and T only by explicit conversion through the Packable class: unpack comes with every newtype that has a representation, and pack with deriving (Packable), which requires every parameter of N to be determined by T. A parameter of a newtype need not appear in its representation (newtype Buffer (n :: Nat) a = List a), which is how a dimension is added to an existing type. See Naming a type: type and newtype and Serializing custom types with Packable.

Type equality. Two types are equal when, with every alias unfolded, they are the same constructors applied to equal arguments, up to renaming of bound variables. Under a recursive alias the unfoldings are infinite, so equality is coinductive: a pair met again while it is being compared holds. A type name denotes its declaration, not its spelling, so two types of one name from different modules are different types. A newtype is equal only to itself. Ground Nat expressions are equal when they reduce to the same number.

From general to concrete. The concrete type of a value in language L is its general type translated through L’s native forms. A native form is a template over the type’s parameters: `type Cpp ⇒ List a = "std::vector<$1>" a spells [Int] by substituting the C++ spelling of Int for $1. The form text is opaque to Morloc and is checked only by the language’s own compiler or interpreter. Translation walks the type from the outside in. A head with a native form in L uses it; an alias with none unfolds one step and retries; a newtype with none uses its representation’s form; a record takes its field names and types from the general declaration and only its container from record L ⇒ R = "name"; a data type with no form is generated under its own name. How these concrete types reach generated code is Realization and Native type mappings.