Lectures onType Theory
Chapter 8
Chapter 8Optional

Type-Preserving Compilation of Polymorphic Records

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

Fix a decidable total order <lab on a countable set of labels. Its running segment is Age<labName<labOffice<labPhone. The selector name=λr.r.Name has one polymorphic record type. Applying it to the two records below needs different machine instructions. Write MrecC when source term M compiles to target term C. If records are vectors ordered by label, then {Name="Joe",Office=403}rec["Joe",403],{Age=21,Name="Hanako",Phone=7222}rec[21,"Hanako",7222]. The first selection needs index 1 and the second needs index 2. Erasing the record type before choosing that number loses information; keeping a run-time label search loses constant-time selection. The type abstraction must therefore also abstract over the index required for that field.

Required fields do not determine a layout

Labels also have decidable equality. The order’s decision procedure returns, for any two labels, exactly one of less than, equal, or greater. Thus sorting a finite label list is an algorithm, not merely an existence argument. Base types are written b, source monotypes are written τ, type variables are written t,u, and result types are written υ. The book-defined source calculus has τ::=btττ{1:τ1,,n:τn},σ::=τt::k.σ,k::=U{{1:τ1,,m:τm}}. Labels in either displayed finite field map are distinct. Their written order has no semantic force.

The calculus isolates index passing. A term is Church-style here when it writes every type abstraction Λt::k.M and every type application M[τ] explicitly. The calculus omits polymorphic let, record modification, variants, and operation annotations. It is therefore a pedagogical simplification inspired by the record-compilation mechanism, not a literal syntactic fragment of Ohori’s source language.

Definition 8.1 — Formation, kind assignment, and record kind

A kind assignment K is an ordered list of distinct bindings t::k. A binding kind is formed under the prefix to its left. Type formation is generated by

Kb type
Ty-Base
t::kK
Kt type
Ty-Var
Kτ typeKυ type
Kτυ type
Ty-Arr
Kτi type(1in)1,,n are distinct
K{i:τi}i=1n type
Ty-Rec

A record kind {{i:τi}}i=1m is formed when every τi is formed and its labels are distinct. The judgment Kτ::k is generated by

Kτ type
Kτ::U
K-Type
K(t)={{1:τ1,,m:τm,}}
Kt::{{1:τ1,,m:τm}}
K-VarRec
K{1:υ1,,n:υn}::U{1:τ1,,m:τm}{1:υ1,,n:υn}
K{1:υ1,,n:υn}::{{1:τ1,,m:τm}}
K-Rec

In K-Rec, the map to the left of is the complete record map, and the map to the right is the required-field map. The formation premise prevents an extra field from hiding an unbound type variable. Thus a record kind states required fields and their types; it does not state the size or order of the complete record.

For example, K={a::U,r::{{Name:a}}}givesKr::{{Name:a}}. Both concrete record types from the opening satisfy the ground instance with a=String.

Definition 8.2 — Kind-respecting substitution

A type substitution S maps each variable in K to a type formed under K. The pair (K,S) respects K if and only if, for every tdom(K), KS(t)::S(K(t)). The substitution acts on field types inside record kinds as well as on ordinary types.

Replacing a required-field map F by a submap FF is a weakening of the record kind: it removes requirements without changing the complete record type.

Lemma 8.3 — Formation and record-kind weakening

The kinding rules have the following two consequences.

  1. If Kτ::k, then Kτ type.

  2. If Kτ::{{F}} and FF, then Kτ::{{F}}.

Here F and F are finite label–type maps formed under K.

Proof of Lemma 8.3 — Formation and record-kind weakening

Proof. For clause 1, invert the final kinding rule. Rule K-Type contains the required formation premise. Rule K-VarRec has subject t, and Ty-Var forms t. Rule K-Rec contains Kτ::U; inversion of K-Type gives formation.

For clause 2, invert the record-kinding derivation. In K-VarRec, the map assigned to the variable contains F and therefore contains F, so a K-VarRec instance gives the result. In K-Rec, the complete record map contains F and FF; transitivity of finite-map inclusion supplies the premise of a K-Rec instance. ◻

Lemma 8.4 — Formation substitution

If Kτ type and (K,S) respects K, then KS(τ) type.

Proof of Lemma 8.4 — Formation substitution

Proof. Induct on the formation derivation. The base case is unchanged. The arrow and record cases apply the induction hypotheses to their premises; record labels remain distinct because substitution changes only field types. In the variable case, respect gives KS(t)::S(K(t)), and clause 1 of lemma 8.3 extracts the required formation judgment. ◻

Lemma 8.5 — Kinding substitution

If Kτ::k and (K,S) respects K, then KS(τ)::S(k).

Proof of Lemma 8.5 — Kinding substitution

