The simply typed lambda-calculus (STLC) is a tiny core
calculus embodying the key concept of functional abstraction.
This concept shows up in pretty much every real-world programming
language in some form (functions, procedures, methods, etc.).
We will follow exactly the same pattern as in the previous chapter
when formalizing this calculus (syntax, small-step semantics,
typing rules) and its main properties (progress and preservation).
The new technical challenges arise from the mechanisms of
variable binding and substitution. It will take some work to
deal with these.
The STLC lives in the lower-left front corner of the famous
lambda cube (also called the Barendregt Cube), which
visualizes three sets of features that can be added to its
simple core:
Moving from bottom to top in the cube corresponds to adding
polymorphic types like ∀α:Type,α→α. Adding just
polymorphism gives us the famous Girard-Reynolds calculus, System F.
Moving from front to back corresponds to adding type operators
like List.
Moving from left to right corresponds to adding dependent types
like ∀n,ArrayOfSizen.
The top right corner on the back, which combines all three features,
is called the Calculus of Constructions. First studied by
Coquand and Huet, it forms the foundation of Lean's logic.
The STLC is built on some collection of base types:
booleans, numbers, strings, etc. The exact choice of base types
doesn't matter much — the definition of the language as well as
its theoretical properties work out the same no matter what we
choose — so for the sake of brevity let's take just Bool for
the moment. In the next chapter we'll see how to add more
base types, and in later chapters we'll enrich the pure STLC with
other useful constructs like pairs, records, subtyping, and
mutable state.
Starting from boolean constants and conditionals, we add three
things:
variables
function abstractions
application
This gives us the following collection of abstract syntax
constructors (written out first in informal BNF notation — we'll
formalize it below) for STLC terms t.
t
::=
x
(variable)
|
λx:T.t
(abstraction)
|
tt
(application)
|
true
(constant true)
|
false
(constant false)
|
iftthentelset
(conditional)
The Greek letter λ ("lambda") in a function abstraction λx:T. t is what gives
the calculus its name. The variable x is called the parameter to the
function; the term t is its body. The annotation :T
specifies the type of arguments that the function can be applied to.
The types of the STLC include Bool, which classifies the
boolean constants true and false as well as more complex
computations that yield booleans, plus arrow types that classify
functions (as is the case in Lean).
T
::=
Bool
|
T→T
Some examples of STLC terms:
λx:Bool. x
The identity function for booleans.
(λx:Bool. x) true
The identity function for booleans, applied to the boolean true.
λx:Bool. if x then false else true
The boolean "not" function.
λx:Bool. true
The constant function that takes every (boolean) argument to
true.
λx:Bool. λy:Bool. x
A two-argument function that takes two booleans and returns
the first one.
(As in Lean, a two-argument function in the
lambda-calculus is really a one-argument function whose body
is also a one-argument function.)
(λx:Bool. λy:Bool. x) false true
A two-argument function that takes two booleans and returns
the first one, applied to the booleans false and true.
(As in Lean, application associates to the left — i.e., this
expression is parsed as ((λx:Bool. λy:Bool. x) false) true.)
λf:Bool → Bool. f (f true)
A higher-order function that takes a functionf (from
booleans to booleans) as an argument, applies f to true,
and applies f again to the result.
(λf:Bool → Bool. f (f true)) (λx:Bool. false)
The same higher-order function, applied to the constantly
false function.
The last two examples show, the STLC is a language of
higher-order functions: we can write down functions that take
other functions as arguments and/or return other functions as results.
The STLC doesn't provide any primitive syntax for defining named
functions: i.e., all functions are "anonymous." We'll see in chapter
MoreStlc that it is easy to add named functions — indeed, the
fundamental naming and binding mechanisms are exactly the same.
Now reconsider our examples, each along with its type:
λx:Bool. x has type Bool → Bool
(λx:Bool. x) true has type Bool
λx:Bool. if x then false else true has type Bool → Bool
λx:Bool. true has type Bool → Bool
λx:Bool. λy:Bool. x has type Bool → Bool → Bool
(i.e., Bool → (Bool → Bool))
(λx:Bool. λy:Bool. x) false true has type Bool
The last two, higher-order examples are left off the list on purpose — working out
their types is the subject of the quizzes that follow.
We need some notation magic to set up the concrete syntax, as
we did in the Types chapter...
The upshot of this section is that STLC types and terms are both written
inside one pair of brackets, <{ … }>, and that ~e inside the brackets
escapes back to an arbitrary Lean expression:
<{ Bool → Bool }> is a type;
<{ λ x : Bool . x }> is a term — a bare identifier inside the brackets is
the object-language variable of that name, so <{ x }> is the variable x;
<{ ~t₁ ~t₂ }> applies one Lean-level term to another.
Lean works out from context which of the two a given bracket holds, so the same
brackets serve for types, for terms, and — when we come to typing — for
typing judgments too. How that works is in the collapsed blocks below; nothing
later in the chapter depends on it.
Notation encoding: types
The stlcTy grammar covers Bool, arrows (written → or ->, associating to
the right), parentheses, and ~e. A bare identifier other than Bool is
spliced in as a Lean term, so a local T — or any Lean expression of type
Ty — can appear directly inside the brackets.
To extend the grammar, a later chapter adds a syntax line to the category and
a matching macro_rules case; that is all it takes to add a new type construct.
Terms are built from variables, application (associating to the left),
abstraction, the two boolean constants, and conditionals. A binding
occurrence — the x in λ x : T . t — has a small grammar of its own,
stlcVar, and varStr turns it into the string that Tm.abs stores.
Because types and terms share the brackets, each macro_rules group says which
bracket it belongs to (kind := tyBracket, kind := tmBracket), and each
antiquote in a nested quotation says which grammar it came from. A bare
identifier is the one genuinely overlapping case: Bool in term position would
otherwise quietly become a variable named Bool, so that rule rejects it, which
also settles which grammar a lone <{ Bool }> belongs to.
The last production, [x := s] t, is the notation for substitution; we give it
its meaning when we define substitution below. It binds tighter than
application, so [x:=s] t₁ t₂ is the application of [x:=s] t₁ to t₂, and a
λ or if body must be parenthesized: [x:=s] (λ y : Bool . x).
declare_syntax_catstlcVarsyntax:maxident:stlcVarsyntax:max"~"term:max:stlcVaropenLeanin/-- The string named by a variable in binding position. -/defvarStr(x:TSyntax`stlcVar):MacroMTerm:=matchxwith|`(stlcVar|$i:ident)=>pure(quotei.getId.toString:Term)|`(stlcVar|~$e)=>puree|_=>Macro.throwUnsupporteddeclare_syntax_catstlcTmsyntax:max"~"term:max:stlcTmsyntax:max"("stlcTm")":stlcTmsyntax:maxident:stlcTmsyntax:75stlcTm:75ppSpacestlcTm:76:stlcTmsyntax:50"λ "stlcVar" : "stlcTy" . "stlcTm:50:stlcTmsyntax:50"if "stlcTm:51" then "stlcTm:50" else "stlcTm:50:stlcTmsyntax:max"["stlcVar" := "stlcTm"] "stlcTm:max:stlcTmsyntax:max(name:=tmBracket)"<{ "stlcTm" }>":termopenLeaninmacro_rules(kind:=tmBracket)|`(<{~$e:term}>)=>puree|`(<{($t:stlcTm)}>)=>`(<{$t:stlcTm}>)|`(<{$x:ident}>)=>matchx.getId.toStringwith|"true"=>`(Tm.tru)|"false"=>`(Tm.fls)|"Bool"=>Macro.throwErrorAtx"`Bool` is a type, not a term"|_=>`(Tm.var$(quotex.getId.toString))|`(<{$t₁:stlcTm$t₂:stlcTm}>)=>`(Tm.app<{$t₁:stlcTm}><{$t₂:stlcTm}>)|`(<{λ$x:$T.$t}>)=>do`(Tm.abs$(←varStrx)<{$T:stlcTy}><{$t:stlcTm}>)|`(<{if$cthen$telse$e}>)=>`(Tm.ite<{$c:stlcTm}><{$t:stlcTm}><{$e:stlcTm}>)Notation encoding: printing it back
A delaborator runs the grammar backwards: it rebuilds the concrete syntax
from a Ty or Tm value, so that types and terms appearing in
goals and in #check output print as <{ λ x : Bool . x }> rather than as a
pile of constructors. (Setting pp.notation false turns it off, revealing the
underlying representation.)
openLeanPrettyPrinterDelaboratorSubExprParenthesizerin/-- Re-inserts parentheses in `stlcTy` output according to the grammar's precedences. -/@[category_parenthesizerstlcTy]defstlcTy.parenthesizer:CategoryParenthesizer|prec=>domaybeParenthesize`stlcTytruewrapParensprec<|parenthesizeCategoryCore`stlcTyprecwherewrapParens(stx:Syntax):Syntax:=Unhygienic.rundoletpstx←`(stlcTy|($(⟨stx⟩)))returnpstx.raw.setInfo(SourceInfo.fromRefstx)openLeanPrettyPrinterDelaboratorSubExprParenthesizerin/-- Re-inserts parentheses in `stlcTm` output according to the grammar's precedences. -/@[category_parenthesizerstlcTm]defstlcTm.parenthesizer:CategoryParenthesizer|prec=>domaybeParenthesize`stlcTmtruewrapParensprec<|parenthesizeCategoryCore`stlcTmprecwherewrapParens(stx:Syntax):Syntax:=Unhygienic.rundoletpstx←`(stlcTm|($(⟨stx⟩)))returnpstx.raw.setInfo(SourceInfo.fromRefstx)openLeanPrettyPrinterDelaboratorSubExprin/-- Rebuild `stlcTy` concrete syntax from a `Ty` value. -/partialdefdelabTyInner:DelabM(TSyntax`stlcTy):=doletstx←match_expr←getExprwith|Ty.bool=>`(stlcTy|$(mkIdent`Bool):ident)|Ty.arrow__=>doleta←withAppFn<|withAppArgdelabTyInnerletb←withAppArgdelabTyInner`(stlcTy|$a→$b)|_=>domatch←delabwith|`($i:ident)=>`(stlcTy|$i:ident)|e=>`(stlcTy|~$e)(⟨·⟩)<$>annotateTermInfo⟨stx.raw⟩openLeanin/-- Is `s` usable as a bare identifier in the object syntax? -/defisPlainName(s:String):Bool:=!s.isEmpty&&s!="_"&&!s.front.isDigit&&s.allfunc=>c.isAlphanum||c=='_'openLeanin/-- Is `s` usable as a bare variable in `stlcTm` rather than as reserved syntax? -/defisPlainTmVarName(s:String):Bool:=isPlainNames&&s!="true"&&s!="false"&&s!="Bool"openLeanPrettyPrinterDelaboratorSubExprin/-- Rebuild `stlcVar` concrete syntax from the string in a binding position. -/defdelabVarInner:DelabM(TSyntax`stlcVar):=domatch←delabwith|`($s:str)=>ifisPlainNames.getStringthen`(stlcVar|$(mkIdent(Name.mkSimples.getString)):ident)else`(stlcVar|~$s)|e=>`(stlcVar|~$e)openLeanPrettyPrinterDelaboratorSubExprin/-- Rebuild `stlcTm` concrete syntax from a `Tm` value. -/partialdefdelabTmInner:DelabM(TSyntax`stlcTm):=doletstx←match_expr←getExprwith|Tm.tru=>`(stlcTm|$(mkIdent`true):ident)|Tm.fls=>`(stlcTm|$(mkIdent`false):ident)|Tm.var_=>doletx←withAppArgdelabmatchxwith|`($s:str)=>ifisPlainTmVarNames.getStringthen`(stlcTm|$(mkIdent(Name.mkSimples.getString)):ident)elseletvar:Term:=mkIdent``Stlc.Tm.var`(stlcTm|~($var$x))|_=>letvar:Term:=mkIdent``Stlc.Tm.var`(stlcTm|~($var$x))|Tm.app__=>doletf←withAppFn<|withAppArgdelabTmInnerleta←withAppArgdelabTmInner`(stlcTm|$f$a)|Tm.abs___=>doletx←withAppFn<|withAppFn<|withAppArgdelabVarInnerletT←withAppFn<|withAppArgdelabTyInnerlett←withAppArgdelabTmInner`(stlcTm|λ$x:$T.$t)|Tm.ite___=>doletc←withAppFn<|withAppFn<|withAppArgdelabTmInnerlett←withAppFn<|withAppArgdelabTmInnerlete←withAppArgdelabTmInner`(stlcTm|if$cthen$telse$e)|_=>do-- `subst` is defined below, so it is matched by name rather than with-- `match_expr`; a substitution prints in its own bracket notation.lete←getExprife.getAppFn.constName?==some`Stlc.subst&&e.getAppNumArgs==3thenletx←withAppFn<|withAppFn<|withAppArgdelabVarInnerlets←withAppFn<|withAppArgdelabTmInnerlett←withAppArgdelabTmInner`(stlcTm|[$x:=$s]$t)elsematch←delabwith|`($i:ident)=>`(stlcTm|$i:ident)|e=>`(stlcTm|~$e)(⟨·⟩)<$>annotateTermInfo⟨stx.raw⟩openLeanPrettyPrinterDelaboratorSubExprin@[delabapp.Stlc.Ty.bool,delabapp.Stlc.Ty.arrow]defdelabTy:Delab:=whenPPOptiongetPPNotationdoguard<|match_expr←getExprwith|Ty.bool=>true|Ty.arrow__=>true|_=>falsematch←delabTyInnerwith|`(stlcTy|~$e)=>puree|e=>`(<{$e:stlcTy}>)openLeanPrettyPrinterDelaboratorSubExprin@[delabapp.Stlc.Tm.var,delabapp.Stlc.Tm.app,delabapp.Stlc.Tm.abs,delabapp.Stlc.Tm.tru,delabapp.Stlc.Tm.fls,delabapp.Stlc.Tm.ite]defdelabTm:Delab:=whenPPOptiongetPPNotationdoguard<|match_expr←getExprwith|Tm.var_=>true|Tm.app__=>true|Tm.abs___=>true|Tm.tru=>true|Tm.fls=>true|Tm.ite___=>true|_=>falsematch←delabTmInnerwith|`(stlcTm|~($e))=>puree|`(stlcTm|~$e)=>puree|e=>`(<{$e:stlcTm}>)
A few checks that the grammar parses the way it should — application
associating to the left, conditionals nesting without parentheses, and ~
escaping to Lean:
Here are the terms we will use as running examples, written in the new
notation:
Note that an abstraction λ x : T . t (formally, Tm.abs applied to
x, T, and t) is
always annotated with the type T of its parameter, in contrast
to Lean (and other functional languages like ML, Haskell, etc.),
which use type inference to fill in missing annotations. We're
not considering type inference at all here.
To define the small-step semantics of STLC terms, we begin,
as always, by defining the set of values. Next, we define the
critical notions of free variables and substitution, which are
used in the reduction rule for application expressions. And
finally we give the small-step relation itself.
To define the values of the STLC, we have a few cases to consider.
First, for the boolean part of the language, the situation is
clear: true and false are the only values. An if expression
is never a value.
Second, an application is not a value: it represents a function
being invoked on some argument, which clearly still has work left
to do.
Third, for abstractions, we have a choice:
We can say that λx:T. t is a value only when t is a
value — i.e., only if the function's body has been
reduced (as much as it can be without knowing what argument it
is going to be applied to).
Or we can say that λx:T. t is always a value, no matter
whether t is one or not — in other words, we can say that
reduction stops at abstractions.
Our usual way of evaluating expressions in Lean makes the first
choice — for example,
fun_x=>7#reducefun_x:Bool=>3+4
yields:
fun _x => 7
But Lean is rather unusual in this respect. Most functional
programming languages make the second choice — reduction of a
function's body only begins when the function is actually applied
to an argument.
The example terms named above are all abstractions, hence all values. We
record that once each, so that the reduction examples can cite the fact by name
instead of unfolding the definition again at every use.
The Rocq source follows each inductive definition in this chapter with a
Hint Constructors … : core, registering the constructors with auto; the
proofs then lean on auto/eauto to assemble derivations. We have no
counterpart here: the proofs below name their constructors explicitly, in the
style of the Types chapter. Lean's grind would be the closest
analogue if a later pass wants automation.
Finally, we must consider what constitutes a complete program.
Intuitively, a "complete program" must not refer to any undefined
variables. We'll see shortly how to define the free variables
in a STLC term. A complete program, then, is one that is
closed — that is, that contains no free variables.
(Conversely, a term that may contain free variables is often
called an open term.)
Note to developers (Chris Henson @chenson2018, before next release)
Is the "shortly" above setting wrong expectations?
Where exactly are we defining the free variables in a STLC term?
BCP 25: Indeed, we need to define "free"!
Having made the choice not to reduce under abstractions, we don't
need to worry about whether variables are values, since we'll
always be reducing programs "from the outside in," and that means
the step relation will always be working with closed terms.
Now we come to the heart of the STLC: the operation of
substituting one term for a variable in another term. This
operation is used below to define the operational semantics of
function application, where we will need to substitute the
argument term for the function parameter in the function's body.
For example, we reduce
(λx:Bool. if x then true else x) false
to
if false then true else false
by substituting false for the parameter x in the body of the
function.
In general, we need to be able to substitute some given term s
for occurrences of some variable x in another term t.
Informally, this is written [x:=s]t and pronounced "substitute
s for x in t."
Here are some examples:
[x:=true] (if x then true else false)
yields if true then true else false
[x:=true] x yields true
[x:=true] (if x then x else y) yields if true then true else y
[x:=true] (λy:Bool. if y then x else false)
yields λy:Bool. if y then true else false
[x:=true] (λy:Bool. x) yields λy:Bool. true
[x:=true] (λy:Bool. y) yields λy:Bool. y
[x:=true] (λx:Bool. x) yields λx:Bool. x
The last example is illuminating: substituting x with true in
λx:Bool. x does not yield λx:Bool. true! The reason for
this is that the x in the body of λx:Bool. x is bound by the
abstraction: it is a new, local name that just happens to be
spelled the same as some global name x.
Here is the definition, informally...
[x:=s]x = s
[x:=s]y = y if x ≠ y
[x:=s](λx:T. t) = λx:T. t
[x:=s](λy:T. t) = λy:T. [x:=s]t if x ≠ y
[x:=s](t₁ t₂) = ([x:=s]t₁) ([x:=s]t₂)
[x:=s]true = true
[x:=s]false = false
[x:=s](if t₁ then t₂ else t₃) =
if [x:=s]t₁ then [x:=s]t₂ else [x:=s]t₃
... and formally:
sectionset_optionhygienefalseinlocalmacro_rules(kind:=tmBracket)|`(<{[$x:=$s]$t}>)=>do`(subst$(←varStrx)<{$s:stlcTm}><{$t:stlcTm}>)defsubst(x:String)(s:Tm)(t:Tm):Tm:=matchtwith-- `.var y`, not `<{ ~y }>`: `y` is the variable's *name*, a `String`-- (see the note below the definition).|.vary=>ifx=ythenselset|<{λ~y:~T.~t₁}>=>ifx=ythentelse<{λ~y:~T.[~x:=~s]~t₁}>|<{~t₁~t₂}>=><{([~x:=~s]~t₁)([~x:=~s]~t₂)}>|<{true}>=><{true}>|<{false}>=><{false}>|<{if~t₁then~t₂else~t₃}>=><{if[~x:=~s]~t₁then[~x:=~s]~t₂else[~x:=~s]~t₃}>endmacro_rules(kind:=tmBracket)|`(<{[$x:=$s]$t}>)=>do`(subst$(←varStrx)<{$s:stlcTm}><{$t:stlcTm}>)Notation encoding: substitution
One more line registers substitutions with the printer, so that a goal
mentioning one reads as [x := s] t rather than as a subst application.
As we did for the evaluators in the Slang chapter, we pair the
definition with one simplification lemma per constructor, saying how subst
behaves on that constructor. The variable and abstraction cases
each need two lemmas, since substitution treats a bound name differently
depending on whether it is the name being substituted for.
Checks that the substitution notation parses and nests as intended.
Quiz
What is the result of the following substitution?
[x:=s](λy:T₁. x (λx:T₂. x))
(1) (λy:T₁. x (λx:T₂. x))
(2) (λy:T₁. s (λx:T₂. s))
(3) (λy:T₁. s (λx:T₂. x))
(4) none of the above
Technical note: Substitution becomes trickier to define if
we consider the case where s, the term being substituted for a
variable in some other term, may itself contain free variables.
We say that s is an open term.
Here is an example. Using the above definition to substitute the open term
s = λx:Bool. r
(where r is a free reference to some global resource) for
the free variable z in the term
t = λr:Bool. z
where r is a bound variable, we would get
λr:Bool. λx:Bool. r
where the free reference to r in s has been "captured" by
the binder at the beginning of t.
Why would this be bad? Because it violates the principle that the
names of bound variables do not matter. For example, if we rename
the bound variable in t, e.g., let
t' = λw:Bool. z
then [z:=s]t' is
λw:Bool. λx:Bool. r
which does not behave the same as the substituting in the original t:
[z:=s]t = λr:Bool. λx:Bool. r
That is, renaming a bound variable in t would change how t
behaves under our simple substitution. So substitution gets more
complicated in that setting, but fortunately we don't have that
problem in our STLC variant.
Fortunately, since we are only interested here in defining the
step relation on closed terms (i.e., terms like λx:Bool. x
that include binders for all of the variables they mention), we
can sidestep this extra complexity, but it must be dealt with when
formalizing richer languages.
Exercise★★★(substi_correct)
The definition that we gave above defines substitution as a
function. Suppose, instead, we wanted to define substitution as an
inductive relationSubsti.
We've begun the definition by providing the inductive header and
one of the constructors; your job is to fill in the rest of the
constructors and prove that the relation you've defined coincides
with the function given above.
The small-step reduction relation for STLC now follows the
same pattern as the ones we have seen before. Intuitively, to
reduce a function application, we first reduce its left-hand
side (the function) until it becomes an abstraction; then we
reduce its right-hand side (the argument) until it is also a
value; and finally we substitute the argument for the bound
variable in the body of the abstraction. This last rule, written
informally as
-------------------------------- (ifTrue)
(if true then t₁ else t₂) ⟶ t₁
--------------------------------- (ifFalse)
(if false then t₁ else t₂) ⟶ t₂
t₁ ⟶ t₁'
---------------------------------------------------- (ifStep)
(if t₁ then t₂ else t₃) ⟶ (if t₁' then t₂ else t₃)
This is call by value reduction: to reduce an
application (t₁ t₂), we
first reduce t₁ to a value: a function λx:T. t
then reduce the argument t₂ to a value v
then reduce the application itself by substituting v for
the bound variable x in the body t.
Formally:
sectionset_optionhygienefalseinlocalnotation:40t:41" ⟶ "t':41=>Steptt'inductiveStep:Tm→Tm→Propwhere|appAbs(x:String)(T:Ty)(tv:Tm)(hv:v.IsValue):<{(λ~x:~T.~t)~v}>⟶<{[~x:=~v]~t}>|app1(t₁t₁'t₂:Tm)(h:t₁⟶t₁'):<{~t₁~t₂}>⟶<{~t₁'~t₂}>|app2(v₁t₂t₂':Tm)(hv:v₁.IsValue)(h:t₂⟶t₂'):<{~v₁~t₂}>⟶<{~v₁~t₂'}>|ifTrue(t₁t₂:Tm):<{iftruethen~t₁else~t₂}>⟶t₁|ifFalse(t₁t₂:Tm):<{iffalsethen~t₁else~t₂}>⟶t₂|ifStep(t₁t₁'t₂t₃:Tm)(h:t₁⟶t₁'):<{if~t₁then~t₂else~t₃}>⟶<{if~t₁'then~t₂else~t₃}>endscopednotation:40t:41" ⟶ "t':41=>Steptt'scopednotation:40t:41" ⟶* "t':41=>MultiSteptt'-- for later use with `normalize`attribute[StlcEval]Step.appAbsStep.app1Step.app2Step.ifTrueStep.ifFalseStep.ifStep
As in the Smallstep chapter, ⟶* is the multi-step closure
of ⟶ — that is, Multi applied to this chapter's step relation. We
inherit its reflexivity lemma along with it, so a zero-step execution goal
t ⟶* t is closed by rfl.
Although we are primarily interested in the binary relation
⊢ t ⦂ T, relating a closed term t to its type T, we need
to generalize a bit to make the definitions work.
Consider checking that λx:T₁₁. t₁₂ has type
T₁₁ → T₁₂. Intuitively, we need to check that t₁₂ has type
T₁₂. However, we have removed the binder λx, so x may occur
free in t₁₂ (that is, t₁₂ may be open). While checking that
t₁₂ has type T₁₂, we must remember that x has type T₁₁, in
order to deal with these free occurrences of x. Similarly, t₁₂
itself could contain abstractions, and typechecking their bodies
could require looking up the declared types of yet more free
variables.
To keep track of all this, we add a third element to the relation,
a typing contextΓ, which records the types of the
variables that may occur free in a term — that is, Γ is a
partial map from variables to types.
The new typing judgment is written Γ ⊢ t ⦂ T and
informally read as "term t has type T, given the types of free
variables in t as specified by Γ".
We'll also write x ↦ T ; Γ for "update the partial map
Γ so that it maps x to T," following the notation from
the Typeclasses chapter.
With these refinements, we are ready to give informal and formal
specifications of the typing relation.
Note to developers (Chris Henson @chenson2018, before next release)
I find the FULL explanation above much better than the
TERSE one below, since the question below seems ill-posed without
extra context. Why would one want to type a term x y if we've
just said that we will just look at closed terms as our programs?
A context is a PartialMap from variable names to types — the partial
maps of the Typeclasses chapter, which are total maps whose values are
optional, so that none at a variable means "not bound here".
We can read the three-place relation Γ ⊢ t ⦂ T as:
"under the assumptions in Γ, the term t has the type T."
In the formal development, we write this judgment inside the same
<{ .. }> brackets we use for types and terms, as introduced by the
following notational conventions.
A context is written ∅ when empty and x ↦ T ; Γ when extended with a
binding, and ~e escapes to a Lean expression of type Context. The
whole judgment then goes inside the same <{ … }> brackets as terms, written
with the turnstile and colon of the Types chapter:
<{ Γ ⊢ t ⦂ T }>.
Notation encoding: contexts and judgments
Contexts get a grammar of their own, stlcCtx. The meaning is the map update
we already have — x ↦ T ; Γ expands to exactly the Typeclasses chapter's
partial-map update on Γ — but its surface syntax has to be our own, because
inside these brackets all three positions are in object syntax. Writing the map
notation directly would mean writing the binding as "x" →ₚ <{ Bool → Bool }> ; Γ:
the name quoted, and the type escaped back out of the brackets it belongs in.
The grammar hides those two encoding details, and nothing else.
declare_syntax_catstlcCtxsyntax:max"∅":stlcCtxsyntax:max"~"term:max:stlcCtxsyntax:maxstlcVar" ↦ "stlcTy" ; "stlcCtx:stlcCtxsyntax:max(name:=judgeBracket)"<{ "stlcCtx" ⊢ "stlcTm" ⦂ "stlcTy" }>":termopenLeanin/-- The `Context` denoted by a context expression. -/partialdefctxTerm(G:TSyntax`stlcCtx):MacroMTerm:=matchGwith|`(stlcCtx|∅)=>`((∅:Context))|`(stlcCtx|~$e)=>puree|`(stlcCtx|$x:stlcVar↦$T:stlcTy;$G:stlcCtx)=>do`(PartialMap.update$(←ctxTermG)$(←varStrx)<{$T:stlcTy}>)|_=>Macro.throwUnsupported
As with subst, the judgment notation is used inside the definition it names,
so it is introduced in two steps: the rule below is declared local with
hygiene off, so the HasType in its expansion resolves to the relation being
declared, and after the section closes it is declared again for real use.
sectionset_optionhygienefalseinlocalmacro_rules(kind:=judgeBracket)|`(<{$G:stlcCtx⊢$t:stlcTm⦂$T:stlcTy}>)=>do`(HasType$(←ctxTermG)<{$t:stlcTm}><{$T:stlcTy}>)inductiveHasType:Context→Tm→Ty→Propwhere|var(Γ:Context)(x:String)(T₁:Ty)(h:Γ[x]=someT₁):<{~Γ⊢~(Tm.varx)⦂~T₁}>|abs(Γ:Context)(x:String)(T₁T₂:Ty)(t₁:Tm)(h:<{~x↦~T₂;~Γ⊢~t₁⦂~T₁}>):<{~Γ⊢λ~x:~T₂.~t₁⦂~T₂→~T₁}>|app(Γ:Context)(T₁T₂:Ty)(t₁t₂:Tm)(h₁:<{~Γ⊢~t₁⦂~T₂→~T₁}>)(h₂:<{~Γ⊢~t₂⦂~T₂}>):<{~Γ⊢~t₁~t₂⦂~T₁}>|tru(Γ:Context):<{~Γ⊢true⦂Bool}>|fls(Γ:Context):<{~Γ⊢false⦂Bool}>|ite(Γ:Context)(t₁t₂t₃:Tm)(T₁:Ty)(h₁:<{~Γ⊢~t₁⦂Bool}>)(h₂:<{~Γ⊢~t₂⦂~T₁}>)(h₃:<{~Γ⊢~t₃⦂~T₁}>):<{~Γ⊢if~t₁then~t₂else~t₃⦂~T₁}>attribute[StlcTyping]HasType.varHasType.absHasType.appHasType.truHasType.flsHasType.iteNotation encoding: the judgment, for real
Closing the section retires the hygiene-free rule; the same rule is then
declared again, hygienically, for every later use.
endmacro_rules(kind:=judgeBracket)|`(<{$G:stlcCtx⊢$t:stlcTm⦂$T:stlcTy}>)=>do`(HasType$(←ctxTermG)<{$t:stlcTm}><{$T:stlcTy}>)Notation encoding: printing judgments back
As with terms, a judgment prints back in its own notation, so that a goal reads
as <{ x ↦ Bool ; ∅ ⊢ x ⦂ Bool }> rather than as a HasType applied to a chain
of map updates.
openLeanPrettyPrinterin/-- Rebuild `stlcCtx` syntax from the term syntax of a `Context`, so that a
context prints as `x ↦ Bool ; Γ` rather than as a chain of map updates. -/partialdefunexpandCtx:Term→UnexpandM(TSyntax`stlcCtx)|`(∅)=>`(stlcCtx|∅)|`($x:str→ₚ$T)=>dounexpandCtx(←`($x→ₚ$T;∅))|`($x:str→ₚ$T;$G)=>doletG'←unexpandCtxGletx':TSyntax`stlcVar←ifisPlainNamex.getStringthen`(stlcVar|$(mkIdent(Name.mkSimplex.getString)):ident)else`(stlcVar|~$x)matchTwith|`(<{$T':stlcTy}>)=>`(stlcCtx|$x':stlcVar↦$T';$G')|_=>`(stlcCtx|$x':stlcVar↦~($T);$G')|G=>`(stlcCtx|~($G))openLeanPrettyPrinterin@[app_unexpanderStlc.HasType]defHasType.unexpand:Unexpander|`($_$G<{$t:stlcTm}><{$T:stlcTy}>)=>do`(<{$(←unexpandCtxG)⊢$t⦂$T}>)|`($_$G<{$t:stlcTm}>$T)=>do`(<{$(←unexpandCtxG)⊢$t⦂~($T)}>)|`($_$G$t<{$T:stlcTy}>)=>do`(<{$(←unexpandCtxG)⊢~($t)⦂$T}>)|`($_$G$t$T)=>do`(<{$(←unexpandCtxG)⊢~($t)⦂~($T)}>)|_=>throw()
The derivation is small enough to write out directly: an abstraction rule
whose premise is the variable rule, and the variable rule's premise — that the
extended context maps x to Bool — holds by computation, hence rfl.
Much like reduction sequences, long derivations of typing rules can grow
quite tedious to prove. Luckily, we can have Lean automate proofs of this sort,
using another tactic: apply_rules. This tactic works much like
normalize, but is more efficient and will make progress even if it cannot
solve the goal outright. Like normalize, apply_rules also
takes a using argument which tells Lean which set of constructors to draw from.
It's worth noting that apply_rules relies on an important property
of our typing rules - namely, that they are syntax directed. A syntax directed
judgment is one where the syntax of a term completely determines which rule
can be applied at any given time; only one rule can be applied to each term.
This is important because apply_rules just applies the first rule in
its set of constructors or lemmas that it can - it doesn't backtrack if that rule
isn't correct. So, making sure that only one rule can apply to any given term
is important to ensure that apply_rules always discovers a valid
derivation, if one exists.
Exercise★★(typing_example_2_full) (Optional)
Prove the same result, applying one rule at a time and
naming the argument type of each application explicitly.
We can also show that some terms are not typable. For example,
we can check that there is no typing derivation assigning a type
to the term λx:Bool. λy:Bool. x y — i.e.,
¬ ∃ T, ∅ ⊢ λx:Bool. λy:Bool. x y ⦂ T
example:¬∃T,<{∅⊢λx:Bool.λy:Bool.xy⦂~T}>:=x✝:Stringy:Strings:Tmt:Tmt₁:Tmt₂:Tmt₃:TmT:Tyx:String⊢ ¬∃T,<{∅⊢λx:Bool.λy:Bool.xy⦂~(T)}>x✝:Stringy:Strings:Tmt:Tmt₁:Tmt₂:Tmt₃:TmT✝:Tyx:StringT:Tyhc:<{∅⊢λx:Bool.λy:Bool.xy⦂~(T)}>⊢ False-- Each `cases` peels off one rule of the derivation, naming the premise it-- leaves behind; the context stays small because the old hypothesis goes away.caseshcwithx✝:Stringy:Strings:Tmt:Tmt₁:Tmt₂:Tmt₃:TmT:Tyx:StringT₁✝:Tyh₁:<{x↦Bool;∅⊢λy:Bool.xy⦂~(T₁✝)}>⊢ Falsecasesh₁withx✝:Stringy:Strings:Tmt:Tmt₁:Tmt₂:Tmt₃:TmT:Tyx:StringT₁✝:Tyh₂:<{y↦Bool;x↦Bool;∅⊢xy⦂~(T₁✝)}>⊢ Falsecasesh₂withx✝:Stringy:Strings:Tmt:Tmt₁:Tmt₂:Tmt₃:TmT:Tyx:StringT₁✝:TyT₂✝:Tyh₂✝:<{y↦Bool;x↦Bool;∅⊢y⦂~(T₂✝)}>hf:<{y↦Bool;x↦Bool;∅⊢x⦂T₂✝→T₁✝}>⊢ Falsecaseshfwithx✝:Stringy:Strings:Tmt:Tmt₁:Tmt₂:Tmt₃:TmT:Tyx:StringT₁✝:TyT₂✝:Tyh₂✝:<{y↦Bool;x↦Bool;∅⊢y⦂~(T₂✝)}>hx:("y"→ₚ<{Bool}>;"x"→ₚ<{Bool}>)["x"]=some<{T₂✝→T₁✝}>⊢ False-- `x` is bound to `Bool` in the context, but the application rule-- needs it to have an arrow type.All goals completed! 🐙
Another nonexample:
¬ ∃ S T, ∅ ⊢ λx:S. x x ⦂ T
example:¬∃ST,<{∅⊢λx:~S.xx⦂~T}>:=x✝:Stringy:Strings:Tmt:Tmt₁:Tmt₂:Tmt₃:TmT:Tyx:String⊢ ¬∃ST,<{∅⊢λx:S.xx⦂~(T)}>solution!-- The two occurrences of `x` force its type `S` to satisfy `S = S → T`,-- and no (finite) type does.x✝:Stringy:Strings:Tmt:Tmt₁:Tmt₂:Tmt₃:TmT:Tyx:Stringarrow_ne:∀(T₁T₂:Ty),T₁≠<{T₁→T₂}>⊢ ¬∃ST,<{∅⊢λx:S.xx⦂~(T)}>intro⟨S,T,hc⟩x✝:Stringy:Strings:Tmt:Tmt₁:Tmt₂:Tmt₃:TmT✝:Tyx:Stringarrow_ne:∀(T₁T₂:Ty),T₁≠<{T₁→T₂}>S:TyT:Tyhc:<{∅⊢λx:S.xx⦂~(T)}>⊢ Falsecaseshcwith|abs_____h₁=>absx✝:Stringy:Strings:Tmt:Tmt₁:Tmt₂:Tmt₃:TmT:Tyx:Stringarrow_ne:∀(T₁T₂:Ty),T₁≠<{T₁→T₂}>S:TyT₁✝:Tyh₁:<{x↦~(S);∅⊢xx⦂~(T₁✝)}>⊢ Falsecasesh₁with|app_____hfha=>abs.appx✝:Stringy:Strings:Tmt:Tmt₁:Tmt₂:Tmt₃:TmT:Tyx:Stringarrow_ne:∀(T₁T₂:Ty),T₁≠<{T₁→T₂}>S:TyT₁✝:TyT₂✝:Tyha:<{x↦~(S);∅⊢x⦂~(T₂✝)}>hf:<{x↦~(S);∅⊢x⦂T₂✝→T₁✝}>⊢ Falsecaseshfwith|var___hx=>abs.app.varx✝:Stringy:Strings:Tmt:Tmt₁:Tmt₂:Tmt₃:TmT:Tyx:Stringarrow_ne:∀(T₁T₂:Ty),T₁≠<{T₁→T₂}>S:TyT₁✝:TyT₂✝:Tyha:<{x↦~(S);∅⊢x⦂~(T₂✝)}>hx:("x"→ₚS)["x"]=some<{T₂✝→T₁✝}>⊢ Falsecaseshawith|var___hy=>abs.app.var.varx✝:Stringy:Strings:Tmt:Tmt₁:Tmt₂:Tmt₃:TmT:Tyx:Stringarrow_ne:∀(T₁T₂:Ty),T₁≠<{T₁→T₂}>S:TyT₁✝:TyT₂✝:Tyhx:("x"→ₚS)["x"]=some<{T₂✝→T₁✝}>hy:("x"→ₚS)["x"]=someT₂✝⊢ Falseexactarrow_ne__((Option.some.injhy).symm.trans(Option.some.injhx))All goals completed! 🐙
Note to developers
The Rocq proof gets to the same contradiction through a chain of inversions
and then an induction on the offending type; the LATER note there asks why
eauto 30 makes no progress on the previous example, and a NOTATION note
from Ori reports an error with the associativity of the arrow in one of the
inversion hypotheses. Neither issue arises in this encoding.
Quiz
Which of the following propositions is not provable?
(A) y ↦ Bool ; ∅ ⊢ λx:Bool. x ⦂ Bool → Bool
(B) ∃ T, ∅ ⊢ λy:Bool → Bool. λx:Bool. y x ⦂ T
(C) ∃ T, ∅ ⊢ λy:Bool → Bool. λx:Bool. x y ⦂ T
(D) ∃ S, x ↦ S ; ∅ ⊢ λy:Bool → Bool. y x ⦂ (Bool → Bool) → S
Quiz
Which of these is not provable?
(A) ∃ T, ∅ ⊢ λy:Bool → Bool → Bool. λx:Bool. y x ⦂ T
(B) ∃ S T, x ↦ S ; ∅ ⊢ x x x ⦂ T
(C) ∃ S U T, x ↦ S ; y ↦ U ; ∅ ⊢ λz:Bool. x (y z) ⦂ T
(D) ∃ S T, x ↦ S ; ∅ ⊢ λy:Bool. x (x y) ⦂ T
endStlc
Source revision: 9cc9a7b, committed 2026-09-28 19:09 UTC