Lectures onType Theory
Chapter 50
Chapter 50Optional

Capability and Region Types for Typed Memory Management

Prerequisites. Direct starred prerequisites: none. No later core chapter depends on this route.

Let a source computation bind one integer that it never returns: let x=1 in 2 end. Region inference may place the dead binding in a fresh local region while placing the returned integer in an outer region. Three static facts are distinct: the result must not mention the local region, the body may access it only while it is live, and explicit deallocation requires unique authority. Tofte–Talpin region inference proves the first two [TT97]; the Walker–Crary–Morrisett capability calculus proves the third [WCM00].

Tofte–Talpin region inference

Write ρ for a region variable, ϵ for an effect variable, and ϕ for a finite region effect: a set of effect variables and actions get(ρ) and put(ρ). A type with place is a pair μ=(τ,ρ); an arrow type carries the arrow effect ϵ.ϕ, the pair of a handle ϵ and a latent effect ϕ. The exact source and target cores are τ::=intαμ1ϵ.ϕμ2,μ::=(τ,ρ),e::=cxλx.ee1e2let x=e1 in e2 endletrec f(x)=e1 in e2 end,e::=c at ρxf[ρ1,,ρk] at ρλx.e at ρe1e2let x=e1 in e2 endletrec f[ρ](x) at ρ=e1in e2 endletregion ρ in e end. The full type grammar adds region- and effect-polymorphic schemes. A type environment TE assigns those schemes to source variables. Write frv(X) for the free region variables of the displayed object or tuple of objects X. The inference judgment TEee:μ,ϕ means that source term e translates to annotated term e, has type with place μ, and may perform the region actions in ϕ.

Rules 20, 21, 25, and 27 suffice for the opening calculation:

TEcc at ρ:(int,ρ),{put(ρ)}
RI-Const
TE(x)=(τ,ρ)
TExx:(τ,ρ),
RI-Var

TEe1e1:(τ1,ρ1),ϕ1TE,x:(τ1,ρ1)e2e2:μ,ϕ2TElet x=e1 in e2 endlet x=e1 in e2 end:μ,ϕ1ϕ2RILet Rule 27 is the scope boundary: TEee:μ,ϕρfrv(TE,μ)TEeletregion ρ in e end:μ,ϕ{get(ρ),put(ρ)}RILetregion There is no premise forbidding ρ in the body effect. The rule exists precisely to discharge those local effects. Freshness concerns the surrounding type environment and the result type-with-place.

Take an outer region ρ0 for the returned integer and a fresh local region ρ for the dead binding. The inferred target is letregion ρ in let x=1 at ρ in 2 at ρ0 end end, and its effect calculation is ϕbody={put(ρ),put(ρ0)},ϕwhole=ϕbody{get(ρ),put(ρ)}={put(ρ0)}. The result type with place is (int,ρ0), so ρfrv(μ); the empty initial TE discharges the other freshness premise.

Exercise 50.1

★☆☆ Reconstruct this derivation. Mark the premise discharged by freshness and the one body effect removed by RI-Letregion; explain why put(ρ0) remains.

Let P map types, type schemes, and environments to their Milner counterparts by erasing places, region variables, and effects. Fixing ρ0 and ϵ0, let R relate Milner objects to region objects by choosing ρ0 at every place and the arrow effect ϵ0.{get(ρ0),put(ρ0),ϵ0} at every arrow; its clauses for simple and compound schemes preserve their distinct quantifier shapes. These are the projection and relation of Tofte–Talpin Section 5.3.

Theorem 50.1 — Region inference refines Milner typing

The projection leaves the source term e unchanged.

  1. If TEee:μ,ϕ, then P(TE)Me:P(μ).

  2. Fix ρ0 and ϵ0. If TEMMe:τ and TEMRTE, then some e,μ,ϕ satisfy TEee:μ,ϕ,τRμ,frv(μ)={ρ0}, frv(e){ρ0},ϕ{get(ρ0),put(ρ0),ϵ0}.

Proof of Theorem 50.1 — Region inference refines Milner typing

Proof. Part 1 is Tofte–Talpin Lemma 5.1, by induction on the region derivation. Part 2 is Lemma 5.2. The displayed R is a relation rather than a function because simple and compound type schemes have different shapes. The variable case selects the appropriate scheme rule; the lambda case uses the effect-enlargement premise. Lemma 5.3 gives simultaneous type, region, and effect substitution. Neither direction claims principal effects or optimal placement. ◻

Semantic correspondence