Proof. Induct on the displayed kinding derivation. In K-Type, lemma 8.4 gives formation of S(τ), so a K-Type instance applies. In K-VarRec, respect gives KS(t)::S(K(t)). The required field map is a submap of S(K(t)), so clause 2 of lemma 8.3 gives the conclusion. In K-Rec, lemma 8.4 forms the substituted complete record. Substitution preserves labels and finite-map inclusion, so K-Rec applies. ◻

Exercise 8.1

★☆☆ Let K= and let K={a::U,r::{{Name:a}}} and let S send a to String and r to {Age:Nat,Name:String}. Check every premise of definition 8.2, then derive the substituted record-kind judgment.

The explicitly typed source

The kinding judgment proves that projection is legal, but it does not yet connect the proof to a term. The source system is fixed here so that every later compiler case has exactly one typing rule to follow.

Source terms are M::=xcbλx:τ.MMMΛt::k.MM[τ]{1=M1,,n=Mn}M.. Here cb is a constant whose base type is b. The record form is part of the raw syntax only when 1,,n are distinct. Thus a duplicate-label input is rejected before it becomes a source term. Terms are identified up to renaming of bound term and type variables. A type assignment T maps distinct term variables to source types formed under K.

Definition 8.6 — Source typing

The judgment K;TRM:σ is generated by the following complete rules:

T(x)=σ
K;TRx:σ
R-Var
K;TRcb:b
R-Const
K;T,x:τRM:υ
K;TRλx:τ.M:τυ
R-Lam
K;TRM:τυK;TRN:τ
K;TRMN:υ
R-App
K;TRMi:τi(1in)1,,n are distinct
K;TR{i=Mi}i=1n:{i:τi}i=1n
R-Record
K;TRM:τKτ::{{:υ}}
K;TRM.:υ
R-Dot
K,t::k;TRM:σtftv(T)
K;TRΛt::k.M:t::k.σ
R-TAbs
K;TRM:t::k.σKτ::k
K;TRM[τ]:σ[τ/t]
R-TApp

The polymorphic selector is now explicit: name:=Λa::U.Λr::{{Name:a}}.λx:r.x.Name. Its complete type is a::U.r::{{Name:a}}.ra. The premise of R-Dot is supplied by K-VarRec; the two uses of R-TAbs then close the derivation.

If type arguments are erased before layout selection, both calls to name become the same target function but demand different numeric indices. This is the obstruction that forces index passing.

A target with vectors and index abstraction

For a concrete record type τ, let layout(τ) be its labels sorted by <lab. If occurs in that list, then pos(τ) is its one-based position. The operation is undefined on an abstract type variable. This chapter’s target uses one-based positions; the array target in chapter 4 uses zero-based offsets. Thus the first component has position 1 here.

Definition 8.7 — Target types and kinds

For a concrete record monotype, a label is required when it occurs in the record. For a type variable, its binding in the target kind assignment states the required labels. For any such label required by a monotype ρ, the index type idx(,ρ) is a singleton type. When ρ is concrete, its sole inhabitant is the positive numeral pos(ρ). When ρ is abstract, an index variable bound at that singleton type supplies its inhabitant.

Target monotypes ρ, target types ω, and target kinds h are generated recursively by ρ::=btρρ{1:ρ1,,n:ρn},ω::=ρt::h.ωidx(,ρ)iω,h::=U{{1:ρ1,,m:ρm}}. Labels in target record monotypes and target record kinds are distinct. A target kind assignment H is an ordered list t::h. If a binding t::h has prefix H, then HVh kind. Target-kind formation is generated by

HVU kind
VK-U
HVρi type(1im)1,,m are distinct
HV{{i:ρi}}i=1m kind
VK-Rec

The judgment HVρ type forms base types, variables bound in H, arrows, and distinct-label records. The judgment HVρ::h assigns U to a formed monotype, assigns a variable every record kind licensed by its binding, and assigns a concrete record every required-field submap that it contains. These are exactly the rules Ty-BaseTy-Rec and K-TypeK-Rec from definition 8.1, under the replacements K,τ,kH,ρ,h and ⊢↦V. Target-type formation adds exactly the rules

HVρ type
HVρ target type
VT-Mono
HVh kindH,t::hVω target type
HVt::h.ω target type
VT-All
HVρ::{{:ρ}}HVω target type
HVidx(,ρ)iω target type
VT-IArrow

An index arrow belongs only to the target type syntax; it is not a source function type.

Index expressions are J::=iI, where i is a positive numeral and I is an index variable.

Definition 8.8 — Index assignments

A source index assignment L maps index variables I to required pairs (,τ). A pair is bookkeeping data for an index certificate, not a source type. A target index assignment I maps index variables to the target singleton types idx(,ρ).

For every pair (t,) fix an index variable It, such that It,=Iu, if and only if t=u and =. This is a globally injective allocator. If K(t)={{1:τ1,,m:τm}}, define LK,t={It,i(i,t)1im}. Write LK for the union of these assignments over the record-kinded variables of K. Global injectivity makes every such union a finite map and makes the extension for a fresh t disjoint from the ambient assignment.

