# Typechecking [← Back to AGENTS.md](../AGENTS.md) · [Documentation index](README.md) The typechecker lives in [`src/elaborate.rs`](../src/elaborate.rs). It is a Hindley–Milner inference engine based on the level-based generalization algorithm in Oleg Kiselyov's [`sound_eager.ml`](https://okmij.org/ftp/ML/generalization/sound_eager.ml). [`src/prelude.rs`](../src/prelude.rs) supplies the standard Caml Light values; the typechecker itself contains no library functions or operators. ## Entry points ```rust use camllight::{ elaborate, elaborate_implementation, elaborate_interface, Environment, Type, TypeError, }; let expression = camllight::parse_expression("let id x = x in id 1").unwrap(); let mut environment = camllight::standard_environment(); let mut types: Vec = Vec::new(); let ty = elaborate(&expression, &mut environment, &mut types).unwrap(); assert_eq!(ty, Type::int()); ``` - `elaborate(&Expr, &mut Environment, &mut Vec) -> Result` typechecks one expression. - `elaborate_implementation(&[ImplPhrase], &mut Environment, &mut Vec) -> Result<(), TypeError>` processes `type`, `exception`, and top-level `let` phrases and adds their declarations and bindings to the environment. - `elaborate_interface(&[IntfPhrase], &mut Environment, &mut Vec) -> Result<(), TypeError>` processes `type`, `exception`, and interface value declarations. - `Elaborator::new(&mut Environment, &mut Vec)` exposes the same operations as methods when a caller wants to reuse one inference state. The `Vec` is indexed by [`ExprId`](../src/ast.rs). It is extended with `Type::Unknown` when it is too short. A successful elaboration fills every expression it reaches. Parenthesised expressions reuse the wrapped expression's ID, so they share one slot. ## Environment `Environment` separates four namespaces: - value bindings, which are scoped (`push_scope` / `pop_scope`); - type constructors and aliases; - variant and exception constructors; - record labels and field mutability. All built-in values and constructors come from `standard_environment()`. Callers that want a smaller environment can build one with `Environment::new()` and bind only what they need. `bind_constructor` registers the constructor and also binds its scheme in the term namespace; `add_record` registers the labels and ensures the record type exists. The typechecker recognizes the primitive type names `unit`, `exn`, `bool`, `int`, `float`, `string`, `char`, `list`, `vect` (also accepted as `array`), `option`, `ref`, and `stream`; user-defined type names must be declared. Module-qualified names are looked up exactly as written. A qualified value, constructor, type, or record label never falls back to an unqualified binding with the same final component. ## Types and schemes `Type` has six forms: ```rust pub enum Type { Var(TypeVar), // inference variable Generic(String), // quantified variable Arrow(Box, Box), Tuple(Vec), // empty tuple is unit Constr { name: String, arguments: Vec }, Unknown, // type-table placeholder } ``` `TypeVar` wraps a shared mutable cell. Unbound variables record the `let` level that owns them; unification lowers exported levels, and `generalize` quantifies only variables above the current level. When the value restriction prevents generalization, `nongen_type` lowers the remaining variables to the current level so a later `let` cannot generalize them indirectly. This avoids scanning the environment and preserves the soundness example ```caml fun x -> let y = x in y ``` which has type `'a -> 'a`, not `'a -> 'b`. `Scheme` is a type schema. A scheme containing `Generic` variables is instantiated freshly at every use; a monomorphic scheme is used for weak types. `Type` equality chases links, so linked variables compare structurally. `Type::resolve` follows links explicitly, and `Type::variable_name` returns the name of an unbound or quantified variable. The LMLI converter uses both when translating inferred types. ## Value restriction The full algorithm — binding groups, levels, `nongen_type`, and worked examples — is described in [Value restriction and binding groups](value_restriction.md). In brief, `let` generalization follows Caml Light's `is_nonexpansive` rule from `Camllight/src/compiler/typing.ml`: - constants, identifiers, functions, tuples, lists, and immutable records are nonexpansive; - only the empty array is nonexpansive; - constructor applications are nonexpansive when the constructor argument is immutable; - `try`, `if`, `let`, and sequences (through their result) are nonexpansive when their component expressions are; - field access is nonexpansive when the record is. Consequently `let r = ref []` has a weak monomorphic type and cannot be used at two different element types. A later value binding cannot launder that weak type back into a polymorphic one: `let s = r` remains monomorphic. Binding groups lower every weak type before generalizing any member, including `let rec ... and ...` groups where one right-hand side is expansive and another is a syntactic value. ## Declarations `type` declarations are processed in two passes so mutually recursive constructors and records work. Type abbreviations are expanded, including parameterized aliases and forward references within a `type ... and ...` group. Expansion is applied recursively to aliases nested in record fields and constructor arguments as well as to annotations. Variant constructors receive schemes such as ```text Some : 'a -> 'a option ``` Record declarations register their labels with field types and mutability. Record construction requires every field; record patterns may omit fields. A label shared by several record types is ambiguous unless the expected type determines the record during construction, or the inferred type of the record expression determines it during field access and assignment. The expected type of a field expression describes the selected field, not its containing record. Exceptions are constructors whose result type is `exn`. `try` cases check their patterns against `exn`. ## Patterns and assignments Patterns support wildcards, variables, constants, constructor application, tuples, records, lists, cons, ranges, aliases, constraints, and or-patterns. Both sides of an or-pattern must bind the same names with unifiable types. Assignments accept: - `r <- v` for a reference `r : 'a ref`; - `record.field <- v` for a mutable declared field; - `vector.(index) <- v` for a `'a vect`; - `string.[index] <- c` for a `char`. Sequence elements, `while` bodies, and `for` bodies are inferred without being constrained to `unit`. This mirrors Caml Light's `type_statement`, which only warns about non-`unit` statements; conditions and indices are still checked. `if` without `else` requires its then branch to have type `unit`. The typechecker never guesses a user constructor or record label. Unknown constructors, unknown labels, and missing declarations produce spanned `TypeError`s. ## Streams Stream expressions have type `'a stream`; `[< ... >]` components unify as follows: - `Term e` contributes `e : 'a`; - `NonTerm s` contributes `s : 'a stream`. Stream parsers (`parser` and `match ... with parser`) are not yet elaborated; they return `TypeErrorKind::Unsupported("stream parsers")`. ## Errors `TypeError` contains a `Span` and a `TypeErrorKind`, including: - `UnboundValue`, `UnboundConstructor`, `UnboundTypeConstructor`; - `Mismatch`, `NotAFunction`, `OccursCheck`; - constructor and type-constructor arity errors; - record-label, duplicate-field, and mutable-field errors; - duplicate type declarations and duplicate value bindings; - invalid patterns and or-pattern binding mismatches; - `Unsupported`. `TypeError` implements `Display` and `std::error::Error`. Large illustrative types in errors are boxed. ## CLI `camllight --typecheck` parses the input, builds `standard_environment()`, and runs `elaborate_implementation` or `elaborate_interface` depending on the file kind: ```sh echo 'let square x = x * x;;' | cargo run -q -- --typecheck ```