Lectures onType Theory
Chapter 36
Chapter 36Core route

Linear and Affine Type Systems

An unrestricted variable may be copied or ignored. That is wrong for an open file. Consider first the unrestricted interface read:FileFile×Bytes,close:FileUnit. Unrestricted typing then admits both λf.(readf,readf)andλf.. We write 1 for Unit and for its sole value below. The first program asks one handle to occupy two future states. The second forgets the obligation to close it. The arrows and products in this opening display are the unrestricted and ×: they exhibit the bug. Giving File a new atomic name changes neither derivation: contraction still copies the assumption and weakening still discards it.

The repair changes the judgment rather than the atom. Its right-hand context contains assumptions used exactly once: application and pairing split it, while both case branches receive the same residual resources because only one branch runs. A handle is owned and consumed; the calculus has no aliases, borrows, lifetimes, or provenance.

The split forced by one handle

Write Γ;Δe:A, read “under reusable assumptions Γ and exactly-once assumptions Δ, term e has type A.” The semicolon is a firewall, not concatenation. Assumptions in Γ are unrestricted. The finite map Δ is a linear context: each assumption in it must be used exactly once. Both contexts are finite maps, their domains are disjoint, and exchange is built into map equality.

The complete linear and affine term rules are collected in subappendix A.33; the derivations below make every context split explicit.

Definition 18.1 — Disjoint union of linear contexts

Write Δ1#Δ2 when their domains are disjoint, and Δ1Δ2 for their union under that condition: Δ1Δ2 is defined iff dom(Δ1)dom(Δ2)=. The same symbol denotes the empty finite map in either context position; “linear” describes the second slot’s role, not a different empty object.

The connective AB is linear implication, commonly read “A lollipop B.” The connective AB, read “A tensor B,” will pair two independently owned resources below.

The ordinary unsplit rule would be Γ;Δe1:ABΓ;Δe2:AΓ;Δe1e2:BTAppBad. With Δ=f:File, it types a function which closes f in one premise and reads f in the other; both premises claim the same unique assumption. The rule that partitions the inputs is instead Γ;Δ1e1:ABΓ;Δ2e2:AΔ1#Δ2Γ;Δ1Δ2e1e2:B. The same obstruction forces tensor introduction: two components cannot both receive the whole linear context.

The split is a partition of ownership, not a copy: e1 receives Δ1, e2 receives Δ2, and their domains are disjoint.

Lemma 18.2 — Split algebra

Whenever either side is defined, Δ=Δ,Δ1Δ2=Δ2Δ1,(Δ1Δ2)Δ3=Δ1(Δ2Δ3). If x:AΔ1Δ2, it belongs to exactly one summand. More precisely, if Δ1Δ2=Θ1Θ2, there are unique pairwise-disjoint contexts Ξij, for i,j{1,2}, such that Δi=Ξi1Ξi2,Θj=Ξ1jΞ2j.

Proof of Lemma 18.2 — Split algebra

Proof. These are finite-map calculations. Disjointness makes membership exclusive. The two bracketings have the same domain and assign the same type to each member. For the refinement clause, let Ξij be the restriction of Δi to dom(Δi)dom(Θj). The two given partitions make the four domains pairwise disjoint and their row and column unions give the displayed equations. Any other four contexts with those equations have the same domains and types, so the refinement is unique. ◻

Exercise 18.1

★☆☆ Suppose Δ1,Δ2,Θ1,Θ2 have pairwise-disjoint domains. Derive ((Δ1Δ2)Θ1)Θ2=Δ1(Θ1(Δ2Θ2)) and (Δ1Θ1)(Δ2Θ2)=(Θ2Δ2)(Θ1Δ1). List the disjointness fact that makes each displayed union defined.

Exercise 18.2

★☆☆ Consider the rejected unsplit rule Γ;Δe1:ABΓ;Δe2:AΓ;Δe1e2:B. For this diagnostic, use the linear primitive types of the file-token extension below: read:File(FileBytes) and close:File1. Set Δ=f:File, e1:=λu.let =u in readf,e2:=closef. Check the two premises separately and observe that the candidate conclusion types e1e2, which closes f and then tries to read it. Identify the duplicated assumption and explain why deleting a separate contraction rule does not repair this rule.

The complete linear calculus

Tensor and linear implication are multiplicative connectives: their rules divide resources between simultaneous premises. Sums are additive connectives: their alternatives share one residual context because only one branch executes. The exponential !A, read “bang A,” marks a value built without capturing a linear resource; eliminating it may therefore expose its payload in the reusable context. These distinctions motivate the grammar rather than merely naming its symbols.

Definition 18.3 — Types, terms, values, and contexts

The formal core λlin is the monomorphic, pure, call-by-value calculus defined by this grammar and the rules of definition 18.5. It has atomic types, multiplicative unit and tensor, linear implication, additive sums, and one exponential.

Let b range over atomic types. The syntax is A,B::=b1ABABAB!A,e::=xλx.ee1e2e1e2let xy=e1 in e2let =e1 in e2inleinrecase e of inlxe1inrye2!vlet !x=e1 in e2,v,w::=xλx.evwinlvinrv!v. Open variables count as values; a closed evaluation contains none. We use let x=e1 in e2 as the abbreviation (λx.e2)e1.

Definition 18.5 — Linear typing

The rules range over well-formed Γ;Δ with disjoint domains.

x:AΓ
Γ;x:A
T-UVar
Γ;x:Ax:A
T-LVar
Γ;:1
T-OneI
Γ;Δ1e1:1Γ;Δ2e2:C
Γ;Δ1Δ2let =e1 in e2:C
T-OneE
Γ;Δ,x:Ae:B
Γ;Δλx.e:AB
T-LolliI
Γ;Δ1e1:ABΓ;Δ2e2:A
Γ;Δ1Δ2e1e2:B
T-LolliE
Γ;Δ1e1:AΓ;Δ2e2:B
Γ;Δ1Δ2e1e2:AB
T-TensorI
Γ;Δ1e1:ABΓ;Δ2,x:A,y:Be2:C
Γ;Δ1Δ2let xy=e1 in e2:C
T-TensorE
Γ;Δe:A
Γ;Δinle:AB
T-PlusI1
Γ;Δe:B
Γ;Δinre:AB
T-PlusI2
Γ;Δ0e0:ABΓ;Δr,x:Ae1:CΓ;Δr,y:Be2:C
Γ;Δ0Δrcasee0ofinlxe1inrye2:C
T-Case