Their source certification judgment is K;LRiJ certifies (,τ), with rules

L(I)=(,τ)
K;LRiI certifies (,τ)
IR-Var
Kτ::{{:υ}}i=pos(τ)
K;LRii certifies (,τ)
IR-Pos

The target judgment H;IViJ:idx(,ρ) is generated by the parallel rules

I(I)=idx(,ρ)
H;IViI:idx(,ρ)
IV-Var
HVρ::{{:ρ}}i=pos(ρ)
H;IVii:idx(,ρ)
IV-Pos

Definition 8.9 — Ground numeral substitution

Call S a ground substitution when every image S(t) is a closed monotype. Let S be ground and respect K. The numeral substitution νS has domain dom(LK) and is defined by νS(It,):=pos(S(t)). It acts on target terms, not on target types. The type substitution S and the numeral substitution νS are distinct operations.

Lemma 8.10 — Totality and typing of numeral substitution

If S is ground and respects K, then equation 8.4 is defined for every binding of LK. Moreover, if K;LKRiI certifies (,t), then ;ViνS(I):idx(,S(t)).

Proof of Lemma 8.10 — Totality and typing of numeral substitution

Proof. Every binding has the form It,:idx(,t) for a field required by K(t). Because S respects K, rule K-Rec or K-VarRec shows that S(t) contains the field. Decidable sorting gives its unique positive position. Rule IV-Pos derives the displayed judgment. ◻

The central layout bookkeeping can be read in three columns. A row begins with a source label, points to its slot in the canonical target vector, and ends with the numeral inhabiting the corresponding index type:

source record canonical slot certified numeral
{Office,Name}: Name 1"Joe" 1:idx(Name,τJ)
{Office,Name}: Office 2403 2:idx(Office,τJ)
{Phone,Name,Age}: Age 121 1:idx(Age,τH)
{Phone,Name,Age}: Name 2"Hanako" 2:idx(Name,τH)
{Phone,Name,Age}: Phone 37222 3:idx(Phone,τH)

Here τJ and τH are the two concrete opening record types. Every row asserts the invariant i=pos(τ); the table illustrates that invariant and does not replace its proof.

Target terms are generated by C::=xcbλx:ρ.CCCΛt::h.CC[ρ][C1,,Cn]CJλiI.CC@J. Angle brackets distinguish vector selection CJ from type application C[ρ].

Definition 8.11 — Target term typing

An index assignment I is well formed under H if and only if each binding I:idx(,ρ) has some ρ such that HVρ::{{:ρ}}. A term assignment U is well formed under H if and only if each binding x:ω satisfies HVω target type. The rules below take a target kind assignment H from definition 8.7, an index assignment I well formed under H, and a term assignment U well formed under H. The target judgment is H;I;UVC:ω. Its complete non-record rules are

U(x)=ω
H;I;UVx:ω
V-Var
H;I;UVcb:b
V-Const
H;I;U,x:ρ1VC:ρ2
H;I;UVλx:ρ1.C:ρ1ρ2
V-Lam
H;I;UVC:ρ1ρ2H;I;UVD:ρ1
H;I;UVCD:ρ2
V-App
H,t::h;I;UVC:ωtftv(I,U)
H;I;UVΛt::h.C:t::h.ω
V-TAbs
H;I;UVC:t::h.ωHVρ::h
H;I;UVC[ρ]:ω[ρ/t]
V-TApp

Its vector and index rules are

H;I;UVCi:ρi(1in)1<lab<labn
H;I;UV[C1,,Cn]:{1:ρ1,,n:ρn}
V-Vec
H;I;UVC:ρHVρ::{{:ρ}}H;IViJ:idx(,ρ)
H;I;UVCJ:ρ
V-Nth
H;I,I:idx(,ρ);UVC:ω
H;I;UVλiI.C:idx(,ρ)iω
V-IAbs
H;I;UVC:idx(,ρ)iωH;IViJ:idx(,ρ)
H;I;UVC@J:ω
V-IApp

The semantic theorem needs the exact compatible closure, not only the two target-specific roots. Source values and target values are v::=cbλx:τ.MΛt::k.M{i=vi}i=1n,A::=cbλx:ρ.CΛt::h.C[A1,,An]λiI.C. The source evaluation contexts ER and target evaluation contexts EV evaluate applications and aggregate components from left to right: ER::=[]ERMvERER[τ]ER.{j=vj}j<i,i=ER,{j=Mj}i<j,EV::=[]EVCAEVEV[ρ]EViEV@i[A1,,Ai1,EV,Ci+1,,Cn]. The comma-separated record-context line denotes the record whose fields before i are values, whose ith field is the hole, and whose later fields are unevaluated. The root contractions are (λx:τ.M)v0M[v/x],(Λt::k.M)[τ]0M[τ/t],{i=vi}i=1n.j0vj(1jn), and (λx:ρ.C)A0C[A/x],(Λt::h.C)[ρ]0C[ρ/t],[A1,,An]i0Ai(1in),(λiI.C)@i0C[i/I]. The relations R and V are the compatible closures under their respective contexts. Their reflexive–transitive closures are R and V. Write MRv when MRv, and write MR when there is an infinite R sequence from M; use the corresponding V notation for target terms.

