stlc design
Design goal
stlc is a small, complete instance of a typed calculus on the shared
substrate: it reuses the named syntax, substitution, rewriting and the
untyped reducer, and adds what types make possible: a decidable type checker
and a normalizer that needs no step limit and returns canonical
(beta-normal, eta-long) forms. It is the model for richer typed cores built on
type_theory.
Constraints
- Shared syntax. Terms are the unannotated
Term[Atom], so the shared analyses, substitution and rewriting apply unchanged. - Decidability. Type checking must terminate on every input, and normalization of well-typed terms must need no step limit.
- Errors are values. Every rejection is a
TypeError.
Mathematical background
Types and terms
Base types are uninterpreted names. Lambdas carry no type annotation (Curry style). A signature gives the types of constants , a context the types of free variables; in both, a later entry for a name shadows an earlier one, written .
Declarative typing
The judgement is given by the standard rules ( is left implicit):
Equality of terms is -conversion, with and for , both at well-typed instances.
Classical results
- Subject reduction. If and then .
- Strong normalization. Every reduction sequence of a well-typed term is finite (Tait’s method of computability predicates).11 W. W. Tait, “Intensional interpretations of functionals of finite type I”, Journal of Symbolic Logic 32, 1967.
- Canonical forms. Every well-typed term is -equal to a unique term in beta-normal, eta-long form, defined below.
Design decisions
Bidirectional type checking
Problem. Without annotations on lambdas, the type of is not determined, and full type inference (unification) is more than the calculus needs.
Choice. Two mutually recursive judgements: inference
(infer) and checking
(check). Information flows from the
expected type into lambdas, and from variables and constants out of
applications.22 J. Dunfield and N. Krishnaswami, “Bidirectional typing”, ACM Computing Surveys 54(5), 2021. The implemented rules are
In the spine is flattened first, so nested Apply nodes are one
application ; if has fewer arrows than arguments the
result is ExpectedFunction, and an Apply node of the spine without
arguments gives EmptyApplication. and
differ only in the mode of the second premise;
in both the spine is flattened in the same way and the parameter is renamed
apart from the trailing arguments:
with the checked bound renaming of the
syntax design; in both cases
and
. With there is nothing to
rename and the second premise is ,
or for . check uses
for every application whose flattened head is a
lambda, and for every other term except a lambda checked
against an arrow; a lambda in inference position fails with
CannotInferLambda. Type equality in is syntactic, which is
exact for simple types.
Why the extra rule. Plain bidirectional typing cannot infer , because the head is a lambda. The rule treats the redex like : the argument’s type is inferred and given to the parameter. It makes terms produced by substitution-style programming, such as , checkable without annotations.
Why a checking-mode . alone
reaches when a redex is checked, so the rest of the spine must
be inferred. When the redex returns a lambda, as in
checked against
, that rest is the lambda ,
and inference fails with CannotInferLambda although the expected type is
known. passes the expected type on to the rest
of the spine instead, as checking
against checks against . It accepts everything that
followed by accepts: by induction on the
spine, its last step reaches either a non-lambda head, where check infers
the rest of the spine as would, or a spine without
arguments, which is checked directly. Versions before the fix had only
and rejected such terms, also as arguments, as in
with
.
Soundness of the checker
Theorem (soundness). If check(Σ, Γ, t, τ) succeeds, then
; if infer(Σ, Γ, t) returns , then
.
Proof sketch. Induction on the algorithmic derivation. and the axioms map to their declarative counterparts; is immediate; is uses of the declarative application rule. For and , write . The second premise is an inference or a checking derivation for the smaller term , so in both cases by induction , and the generation lemma for application gives types with and for . Then
The argument does not use the mode of the second premise, so it proves both rules; for only the first three lines are needed, with of type , which may be an arrow when is a lambda.
The strengthening step is where the renaming is needed. For the term
has declarative type and no other. Without the renaming, the trailing
would be typed in and the checker would
answer Unit; versions before the fix did exactly that, and check accepted
the term at Unit. With the trailing keeps its type , and
infer returns . renames in the same way, so
checks against and
not against .
The typed evaluator walks a spine the same way. It flattens nested Apply
nodes before typing the head, so the curried
is the same spine as the term above.
A lambda head cannot be inferred, so its type is rebuilt from the premises of
or and the expected type of the whole application. Write
with not an application ( if is not
one). The head gets the type , where is inferred
for and , the type of , is computed recursively: take the
head type of the flattened spine under
and remove its first domains. If that spine is
empty, is in checking position as in and
; this covers a body that is a lambda, such as in
at . Any
other head is inferred. A redex body that consumes
the outer arguments, as in ,
is therefore handled as infer handles it, and normalize_eta_long accepts
the same terms as check. Versions before the fix only recognised a bare
lambda head and rejected both terms with CannotInferLambda.
Completeness for normal forms. If is beta-normal and
, then check(Σ, Γ, t, τ) succeeds. A beta-normal
term is either a lambda, handled by , or a spine whose head is a
variable, a constant or ; its type is determined by or
and its arguments are again normal, so and induction apply.
Terms with redexes are accepted when every argument that the spine walk gives
to a lambda head is inferable: in each spine
, and then, recursively, the arguments that
gives to a lambda head. This holds whether
the redex returns a lambda or not, and at every type of the term. The proof
extends the one above. An inferable term has exactly one declarative type (by
induction on the inference derivation: the head of and the
argument of have unique types), so a derivation of
gives the parameter the
type that infer returns for , and, by weakening with
,
;
and induction on the size of the term apply. The condition is needed: both
and
are typable and rejected
with CannotInferLambda, the second because the walk gives
to the lambda head .
The checker terminates. Measure a call by the size of its term, and break
ties by counting a check call above an infer call. goes
from check to infer on the same term, which lowers the measure; every
other recursive call is on a strictly smaller term ( and
recurse
on , which lacks the binder and ;
renaming does not change the size).
Two normalizers with different jobs
normalize_checked reuses the untyped normal-order beta-eta reducer of
utlc/lambda after checking the type. Its value is that it is
the reference semantics, with traces and step counts; it is step-bounded
only because it is shared with the untyped calculus. By strong normalization
it always ends in NormalForm for a large enough limit. Its normal forms are
eta-short.
normalize_eta_long is typed normalization by evaluation. It needs no limit,
and it returns the canonical representative of the class, so two
well-typed terms are -equal iff their eta-long normal forms are
alpha-equivalent: the normalizer decides conversion.
Beta-normal, eta-long forms
Normal forms and neutral terms are defined by type:
Every term of arrow type is a lambda (eta-long), and every application has a variable or a constant at its head (beta-normal). Neutral terms of type are kept: the eta law for the unit type ( for every ) is not implemented, so for and the terms and have different normal forms.
Typed normalization by evaluation
The semantic domain interprets each type:
where a closure stores a lambda body with its environment and its type, and a semantic neutral is a free variable, a constant, or a neutral applied to a value together with the value’s type. Evaluation maps variables through the environment, lambdas to closures, constants to neutrals, and applies closures by evaluating their bodies (call by value, which is safe because evaluation of typed terms terminates). Reflection embeds a neutral as a value; here it is the identity on neutrals, because all eta expansion is deferred to reification. Reification is
and the normal form of is , where maps each to . Reifying at an arrow type applies the value to a fresh variable, which performs eta expansion; a neutral application records the domain type of its argument so that the argument can be reified at the right type later.33 U. Berger and H. Schwichtenberg, “An inverse of the evaluation functional for typed λ-calculus”, LICS 1991. The type-directed presentation follows A. Abel, Normalization by Evaluation: Dependent Types and Impredicativity, habilitation thesis, 2013.
Correctness (sketch). Define a Kripke logical relation between terms and values, monotone under context extension:
By induction on one proves two lemmas together: reflection ( implies ) and reification ( implies ). The arrow case of reification is the eta step:
using (reflection) and the definition of . The fundamental lemma states that and imply ; it is proved by induction on the typing derivation, the lambda case using that beta-reduction is in . With the identity and (related by reflection), reification gives (soundness). Completeness, that -equal terms have alpha-equivalent normal forms, needs a second argument: a partial equivalence relation on values, defined by induction on types like , under which and are related whenever (beta is function application in the model, and eta holds because reification always expands), and related values reify to the same normal form; Abel’s thesis, cited above, gives the details. The relation , read as a computability predicate, also shows that evaluation terminates on well-typed terms, which is why no fuel is needed.
Fresh names in readback
Readback invents binder names with fresh_name("x", used), where used
contains every name of the input term and context, the names in closure
environments, and the names already introduced on the path. Generated names
are therefore distinct from each other along a path and from all names of the
input, and a neutral variable is never captured by a binder introduced later.
A bounded host stack
Problem. Written as host functions, the checker (infer, check, their
spine versions and the loop over the arguments of ), typed
evaluation, readback and the derived equality of types recurse once per level
of the term, of the type or of the normal form. The js, wasm and wasm-gc
stacks overflow at a depth of a few thousand, so deep binders, deep argument
positions, long curried spines, nested redexes and types nested in their
domains crashed the package (issue #13).
Choice. Each of the three algorithms runs as one loop over an explicit
continuation, like the untyped evaluator of utlc/nbe: a
control says what to compute next, and a stack of frames in the heap holds
the rest of the callers. A call in tail position replaces the control; a
call whose result is still needed first pushes a frame for the rest of its
caller. The single bidirectional machine is build_typed_plan, with
PlanControl and PlanFrame in the code. infer starts it in inference mode
and returns the plan’s type; check starts it in checking mode and discards
the plan; normalize_eta_long starts it in checking mode and evaluates the
plan. Their typing rules and first-error order cannot diverge through separate
implementations (#32).
The machine flattens each application spine, infers a non-lambda head, checks
its operands in order and compares the result with the expected type when
checking. A lambda body is checked against the codomain of its expected arrow.
A redex parameter is renamed apart before its first argument is inferred;
only after inference succeeds does redex_finish flatten the body and join
the trailing arguments. The remaining spine continues in its original mode.
Assembly frames record checked lambdas, applications and strict lets without
introducing new failures. All pending work lives in heap arrays.
Typed evaluation runs the private plan. Its controls evaluate a plan, apply a semantic value, or return a value; its frames wait for a function, an operand, or a strict-let argument. Applying a closure and entering a strict-let body are tail calls. Readback retains controls for , for and for returning a term, and frames for a binder, an argument still to read back, and a function waiting for its argument.
Same results, same errors. Read a frame as the function that the rest of
its caller applies to the returned value, and a state as the stack applied to
the value of its control. Every transition is one equation of the recursive
definition, so it preserves that reading, and a run ends with the value the
recursive functions return. The machines make the calls of the definition in
its order, and no rule of the definition catches an error: every Err
propagates unchanged to the top. The result of the recursive functions is
therefore the first error met in that order, and the machines stop at the
same one; which TypeError is reported does not change.
Equality of types. Ty has a hand-written Eq that compares a heap array
of pending pairs, and skips a pair of physically equal types, which is sound
because the equality is reflexive.
Linear time. Two hidden quadratic costs would dominate at depth , so they are removed without changing results. Contexts and environments built from one another share an append-only array and read only their own prefix, so entering binders costs instead of . Readback chooses binder names with , the first of the candidates , , , … not in , and eta-expanding at a type nested levels deep would retry the names chosen before. It carries, with , a position such that every with is in , and starts the search there. If is chosen, every with is in , so is a valid position for the extended set; readback only ever adds names to , so the position stays valid along the path, and the name found is the one returns.
Checking once for evaluation (issue #27)
The former evaluator reconstructed the type of each redex head by inferring its first argument again. For nested identity redexes in argument position, that revisited suffixes of sizes , even after the initial check succeeded. Removing repeated argument checks in PR #30 left this second source of quadratic traversal.
build_typed_plan now performs the bidirectional checking rules while
recording a private TypedPlan. Values and variables record their inferred
type; lambdas record their expected arrow and checked body; each application
records its domain and checked operand. The redex rule records a strict let:
first evaluate the inferred argument, bind the renamed parameter, then run
the plan for the body joined with the trailing arguments. The public syntax,
check and infer APIs are unchanged. Evaluation and closure application
execute these plans and never call check or infer.
Error correspondence. Erase the plan returned by each control to its type
(for inference) or successful check (for checking). PlanHead, PlanArgument
and PlanCompare perform the same head inference, argument check and type
comparison prescribed by the bidirectional rules. PlanRedexFirst renames before
inferring the first argument, calls redex_finish only after it succeeds,
and continues the remaining spine in the original inference/checking mode.
PlanBindBody and PlanRedexRest only assemble successful plans; neither can
fail. Induction over machine transitions therefore gives the same acceptance
and first TypeError as the original checker. Public check and
normalize_eta_long now start this same machine in the same checking mode
(#32), so their typing acceptance and first error have one implementation.
The frozen baseline remains available for compatibility comparisons.
Semantic correspondence. A planned application evaluates its function, then its operand, then applies the value. A planned redex implements by evaluating and continuing under its value. The existing capture-avoidance step renames away from the free variables of every trailing argument; adding that binding therefore leaves their meanings unchanged (environment weakening). Induction on the successful typing derivation relates the plan to the source term in the same STLC semantic domain. Readback is unchanged. Environment entries retain both the internal lookup name and its source name: internal capture-avoidance names must not occupy additional output binder candidates. Source names are already in the initial avoidance set. These are structural arguments, not machine-checked proofs.
Cost and limits. Each successful typing visit creates a constant number of
plan nodes; such visits add plan storage and pending frames
at traversal depth . Public infer and check also build a plan and
discard it, adding temporary plan storage compared with the former
checker. This allocation is the explicit tradeoff for one rule implementation
(#32); no allocation-free checking mode is provided. The retained plan can
live as long as a closure.
Evaluation traverses plans without the repeated type-inference suffixes. For
the nested identity-redex regression with fixed signature and empty initial
context, checking, plan construction and evaluation take work and
heap storage. This is not a linear-time bound for arbitrary STLC
normalization: reduction can duplicate work and normal forms can grow;
context lookup, branch-prefix copies, type equality, spine copying and name
analysis retain their existing costs. In particular, capture avoidance may
scan trailing arguments at multiple redexes, and name collection for closure
readback is unchanged.
Evidence. src/stlc/issue27_test.mbt covers 100,000 nested identity redexes,
100,000 neutral argument positions, first-error ordering and a capture case
with exact binder-name comparison. python3 tools/verify_stlc_plan.py --target all compares 43,120 bounded term/type combinations per backend with the
frozen PR #30 implementation at db53d775e9248e8712a240adc8327be72675c80f,
including exact output names and error values. It also compares public
check on those combinations and infer on all 8,624 generated terms. It requires that Git object
locally and removes its temporary oracle afterward. The corpus is finite;
it supports compatibility but does not establish a universal theorem.
Correctness and invariants
checkandinferterminate; on success, the term is declaratively typable at the reported type (soundness theorem). The regression tests include redexes whose parameter occurs free in a trailing argument.checkaccepts every well-typed beta-normal term, and every well-typed term in which each argument given to a lambda head is inferable, including redexes that return a lambda.normalize_eta_longreturnsOkexactly for terms thatcheckaccepts; its result is in , is -equal to the input, and is the same (up to ) for -equal inputs.normalize_checkedreturnsErrbefore any reduction for ill-typed input.NormalizationErrorsignals a violated internal invariant and is not produced for checked input.check,infer,normalize_checked,normalize_eta_longand==on types use a constant host stack depth; terms and types nested 100 000 levels deep are handled on every backend (src/stlc/deep_test.mbt).
The tests in src/stlc/stlc_test.mbt cover typing and rejection, shadowing,
eta expansion of open variables and of constants (including nested arrow
types and higher-order arguments), agreement of the two normalizers on
small terms, and agreement of check and normalize_eta_long on redexes with
curried heads, mixed flat and nested spines, and bodies that consume the outer
arguments. They also cover redexes checked against an arrow
(): redexes that return a lambda, alone and as
arguments, in curried and flat spines, nested ones, the renaming shape above
in checking mode, and ill-typed variants that are still rejected.
Alternatives rejected
- Church-style annotated lambdas. Annotations would make inference
complete but change the shared
Termsyntax; the bidirectional checker keeps terms unannotated. - Hindley–Milner inference. Unification would infer types of unannotated lambdas, but polymorphism and type variables are beyond this calculus.
- Fuel for typed NbE. Unnecessary by strong normalization; the untyped utlc/nbe keeps fuel because it needs it.
- Eta for the unit type. Implementable by reifying every neutral of type as ; not done, so that neutrals stay observable. The decided equality is for arrows only.
Boundaries
- Types are , and arrows: no products, sums, polymorphism or dependent types.
- No unit eta; normal forms are eta-long for arrow types only.
- Constants are opaque: there are no delta rules.
normalize_checkedis bounded by a step limit because it reuses the untyped reducer.normalize_eta_longexecutes a plan produced by one checking pass, with no type inference during evaluation (#27). It does not promise linear time for arbitrary terms: reduction, context lookup, capture avoidance, spine copying and readback can still require more work than the input size.Debugof a deep term, type or error recurses and can overflow the stack.
Footnotes
-
W. W. Tait, “Intensional interpretations of functionals of finite type I”, Journal of Symbolic Logic 32, 1967. ↩
-
J. Dunfield and N. Krishnaswami, “Bidirectional typing”, ACM Computing Surveys 54(5), 2021. ↩
-
U. Berger and H. Schwichtenberg, “An inverse of the evaluation functional for typed λ-calculus”, LICS 1991. The type-directed presentation follows A. Abel, Normalization by Evaluation: Dependent Types and Impredicativity, habilitation thesis, 2013. ↩