The same Δr appears in both alternatives because the two premises describe mutually exclusive futures of one run. The derivation contains both proof branches, but reduction selects exactly one of them; no execution ever owns two copies of Δr.

Γ;v:A
Γ;!v:!A
T-BangI
Γ;Δ1e1:!AΓ,x:A;Δ2e2:B
Γ;Δ1Δ2let !x=e1 in e2:B
T-BangE

Bang introduction is the firewall: no linear assumption can be sealed inside a duplicable value. Its premise is a value, not a computation. This call-by-value restriction also prevents an effect from happening while a bang is being constructed. Bang elimination reveals x in Γ.

Definition 18.4 — Root reduction

Evaluation is left to right. Its contexts are E::=[]EevEEevElet xy=E in elet =E in einlEinrEcase E of inlxe1inrye2let !x=E in e. There is no reduction beneath a lambda or inside an unselected branch. The root rules are

(λx.e)v0e[v/x]
E-LinBeta
let xy=vw in e0e[v/x,w/y]
E-Tensor
let = in e0e
E-One
case (inlv) of inlxe1inrye20e1[v/x]
E-InL
case (inrv) of inlxe1inrye20e2[v/y]
E-InR
let !x=!v in e0e[v/x]
E-Bang

The one-step relation is the compatible closure E[e]E[e] of e0e.

For example, swap=λp.let xy=p in yx:(AB)(BA). Tensor elimination extends the body context by x:A,y:B; tensor introduction assigns them to opposite singleton premises.

Example 18.6 — Local copying and discard

The exponential makes precisely marked data structural: copyA=λu.let !x=u in !x!x:!A(!A!A), discardA=λu.let !x=u in :!A1. After T-BangE, x:A belongs to Γ. Each occurrence uses T-UVar with empty linear context. The value u:!A itself is still eliminated exactly once.

Example 36.7 — A sum shares its residual resources

Let route:=λz.λr.case z of inlxxrinryyr. In either branch, tensor introduction splits the residual context into the singletons containing the payload and r:R. Write q for the case expression in the definition of route. Then: ;z:AAz:AA;x:A,r:Rxr:AR;y:A,r:Ryr:AR;z:AA,r:Rq:ARTCase. Two uses of T-LolliI therefore give ;route:(AA)(RAR). The common residual is copied between proof alternatives, but a reduction selects only one alternative.

Exercise 18.3

★☆☆ Draw the derivation of swap, including the singleton contexts at T-TensorI.

Exercise 18.4

★☆☆ Give two separate inversion arguments.

  1. Show that λx.xx does not have type A(AA), and name the impossible context split.

  2. Show that λx. does not have type A1, and name the unused linear assumption at the empty-context premise.

Exercise 18.5

★☆☆ Modify route so the left branch returns inr(xr) and the right branch returns inl(yr). Derive its result type and explain why r still belongs to the common residual context.

A handle that is read and closed

Fix an infinite set Tok of runtime tokens. Extend the core by atomic File and Bytes, primitive values open:1File,read:File(FileBytes),close:File1, and runtime values fileh and bytesh, where hTok. A token is live exactly while it belongs to a finite set HTok. The closed primitive typing axioms are

Γ;open:1File
T-Open
Γ;read:File(FileBytes)
T-Read
Γ;close:File1
T-Close
Γ;bytesh:Bytes
T-Bytes

The runtime file value has no closed source typing axiom. Its ownership is recorded by the configuration judgment below.

Definition 18.7 — File-token dynamics

Reduction acts on (H,e). Core steps leave H unchanged. The new roots, closed under the existing evaluation contexts, are

hTokH
(H,open)(H{h},fileh)
E-Open
hH
(H,readfileh)(H,filehbytesh)
E-Read
hH
(H,closefileh)(H{h},)
E-Close

Fresh allocation creates a token; close is its only destructor; read returns the same token with ordinary bytes. Since Tok is infinite and H is finite, TokH is nonempty, so E-Open always has a fresh choice.

The missing file-value axiom is load bearing. If one added XΓ;fileh:FileTFileBad, then T-TensorI could use that closed derivation twice and conclude Γ;filehfileh:FileFile. One runtime token would already have two owners. The configuration judgment below replaces this axiom by one linear placeholder for each live token.

The value premise of T-BangI is essential for the same extension. If promotion accepted a computation and evaluation included a context !E, then (,!(open))EOpen({h},!fileh). The result cannot be represented by a linear placeholder beneath the bang. The value restriction excludes this term, while !open remains legal and allocates a fresh token at each later call.

Define readClose=λu.let f=openu inlet fb=readf inlet =closef in b.

The live-set trace is , then {h} after open and read, then after close; the file placeholder is the unique syntactic owner while h is live.

Proposition 18.8 — The read-close derivation

;readClose:1Bytes. On input , evaluation allocates one token, threads it through read, closes it, and returns bytes.

Proof of Proposition 18.8 — The read-close derivation

Proof. The three load-bearing splits are visible in these judgments: ;open:1File;u:1u:1;(u:1)openu:File;read:File(FileBytes);f:Filef:File;(f:File)readf:FileBytes;f:Fileclosef:1;b:Bytesb:Bytes;(f:File)(b:Bytes)let =closef in b:Bytes. The first two conclusions use T-LolliE; the third uses T-LolliE for close and then T-OneE. Now T-TensorE combines the second conclusion with the third: its scrutinee owns exactly f:File, and its body owns exactly f:File,b:Bytes. Thus the body of the outer let has type Bytes under f:File. The let abbreviation is an application; its function premise abstracts f, and its argument premise is the first displayed conclusion. Their split is (u:1), so one final T-LolliI over u gives the claimed type.

For any hTok, the informative part of the trace is (,readClose)ELinBeta(,let f=open in)EOpen({h},let f=fileh in)ELinBeta({h},let fb=readfileh in)ERead({h},let fb=filehbytesh in)ETensor({h},let =closefileh in bytesh)EClose(,let = in bytesh)EOne(,bytesh). The rule names on the arrows identify every core segment and every file step. ◻

The terms λf.(readf)(readf), λf., and λf.let fb=readf in b fail respectively by duplicating f, dropping f, and dropping the returned f.