Lemma 8.12 — Determinism and evaluation-prefix closure

Both one-step relations are deterministic. Let W be any relation on closed source and target values, and relate closed terms when both diverge or when they terminate at a pair in W. If MRM and CVC, then (M,C) belongs to this lifting of W if and only if (M,C) does.

Proof of Lemma 8.12 — Determinism and evaluation-prefix closure

Proof. Each nonvalue has at most one decomposition into a displayed evaluation context and a displayed root redex: application and aggregate contexts choose the leftmost nonvalue, while type application, projection, selection, and index application evaluate only their operator. The raw-syntax distinctness condition gives exactly one field with the projected label, and a numeric vector position names exactly one component. Every root therefore has one contractum, so both step relations are deterministic.

For prefix closure, a finite prefix cannot change whether a deterministic sequence is infinite. If evaluation terminates, deleting or adding a finite prefix preserves its unique terminal value. Hence the two terms diverge together before the prefixes exactly when they do afterward, and their terminal pair belongs to W before the prefixes exactly when it does afterward. ◻

Exercise 8.2

★☆☆ Using the fixed running label order, compute the two layouts from the chapter opening and the position of Name in each. Then type both selections with V-Nth and perform both vector root contractions from equation 8.6.

Type-directed index passing

The translation of a quantified type records the index arguments required by its kind. Before translating a record kind, enumerate its finite field map in increasing label order; hence the indices 1,,m below are canonical and do not depend on the source presentation order. Write k={{i:τi}}i=1m and k={{i:τi}}i=1m. Define b=b,t=t,(τ1τ2)=τ1τ2,({i:τi}i=1n)={π(j):τπ(j)}j=1n,π(1)<lab<labπ(n),(t::U.σ)=t::U.σ,(t::k.σ)=t::k.idx(1,t)iiidx(m,t)iσ. In the record-type line, the superscript star applies to the whole type on the left; labels are not translated. Translation acts pointwise on contexts: =,(K,t::k)=K,t::k,(T,x:σ)=T,x:σ,(L,I(,τ))=L,I:idx(,τ). Thus K is a target kind assignment, T is a target term assignment, and L is a target index assignment.

Lemma 8.13 — Canonical translation and index transport

For every source monotype τ, the type τ has the same finite record maps as τ and presents every map in canonical label order. The following judgments and equations hold.

  1. If Kτ type, then KVτ type.

  2. If Kτ::k, then KVτ::k.

  3. If K;LRiJ certifies (,τ), then K;LViJ:idx(,τ).

  4. (σ[τ/t])=σ[τ/t], (LK)=LK, and ftv(T)=ftv(T).

  5. If K is a well-formed source kind assignment, then K is a well-formed target kind assignment.

Proof of Lemma 8.13 — Canonical translation and index transport

Proof. Prove clauses 1 and 2 simultaneously by induction on source formation and kinding. Base and variable translations are identities. Arrow premises use the two formation induction hypotheses. In a record premise, decidable sorting changes neither labels nor their associated translated field types, so it preserves formation and finite-map inclusion. These are exactly the target instances of Ty-Rec, K-VarRec, and K-Rec.

For clause 3, invert the source index judgment. Rule IR-Var becomes IV-Var by the pointwise definition of L. Rule IR-Pos uses clause 2; translation preserves the label set and hence the sorted position, so IV-Pos applies with the same numeral.

The substitution equation follows by induction on σ. At a record type, substitution changes field types but not labels, so both sides use the same sorting permutation. The canonical-assignment equation follows from the pairwise definition of It,, and the free-variable equation follows by induction on every type in T. Finally, induction on the ordered bindings of K uses clause 1 on every field type of the translated kind and then applies VK-U or VK-Rec. ◻

Definition 8.14 — Compilation

Compilation is a derivation-directed judgment K;L;TMrecC:σ. This judgment is defined only when L=LK. Consequently, extending K by a fresh record-kinded variable t extends the compiler assignment by the disjoint map LK,t from equation 8.3. The pair-index allocator therefore makes lookup a function of (t,) rather than a search among assignments that happen to share one index type. Its homomorphic term rules are

T(x)=σ
K;L;Txrecx:σ
C-Var
K;L;Tcbreccb:b
C-Const
K;L;T,x:τMrecC:υ
K;L;T(λx:τ.M)rec(λx:τ.C):τυ
C-Lam
K;L;TM1recC1:τυK;L;TM2recC2:τ
K;L;TM1M2recC1C2:υ
C-App