The ordinary semantics evaluates Eev in source environment E. The region semantics evaluates s,VE,Rev,s, where R maps region variables to concrete region names and s is a region-indexed store. Tofte and Talpin’s coinductive relation C(R,TE,E,s,VE) w.r.t. ϕϕ relates configurations. A region environment R connects an effect ϕ to s when frv(ϕ)dom(R) and R(ρ)dom(s) for every ρfrv(ϕ); RϕR means agreement on frv(ϕ).

Theorem 50.2 — Tofte–Talpin semantic correspondence

Assume TEee:μ,ϕ,Eev,C(R,TE,E,s,VE) w.r.t. ϕϕ,R connects ϕϕ to s,RϕϕR,frv(e)dom(R). Then some s,v satisfy s,VE,Rev,sandC(R,μ,v,s,v) w.r.t. ϕ.

Proof of Theorem 50.2 — Tofte–Talpin semantic correspondence

Proof. This is Theorem 6.1 of Tofte and Talpin. Section 7 defines consistency; Section 8 proves its closure and store-extension properties. Section 9 uses an outer induction on the source-evaluation derivation and, in each case, an inner induction on the region-inference derivation. In the region case, Lemma 5.3 permits choosing ρfrv(ϕ) in addition to RI-Letregion’s freshness for TE and μ. Allocate a fresh concrete region, invoke the induction hypothesis, and remove it; the two freshness facts separately protect the result and continuation. This chapter imports that complete proof for the exact source and target cores displayed above. ◻

Effects approximate future region use, whereas tracing collection follows reachability; neither approximation contains the other. The later ML Kit work turns constraints into spreading and fixed-point computations. The historical and engineering account belongs to the region-memory retrospective [TBEH04], not to Theorem 6.1.

The capability machine

Walker, Crary, and Morrisett use region variables ρ, concrete region names ν, and regions r::=ρν. The runtime value handle(ν), a region handle, is distinct from the compile-time name ν. Selected syntax is C::=ε{rφ}C1C2C,φ::=1+,Δ::=Δ,ρ:RgnΔ,εC,v::=xiν.handle(r),h::=v0,,vn1fix f[Δ](C,x:τ).e,d::=x=vx=h at vx=πivnewrgn ρ,xfreergn v,e::=let d in eif0 v then e else ev(v)halt v. The capability variable ε ranges over unknown authority. The duplicable authority {r+} permits shared access; the unique authority {r1} permits destruction. The stripping operation C changes unique flags to duplicable ones, distributes over , and is idempotent. In particular, C=C,{r1}={r+},C1C2=C1C2,C=C. The judgment ΔC1=CapC2 is the congruence generated by these equations, associativity, commutativity, and the bounded variables in Δ. Write ΔC1CapC2 when some C3 satisfies ΔC1=CapC2C3. Stripped authority is idempotent; {r1}{r1} is not satisfiable. Subcapability admits {r1}{r+}, not the converse.

A memory M maps ν to finite region heaps. A memory type Ψ maps each ν to a region type Υ, which maps allocated labels to their heap-value types. The judgment M:Ψ checks the same region names and gives every allocated label the heap-value type recorded by Υ. The declaration judgment Ψ;Δ;Γ;CdΔ;Γ;C threads authority. The expression rules connecting it to programs are

Ψ;Δ;Γ;CdΔ;Γ;CΨ;Δ;Γ;Ce
Ψ;Δ;Γ;Clet d in e
Cap-LetDec
Ψ;Δ;Γv:intΔC=Cap
Ψ;Δ;Γ;Chalt v
Cap-Halt

Four declaration rules expose the resource boundary: ρdom(Δ)xdom(Γ)Ψ;Δ;Γ;Cnewrgn ρ,xΔ,ρ:Rgn;Γ,x:ρ handle;C{ρ1}CapNew Ψ;Δ;Γv:r handleΨ;Δ;Γh at r:τΔCCapC{r+}Ψ;Δ;Γ;Cx=h at vΔ;Γ,x:τ;CCapAlloc Ψ;Δ;Γv:τ0,,τn1 at rΔCCapC{r+}0i<nΨ;Δ;Γ;Cx=πivΔ;Γ,x:τi;CCapProject Ψ;Δ;Γv:r handleΔC=CapC{r1}Ψ;Δ;Γ;Cfreergn vΔ;Γ;CCapFree For example, Cap-New followed by Cap-Alloc derives allocation under {ρ1}, since unique authority is a subcapability of duplicable access authority. Cap-Free then consumes exactly the unique occurrence.