The comparison with a move-only API is limited: this calculus demands an explicit exactly-once path, whereas an affine language may drop an unused value and insert destructors. The theorem therefore concerns the displayed token machine.

Structural lemmas and exact use

Lemma 18.9 — Exchange and unrestricted weakening

Typing is invariant under permutations of either map. If Γ;Δe:A and xdom(Γ)dom(Δ), then Γ,x:B;Δe:A. There is no linear weakening lemma.

Proof of Lemma 18.9 — Exchange and unrestricted weakening

Proof. Permutation is finite-map equality. For weakening, induct on typing and add x:B to each unrestricted premise, renaming binders when necessary. A linear weakening would derive Γ;y:C,z:By:C, but no rule consumes z. Direct inspection of the last rule proves the impossibility; the exact-use induction below extends this last-rule contradiction by proving that every derivable term consumes each linear assumption exactly once. ◻

Lemma 18.10 — Unrestricted substitution

If Γ,x:A;Δe:B and Γ;v:A, then Γ;Δe[v/x]:B.

Proof of Lemma 18.10 — Unrestricted substitution

Proof. Induct on typing. At T-UVar, the selected variable is x, when the second premise concludes, or another variable, when the rule reapplies. For a split rule apply the hypotheses to all premises: the substituted value contributes no linear context. Both alternatives of T-Case receive the substitution and retain the same residual context. Bang introduction remains legal because the value has empty linear context. In the T-LolliI case, alpha-rename its binder y away from x and the free variables of v, apply the induction hypothesis to Γ,x:A;Δ,y:Ce:D, and reapply T-LolliI to the resulting premise Γ;Δ,y:Ce[v/x]:D. The other binders use the same freshness convention, after which the final rule reapplies. ◻

Lemma 18.11 — Linear substitution

If Γ;Δ1,x:Ae:B, Γ;Δ2v:A, and Δ1#Δ2, then Γ;Δ1Δ2e[v/x]:B.

Proof of Lemma 18.11 — Linear substitution

Proof. Induct on the first derivation. At T-LVar, the distinguished variable is x, Δ1=, and the second premise concludes. In a binary multiplicative rule, exclusive membership puts x in one premise. For example, if the last rule is T-LolliE, write its conclusion split as Σ1Σ2=Δ1,x:A. Exclusive membership gives exactly one of Σ1=Σ1,x:AorΣ2=Σ2,x:A. In the first case, the induction hypothesis changes the function premise to Γ;Σ1Δ2e1[v/x]:CB, while the argument premise retains context Σ2. Reapplying T-LolliE gives context (Σ1Δ2)Σ2=(Σ1Σ2)Δ2=Δ1Δ2. In the second case, the function premise retains Σ1, and the induction hypothesis changes the argument premise to Γ;Σ2Δ2e2[v/x]:C. The rebuilt context is Σ1(Σ2Δ2)=(Σ1Σ2)Δ2=Δ1Δ2. Tensor introduction uses this exclusive-membership calculation. So does each elimination rule whose displayed premises split the context.

For T-Case, if xΔ0, substitute only in the scrutinee. If xΔr, substitute in both branch premises. This duplicates syntax between alternatives, not along an execution; both branches retain the same enlarged residual context. Bang introduction cannot be final because its linear context is empty. Bang elimination is another split. Injections use their sole premise, and binders are renamed fresh. These cases exhaust the rules. ◻

Corollary 18.12 — Two-variable linear substitution

If Γ;Δ,x:A,y:Be:C, Γ;Δ1v:A, and Γ;Δ2w:B, with pairwise disjoint contexts, then Γ;ΔΔ1Δ2e[v/x,w/y]:C.

Proof of Corollary 18.12 — Two-variable linear substitution

Proof. Alpha-rename x,y away from each other’s substituent. Regard the first premise as Γ;(Δ,y:B),x:Ae:C. Because Δ1 is disjoint from both Δ and y, linear substitution gives Γ;ΔΔ1,y:Be[v/x]:C. The second substitution, using Δ2, gives Γ;ΔΔ1Δ2e[v/x][w/y]:C. The freshness choices and yFV(v) give e[v/x][w/y]=e[v/x,w/y]. Associativity from lemma 18.2 gives (ΔΔ1)Δ2=Δ(Δ1Δ2) for the displayed context. ◻

Definition 18.13 — Pathwise free use