A record is sorted by the unique permutation π satisfying π(1)<lab<labπ(n):

K;L;TMirecCi:τi(1in)π(1)<lab<labπ(n)
K;L;T{i=Mi}i=1nrec[Cπ(1),,Cπ(n)]:{π(j):τπ(j)}j=1n
C-Record
K;L;TMrecC:τKτ::{{:υ}}K;LRiJ certifies (,τ)
K;L;TM.recCJ:υ
C-Dot

For a concrete τ, the last premise chooses J=pos(τ); for τ=t, it chooses It, with LK(It,)=(,t) in the canonical map LK.

Let k={{i:τi}}i=1m be enumerated in canonical label order, let LK,t={It,i(i,t)}i=1m, and let Ji be the index expression certified for i at an actual type τ. The type-directed rules are

K,t::k;L,LK,t;TMrecC:σtftv(T)
K;L;T(Λt::k.M)rec(Λt::k.λiIt,1λiIt,m.C):t::k.σ
C-TAbsRec
K;L;TMrecC:t::k.σKτ::kK;LRiJi certifies (i,τ)(1im)
K;L;TM[τ]recC[τ]@J1@Jm:σ[τ/t]
C-TAppRec
K,t::U;L;TMrecC:σtftv(T)
K;L;T(Λt::U.M)rec(Λt::U.C):t::U.σ
C-TAbsU
K;L;TMrecC:t::U.σKτ::U
K;L;TM[τ]recC[τ]:σ[τ/t]
C-TAppU

By C-TAbsU, C-TAbsRec, C-Lam, and C-Dot, the selector of equation 8.2 compiles to Λa::U.Λr::{{Name:a}}.λiIr,Name.λx:r.xIr,Name. The two ground instantiations of equation 8.9 pass 1 and 2, respectively. After those index applications, every field access is the constant-time vector operation in V-Nth; no labels remain in the selection instruction.

Lemma 8.15 — Index availability

Suppose Kτ::{{:υ}}. Under LK, compilation determines an index expression J with K;LKRiJ certifies (,τ). If τ is concrete, J is its unique sorted position. If τ=t, J is the unique index variable allocated to the field of t.

Proof of Lemma 8.15 — Index availability

Proof. Invert the kinding derivation. If it ends in K-Rec, the finite-map inclusion places in the concrete record type. Sorting distinct labels gives one position, so the numeric index judgment holds. If it ends in K-VarRec, the kind assignment for t contains the field. Equation 8.3 places exactly one corresponding binding in LK. ◻

Theorem 8.16 — Total and deterministic compilation

Let K and T be well formed. If K;TRM:σ, then there is a target term C such that K;LK;TMrecC:σ. If D satisfies the same judgment, then C and D are equal up to renaming of bound term, type, and index variables.

Proof of Theorem 8.16 — Total and deterministic compilation

Proof. Induct on the displayed source typing derivation. Rules R-Var and R-Const determine C-Var and C-Const. The induction hypothesis for the body of R-Lam determines its target body; C-Lam then determines the target annotation. The two induction hypotheses for R-App determine both target subterms, so C-App determines their application.

For R-Record, apply the induction hypothesis to every field. Decidable comparison computes one sorting permutation of the distinct labels, so C-Record exists and no second target vector order is possible. For R-Dot, lemma 8.15 gives exactly one J; C-Dot therefore exists and is determined.

For R-TAbs at a record kind, the pair-index allocator gives the unique extension LK,t. It is disjoint from LK because t is fresh. The induction hypothesis determines the body, and C-TAbsRec inserts the index binders in canonical label order. Renaming those binders accounts for the stated alpha-equivalence. At kind U, C-TAbsU adds no index binder. For R-TApp, lemma 8.15 determines each required actual index; C-TAppRec or C-TAppU then determines the target. These are all source rules. ◻

Theorem 8.17 — Type preservation of record compilation

If K;TRM:σ and K;LK;TMrecC:σ, then K;(LK);TVC:σ.

Proof of Theorem 8.17 — Type preservation of record compilation

Proof. Induct simultaneously on the source typing derivation and the matching compilation derivation. At each premise, translate all three assignments by equation 8.8; this is necessary because record types in kind, index, and term assignments are canonically reordered.

Variable and constant. Translation of the type assignment gives the target variable rule, and base constants retain their base type.

Term abstraction. The induction hypothesis under T,x:τ1 gives C:τ2 under T,x:τ1. Target abstraction derives λx:τ1.C:τ1τ2.

Application. The two induction hypotheses give C1:τ1τ2 and C2:τ1. Target application gives C1C2:τ2.

Record. For every field, the induction hypothesis gives Ci:τi. The rule C-Record reorders the type entries by the same label permutation. Rule V-Vec therefore derives the canonically presented translated record type from equation 8.7.