The machine dynamics has the same phase distinction: (M,let newrgn ρ,x in e)(M[ν],e[ν,handle(ν)/ρ,x]),(M,let x=h at handle(ν) in e)(M[ν.h],e[ν./x]),(M,let x=πi(ν.) in e)(M,e[vi/x]),(M,let freergn handle(ν) in e)(Mν,e), where νdom(M) in the first line; νdom(M) and is fresh in its heap in the second; and M(ν.)=v0,,vn1 with 0i<n in the third. The free rule likewise requires νdom(M).

Definition 50.3 — Satisfiability and closed program states

If Ψ={ν1:Υ1,,νn:Υn}, then ΨC holds exactly when the νi are distinct and C=Cap{ν1φ1}{νnφn}. A closed state is well typed by the program rule M:ΨΨCΨ;;;Ce(M,e)CapProgram The constructor and term contexts are empty; otherwise an open stuck term could pass for a program.

Lemma 50.4 — Capability–memory correspondence

If ΨC, then νdom(Ψ) exactly when C contains authority for ν. Equality and subcapability preserve this set, and removing a unique {ν1} preserves satisfiability for Ψν.

Proof of Lemma 50.4 — Capability–memory correspondence

Proof. Invert the single satisfiability rule. The normal form lists exactly the distinct names in Ψ. Capability-equality cardinality preservation keeps unique occurrences unique; stripping may change 1 to + but does not change the name set. Removing the unique singleton and the matching memory-type entry yields the final clause. These are the report’s CECP lemma and Lemmas 34–35. ◻

Theorem 50.5 — Capability preservation and progress

If (M,e), then:

  1. a step (M,e)(M,e) implies (M,e);

  2. either e=halt v with Ψ;;v:int, or the state steps.

Proof of Theorem 50.5 — Capability preservation and progress

Proof. These are technical-report Lemmas 36–37. Preservation uses substitution, memory-type extension, and memory garbage collection. In the free case, Cap-Free exposes a unique singleton and lemma 50.4 removes it together with its region. Progress inverts Cap-Program; canonical memory typing turns every typed address into an allocated label, while satisfiability turns every required region authority into a live concrete region. Thus allocation, projection, and free have matching dynamic rules. ◻

Proof of Corollary 50.6 — Capability-calculus memory safety

Proof. Induct on the reduction length with preservation and finish with progress. This is technical-report Theorem 39. ◻

Theorem 50.7 — Complete collection

A well-typed capability program either diverges or reduces to ({},halt v) for some word value v of type int.

Proof of Theorem 50.7 — Complete collection

Proof. A terminating run ends in a well-typed halt by preservation and progress. Invert Cap-Halt. By lemma 50.4, satisfiability under empty authority forces Ψ={}. Inversion of memory typing forces M={}. This is technical-report Theorem 40. ◻

A separate region calculus and its CPS translation

The source of the Walker–Crary–Morrisett translation is not the inference language above. It is a second, explicitly typed region calculus: ψ::=α{r}ψ1ψ2,eR::=e1,,en at ehπieletregion ρ,xρ in e. Its effects record region access without distinguishing get from put. Its delimiter binds both a compile-time region variable and the runtime handle. The projection and delimiter rules are Δ;ΓRe:τ0,,τn1 at r,ψ0i<nΔ;ΓRπie:τi,ψ{r}RProject and Δ,ρ:Rgn;Γ,xρ:ρ handleRe:τ,ψρftv(τ)dom(Δ)xρdom(Γ)Δ;ΓRletregion ρ,xρ in e:τ,ψ{ρ}RLetregion Again the body may mention ρ; the conclusion discharges it.

The running region-calculus term is epairFirst=letregion ρ,xρ in π0(1,2 at xρ). Allocation gives the pair type int,int at ρ; R-Project returns an integer while retaining effect {ρ}, and R-Letregion discharges that effect because the result type contains no free ρ.

The named effect-to-capability translation is total on that grammar: CapOf(α)=α,CapOf()=,CapOf({r})={r+}, CapOf(ψ1ψ2)=CapOf(ψ1)CapOf(ψ2). Every translated arrow effect is stripped, hence duplicable; equality of such capabilities is therefore set equality. Terms use the context- and continuation-indexed translation CPSΔ;Γ;Θ(e;k). The delimiter uses a WCM meta-level continuation, written k=xk;ek. Its application is the target term apply(k,v)=let xk=v in ek. The delimiter clause is CPSΔ;Γ;Θ(letregion ρ,xρ in e;k)=let newrgn ρ,xρ inCPSΔ,ρ:Rgn;Γ,xρ:ρhandle;Θ(e;x;let freergn xρ in apply(k,x)), where Θ extends both the current capability CΘ and its bound BΘ by {ρ1}. No object-level lambda is introduced.