For a variable z, define a partial natural usez(e). “Partial” means that the function is deliberately undefined when the two alternatives of a case use z a different number of times; the case clause below states that condition. Put usez(z)=1, usez(x)=0 for xz, and give every constant use zero. Write usezx(e)={0z=x,usez(e)zx, and define usezx,y by masking both binders. The remaining clauses are usez(λx.e)=usezx(e),usez(e1e2)=usez(e1)+usez(e2),usez(e1e2)=usez(e1)+usez(e2),usez(let =e1 in e2)=usez(e1)+usez(e2),usez(let xy=e1 in e2)=usez(e1)+usezx,y(e2),usez(inle)=usez(e),usez(inre)=usez(e),usez(!v)=usez(v),usez(let !x=e1 in e2)=usez(e1)+usezx(e2). For case e0 of inlxe1inrye2, first calculate k1=usezx(e1) and k2=usezy(e2). The use is defined exactly when both branch uses and the scrutinee use are defined and k1=k2; its value is usez(e0)+k1. Every displayed sum is defined only when its summands are.

Theorem 18.14 — Exact pathwise use

If Γ;Δe:A, then usez(e)=1 for every zdom(Δ). If zdom(Γ,Δ), then usez(e)=0. There is no bound for variables from Γ.

Proof of Theorem 18.14 — Exact pathwise use

Proof. Prove both clauses simultaneously by induction on typing, alpha-renaming each new binder away from the queried z. The two variable rules give one for the selected linear variable and zero for an absent variable. In every multiplicative split, exclusive membership puts a linear z in exactly one premise. Its induction hypothesis gives use count one there; because z is absent from every other premise context, their induction hypotheses give use count zero.

In T-Case, a variable from Δ0 contributes one in the scrutinee and zero in both branches. A variable from Δr contributes zero in the scrutinee and one in each branch. Thus the partial case clause is defined and has value one in either placement. If z is absent, all three uses are zero. Bang introduction has empty linear context; bang elimination is another split, with its bound variable masked in the body. The one-premise rules and introductions follow from their displayed structural clauses. This also proves that every use invoked in the theorem is defined. ◻

Exercise 18.7

★★☆ Write the application case of linear substitution in full, including the unique premise containing x and the final associativity equation.

Preservation, progress, and resource safety

Definition 18.19 — Well-owned file configuration

Write He:A, read “the live-token set H owns e at type A,” when pairwise distinct variables (xh)hH and a template e0 satisfy ;(xh:File)hHe0:A,e=e0[fileh/xh]hH. The same placeholder may occur in corresponding case alternatives; exact pathwise use still gives one demand on each execution path.

Lemma 18.15 — Canonical forms

For a closed value typed in the pure core: a value at 1 is ; at AB it is a lambda; at AB it is a tensor; at AB it is the corresponding injection; and at !A it is a bang.

For the file extension, if Hv:A, the same clauses hold except that a function value may also be the uniquely typed primitive open, read, or close. A value at File is fileh for a unique live hH.

Proof of Lemma 18.15 — Canonical forms

Proof. For the first claim, inspect the core value grammar and invert the final typing rule. There is no subsumption to obscure the outer constructor, and a closed variable is impossible. For the second, invert a witnessing template from definition 18.19. A value template at function type is a lambda or one of the three primitive constants. The only template value at File is a linear placeholder xh, and the closing substitution turns it into fileh; distinct placeholders and tokens give uniqueness. ◻

Lemma 18.16 — Evaluation-context replacement

Every derivation of Γ;ΔE[e]:A contains a uniquely designated hole subderivation Γ;Θe:B; within that derivation, Θ and B are determined by the path through E. Replacing that subderivation by Γ;Θe:B yields Γ;ΔE[e]:A.

Proof of Lemma 18.16 — Evaluation-context replacement

Proof. Proceed simultaneously by structural induction on E and inversion of the outer typing derivation. At the hole, the whole derivation is the designated subderivation. Each application and tensor frame selects one of the two premises of its unique syntax-directed outer rule; each tensor, unit, case, or bang-elimination frame selects its scrutinee premise; and an injection frame selects its sole premise. The induction hypothesis decomposes that premise and fixes Θ,B; the untouched premises and their original context split then reconstruct the outer derivation. A case context changes only its scrutinee, so the common branch context is unchanged. These constructors exhaust the evaluation-context grammar, and there is no context beneath a bang because T-BangI accepts only a value. Replacing the designated premise and reversing this induction proves recomposition. ◻

Theorem 18.17 — Preservation

If Γ;Δe:A and ee, then Γ;Δe:A.

Proof of Theorem 18.17 — Preservation

Proof. Contextual steps use lemma 18.16. For beta, invert implication elimination and introduction, then apply linear substitution and split associativity. For tensor, invert tensor elimination and introduction, then apply two-variable substitution. For unit, inversion says that contributes the empty context.

For a left sum root, injection inversion gives Γ;Δ0v:A, and the selected branch has Γ;Δr,x:Ae1:C; linear substitution restores Δ0Δr. For the right root, replace inl,v,x,e1,A by inr,v,y,e2,B; the same substitution argument restores the same split. For bang, introduction inversion gives an empty linear context; elimination puts x:A in Γ, so unrestricted substitution concludes. ◻

Theorem 18.18 — Progress and ordinary safety

If ;e:A, then e is a value or takes a step. Consequently no closed, well-typed core term reaches a stuck nonvalue.

Proof of Theorem 18.18 — Progress and ordinary safety

Proof. Induct on typing. A closed derivation cannot end in a variable rule. For application, step the function and argument in order; when both are values, the function is a lambda by canonical forms, so beta applies. For e1e2, step e1, then e2; two values form a tensor value. An injection steps its payload; an injected value is a value. Each elimination first steps its scrutinee. At a value scrutinee, canonical forms gives the matching tensor, injection, unit, or bang introduction, so the corresponding root rule applies. A bang introduction is already a value.

If a closed typed term reaches e, repeated preservation gives ;e:A. Progress therefore excludes a stuck nonvalue e. ◻

Lemma 36.21 — Fresh-token insertion

If HE[open]:A and hTokH, then H{h}E[fileh]:A.

Proof of Lemma 36.21 — Fresh-token insertion

Proof. Choose the witnessing template for the premise. Substitution of file tokens for variables changes no constructor in the evaluation-context spine, and the active term open contains no token. The template therefore factors as E0[open], with E0 closing to E.

The hole has type File under the empty linear context: both open and have empty linear context and application unions those two empty maps. Replace that subderivation by ;xh:Filexh:File. Induction outward through E0 adds the fresh singleton to the unique multiplicative premise containing the hole. For a case scrutinee it is added to Δ0, leaving the common branch context unchanged. An application or tensor frame places the hole in its left or right premise; tensor, unit, and bang elimination place it in the scrutinee premise; an injection places it in its payload premise; and a case frame places it in its scrutinee premise. Each frame therefore adds the singleton only to the premise containing the hole. No evaluation context descends under bang, so the induction has no T-BangI case. The rebuilt template has the old placeholders together with xh, and its closing substitution is E[fileh]. ◻

Lemma 36.22 — Active token factorization

Suppose HE[rh]:A, where rh is readfileh or closefileh. A witnessing template can be chosen with the same evaluation-context spine and active redex readxh or closexh, respectively. Replacing the former by xhbytesh preserves the template typing. Replacing the latter by removes xh:File and preserves the remaining template typing.

Proof of Lemma 36.22 — Active token factorization

Proof. Induct on the evaluation context. At the hole, use the unique placeholder whose closing image is fileh. Each context constructor corresponds to one typing premise and retains its original split. If the hole is the scrutinee of a case, exact use puts xh in the scrutinee context and the absent-variable clause of theorem 18.14 gives zero uses in both branches. Reduction never enters an unselected branch. The other split constructors are simpler: exclusive membership places xh only in the premise containing the hole.

For read, T-LolliE, T-Read, and T-LVar type the active redex. The replacement is typed by T-TensorI from the same linear placeholder and the closed T-Bytes value. For close, the active T-LolliE consumes the sole placeholder; replacing its unit result by T-OneI therefore removes that singleton from the witnessing context. Context replacement rebuilds the outer derivation. ◻

Theorem 18.20 — File-token preservation and cleanup

If He:A, then e is a value or the configuration takes a step. If moreover (H,e)(H,e), then He:A. Core reduction and read preserve the one owner of each live token, open adds one fresh owner, and close removes its selected owner. If a well-owned configuration of type 1 reaches (H,v), then H= and v=.

Proof of Theorem 18.20 — File-token preservation and cleanup

Proof. For progress, induct on the typing derivation of the template while following the corresponding closed term. The core cases repeat theorem 18.18. At a value-headed application, the extended canonical-forms clause gives either a lambda, when beta applies, or one of the three primitives. Its unique declared domain and the argument canonical-form clause force for open and a live fileh for read or close, so the corresponding configuration root applies.

At a core root, template substitution preserves every context split. For read and close, lemma 36.22 replaces the active placeholder while preserving the surrounding template. For open, lemma 36.21 gives directly H{h}E[fileh]:A from HE[open]:A and hH. Thus the reconstructed template has exactly one path to each live token. For every hH, the placeholder xh:File belongs to the template’s linear context, so theorem 18.14 gives usexh(e0)=1. Pairwise distinct placeholders and the closing substitution map only that xh to fileh. Read preserves the same occurrence, open adds the fresh occurrence proved above, and close removes precisely its selected occurrence.

At result type 1, canonical forms gives v=. If H were nonempty, exact use would force a file-placeholder occurrence in that unit value, a contradiction. ◻

The theorem does not assert termination or success of a host close operation. It states only that the abstract token cannot be duplicated, silently lost, or present after a returned unit.

Exercise 18.9

★★☆ Write the complete tensor-root preservation derivation, including two substitutions and the final context equation.

Proofs, cuts, and their computations

Under Curry–Howard, AB is implication using its assumption once, AB is simultaneous possession, AB is a choice, 1 is the empty multiplicative resource, and !A admits a proof to the unrestricted context. Their context rules are their meanings.

The cut Γ;Δ1v:AΓ;Δ2,x:Ae:BΓ;Δ1Δ2e[v/x]:B is linear substitution; unrestricted cut is unrestricted substitution. It is the resource-sensitive counterpart of the cut-as-substitution calculation in section 3.5: a proof of A is inserted at one marked use of A, while the split records exactly which resources travel with it.

Proposition 18.21 — Principal cut computations

When every introduced payload required by call by value is already a value, the principal implication, tensor, unit, sum, and exponential cuts are the six root reductions of definition 18.4. Each preserves its conclusion and removes an introduction immediately followed by elimination of its principal formula. With a nonvalue payload, evaluation contexts first perform administrative steps until this value-principal configuration is reached; no claim of unrestricted proof cut elimination is being made.

Proof of Proposition 18.21 — Principal cut computations

Proof. Implication substitutes an argument into a lambda body. Tensor substitutes both components; unit removes the empty proof; either sum introduction selects one branch; and bang uses unrestricted substitution because its introduction had empty linear context. These are precisely the root cases of theorem 18.17.

For example, tensor introduction immediately followed by tensor elimination has the typed principal contraction Γ;Δvv:AΓ;Δww:BΓ;ΔvΔwvw:ABTTensorIΓ;Δn,x:A,y:Bn:CΓ;(ΔvΔw)Δnlet xy=vw in n:CTTensorE. The term contracts to n[v/x,w/y]. The two-variable instance of linear substitution derives Γ;ΔvΔwΔnn[v/x,w/y]:C; the split displays which resources travel with each value. ◻

A commuting conversion moves an elimination past an independent case analysis; it changes proof schedule without changing which introduction that elimination is paired with. A representative conversion is let pq=(case s of inlxe1inrye2) in ncommutes tocase s of inlxlet pq=e1 in ninrylet pq=e2 in n, after alpha-renaming p,q,x,y pairwise distinct and requiring x,yFV(n). If s uses Δ0, both branch bodies use the same Δr, and n uses Δn,p:P,q:Q, both sides use Δ0ΔrΔn.

Proposition 18.22 — One commuting cut

If the left side is typable, so is the right side at the same type and under the same context.

Proof of Proposition 18.22 — One commuting cut

Proof. Invert tensor elimination and then T-Case. Its two branches have one common residual context. Combine that context with the context of n, apply tensor elimination separately in both alternatives, and rebuild the outer case. Split associativity identifies the conclusion contexts. ◻

This proves the computational reading of the displayed principal and commuting cuts, not proof-net normalization for full linear logic.

Four structural regimes

Definition 18.23 — Structural deltas

For ρ{,a,r,u}, write Γ;Δρe:A. The subscript names the linear, affine, relevant, or unrestricted judgment, respectively. Each contains every rule of definition 18.5, with the judgment subscript changed uniformly. Their only differences are these structural rules:

  1. adds no structural rule;

  2. affine typing adds weakening Γ;Δae:Axdom(Γ,Δ)Γ;Δ,x:Bae:AWAff;

  3. relevant typing adds contraction but no weakening Γ;Δ,x:A,y:Are:Bzdom(Γ,Δ)Γ;Δ,z:Are[z/x,z/y]:BCRel;

  4. unrestricted typing adds both W-Aff and C-Rel, with every judgment subscript changed to u.

Equivalently: ρadded structural rulesuse disciplinenoneexactly onceaWAffat most oncerCRelat least onceuWAff,CRelarbitrarily often

In C-Rel, read the rule from premise to conclusion: the premise checks two distinct assumptions x:A,y:A; the conclusion identifies both with one assumption z:A and simultaneously replaces their occurrences by z. It is contraction, not a rule that expands one resource while the term evaluates.

Thus linear means exactly once, affine at most once, relevant at least once, and unrestricted any number. The identity belongs to all four; λx. needs weakening; λx.xx needs contraction. The affine derivation is XΓ;a:1TOneIΓ;x:Aa:1WAffΓ;aλx.:A1TLolliI For relevant typing, contraction gives Γ;x1:Arx1:AΓ;x2:Arx2:AΓ;x1:A,x2:Arx1x2:AATTensorIΓ;x:Arxx:AACRelΓ;rλx.xx:A(AA)TLolliI. The unrestricted judgment admits both trees. The linear judgment admits neither conclusion.

Lemma 36.27 — Simultaneous substitution

Fix ρ{,a,r,u} and n0. Suppose Γ;Δ,x1:A1,,xn:Anρe:B and, for every 1in, Γ;Θiρvi:Ai. Assume that Δ,Θ1,,Θn have pairwise-disjoint domains; that the xi are distinct and absent from those contexts and from Γ; and that xiFV(vj) for all i,j. Then capture-avoiding simultaneous substitution gives Γ;ΔΘ1Θnρe[v1/x1,,vn/xn]:B.

Proof of Lemma 36.27 — Simultaneous substitution

Proof. Induct on the first derivation, with the statement strengthened over every finite n. Alpha-rename each rule binder away from the xi and the free variables of the vi. At T-LVar, either the selected variable belongs to Δ, when the rule reapplies, or it is the sole xi, when the corresponding substituent derivation is the conclusion. The unrestricted variable and constant cases are one line each: T-UVar reapplies under the substituted unrestricted context, while a constant has no variable premise to transform.

For a multiplicative rule, exclusive membership partitions the xi between its premises. Apply the induction hypothesis to each part and use the pairwise disjointness of the Θi to rebuild the conclusion. The common-refinement clause of lemma 18.2 gives a partition of the reassociated split with each xi in the same premise. For T-Case, send variables from the scrutinee context only to the scrutinee; send variables from the residual context, with the same substituents, to both alternatives. Only one alternative contributes to the conclusion context, so each Θi still occurs once. The one-premise rules follow directly. T-BangI can be final only when n=0, because its linear context is empty.

It remains to treat the added structural rules. Suppose W-Aff adds z:C. If z belongs to Δ, apply the induction hypothesis to the premise and restore the weakening. If z=xk, omit xk and vk from the induction hypothesis; the term does not contain xk. Then apply W-Aff once for every declaration of Θk. This adds exactly the missing context and proves the affine case. The same calculation handles weakening in u.

Now suppose C-Rel contracts z1:C,z2:C to z:C. If zdom(Δ), apply the induction hypothesis to the premise and contract z1,z2 again. If z=xk, take two fresh renamings Θk1,Θk2 of Θk, and let vk1,vk2 be the corresponding renamings of vk. Apply the induction hypothesis to the strict premise with the substitution list x1v1,,xk1vk1,z1vk1,z2vk2,xk+1vk+1,,xnvn. Its contexts are pairwise disjoint by the fresh renamings. For every declaration q:Cq in Θk, apply C-Rel to the corresponding pair q1:Cq,q2:Cq. After all these contractions and renaming back to q, the duplicated context Θk1Θk2 has become Θk, and the term is e[vk1/z1,vk2/z2][q/q1,q/q2]qdom(Θk)=e[vk/z1,vk/z2]. This is precisely the substitution instance of the contraction conclusion. No weakening is used. The unrestricted case admits the same contraction calculation, and these cases exhaust the derivation. ◻

Lemma 36.28 — Substitution in every structural regime

Fix ρ{,a,r,u}.

  1. If Γ,x:A;Δρe:B and Γ;ρv:A, then Γ;Δρe[v/x]:B.

  2. If Γ;Δ,x:Aρe:B, Γ;Θρv:A, and Δ#Θ, then Γ;ΔΘρe[v/x]:B.

Proof of Lemma 36.28 — Substitution in every structural regime

Proof. Clause (b) is the n=1 instance of lemma 36.27. For (a), induct on the first derivation. At T-UVar, use the substituent when the selected variable is x, and reapply the rule otherwise. In every split, apply the induction hypothesis to all premises: the substituent contributes no linear context. Both alternatives of T-Case receive it and retain the same residual context. Substitution of a value for a variable in a value yields a value, so T-BangI’s value premise is preserved. If the last rule is weakening or contraction, its affected variable is linear and therefore different from the unrestricted x; apply the induction hypothesis to its premise and restore that rule. In the contraction case the two substitutions commute: the substituent has empty linear context, so it contains neither contracted variable. Variable, abstraction, application, tensor, sum, bang, weakening, and contraction rules exhaust the derivation. ◻

Lemma 36.29 — Reduction reflects variable identification

Let σ be a capture-avoiding simultaneous map from free variables to variables. If eσe, then there is d such that ed and e=dσ.

Proof of Lemma 36.29 — Reduction reflects variable identification

Proof. A variable-to-variable map preserves the outer constructor. By the constructor-directed value grammar, it maps a variable to a variable, a lambda to a lambda, unit to unit, a tensor of values to a tensor of values, an injection of a value to the same injection, and a bang value to a bang value. Conversely, the outer constructor of an application or elimination is unchanged, and a tensor or injection whose payload was a nonvalue retains that nonvalue recursively. Structural induction therefore gives that e is a value exactly when eσ is a value. Now induct on the evaluation context of the given step. At the root, inspect the six reductions. For example, ((λx.n)v)σ contracts to (n[v/x])σ=(nσ)[vσ/x], after alpha-renaming x away from σ. Tensor and bang use the same substitution equation; unit and sums merely select a displayed subterm. The context case follows by the induction hypothesis and reconstruction of the unchanged context constructor. ◻

Theorem 36.30 — Safety after each structural delta

Fix one of the four subscripts ρ{,a,r,u}. Then:

  1. if Γ;Δρe:A and ee, then Γ;Δρe:A;

  2. if ;ρe:A, then e is a value or takes a step.

Hence a closed well-typed term in any of the four pure regimes never reaches a stuck nonvalue.

Proof of Theorem 36.30 — Safety after each structural delta

Proof. For preservation, induct on typing. A syntax-directed last rule is handled exactly as in theorem 18.17, using lemma 36.28 at beta, tensor, sum, and bang roots. If the last rule is affine weakening, apply the induction hypothesis to its premise and restore the same weakening. If it is relevant contraction, write its conclusion as d[z/x,z/y]. By lemma 36.29, the observed step is d[z/x,z/y]d[z/x,z/y] for a step dd. Apply the induction hypothesis to the contraction premise and reapply C-Rel. The unrestricted judgment has both cases.

For progress, neither weakening nor contraction can be the final rule of a derivation whose linear conclusion is empty: each adds a declaration to that conclusion. The final rule is therefore syntax directed. Its premises also have empty linear contexts wherever the existing progress induction needs a closed term. The canonical-form argument from theorem 18.18 applies unchanged because the structural deltas add no term or value. Iterate preservation to obtain the final safety claim. ◻

For comparison with the strict configuration judgment, write Hρe:A(xh)hH,e0.;(xh:File)hHρe0:Ae=e0[fileh/xh]hH. where the xh are pairwise distinct. Thus an affine placeholder may be unused, a relevant placeholder may be contracted to several occurrences, and an unrestricted placeholder may do either. This notation changes the static template discipline; it does not change the file machine, in which a single handle name still denotes a single live token.

Proposition 36.31 — The file boundary in the four regimes

The pure progress theorem theorem 36.30 holds in all four regimes. For the separate file machine, however, its consequences divide as follows.

  1. Linear typing has configuration progress, preservation, exactly one dynamic owner of every live token, and cleanup, as in theorem 18.20.

  2. Affine typing has configuration progress and preservation and maintains at most one displayed owner of a live token, but cleanup fails: a live token may have no owner.

  3. Relevant typing forbids static abandonment—in particular, Hrv:1 implies H=—but contraction can give one token several displayed owners. Configuration preservation, and hence the iterated progress guarantee, can fail after the first consuming operation.

  4. Unrestricted typing admits both the affine cleanup failure and the relevant preservation/progress failure.

Proof of Proposition 36.31 — The file boundary in the four regimes

Proof. The linear clause is the previous theorem. In the affine case the progress and preservation proofs repeat its template induction with weakening carried unchanged. Since affine typing has no contraction, no live token acquires more than one displayed placeholder occurrence. But affine typing derives λf.:File1. For fresh h, its closed use has the trace (,(λf.)(open))EOpen({h},(λf.)fileh)ELinBeta({h},), so evaluation returns unit while h is live.

For the relevant boundary, contract two premises of type File in badClose:=(λf.let =closef inclosef)(open). After allocation and beta, its two occurrences display the same token. Write ch:=closefileh; then ({h},let =ch in ch)EClose(,let = in ch)EOne(,ch). The last term is a nonvalue with no applicable file rule, because h. Equivalently, the first close destroys the premise of the relevant template judgment for the remaining occurrence. This is a preservation failure, not a cleanup trace: the computation never returns unit. Conversely, a well-owned relevant value at unit is by the value grammar and inversion of its closing substitution. A derivation of ;Δr:1 has Δ=: the T-OneI case is immediate, and a final C-Rel reduces the claim to its strictly smaller premise derivation, while no other rule concludes a typing for . Hence the placeholder context indexed by H is empty, so H=, without appealing to an unstated relevant-use theorem. Unrestricted typing derives both counterexamples. None is a counterexample to theorem 18.20, whose premise is strictly linear. ◻

The exponential is a local permission, not a global regime change: !A enters Γ only after introduction with empty linear context.

The number three

Zero, one, and arbitrary use do not express a fixed larger demand. Consider thrice=λf.λx.f(f(fx)). For f:AA, the term is rejected because its three occurrences cannot occupy disjoint singleton contexts. Unpacking an !(AA) yields the typable named wrapper: thrice!:=λg.let !f=g in λx.f(f(fx)),thrice!:!(AA)(AA). But that type says only “unrestricted”; it also types one, two, or a thousand calls. Affine and relevant typing say at most one and at least one. An exact three needs grades with addition for sibling uses and multiplication for nested uses. A quantitative judgment must therefore record a number, not only permission or prohibition.

Zero use is still information

Prerequisites.

This card uses only the dependent function displayed below and capture-avoiding substitution in its result family; both operations are specified locally. It is not a prerequisite for the chapter’s core calculus. The structural judgment established earlier is Γ;Δρe:A. To avoid a collision with it, we alpha-rename McBride’s source symbols R,Γ,Δ,ρ,π to Q,Θ,Ξ,q,p.

The number zero has a finer role once types may depend on terms. Removing a variable from a context makes it unavailable even to a type. Giving it zero run-time quantity can instead retain it for forming a type while forbidding its computational consumption.

Definition 36.32 — McBride's rig-indexed card

Fix a rig Q, with zero, addition, and multiplication but no additive negation. A resource context Ξ marks every variable of one precontext Θ by a quantity in Q; context addition is pointwise and therefore retains zero-marked variables. The checking and synthesis judgments are ΞqTt,ΞqeS. The quantity q asks for q copies of the subject. Types are formed at quantity zero. A dependent function (px:S)T has unit price p, and its application rule is

Ξ0qf(px:S)TΞ1qpSs
Ξ0+Ξ1qfsT[s:S/x]
R-App

This is the bidirectional dependent calculus of [McB16], not a rule extension of λlin.

Because Ξ0 and Ξ1 mark the same precontext, substitution in the result type remains meaningful even where an argument has quantity zero in one premise. In the none–one–tons rig {0,1,ω}, the three prices read (0x:S)Tstatic contemplation,(1x:S)Tlinear consumption,(ωx:S)Tunbounded use. The comparison needs no indexed family: if the result family T(x) mentions x, then (0x:S)T(x) may contemplate x without consuming it, whereas (1x:S)T(x) permits one run-time use. Type-level dependency does not itself request a second run-time copy.

Proposition 36.33 — Four different notions at zero

In the card of definition 36.32:

  1. absence means that the variable is not in the shared precontext;

  2. quantity zero retains the variable for contemplation in types but forbids run-time consumption;

  3. discardability is supplied only by a separate weakening order on quantities; and

  4. proof irrelevance would require an equality principle identifying proofs, which quantity zero does not supply.

Proof of Proposition 36.33 — Four different notions at zero

Proof. The first two clauses follow from the shapes of precontexts and marked contexts. A zero-marked entry survives pointwise splitting, but the variable rule cannot consume it at a nonzero result quantity. The rigid calculus has no weakening rule. McBride’s later ordered variant adds ΞqTtΞΞΞqTtRWeak, with extra factorization, splitting, and zero-reflection conditions; that is the separate source of discardability. Finally, the judgments contain no rule equating all inhabitants of a proposition. Erasing a zero-priced argument from a run-time program is computational irrelevance, not definitional proof irrelevance. ◻

At the exact source signature, preservation is Corollary 36, unique erasure existence is Lemma 40 for q0, and erased program steps are simulated by source computation in Theorem 44 of [McB16]. The erasure development assumes the zero-sum property q+p=0q=0=p, rendering McBride’s stated “absence of negation” hypothesis in the book’s notation, so zero cannot arise by cancellation. The ordered-rig variant is the separate development in §12 of the same source. These results motivate quantities in later calculi; without a translation, they are not theorems about graded coeffects or dependent quantitative type theory.

Exercise 36.8

★★☆ In the none–one–tons rig, classify each change to a context containing x:S: remove x; mark it by zero; add an ordered weakening that permits an unused unit-priced input; postulate that all inhabitants of a proof type are equal. For each change, name which clause of proposition 36.33 it realizes and whether zero-erasure alone justifies it.

Sources.

Wadler gives the connective order, term presentation, proof reductions, and the embedding of intuitionistic implication as !AB [Wad93]. The dual-context reconstruction and operational theorems above are local. In particular, the file-token extension strengthens general promotion to value promotion; that premise blocks allocation beneath a duplicable constructor.

Girard develops the proof-theoretic discipline [Gir87], while Benton gives the historical mixed linear/nonlinear comparison [Ben94]. No categorical structure is used in the local proofs. McBride supplies the source-bounded zero-use comparison and its preservation and erasure theorems [McB16]; no result is transferred from that dependent calculus to the chapter’s token machine.

Suggested first pass.

Begin with exercise 18.11, exercise 18.6, exercise 18.14; continue with exercise 36.15, exercise 18.15; then use the remaining problems to compare commuting conversions, branchwise resource use, and the four structural regimes.

None of these problems is a prerequisite for a later chapter.

Each problem below combines two mechanisms already proved. No new rule is needed; the point is to locate the exact boundary at which a tempting stronger claim fails.

Exercise 18.11

★★☆ Assume pairwise-disjoint Δv,Δw,Δe and derivations Γ;Δvv:P,Γ;Δww:Q,Γ;Δe,x:P,y:Qe:C. Type both let xy=vw in e and its reduct e[v/x,w/y] under Γ;ΔvΔwΔe. Display the two one-variable substitutions and the associativity equation that identifies their conclusion context with the redex context.

Exercise 18.12

★★★ Assume that Δt,Δs,Δr are pairwise disjoint and that Γ;Δtt:PQ,Γ;Δss:AB,Γ;Δr,p:P,q:Q,x:Ae1:C,Γ;Δr,p:P,q:Q,y:Be2:C. Take p,q,x,y pairwise distinct, with p,qFV(s) and x,yFV(t). Prove that both sides of let pq=t in(case s of inlxe1inrye2)commutes tocase s of inlxlet pq=t in e1inrylet pq=t in e2 have type C under Γ;ΔtΔsΔr. Display the common residual context at T-Case on each side.

Exercise 18.8

★★★ Let Δ0,Δr,Θ be pairwise disjoint and assume Γ;Θv:A. First take Γ;Δ0,x:As:PQ,Γ;Δr,p:Pe1:C,Γ;Δr,q:Qe2:C. Derive the substituted case under Γ;(Δ0Θ)Δr. Then instead take Γ;Δ0s:PQ,Γ;Δr,x:A,p:Pe1:C,Γ;Δr,x:A,q:Qe2:C. Substitute in both alternatives and derive the case under Γ;Δ0(ΔrΘ). Explain why unequal residual contexts for the two alternatives would make T-Case inapplicable.

Exercise 18.6

★★☆ Give inversion proofs that none of λf.(readf)(readf):File((FileBytes)(FileBytes)),λf.:File1,λf.let fb=readf in b:FileBytes has its displayed type. Name the impossible split or missing use in the first two terms. In the third, show that tensor elimination leaves f:File in the branch context after b is returned.

Exercise 18.10 — *

★★☆ Define q(z,f):=case z ofinlulet =u inlet =closef in inrvlet =v inlet =closef in . Derive ;z:11,f:Fileq(z,f):1. Although f is printed in both alternatives, calculate usef(q(z,f))=1. For hTok, trace both q(inl,fileh) and q(inr,fileh) from live set {h} to (,).

Exercise 18.14

★★☆ Let drop:=(λf.)(open). Using exactly one W-Aff, derive ;adrop:1. Then, for fresh hTok, calculate (,drop)({h},(λf.)fileh)({h},). Identify the cleanup conclusion of theorem 18.20 that fails to transfer to the affine regime. Explain why this is not a counterexample to the theorem, whose premise uses from the strictly linear system.

Exercise 36.15

★★☆ Derive the relevant typing of badClose from proposition 36.31, displaying the two distinct file assumptions immediately above C-Rel. Give its complete file-machine trace through the stuck final configuration. Then state, separately, which of configuration preservation, one-owner, and cleanup fail in the affine, relevant, and unrestricted regimes. Do not call the relevant trace a cleanup counterexample.

Exercise 18.13

★★☆ For an atomic A, classify λx.x:AA,λx.:A1,λx.xx:A(AA), and λx.(xx)x:A((AA)A) by the inclusion-minimal rule set among ,a,r,u that derives each judgment. Give the required number of weakenings and contractions. Prove by inversion that the discarded function is not relevant or linear and that each copying function is not affine or linear.

Exercise 18.15

★★☆ Derive the displayed exponential type of the named term thrice!. Identify its three T-UVar uses of the variable released by T-BangE, and explain why the derivation records no numeral three. Finally explain why the unwrapped thrice has no linear typing at (AA)(AA).

Exercise 36.18

★★★ Practical project.linear-token-checker Implement the finite linear checker and token evaluator in Kappa. The oracle must accept tensor swap, equal-residual case analysis, copying after bang elimination, and readClose with an empty final live set; it must reject duplicated and discarded linear variables, unequal branch residuals, a dropped post-read file, and effectful promotion. Mutate tensor so its second component receives the original context instead of the first component’s residual; the mutant must type-check and audit cleanly but fail at least the duplication case. Maintain two invariants explicitly: each linear variable is consumed exactly once on every accepted control-flow path, and each live runtime token has exactly one syntactic owner. Require the observable acceptance checks to report an empty final residual context for every accepted closed program and an empty final live-token set for the successful read-close run. The pathwise owner theorem remains the mathematical invariant proved in the chapter; the corpus does not emit a per-step ownership trace. Appendix E records the four acceptance commands and appendix F gives the implementation stages.

Search the book

Type to search the local edition.