Projection. The induction hypothesis gives C:τ. Clause 2 of lemma 8.13 translates the kinding premise to KVτ::{{:υ}}. The compilation premise certifies (,τ) for J in the source index judgment; clause 3 transports it to K;(LK)ViJ:idx(,τ). Rule V-Nth yields CJ:υ.

Type abstraction. First consider the record kind k={{i:τi}}i=1m. The induction hypothesis under K,t::k has target kind assignment K,t::k. The disjoint source extension translates as (LK,t)={It,i:idx(i,t)1im}. Thus the induction hypothesis uses the two disjoint target assignments (LK),(LK,t). Repeated V-IAbs removes this disjoint suffix and derives the index-arrow body of equation 8.7. Since t is fresh for K and the source premise has tftv(T), clause 4 of lemma 8.13 gives tftv((LK),T). Rule V-TAbs therefore derives the outer t::k. For k=U, freshness of t for K together with the source freshness premise for T gives the two target freshness conditions, so V-TAbs applies directly.

Type application. The induction hypothesis gives the translated universal type. Clause 2 of lemma 8.13 gives KVτ::k, so V-TApp derives the translated universal body. For every record-kind field, the matching compilation premise certifies (i,τ) for Ji in the source index judgment. Clause 3 transports it to Ji:idx(i,τ) in the target index judgment. Applying V-IApp m times gives σ[τ/t], equal to (σ[τ/t]) by structural induction on σ. No index applications occur for U.

These cases cover every source typing rule. ◻

Exercise 8.3

★★☆ Instantiate equation 8.9 at a=String and r={Age:Nat,Name:String,Phone:Nat}. Give the target typing derivation for the index application with J=2, then derive the type of its application to [21,"Hanako",7222].

The logical relation follows the representation

Type preservation says where compiled terms live. It does not yet say that vector position 2 denotes the source field named Name. Define a relation that follows the canonical layout.

Definition 8.18 — Closing logical relation

Let S map every free type variable under consideration to a closed monotype. An S-indexed relation environment χ maps each such variable t to a relation between closed source values of type S(t) and closed target values of type S(t). Define the value relation VrecS,χ(σ) and term relation ErecS,χ(σ) by structural induction on the open type σ.

The variable and base clauses are VrecS,χ(t)=χ(t),VrecS,χ(b)={(cb,cb)cb is a constant of base type b}. The arrow clause is (v,A)VrecS,χ(τυ)(a,B)VrecS,χ(τ). (va,AB)ErecS,χ(υ). For record values vr={i=vi}i=1n and Ar=[Aπ(1),,Aπ(n)], the record clause is (vr,Ar)VrecS,χ({i:τi}i=1n)π(1)<lab<labπ(n) and(vi,Ai)VrecS,χ(τi)(1in).

For the universal clause, let τ be a closed monotype satisfying τ::S(k). Put S=S[tτ] and χ=χ[tVrec,(τ)]. If S(k)={{i:S(τi)}}i=1m in canonical label order, let ji=posi(τ); when S(k)=U, the list of ji is empty. Then (v,A)VrecS,χ(t::k.σ)for every such τ,(v[τ],A[τ]@j1@jm)ErecS,χ(σ). The recursive call is on the syntactic body σ. The closing environment S makes every type in the binder kind closed; χ records the relation chosen for the bound type.

Finally, (M,C)ErecS,χ(σ) if and only if either MR and CV, or there are values v,A such that MRv,CVA,(v,A)VrecS,χ(σ). For a closed σ, write Rrecσ for Erec,(σ).

For the outer selector binder, choose S(a)=String. The inner binder kind is interpreted as S({{Name:a}})={{Name:String}}. Thus both opening record types are well-scoped choices for r; the type environment carries the ground type that a relation-only environment loses.

Let vJ,AJ and vH,AH be the two source-record/target-vector pairs in the opening calculation, and let τJ,τH be their record types. The record clause computes to (vJ,AJ)Vrec,(τJ),(vH,AH)Vrec,(τH). The pair with target [403,"Joe"] is not in the first relation: its first component would have to relate the source Name string to the target office numeral. This near-nonexample tests the canonical permutation clause.

Lemma 8.19 — Closing and compatibility

Let S be ground, and define χS(t)=Vrec,(S(t)). For every type σ formed under dom(S), ErecS,χS(σ)=RrecS(σ), and the analogous equality holds for the value relations. The term relation is closed under the following constructors:

  1. related functions applied to related arguments yield related terms;

  2. fieldwise related terms yield a related source record and canonically permuted target vector;

  3. projection of and target selection at pos(S(τ)) yield related terms; and

  4. a universally related pair instantiated at a kind-respecting closed τ remains related after the target receives the positions required by the instantiated kind.

Proof of Lemma 8.19 — Closing and compatibility

Proof. The two equalities follow by induction on σ. The variable case is the definition of χS. In the universal case, both sides quantify over τ::S(k) and extend by the same closed type and the same closed value relation.

