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

τ,σ  ::=  b  ∣  Unit  ∣  σ→τ,t  ::=  ()  ∣  c  ∣  x  ∣  λx. t  ∣  t u1⋯un.\tau, \sigma \;::=\; b \;\mid\; \mathsf{Unit} \;\mid\; \sigma \to \tau, \qquad t \;::=\; () \;\mid\; c \;\mid\; x \;\mid\; \lambda x.\,t \;\mid\; t\,u_1 \cdots u_n .

Base types bb are uninterpreted names. Lambdas carry no type annotation (Curry style). A signature Σ\Sigma gives the types of constants cc, a context Γ\Gamma the types of free variables; in both, a later entry for a name shadows an earlier one, written Γ,x:σ\Gamma, x{:}\sigma.

Declarative typing

The judgement Σ;Γ⊢t:τ\Sigma; \Gamma \vdash t : \tau is given by the standard rules (Σ\Sigma is left implicit):

Γ⊢():UnitΣ(c)=τΓ⊢c:τΓ(x)=τΓ⊢x:τΓ,x:σ⊢t:τΓ⊢λx. t:σ→τΓ⊢f:σ→τΓ⊢a:σΓ⊢f a:τ\frac{}{\Gamma \vdash () : \mathsf{Unit}} \qquad \frac{\Sigma(c) = \tau}{\Gamma \vdash c : \tau} \qquad \frac{\Gamma(x) = \tau}{\Gamma \vdash x : \tau} \qquad \frac{\Gamma, x{:}\sigma \vdash t : \tau}{\Gamma \vdash \lambda x.\,t : \sigma \to \tau} \qquad \frac{\Gamma \vdash f : \sigma \to \tau \qquad \Gamma \vdash a : \sigma}{\Gamma \vdash f\,a : \tau}

Equality of terms is βη\beta\eta-conversion, with (λx. b) a=βb[x:=a](\lambda x.\,b)\,a =_\beta b[x := a] and λx. f x=ηf\lambda x.\,f\,x =_\eta f for x∉FV(f)x \notin \mathrm{FV}(f), both at well-typed instances.

Classical results

  • Subject reduction. If Γ⊢t:τ\Gamma \vdash t : \tau and t→βηut \to_{\beta\eta} u then Γ⊢u:τ\Gamma \vdash u : \tau.
  • 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 βη\beta\eta-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 λx. x\lambda x.\,x is not determined, and full type inference (unification) is more than the calculus needs.

Choice. Two mutually recursive judgements: inference Γ⊢t⇒τ\Gamma \vdash t \Rightarrow \tau (infer) and checking Γ⊢t⇐τ\Gamma \vdash t \Leftarrow \tau (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

Γ⊢()⇒UnitΣ(c)=τΓ⊢c⇒τΓ(x)=τΓ⊢x⇒τ\frac{}{\Gamma \vdash () \Rightarrow \mathsf{Unit}} \qquad \frac{\Sigma(c) = \tau}{\Gamma \vdash c \Rightarrow \tau} \qquad \frac{\Gamma(x) = \tau}{\Gamma \vdash x \Rightarrow \tau} \textscApp  Γ⊢h⇒τ1→⋯→τn→τΓ⊢ai⇐τi  (1≤i≤n)Γ⊢h a1⋯an⇒τ(h not a λ, n≥1)\textsc{App}\; \frac{\Gamma \vdash h \Rightarrow \tau_1 \to \cdots \to \tau_n \to \tau \qquad \Gamma \vdash a_i \Leftarrow \tau_i \ \ (1 \le i \le n)} {\Gamma \vdash h\,a_1 \cdots a_n \Rightarrow \tau} \quad (h \text{ not a } \lambda,\ n \ge 1) \textscRedex  Γ⊢a1⇒σΓ,x′:σ⊢b{x↦x′} a2⋯an⇒τΓ⊢(λx. b) a1 a2⋯an⇒τ\textscRedex⇐  Γ⊢a1⇒σΓ,x′:σ⊢b{x↦x′} a2⋯an⇐τΓ⊢(λx. b) a1 a2⋯an⇐τ(n≥1)\textsc{Redex}\; \frac{\Gamma \vdash a_1 \Rightarrow \sigma \qquad \Gamma, x'{:}\sigma \vdash b\{x \mapsto x'\}\,a_2 \cdots a_n \Rightarrow \tau} {\Gamma \vdash (\lambda x.\,b)\,a_1\,a_2 \cdots a_n \Rightarrow \tau} \qquad \textsc{Redex}^{\Leftarrow}\; \frac{\Gamma \vdash a_1 \Rightarrow \sigma \qquad \Gamma, x'{:}\sigma \vdash b\{x \mapsto x'\}\,a_2 \cdots a_n \Leftarrow \tau} {\Gamma \vdash (\lambda x.\,b)\,a_1\,a_2 \cdots a_n \Leftarrow \tau} \quad (n \ge 1) \textscLam  Γ,x:σ⊢b⇐τΓ⊢λx. b⇐σ→τ\textscSub  Γ⊢t⇒τ′τ′=τΓ⊢t⇐τ\textsc{Lam}\; \frac{\Gamma, x{:}\sigma \vdash b \Leftarrow \tau}{\Gamma \vdash \lambda x.\,b \Leftarrow \sigma \to \tau} \qquad \textsc{Sub}\; \frac{\Gamma \vdash t \Rightarrow \tau' \qquad \tau' = \tau}{\Gamma \vdash t \Leftarrow \tau}