Theorem 50.8 — Region-to-capability CPS type preservation

If the closed region-calculus term e has type int and empty effect, then its CPS translation applied to a fresh halting continuation is well typed under empty memory, constructor, term, and capability contexts.

Proof of Theorem 50.8 — Region-to-capability CPS type preservation

Proof. This is technical-report Theorem 52. Its strengthened induction carries a translation environment Θ, current capability CΘ, and bound BΘ satisfying BΘ=BΘCapOf(ψ). Lemmas 43–48 preserve well-formedness, substitution, equality, and effect inclusion. In the R-Letregion case both CΘ and the bound grow by {ρ1}, the translated body runs while ρ is live, and the continuation is typed by Cap-Free. Instantiating the strengthened result with empty contexts yields the theorem. ◻

For epairFirst, dynamics chooses a concrete ν. The authority calculation is CapNew{ν1}CapAlloc,CapProject{ν1}CapFreehandle(ν). After the last arrow, both M(ν) and authority for ν are absent.

Exercise 50.2

★☆☆ Starting from empty M,Ψ,C, write all three after Cap-New, Cap-Alloc, Cap-Project, and Cap-Free. Cite the premise that forbids projection after free.

Exercise 50.3

★☆☆ Change epairFirst to return the allocated pair. Show the free occurrence of ρ in its result type and identify the failed premise of R-Letregion.

Cyclone: handles, inference, and region order

Cyclone combines explicit handles, lexically scoped regions, effects, local inference, and region subtyping in a C-like language [GMJ^+02]. Let γrlongrshort mean that the region-order context γ proves the first region outlives the second. A pointer into the longer-lived region may be used where the shorter guarantee is expected: γrlongrshortΔ;γptr(τ,rlong)ptr(τ,rshort)CycRegionSub The reverse coercion is not derivable.

Cyclone’s right-expression judgment has the form Δ;Γ;γ;ϵrhse:τ. Here Δ binds type and region names, Γ binds values, γ records outlives constraints, and the live-region effect ϵ is a set of regions—not a set of get/put actions. For a live lexical region r, the two relevant judgments are Δ;Γ,hr:r handle;γ;{r}rhsalloc(hr,7):ptr(int,r),Δ;Γ,hr:r handle,p:ptr(int,r);γ;{r}rhsread(p):int,eval(region r in (alloc;read))=(7, region r deallocated). The first two lines expose the core context discipline; the last is a bounded execution schematic, not executable Cyclone code. The cited technical report proves type soundness [GMJ^+01]. The PLDI paper summarizes the design. Neither document proves correspondence for a particular compiler revision.

Three source-bounded system cards

Definition 50.9 — L^3 linear-location card

An L3 configuration is (σ,e). The linear type Capρτ owns the store fact that abstract location ρ contains a τ. The type Ptrρ is also linear; only !Ptrρ is duplicable. The three source rules are

Δ;Γe:τ
Δ;Γnew e:ρ.(Capρτ!Ptrρ)
L3-New
Δ;Γe:ρ.(Capρτ!Ptrρ)
Δ;Γfree e:ρ.τ
L3-Free

Δ;Γ1e1:Capρτ1Δ;Γ2e2:PtrρΔ;Γ3e3:τ3Δ;Γ1,Γ2,Γ3swap e1 e2 e3:Capρτ3τ1L3Swap Thus swap consumes its pointer and returns only the updated capability and the old content. Its root dynamics, together with allocation and deallocation, is (σ,new v)L3(σ[v],,cap,!ptr()),(σ[v],free,cap,!ptr())L3(σ,,v),(σ[v1],swap cap (ptr()) v2)L3(σ[v2],cap,v1).

Theorem 50.10 — Core L^3 soundness

If Δ;Γe:τ, then that judgment belongs to the source’s semantic interpretation. Hence a closed well-typed term terminates at a final configuration in the value interpretation of τ.

Proof of Theorem 50.10 — Core L^3 soundness

Proof. This is Theorem 3.1 and Corollary 3.1 of [AFM07]. Their logical relation interprets Capτ by a singleton owned store fragment and Ptr by an empty fragment; the fundamental induction therefore validates the three rules and frames every disjoint store fragment. ◻

For a cell initially containing 7, swapping in a pair transforms before: Capρint,after: Capρ(int×int). An unrestricted reference calculus must keep one fixed content type; it cannot validate this strong update without an additional exclusivity argument.

Definition 50.11 — Linear-region card