For clause 1, split on the term relation for the function and then for the argument. Matched divergence makes both call-by-value applications diverge. Matched termination gives an arrow-related pair of function values and a value-related argument pair; the arrow clause gives the result, and lemma 8.12 adds the evaluation prefixes.

For clause 2, first suppose every related field pair terminates. The source record reaches its field values in written order, while the target vector reaches the related target values in canonical label order. The two orders may differ, but both evaluations are finite; after both finish, equation 8.11 relates the resulting aggregates. Otherwise, let p label the first divergent source field in presentation order, and let q label the first divergent target component in canonical order. Fieldwise relatedness makes the set of divergent labels the same on both sides. Every source field preceding the occurrence labelled p terminates, as does every target component preceding the occurrence labelled q. The two aggregates therefore take possibly different finite prefixes and then both diverge. This proves clause 2 without claiming that source and target visit fields in the same order.

For clause 3, matched divergence is preserved by the projection contexts. In the terminating case, equation 8.11 places the components at the source field and canonical target position; the two roots in equation 8.5, equation 8.6 return those components. Clause 4 is exactly equation 8.12, followed by evaluation-prefix closure. ◻

Lemma 8.20 — Closing substitution equality

Let tdom(S), let τ be formed under dom(S), put τ^=S(τ), and put S=S[tτ^]. For every σ formed under dom(S),t, S(σ)=S(σ[τ/t]).

Proof of Lemma 8.20 — Closing substitution equality

Proof. Induct on σ. The variable case distinguishes t from the variables in dom(S); the remaining constructors apply the induction hypotheses to their immediate type components. ◻

Theorem 8.21 — Fundamental compilation relation

Suppose K;TRM:σ and K;LK;TMrecC:σ. Let S be a ground substitution respecting K, and put χS(t)=Vrec,(S(t)). Suppose source and target value environments η and ζ satisfy (η(x),ζ(x))VrecS,χS(υ)for every x:υT. Then (M[S][η], C[S][νS][ζ])ErecS,χS(σ). By lemma 8.19, the relation in equation 8.13 equals RrecS(σ).

Proof of Theorem 8.21 — Fundamental compilation relation

Proof. Induct simultaneously on the source typing derivation and the matching compilation derivation, keeping S,η,ζ arbitrary. The decisive invariant is that S closes kinds while the separate νS closes index variables.

Variable and constant. The environment hypothesis is exactly the variable conclusion. A base constant compiles to itself, so the base clause applies.

Term abstraction. Take any (a,A)VrecS,χS(τ1). Extend η by xa and ζ by xA. The induction hypothesis for the body gives the term relation at τ2. The two term-beta roots and lemma 8.12 establish the arrow clause.

Application. The two induction hypotheses give the function and argument term relations. Clause 1 of lemma 8.19 gives the application relation.

Record. Each field induction hypothesis gives the corresponding term relation. Clause 2 of lemma 8.19 builds the labeled record and the target vector in the permutation computed by C-Record.

Projection. The induction hypothesis gives the record term relation. If compilation chose a concrete numeral, it is pos(S(τ)). If it chose It,, lemma 8.10 gives νS(It,)=pos(S(t)). Clause 3 of lemma 8.19 therefore gives the projection result.

Type abstraction. Take a closed type τ with τ::S(k), and put S=S[tτ]. Global injectivity gives the disjoint equation νS=νS,{It,iposi(τ)}i=1m. The induction hypothesis for the body under S gives the relation after the source type-beta root, target type-beta root, and the m index-beta roots. This proves equation 8.12; for k=U, m=0.

Type application. The induction hypothesis for the polymorphic term gives the universal term relation. Put τ^=S(τ) and S=S[tτ^]. Kinding substitution gives τ^::S(k). Clause 4 of lemma 8.19 applies the target to the positions inserted by C-TAppRec; lemma 8.10 identifies each closed Ji with that position. Its conclusion is indexed by S and χS=χS[tVrec,(τ^)]. The type-application case therefore reduces to the equality of term relations ErecS,χS(σ)=lemma8.19RrecS(σ)=lemma8.20RrecS(σ[τ/t])=lemma8.19ErecS,χS(σ[τ/t]).

The listed cases cover every source and compilation rule, so equation 8.13 follows. ◻

Corollary 8.22 — Semantic correctness at observable types

Let M be closed and well typed at a type σ generated by base types and finite records. If ;;MrecC:σ, then M and C terminate together. When they terminate, C contains the same base values as M, arranged in the canonical layout of each record type.

Proof of Corollary 8.22 — Semantic correctness at observable types

Proof. Apply theorem 8.21 with empty environments and the identity ground substitution. Induction on the observable type turns the clauses of Rrecσ into equality of base constants and the stated canonical record permutation. ◻

Exercise 8.4

★★☆ Prove the projection case of theorem 8.21 for the two records in the opening calculation, including both source contractions, both target contractions, and the two uses of the record-relation clause.