In \textscApp\textsc{App} the spine is flattened first, so nested Apply nodes are one application h a1⋯anh\,a_1 \cdots a_n; if hh has fewer arrows than arguments the result is ExpectedFunction, and an Apply node of the spine without arguments gives EmptyApplication. \textscRedex\textsc{Redex} and \textscRedex⇐\textsc{Redex}^{\Leftarrow} 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:

x′={xif x∉FV(a2,…,an),fresh⁡(x, names(b)∪names(a2,…,an)∪dom⁡Γ∪{x})otherwise,x' = \begin{cases} x & \text{if } x \notin \mathrm{FV}(a_2, \dots, a_n),\\ \operatorname{fresh}\big(x,\ \mathrm{names}(b) \cup \mathrm{names}(a_2, \dots, a_n) \cup \operatorname{dom}\Gamma \cup \{x\}\big) & \text{otherwise,} \end{cases}

with b{x↦x′}b\{x \mapsto x'\} the checked bound renaming of the syntax design; in both cases λx. b=αλx′. b{x↦x′}\lambda x.\,b =_\alpha \lambda x'.\,b\{x \mapsto x'\} and x′∉FV(a2,…,an)x' \notin \mathrm{FV}(a_2, \dots, a_n). With n=1n = 1 there is nothing to rename and the second premise is Γ,x:σ⊢b⇒τ\Gamma, x{:}\sigma \vdash b \Rightarrow \tau, or Γ,x:σ⊢b⇐τ\Gamma, x{:}\sigma \vdash b \Leftarrow \tau for \textscRedex⇐\textsc{Redex}^{\Leftarrow}. check uses \textscRedex⇐\textsc{Redex}^{\Leftarrow} for every application whose flattened head is a lambda, and \textscSub\textsc{Sub} for every other term except a lambda checked against an arrow; a lambda in inference position fails with CannotInferLambda. Type equality in \textscSub\textsc{Sub} is syntactic, which is exact for simple types.

Why the extra \textscRedex\textsc{Redex} rule. Plain bidirectional typing cannot infer (λx. b) a(\lambda x.\,b)\,a, because the head is a lambda. The rule treats the redex like let x=a in b\mathsf{let}\ x = a\ \mathsf{in}\ b: the argument’s type is inferred and given to the parameter. It makes terms produced by substitution-style programming, such as (λx. x) ()(\lambda x.\,x)\,(), checkable without annotations.

Why a checking-mode \textscRedex⇐\textsc{Redex}^{\Leftarrow}. \textscRedex\textsc{Redex} alone reaches \textscSub\textsc{Sub} when a redex is checked, so the rest of the spine must be inferred. When the redex returns a lambda, as in (λx. λy. y)  ()(\lambda x.\,\lambda y.\,y)\;() checked against Unit→Unit\mathsf{Unit} \to \mathsf{Unit}, that rest is the lambda λy. y\lambda y.\,y, and inference fails with CannotInferLambda although the expected type is known. \textscRedex⇐\textsc{Redex}^{\Leftarrow} passes the expected type on to the rest of the spine instead, as checking let x=a in b\mathsf{let}\ x = a\ \mathsf{in}\ b against τ\tau checks bb against τ\tau. It accepts everything that \textscRedex\textsc{Redex} followed by \textscSub\textsc{Sub} accepts: by induction on the spine, its last step reaches either a non-lambda head, where check infers the rest of the spine as \textscRedex\textsc{Redex} would, or a spine without arguments, which is checked directly. Versions before the fix had only \textscRedex\textsc{Redex} and rejected such terms, also as arguments, as in f ((λx. λy. y)  ())f\,((\lambda x.\,\lambda y.\,y)\;()) with f:(A→A)→Af : (A \to A) \to A.

Soundness of the checker

Theorem (soundness). If check(Σ, Γ, t, τ) succeeds, then Γ⊢t:τ\Gamma \vdash t : \tau; if infer(Σ, Γ, t) returns τ\tau, then Γ⊢t:τ\Gamma \vdash t : \tau.

Proof sketch. Induction on the algorithmic derivation. \textscLam\textsc{Lam} and the axioms map to their declarative counterparts; \textscSub\textsc{Sub} is immediate; \textscApp\textsc{App} is nn uses of the declarative application rule. For \textscRedex\textsc{Redex} and \textscRedex⇐\textsc{Redex}^{\Leftarrow}, write b′=b{x↦x′}b' = b\{x \mapsto x'\}. The second premise is an inference or a checking derivation for the smaller term b′ a2⋯anb'\,a_2 \cdots a_n, so in both cases by induction Γ,x′:σ⊢b′ a2⋯an:τ\Gamma, x'{:}\sigma \vdash b'\,a_2 \cdots a_n : \tau, and the generation lemma for application gives types τ2,…,τn\tau_2, \dots, \tau_n with Γ,x′:σ⊢b′:τ2→⋯→τn→τ\Gamma, x'{:}\sigma \vdash b' : \tau_2 \to \cdots \to \tau_n \to \tau and Γ,x′:σ⊢ai:τi\Gamma, x'{:}\sigma \vdash a_i : \tau_i for i≥2i \ge 2. Then

Γ⊢λx′. b′:σ→τ2→⋯→τabstractionΓ⊢λx. b:σ→τ2→⋯→τλx. b=αλx′. b′Γ⊢(λx. b) a1:τ2→⋯→τapplication, Γ⊢a1:σΓ⊢ai:τi (i≥2)strengthening, x′∉FV(ai)Γ⊢(λx. b) a1⋯an:τapplication (n−1 times).\begin{aligned} &\Gamma \vdash \lambda x'.\,b' : \sigma \to \tau_2 \to \cdots \to \tau && \text{abstraction} \\ &\Gamma \vdash \lambda x.\,b : \sigma \to \tau_2 \to \cdots \to \tau && \lambda x.\,b =_\alpha \lambda x'.\,b' \\ &\Gamma \vdash (\lambda x.\,b)\,a_1 : \tau_2 \to \cdots \to \tau && \text{application, } \Gamma \vdash a_1 : \sigma \\ &\Gamma \vdash a_i : \tau_i \ (i \ge 2) && \text{strengthening, } x' \notin \mathrm{FV}(a_i) \\ &\Gamma \vdash (\lambda x.\,b)\,a_1 \cdots a_n : \tau && \text{application } (n - 1 \text{ times}). \end{aligned}

The argument does not use the mode of the second premise, so it proves both rules; for n=1n = 1 only the first three lines are needed, with b′b' of type τ\tau, which may be an arrow when b′b' is a lambda. □\square

The strengthening step is where the renaming is needed. For Γ=x:B\Gamma = x{:}B the term

(λx. λy. y)  ()  x(\lambda x.\,\lambda y.\,y)\;()\;x

has declarative type BB and no other. Without the renaming, the trailing xx would be typed in Γ,x:Unit\Gamma, x{:}\mathsf{Unit} and the checker would answer Unit; versions before the fix did exactly that, and check accepted the term at Unit. With x′=x1x' = x_1 the trailing xx keeps its type BB, and infer returns BB. \textscRedex⇐\textsc{Redex}^{\Leftarrow} renames in the same way, so (λx. λy. λz. y)  ()  x(\lambda x.\,\lambda y.\,\lambda z.\,y)\;()\;x checks against A→BA \to B and not against A→UnitA \to \mathsf{Unit}.

The typed evaluator walks a spine the same way. It flattens nested Apply nodes before typing the head, so the curried ((λx. λy. y)  ())  x((\lambda x.\,\lambda y.\,y)\;())\;x is the same spine as the term above. A lambda head cannot be inferred, so its type is rebuilt from the premises of \textscRedex\textsc{Redex} or \textscRedex⇐\textsc{Redex}^{\Leftarrow} and the expected type τ\tau of the whole application. Write b′=h c1⋯ckb' = h\,c_1 \cdots c_k with hh not an application (k=0k = 0 if b′b' is not one). The head gets the type σ→ρ\sigma \to \rho, where σ\sigma is inferred for a1a_1 and ρ\rho, the type of b′b', is computed recursively: take the head type of the flattened spine h c1⋯ck a2⋯anh\,c_1 \cdots c_k\,a_2 \cdots a_n under Γ,x′:σ\Gamma, x'{:}\sigma and remove its first kk domains. If that spine is empty, b′b' is in checking position as in \textscRedex⇐\textsc{Redex}^{\Leftarrow} and ρ=τ\rho = \tau; this covers a body that is a lambda, such as λy. y\lambda y.\,y in (λx. λy. y)  ()(\lambda x.\,\lambda y.\,y)\;() at Unit→Unit\mathsf{Unit} \to \mathsf{Unit}. Any other head is inferred. A redex body that consumes the outer arguments, as in (λx. (λy. λz. z) x)  ()  v(\lambda x.\,(\lambda y.\,\lambda z.\,z)\,x)\;()\;v, 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 tt is beta-normal and Γ⊢t:τ\Gamma \vdash t : \tau, then check(Σ, Γ, t, τ) succeeds. A beta-normal term is either a lambda, handled by \textscLam\textsc{Lam}, or a spine whose head is a variable, a constant or ()(); its type is determined by Γ\Gamma or Σ\Sigma and its arguments are again normal, so \textscApp\textsc{App} and induction apply.

Terms with redexes are accepted when every argument that the spine walk gives to a lambda head is inferable: a1a_1 in each spine (λx. b) a1⋯an(\lambda x.\,b)\,a_1 \cdots a_n, and then, recursively, the arguments that b{x↦x′} a2⋯anb\{x \mapsto x'\}\,a_2 \cdots a_n 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 \textscApp\textsc{App} and the argument of \textscRedex\textsc{Redex} have unique types), so a derivation of Γ⊢(λx. b) a1⋯an:τ\Gamma \vdash (\lambda x.\,b)\,a_1 \cdots a_n : \tau gives the parameter the type σ\sigma that infer returns for a1a_1, and, by weakening with x′∉FV(a2,…,an)x' \notin \mathrm{FV}(a_2, \dots, a_n), Γ,x′:σ⊢b{x↦x′} a2⋯an:τ\Gamma, x'{:}\sigma \vdash b\{x \mapsto x'\}\,a_2 \cdots a_n : \tau; \textscRedex⇐\textsc{Redex}^{\Leftarrow} and induction on the size of the term apply. The condition is needed: both (λf. f ()) (λy. y)(\lambda f.\,f\,())\,(\lambda y.\,y) and (λx. λy. y)  ()  (λz. z)(\lambda x.\,\lambda y.\,y)\;()\;(\lambda z.\,z) are typable and rejected with CannotInferLambda, the second because the walk gives λz. z\lambda z.\,z to the lambda head λy. y\lambda y.\,y.

The checker terminates. Measure a call by the size of its term, and break ties by counting a check call above an infer call. \textscSub\textsc{Sub} goes from check to infer on the same term, which lowers the measure; every other recursive call is on a strictly smaller term (\textscRedex\textsc{Redex} and \textscRedex⇐\textsc{Redex}^{\Leftarrow} recurse on b{x↦x′} a2⋯anb\{x \mapsto x'\}\,a_2 \cdots a_n, which lacks the binder and a1a_1; 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 βη\beta\eta class, so two well-typed terms are βη\beta\eta-equal iff their eta-long normal forms are alpha-equivalent: the normalizer decides conversion.

Beta-normal, eta-long forms

Normal forms Nfτ\mathit{Nf}^\tau and neutral terms Ne\mathit{Ne} are defined by type:

Nfσ→τ::=λx. Nfτ,Nfb::=Ne,NfUnit::=()∣Ne,Ne::=x∣c∣Ne  Nfσ.\begin{aligned} \mathit{Nf}^{\sigma \to \tau} &::= \lambda x.\,\mathit{Nf}^{\tau}, & \mathit{Nf}^{b} &::= \mathit{Ne}, & \mathit{Nf}^{\mathsf{Unit}} &::= () \mid \mathit{Ne}, \\ \mathit{Ne} &::= x \mid c \mid \mathit{Ne}\;\mathit{Nf}^{\sigma} . \end{aligned}

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 Unit\mathsf{Unit} are kept: the eta law for the unit type (t=()t = () for every t:Unitt : \mathsf{Unit}) is not implemented, so for f:Unit→Unitf : \mathsf{Unit} \to \mathsf{Unit} and u:Unitu : \mathsf{Unit} the terms f uf\,u and f ()f\,() have different normal forms.

Typed normalization by evaluation

The semantic domain interprets each type:

Vb=NeV,VUnit={()}+NeV,Vσ→τ=Cloσ→τ+NeV,V_b = \mathit{Ne}_V, \qquad V_{\mathsf{Unit}} = \{()\} + \mathit{Ne}_V, \qquad V_{\sigma \to \tau} = \mathit{Clo}_{\sigma \to \tau} + \mathit{Ne}_V,

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 ⟦t⟧ρ\llbracket t \rrbracket\rho 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 ↑τ\uparrow^\tau embeds a neutral as a value; here it is the identity on neutrals, because all eta expansion is deferred to reification. Reification ↓τ:Vτ→Nfτ\downarrow^\tau : V_\tau \to \mathit{Nf}^\tau is

↓σ→τf=λx.  ↓τ(f⋅↑σx)x fresh,↓bn=quote(n),↓Unit()=(),↓Unitn=quote(n),quote(x)=x,quote(c)=c,quote(n⋅σv)=quote(n)  ↓σv,\begin{aligned} \downarrow^{\sigma \to \tau} f &= \lambda x.\; \downarrow^{\tau}\big(f \cdot \uparrow^{\sigma} x\big) \qquad x \text{ fresh}, \\ \downarrow^{b} n &= \mathrm{quote}(n), \qquad \downarrow^{\mathsf{Unit}} () = (), \qquad \downarrow^{\mathsf{Unit}} n = \mathrm{quote}(n), \\ \mathrm{quote}(x) &= x, \quad \mathrm{quote}(c) = c, \quad \mathrm{quote}(n \cdot^{\sigma} v) = \mathrm{quote}(n)\;\downarrow^{\sigma} v, \end{aligned}

and the normal form of Γ⊢t:τ\Gamma \vdash t : \tau is ↓τ⟦t⟧ρΓ\downarrow^\tau \llbracket t \rrbracket \rho_\Gamma, where ρΓ\rho_\Gamma maps each x:σ∈Γx{:}\sigma \in \Gamma to ↑σx\uparrow^\sigma x. 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 tRτdt \mathrel{R_\tau} d between terms and values, monotone under context extension:

tRbn  ⟺  t=βηquote(n),tRUnitd  ⟺  t=βη↓Unitd,tRσ→τf  ⟺  ∀ Γ′⊇Γ, sRσe  ⟹  t sRτf⋅e.\begin{aligned} t \mathrel{R_b} n &\iff t =_{\beta\eta} \mathrm{quote}(n), \\ t \mathrel{R_{\mathsf{Unit}}} d &\iff t =_{\beta\eta} \downarrow^{\mathsf{Unit}} d, \\ t \mathrel{R_{\sigma \to \tau}} f &\iff \forall\, \Gamma' \supseteq \Gamma,\ s \mathrel{R_\sigma} e \implies t\,s \mathrel{R_\tau} f \cdot e . \end{aligned}

By induction on τ\tau one proves two lemmas together: reflection (t=βηquote(n)t =_{\beta\eta} \mathrm{quote}(n) implies tRτ↑τnt \mathrel{R_\tau} \uparrow^\tau n) and reification (tRτdt \mathrel{R_\tau} d implies t=βη↓τdt =_{\beta\eta} \downarrow^\tau d). The arrow case of reification is the eta step:

t  =η  λx. t x  =βη  λx. ↓τ(f⋅↑σx)  =  ↓σ→τf,t \;=_\eta\; \lambda x.\,t\,x \;=_{\beta\eta}\; \lambda x.\,\downarrow^\tau (f \cdot \uparrow^\sigma x) \;=\; \downarrow^{\sigma \to \tau} f ,

using xRσ↑σxx \mathrel{R_\sigma} \uparrow^\sigma x (reflection) and the definition of Rσ→τR_{\sigma \to \tau}. The fundamental lemma states that Γ⊢t:τ\Gamma \vdash t : \tau and γRΓρ\gamma \mathrel{R_\Gamma} \rho imply t[γ]Rτ⟦t⟧ρt[\gamma] \mathrel{R_\tau} \llbracket t \rrbracket \rho; it is proved by induction on the typing derivation, the lambda case using that beta-reduction is in =βη=_{\beta\eta}. With γ\gamma the identity and ρΓ\rho_\Gamma (related by reflection), reification gives t=βηnf(t)t =_{\beta\eta} \mathrm{nf}(t) (soundness). Completeness, that βη\beta\eta-equal terms have alpha-equivalent normal forms, needs a second argument: a partial equivalence relation on values, defined by induction on types like RR, under which ⟦t⟧\llbracket t \rrbracket and ⟦t′⟧\llbracket t' \rrbracket are related whenever t=βηt′t =_{\beta\eta} t' (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 RR, 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 \textscApp\textsc{App}), 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 ↓τ\downarrow^\tau, for quote\mathrm{quote} 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 100 000100\,000, 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 nn binders costs O(n)O(n) instead of O(n2)O(n^2). Readback chooses binder names with fresh⁡(x,U)\operatorname{fresh}(x, U), the first of the candidates c0=xc_0 = x, c1=x_1c_1 = x\_1, c2=x_2c_2 = x\_2, … not in UU, and eta-expanding at a type nested nn levels deep would retry the nn names chosen before. It carries, with UU, a position pp such that every cqc_q with q<pq < p is in UU, and starts the search there. If cp′c_{p'} is chosen, every cqc_q with q≤p′q \le p' is in U∪{cp′}U \cup \{c_{p'}\}, so p′+1p' + 1 is a valid position for the extended set; readback only ever adds names to UU, so the position stays valid along the path, and the name found is the one fresh⁡\operatorname{fresh} 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 n,n−1,…,1n, n-1, \ldots, 1, 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 (λx.b) a1 a2⋯an(\lambda x.b)\,a_1\,a_2\cdots a_n by evaluating a1a_1 and continuing b a2⋯anb\,a_2\cdots a_n under its value. The existing capture-avoidance step renames xx 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; pp such visits add O(p)O(p) plan storage and O(d)O(d) pending frames at traversal depth dd. Public infer and check also build a plan and discard it, adding O(p)O(p) 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 O(n)O(n) work and O(n)O(n) 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

  • check and infer terminate; 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.
  • check accepts 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_long returns Ok exactly for terms that check accepts; its result is in Nfτ\mathit{Nf}^\tau, is βη\beta\eta-equal to the input, and is the same (up to =α=_\alpha) for βη\beta\eta-equal inputs.
  • normalize_checked returns Err before any reduction for ill-typed input.
  • NormalizationError signals a violated internal invariant and is not produced for checked input.
  • check, infer, normalize_checked, normalize_eta_long and == 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 (\textscRedex⇐\textsc{Redex}^{\Leftarrow}): 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 Term syntax; 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 Unit\mathsf{Unit} as ()(); not done, so that neutrals stay observable. The decided equality is βη\beta\eta for arrows only.

Boundaries

  • Types are bb, Unit\mathsf{Unit} 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_checked is bounded by a step limit because it reuses the untyped reducer.
  • normalize_eta_long executes 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.
  • Debug of a deep term, type or error recurses and can overflow the stack.

Footnotes

  1. W. W. Tait, “Intensional interpretations of functionals of finite type I”, Journal of Symbolic Logic 32, 1967. ↩

  2. J. Dunfield and N. Krishnaswami, “Bidirectional typing”, ACM Computing Surveys 54(5), 2021. ↩

  3. 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. ↩