In λrgnUL, a configuration (ψ,e) pairs a region store with a term; ψ(ν) is the heap for concrete region ν. Suppressing the source’s explicit (U/L) wrappers, the two management interfaces have the shapes newrgn:1ρ.(capρhndρ),freergn:ρ.(capρhndρ)1. A linear region capability is threaded through new, read, and write; the handle is unrestricted, but it cannot justify destruction without the matching linear capability. The root allocation and deallocation steps have the shape (ψ,newrgn)lr(ψ[ν{}],packνcap,hnd(ν)), (ψ[νH],freergnνcap,hnd(ν))lr(ψ,).

Theorem 50.12 — Linear-region safety

If ;e1:τ and ({},e1)lr(ψ2,e2), then e2 is a value or the state steps.

Proof of Theorem 50.12 — Linear-region safety

Proof. This is Theorem 1 of [FMA06]. The paper reports a Twelf verification for a richer target. The displayed theorem is only target safety; its lexical-region, first-class-region, and unique-pointer encodings are sketches rather than separately stated preservation theorems. ◻

For the paper’s FRGN translation, a stack of regions becomes a nested linear tuple of capabilities. The letRgn clause allocates a fresh capability, pairs it onto that tuple, translates the body, then projects the same capability and feeds it to freergn. Consequently the one-step interface calculation is SFRGNScapρFRGNScapρFRGNS. The first and last arrows are the displayed allocation and deallocation steps; the middle arrow summarizes accesses that thread the capability. This is a representation calculation at the paper’s translation signature, not a separate theorem for the sketched Cyclone encodings.

Definition 50.13 — Monadic-region card

The monadic region interface has the rank-2 delimiter runRGN:α.(γ.RGNHandleγRGNγα)α. Store-tower typing records live stacks and regions; command evaluation threads the selected region store, and leaving runRGN removes the hidden region. If s,r are fresh, its root evaluation extends a tower T by an empty one-region stack, evaluates the command there, and then substitutes dead stack and region markers in the result: T;runRGN[τ]vv[/s][/r],after evaluation under T,s(,r{}).

Theorem 50.14 — Monadic-region soundness

Every closed well-typed FRGN expression either diverges or evaluates to a value of the same type. The SEC-to-FRGN translation preserves semantics and is correct for closed programs.

Proof of Theorem 50.14 — Monadic-region soundness

Proof. Preservation, progress, and soundness are Theorems 3.1–3.3; translation preservation and closed-program correctness are Theorems 5.1–5.2 of [FM06]. The source proofs carry tower-domain typing through fresh-stack extension and substitute the dead markers on exit. ◻

Parametricity prevents a result of runRGN from exposing γ. An existential package could hide a name but still permit the package to escape; the rank-2 interface instead scopes every client of the handle under the quantifier. A one-cell run allocates, reads, and removes its store before returning the integer: runRGN(Λγ.λh.new h 7=FRGNλr.read r)7.

Affe combines ML inference with affine kinds and scoped shared or exclusive borrows [RST20]. It is a useful modern comparison, but its borrow regions are not a theorem-preserving presentation of either the Tofte–Talpin or WCM calculus.

Sources.

Tofte–Talpin Sections 5.2–5.4 own inference, Milner refinement, and substitution; Sections 7–9 own Theorem 6.1 [TT97]. Walker–Crary–Morrisett Sections 2–3 and technical-report Appendices A–B own capability safety, complete collection, and CPS preservation [WCM00]. The four later designs retain their own signatures and theorem boundaries.

Suggested first pass.

Calculate exercise 50.4, exercise 50.5 before comparing the three system cards.

Exercise 50.4

★★☆ Reconstruct theorem 50.7 using Cap-Halt, lemma 50.4, and inversion of memory typing.

Exercise 50.5

★★☆ Translate the R-Letregion derivation for epairFirst. Display the freeing continuation and check the bound BΘ=BΘCapOf(ψ) before and after free.

Exercise 50.6

★★☆ For each card, write the store typing and authority across its displayed allocation/deallocation example. For L3, also change one cell from an integer to a pair with L3-Swap. State the exact theorem boundary for each card: which owns strong update, and which owns lifetime hiding?

Exercise 50.7

★★★ Practical project.region-capability-trace-auditor Implement absent, unique, shared, and freed states in Kappa. Maintain the invariant that access has live authority, free has unique authority, and halt has no live region. Accept the chapter’s allocate–access–free trace; reject access after free, shared free, double free, and live-region halt. Mutate free to accept shared authority: the mutant must check and audit cleanly but fail its named negative oracle. State explicitly that this finite machine does not prove theorem 50.5.

Search the book

Type to search the local edition.