The theorem owned by the full Ohori calculus

The local calculus omitted let-generalization, record modification, and variants so that the index-passing proof could be followed without an inference algorithm. Ohori’s theorem applies to a larger, fixed signature.

Theorem 8.23 — Ohori's compilation theorem

Let Λlet,K,TM:σ be a typing in Ohori’s explicitly typed, kinded source calculus. This source includes functions, kinded polymorphism, records, record modification, variants, case, and the paper’s explicit polymorphic-let form. If the paper’s algorithm gives C(LK,T,M)=C, then for every ground substitution S respecting K and every pair of environments (η1,η2) related at S(T), (η1(erase(M)),η2,S(LK)(C))RS(σ). Here R is Ohori’s termination-sensitive logical relation, records are vectors, variants are numeric tags, and polymorphic record or variant operations receive explicit indices. This is Theorem 4.5.1 of the source at its stated source and implementation calculi [Oho95].

Proof of Theorem 8.23 — Ohori's compilation theorem

Imported proof. The proof in Ohori’s appendix is a logical-relations induction. Its projection mechanism matches the local relation. Its additional cases cover modification, tag selection, switches, polymorphic let, vacuous type-variable elimination, and interacting index assignments. The imported theorem owns those cases. They are not consequences of the book-defined record-only proof. ◻

Remark 8.24 — Implementation boundary

The theorem targets the idealized implementation calculus in Ohori’s paper. The reported SML implementation did not include polymorphic variants and did not evaluate inside index abstractions according to that calculus. The modern poly-record-ml program is useful for inspectable layouts and generated code, but running it proves neither theorem 8.17, theorem 8.23. The row theory of chapter 4 also has different kinds, equations, and principality hypotheses; no inference theorem transfers between the two systems.

The source and target calculi, type translation, and general correctness signature are due to Ohori [Oho95]. The final seminar sequence is adapted to the representation calculations in the Régis-Gianas–Rémy examination [RGR11]; the implementation comparison uses the pinned program of [Uta19] only as executable corroboration.

Suggested first pass.

None of these problems is a prerequisite for later chapters. Begin with exercise 8.5, reconstruct the decisive proof case in exercise 8.6, and then implement exercise 8.9.

Exercise 8.5

★★☆ Compile Λa::U.Λr::{{Age:Nat,Name:a}}.λx:r.{Name=x.Name,Age=x.Age}. Give its translated type, every inserted index abstraction, and its instantiation at {Name:String,Phone:Nat,Age:Nat}. Display the final two vector selections and their result layout.

Exercise 8.6

★★☆ Reconstruct the record-kinded type-abstraction and type-application cases of theorem 8.17. State the induction hypothesis, prove that LK,t is disjoint from LK, derive every V-IAbs and V-IApp premise, and finish with the substitution equation from lemma 8.13.

Exercise 8.7

★★☆ Consider a compiler that erases kinded type abstraction without inserting index abstraction. Compile the two calls to name from the opening as far as this compiler permits. Prove that no one numeral can make both target selections return the Name field. State why a dynamic label search repairs behavior but fails the chapter’s constant-index target specification.

Exercise 8.8

★★☆ Suppose a target vector is accompanied only by its length, not its source labels. Give two record types of equal length whose Name fields have different positions. State all field types and the two exact length witnesses. Prove that the vector and length do not determine the source projection. Identify the index-passing datum that restores the missing information.

Exercise 8.9

★★★ Practical project.polymorphic-record-compiler Implement the finite executable slice of C-Record, C-Dot, C-TAbsRec, and C-TAppRec from definition 8.14. Maintain the invariant that each layout contains every source label exactly once in <lab order and that every emitted numeric selection is the position certified by that layout. Print the source field map, sorted layout, chosen index, and translated selection. The acceptance test must compile the two opening records to layouts [Name,Office] and [Age,Name,Phone], emit indices 1 and 2 for Name, return "Joe" and "Hanako" after vector selection, and reject selection of a missing Phone field from the first layout. The rejection must occur before target execution. Also reject a source record containing the same label twice before constructing its layout. Finally, compile the polymorphic selector equation 8.2: display the inserted index abstraction, instantiate it at the two opening record types, and display the emitted @1 and @2 applications before replaying both selections. Then place a second record-kinded type abstraction inside the selector body and verify that a projection from the outer type still uses its outer index variable. Repeat with both binders requiring Name and verify that the emitted names Ir,Name and Is,Name are distinct. Finally, compile a record-kinded type application whose operator is a source variable, so the application case cannot inspect the operator for a syntactic type abstraction. Represent source and target terms by separate recursive ASTs. The target AST must contain binder-bearing index abstraction, index application, vector construction, and vector selection nodes. Pretty-print the structures computed by compilation rather than fixed trace literals, and keep compilation separate from evaluation so each success line is conditional on the emitted syntax and its result.

Search the book

Type to search the local edition.