Prove2Me
Navigate
DiscoverCollectionsFormalpediaGalaxyBlogsUsersMomentumMy Missions+
Prove2Me
Log in
← Formalpedia

Chapter 4 & Section 5.5: System F_ω^{cop, SCT} Syntax, Polarities, Sizes, Kinds, Types, Spines, Invocation Graphs, and F_ω^{cop} Erasure

Definition
NishtAbel2024_Syntax

by kmehltretter82 · Oct 31, 2026 · Mathlib 0df444a (Lean v4.33.1)

agdacopatternssize-change-terminationsized-typesstrong-normalizationtermination-checkingtype-theory

Formalizes Chapter 4 (pp. 19–30) and Section 5.5 (pp. 38–40) of Nisht & Abel (2024): the 4-element polarity lattice, size expressions with formal minima (a₁ ⊓ ⋯ ⊓ aₘ), size contexts Ψ and inequality judgments (SizeLt, SizeLe), polarized kinds and subkinding, higher-kinded System F_ω^{cop, SCT} types (μ^a S, ν^a R, ∀, ∃) and subtyping, patterns and copattern spines, bipartite invocation graphs and the Size-Change Termination criterion SCTValid, bidirectional term/clause/mutual-block/program typing, and System F_ω^{cop} lexicographic measure erasure.

Definition code
import Std

/-!
# Syntax of System F_ω^{cop, SCT} and System F_ω^c (Nisht & Abel 2024, Chapter 4 & Appendix A)

Source: Kanstantsin Nisht (supervised by Andreas Abel),
"Type-Based Termination Checking in Agda",
Master's thesis, Chalmers University of Technology and University of Gothenburg, 2024
(and K. Nisht & A. Abel, *TYPES 2024*, Copenhagen), Chapter 4 (pp. 19–30) and Appendix A (pp. I–V).

This module formalizes:
- **Section 4.1.1 (p. 20) — Polarities (`Polarity`)**:
  Variance lattice `◦ ≤ +, − ≤ ⊤` (`Polarity.le`), commutative composition `π π'` (`Polarity.comp`),
  inverse composition `π⁻¹ π'` (`Polarity.invComp`), and context polarity scaling `πΔ`, `π⁻¹Δ`.
- **Section 4.1.2 (pp. 20–22) — Sizes (`SizeVar`, `SizeMin`, `SizeExp`, `SizeCtx`)**:
  Bounded meet-semilattice of size expressions (`∞ + n` and finite meets `a^∧` of shifted size
  variables `i + n`), size increment `a + m` (`SizeExp.shift`), bound normalization `a^↑`
  (`SizeExp.boundNorm`), bounded variable lookup `Ψ ⊢ i < a` (`SizeVarBound`), well-formed size
  expressions `Ψ ⊢ a` (`SizeWf`), well-formed size contexts `⊢ Ψ` (`SizeCtxWf`), size substitutions
  `Ψ ⊢ a⃗ ⇐ Ψ'` (`SizeSubstWf`), strict and non-strict size inequality judgments `Ψ ⊢ a < b`
  (`SizeLt`) and `Ψ ⊢ a ≤ b` (`SizeLe`), and consistent size-context extension `Ψ ⊢ ∃Ψ'`
  (`SizeCtxConsistentExt`).
- **Section 4.1.3 (p. 22) — Kinds and Subkinding (`SKind`, `Kind`)**:
  Simple kinds `ι` and polarized kinds `κ ::= * | <a | πκ₁ → κ₂`, kind well-formedness `Ψ ⊢ κ`
  (`KindWf`), subkinding `Ψ ⊢ κ ≤ κ'` (`SubKind`), and polarized comparison `Ψ ⊢ O ≤^π O'`
  for sizes (`SizeLePol`) and kinds (`KindLePol`).
- **Section 4.2 (pp. 23–25) — Types, Bidirectional Kind Checking, and Subtyping**:
  Type atoms `K`, type expressions `F, A` (including sized inductive fixpoints `μ^a S` and
  coinductive fixpoints `ν^a R`), normalizing application `F @_κ G` (`normTypeApp`), bidirectional
  kind inference `Δ ⊢ F ⇒ κ` (`KindInfer`) and kind checking `Δ ⊢ F ⇐ κ` (`KindCheck`),
  context well-formedness `Δ ⊢ Δ'` (`KindingCtxWf`) and `Δ ⊢ Γ` (`TermCtxWf`), and bidirectional
  polarized subtyping `Δ ⊢ F ≤^π F' ⇒ κ` (`SubTypeInfer`), `Δ ⊢ F ≤^π F' ⇐ κ` (`SubTypeCheck`),
  and `Δ ⊢ A ≤ A'` (`SubType`).
- **Section 4.3 (p. 25) — Patterns and Copattern Spines (`Pat`, `Copat`, `PatSpine`)**:
  Pattern typing `Δ; Γ ⊢_{Δ₀} p ⇐ A` (`PatTyping`) and copattern spine typing
  `Δ; Γ | A ⊢_{Δ₀} q⃗ ⇒ C` (`SpineTyping`).
- **Section 4.4 (pp. 26–27) — Invocation Graphs and the Size-Change Termination Criterion**:
  Bipartite invocation graphs `G = (L_G, R_G, E_G : L_G × R_G ⇀ {<, ≤})` (`InvGraph`), tuple
  conformance `s⃗ ≺_G s⃗'` (`ConformsToGraph`), graph composition `G₁ ∘ G₂` (`InvGraph.comp`),
  invocation graph families `G(f, g)` (`InvGraphFamily`), transitive closure `G*(f, g)`
  (`InvGraphClosure`), and the Size-Change Termination criterion `⊢ G` (`SCTValid`).
- **Sections 4.5–4.6 (pp. 27–30) & Appendix A (pp. I–V) — Terms, Clauses, Mutual Blocks, and Programs**:
  Terms, eliminations, clauses `D = {q⃗ → t}`, declarations `f : ∀Ψ. A = D⃗`, mutual blocks `Ξ`,
  global signatures `Σ`, and programs `P = (Σ; u)` for both sized System `F_ω^{cop, SCT}` and
  unannotated System `F_ω^c` (plus measure erasure `|Ξ|` from System `F_ω^{cop}`, Section 5.5, p. 38).
-/

namespace NishtAbel2024

/-! ## Section 4.1.1: Polarities (p. 20) -/

/-- Variance / polarity annotations `π ∈ {◦, +, −, ⊤}` (Section 4.1, Table 1, p. 20):
- `mixed` (`◦`): mixed / invariant polarity (bottom of the information lattice)
- `pos` (`+`): covariant polarity
- `neg` (`−`): contravariant polarity
- `top` (`⊤`): constant / unused polarity (top of the information lattice). -/
inductive Polarity where
  | mixed : Polarity
  | pos : Polarity
  | neg : Polarity
  | top : Polarity
  deriving DecidableEq, Repr

namespace Polarity

/-- Lattice ordering `π ≤ π'` on polarities (Section 4.1.1, p. 20):
`◦ ≤ + ≤ ⊤` and `◦ ≤ − ≤ ⊤`, with `π ≤ π`. -/
def le : Polarity → Polarity → Bool
  | .mixed, _ => true
  | _, .top => true
  | .pos, .pos => true
  | .neg, .neg => true
  | _, _ => false

/-- Lattice join `max(π₁, π₂)` in the polarity lattice `{◦ ≤ +, − ≤ ⊤}`. -/
def join : Polarity → Polarity → Polarity
  | .mixed, π => π
  | π, .mixed => π
  | .top, _ => .top
  | _, .top => .top
  | .pos, .pos => .pos
  | .neg, .neg => .neg
  | .pos, .neg => .top
  | .neg, .pos => .top

/-- Lattice meet `min(π₁, π₂)` in the polarity lattice `{◦ ≤ +, − ≤ ⊤}`. -/
def meet : Polarity → Polarity → Polarity
  | .top, π => π
  | π, .top => π
  | .mixed, _ => .mixed
  | _, .mixed => .mixed
  | .pos, .pos => .pos
  | .neg, .neg => .neg
  | .pos, .neg => .mixed
  | .neg, .pos => .mixed

/-- Polarity negation `−π` (flips `+` and `−`, fixes `◦` and `⊤`). -/
def negPol : Polarity → Polarity
  | .mixed => .mixed
  | .pos => .neg
  | .neg => .pos
  | .top => .top

/-- Commutative composition `π π'` of polarities (Section 4.1.1, p. 20):
- `⊤ π = ⊤`
- `◦ π = ◦` for `π ≠ ⊤`
- `+ π = π`
- `− − = +`. -/
def comp : Polarity → Polarity → Polarity
  | .top, _ => .top
  | _, .top => .top
  | .mixed, _ => .mixed
  | _, .mixed => .mixed
  | .pos, π => π
  | π, .pos => π
  | .neg, .neg => .pos

/-- Inverse composition `π⁻¹ π'` of polarities (Section 4.1.1, p. 20):
- `⊤⁻¹ π' = ◦`
- `◦⁻¹ ◦ = ◦`
- `◦⁻¹ π' = ⊤` for `π' ≠ ◦`
- `+⁻¹ π' = π'`
- `−⁻¹ π' = −π'`. -/
def invComp : Polarity → Polarity → Polarity
  | .top, _ => .mixed
  | .mixed, .mixed => .mixed
  | .mixed, _ => .top
  | .pos, π' => π'
  | .neg, π' => comp .neg π'

end Polarity

/-! ## Section 4.1.2: Sizes (pp. 20–22) -/

/-- Size variable identifier `i, j ∈ SizeVar` (Table 1, p. 20). -/
abbrev SizeVar := Nat

/-- A shifted size variable `(i + n)` occurring in a minimum `a^∧` (Table 1, p. 20). -/
structure ShiftedSizeVar where
  var : SizeVar
  shift : Nat := 0
  deriving DecidableEq, Repr

/-- Non-empty formal minimum `a^∧ = (i₁ + n₁) ∧ ... ∧ (iₖ + nₖ)` of shifted size variables
(Table 1, p. 20). Represented by its head and tail so it is non-empty by construction. -/
structure SizeMin where
  head : ShiftedSizeVar
  tail : List ShiftedSizeVar := []
  deriving DecidableEq, Repr

namespace SizeMin

/-- All shifted variable summands `(i + n)` in `a^∧`. -/
def toList (m : SizeMin) : List ShiftedSizeVar :=
  m.head :: m.tail

/-- Single shifted size variable `i + n` as a `SizeMin`. -/
def single (i : SizeVar) (n : Nat := 0) : SizeMin :=
  ⟨⟨i, n⟩, []⟩

/-- Append two `SizeMin` expressions `a^∧ ∧ b^∧`. -/
def append (m₁ m₂ : SizeMin) : SizeMin :=
  ⟨m₁.head, m₁.tail ++ m₂.toList⟩

/-- Increment `(a^∧) + m` (Section 4.1.2, p. 21): adds `m` to every shifted variable in `a^∧`. -/
def shift (a : SizeMin) (m : Nat) : SizeMin :=
  ⟨⟨a.head.var, a.head.shift + m⟩, a.tail.map (fun s => ⟨s.var, s.shift + m⟩)⟩

/-- All size variables occurring in `a^∧`. -/
def vars (a : SizeMin) : List SizeVar :=
  (a.toList.map (·.var)).eraseDups

end SizeMin

/-- Size expressions `a, b ::= ∞ + n | a^∧` (Table 1, p. 20). -/
inductive SizeExp where
  | inf : Nat → SizeExp
  | meet : SizeMin → SizeExp
  deriving DecidableEq, Repr

namespace SizeExp

/-- Unshifted infinity `∞ := ∞ + 0` (p. 20). -/
def infty : SizeExp := .inf 0

/-- Single shifted size variable `i + n` as a `SizeExp`. -/
def var (i : SizeVar) (n : Nat := 0) : SizeExp :=
  .meet (SizeMin.single i n)

/-- Size increment `a + m` (Section 4.1.2, p. 21):
- `(∞ + n) + m = ∞ + (n + m)`
- `(a^∧) + m = (a^∧ + m)`. -/
def shift : SizeExp → Nat → SizeExp
  | .inf n, m => .inf (n + m)
  | .meet a, m => .meet (a.shift m)

/-- Bound normalization `a^↑` (Section 4.1.2, p. 22):
- `(∞ + n)^↑ = ∞ + 1`
- `(a^∧)^↑ = a^∧`. -/
def boundNorm : SizeExp → SizeExp
  | .inf _ => .inf 1
  | .meet a => .meet a

/-- Meet of two size expressions when both are variable meets; if either is `∞ + n`, returns the
other (supporting `∧_{i ∈ Ψ} i` in Algorithm 1, p. 58). -/
def meetExp : SizeExp → SizeExp → SizeExp
  | .meet a, .meet b => .meet (a.append b)
  | .meet a, .inf _ => .meet a
  | .inf _, .meet b => .meet b
  | .inf n, .inf m => .inf (Nat.min n m)

/-- All size variables occurring in a size expression `a`. -/
def vars : SizeExp → List SizeVar
  | .inf _ => []
  | .meet a => a.vars

/-- Substitute a single size variable `i ↦ s` inside a shifted variable `(j + n)`. -/
def substShiftedVar (i : SizeVar) (s : SizeExp) (sv : ShiftedSizeVar) : SizeExp :=
  if sv.var == i then s.shift sv.shift else .var sv.var sv.shift

/-- Substitute a mapping `σ : List (SizeVar × SizeExp)` simultaneously into a size expression `a`
(`a[a⃗ / Ψ̂]`, Section 4.1.2, p. 21). -/
def subst (σ : List (SizeVar × SizeExp)) : SizeExp → SizeExp
  | .inf n => .inf n
  | .meet m =>
      let evalOne (sv : ShiftedSizeVar) : SizeExp :=
        match σ.find? (fun p => p.1 == sv.var) with
        | some (_, s) => s.shift sv.shift
        | none => .var sv.var sv.shift
      (m.tail.map evalOne).foldl meetExp (evalOne m.head)

end SizeExp

/-- Entry `i : π(< a)` in a size context `Ψ` (Table 1, p. 20). -/
structure SizeDecl where
  var : SizeVar
  pol : Polarity := .pos
  bound : SizeExp := .infty
  deriving DecidableEq, Repr

/-- Size variable context `Ψ ::= · | Ψ, i : π(< a)` (Table 1, p. 20). -/
abbrev SizeCtx := List SizeDecl

namespace SizeCtx

/-- Domain `{i | (i : π(< a)) ∈ Ψ}` of a size context `Ψ`. -/
def dom (Ψ : SizeCtx) : List SizeVar :=
  Ψ.map (·.var)

/-- Scale polarities in `Ψ` by `π`: `π(Ψ, i : π'(< a)) = (πΨ), i : (ππ')(< a)` (p. 20). -/
def scalePol (π : Polarity) (Ψ : SizeCtx) : SizeCtx :=
  Ψ.map (fun d => { d with pol := Polarity.comp π d.pol })

/-- Inverse-scale polarities in `Ψ` by `π⁻¹`: `π⁻¹(Ψ, i : π'(< a)) = (π⁻¹Ψ), i : (π⁻¹π')(< a)` (p. 20). -/
def invScalePol (π : Polarity) (Ψ : SizeCtx) : SizeCtx :=
  Ψ.map (fun d => { d with pol := Polarity.invComp π d.pol })

end SizeCtx

/-- Bounded size variable judgment `Ψ ⊢ i < a` (Section 4.1.2, p. 21):
`(i : π(< a)) ∈ Ψ` with `π ≤ +`. -/
def SizeVarBound (Ψ : SizeCtx) (i : SizeVar) (a : SizeExp) : Prop :=
  ∃ π : Polarity, SizeDecl.mk i π a ∈ Ψ ∧ Polarity.le π .pos = true

/-- Well-formedness of a size expression `Ψ ⊢ a` (Section 4.1.2, p. 21):
- `Ψ ⊢ ∞ + n`
- `Ψ ⊢ a^∧` iff every `(i + n) ∈ a^∧` has some bound `b` with `Ψ ⊢ i < b`. -/
def SizeWf (Ψ : SizeCtx) : SizeExp → Prop
  | .inf _ => True
  | .meet a => ∀ sv ∈ a.toList, ∃ b : SizeExp, SizeVarBound Ψ sv.var b

/-- Well-formedness of a size context `⊢ Ψ` (Section 4.1.2, p. 21):
- `⊢ ·`
- if `⊢ Ψ`, `◦⁻¹Ψ ⊢ a`, and `i ∉ dom(Ψ)`, then `⊢ Ψ, i : π(< a)`. -/
inductive SizeCtxWf : SizeCtx → Prop where
  | nil : SizeCtxWf []
  | snoc {Ψ : SizeCtx} {i : SizeVar} {π : Polarity} {a : SizeExp} :
      SizeCtxWf Ψ →
      i ∉ Ψ.dom →
      SizeWf (Ψ.invScalePol .mixed) a →
      SizeCtxWf (Ψ ++ [⟨i, π, a⟩])

/-- Strict size comparison `Ψ ⊢ a < b` (Section 4.1.2, pp. 21–22), together with non-strict
comparison `Ψ ⊢ a ≤ b` defined by `Ψ ⊢ a < b + 1` (p. 22). -/
inductive SizeLt (Ψ : SizeCtx) : SizeExp → SizeExp → Prop where
  /-- `n < m ⟹ Ψ ⊢ ∞ + n < ∞ + m` (p. 21). -/
  | inf_lt_inf {n m : Nat} :
      n < m →
      SizeLt Ψ (.inf n) (.inf m)
  /-- `n < m ∧ Ψ ⊢ i < a ⟹ Ψ ⊢ i + n < i + m` (p. 21). -/
  | var_lt_var {i : SizeVar} {n m : Nat} {a : SizeExp} :
      n < m →
      SizeVarBound Ψ i a →
      SizeLt Ψ (.var i n) (.var i m)
  /-- `Ψ ⊢ i < ∞ ⟹ Ψ ⊢ i + n < ∞ + m` (p. 21: any variable bounded below limit ordinal `∞`
  remains below `∞ + m` under finite shifts `+ n`). -/
  | var_lt_inf {i : SizeVar} {n m : Nat} :
      SizeVarBound Ψ i .infty →
      SizeLt Ψ (.var i n) (.inf m)
  /-- `Ψ ⊢ i < ∞ + m ⟹ Ψ ⊢ i + n < ∞ + (m + n)` (p. 21). -/
  | var_lt_inf_add {i : SizeVar} {n m : Nat} :
      SizeVarBound Ψ i (.inf m) →
      SizeLt Ψ (.var i n) (.inf (m + n))
  /-- Transitive step through context bound: if `(i : π(< a)) ∈ Ψ` with `π ≤ +` and
  `Ψ ⊢ a + n ≤ b` (i.e., `Ψ ⊢ a + n < b + 1`), then `Ψ ⊢ i + n < b` (p. 21). -/
  | var_bound_step {i : SizeVar} {n : Nat} {a b : SizeExp} :
      SizeVarBound Ψ i a →
      SizeLt Ψ (a.shift n) (b.shift 1) →
      SizeLt Ψ (.var i n) b
  /-- Left meet rule: if `Ψ ⊢ a^∧` and `Ψ ⊢ (i + n) < b` for some `(i + n) ∈ a^∧`,
  then `Ψ ⊢ a^∧ < b` (p. 21). -/
  | meet_lt_left {a : SizeMin} {sv : ShiftedSizeVar} {b : SizeExp} :
      SizeWf Ψ (.meet a) →
      sv ∈ a.toList →
      SizeLt Ψ (.var sv.var sv.shift) b →
      SizeLt Ψ (.meet a) b
  /-- Right meet rule: if `Ψ ⊢ a < (i + n)` for all `(i + n) ∈ b^∧`,
  then `Ψ ⊢ a < b^∧` (p. 21). -/
  | lt_meet_right {a : SizeExp} {b : SizeMin} :
      (∀ sv ∈ b.toList, SizeLt Ψ a (.var sv.var sv.shift)) →
      SizeLt Ψ a (.meet b)

/-- Non-strict size comparison `Ψ ⊢ a ≤ b` defined by `Ψ ⊢ a < b + 1` (Section 4.1.2, p. 22). -/
def SizeLe (Ψ : SizeCtx) (a b : SizeExp) : Prop :=
  SizeLt Ψ a (b.shift 1)

/-- Polarized size comparison `Ψ ⊢ a ≤^π b` (Section 4.1.3, p. 22):
- `Ψ ⊢ a ≤^◦ b ⟺ Ψ ⊢ a ≤ b ∧ Ψ ⊢ b ≤ a`
- `Ψ ⊢ a ≤^+ b ⟺ Ψ ⊢ a ≤ b`
- `Ψ ⊢ a ≤^− b ⟺ Ψ ⊢ b ≤ a`
- `Ψ ⊢ a ≤^⊤ b ⟺ True`. -/
def SizeLePol (Ψ : SizeCtx) (π : Polarity) (a b : SizeExp) : Prop :=
  match π with
  | .mixed => SizeLe Ψ a b ∧ SizeLe Ψ b a
  | .pos => SizeLe Ψ a b
  | .neg => SizeLe Ψ b a
  | .top => True

/-- Well-formedness of a size substitution `Ψ ⊢ a⃗ ⇐ Ψ'` (Section 4.1.2, p. 21):
checks that `|a⃗| = |Ψ'|` and for each `(iₖ : πₖ(< bₖ))` in `Ψ'`, `Ψ ⊢ aₖ < bₖ[a⃗ / Ψ̂']`. -/
inductive SizeSubstWf (Ψ : SizeCtx) : List SizeExp → SizeCtx → Prop where
  | nil : SizeSubstWf Ψ [] []
  | snoc {as : List SizeExp} {Ψ' : SizeCtx} {a : SizeExp} {d : SizeDecl} :
      SizeSubstWf Ψ as Ψ' →
      SizeLt Ψ a (d.bound.subst (Ψ'.dom.zip as)) →
      SizeSubstWf Ψ (as ++ [a]) (Ψ' ++ [d])

/-! ## Section 4.1.3: Kinds and Subkinding (p. 22) -/

/-- Simple kinds `ι ::= * | o | ι₁ → ι₂` (Table 1, p. 20) and polarized simple kinds
`ι ::= * | π ι₁ → ι₂` (Appendix A, Table 8, p. I). -/
inductive SKind where
  | star : SKind
  | prop : SKind
  | arr : Polarity → SKind → SKind → SKind
  deriving DecidableEq, Repr

/-- Kinds with variance and bounded sizes `κ ::= * | <a | π κ₁ → κ₂` (Section 4.1, Table 1, p. 20). -/
inductive Kind where
  | star : Kind
  | lt : SizeExp → Kind
  | arr : Polarity → Kind → Kind → Kind
  deriving DecidableEq, Repr

namespace Kind

/-- Embed a simple kind `ι` into `Kind`. -/
def ofSKind : SKind → Kind
  | .star => .star
  | .prop => .star
  | .arr π ι₁ ι₂ => .arr π (ofSKind ι₁) (ofSKind ι₂)

/-- Erase size bounds from a `Kind` to obtain its underlying simple kind `|κ|`. -/
def toSKind : Kind → SKind
  | .star => .star
  | .lt _ => .star
  | .arr π κ₁ κ₂ => .arr π (toSKind κ₁) (toSKind κ₂)

end Kind

/-- Well-formedness of a kind `Ψ ⊢ κ` (Section 4.1.3, p. 22):
- `Ψ ⊢ *`
- `Ψ ⊢ a ⟹ Ψ ⊢ <a`
- `−Ψ ⊢ κ₁ ∧ Ψ ⊢ κ₂ ⟹ Ψ ⊢ π κ₁ → κ₂`. -/
inductive KindWf : SizeCtx → Kind → Prop where
  | star (Ψ : SizeCtx) : KindWf Ψ .star
  | lt {Ψ : SizeCtx} {a : SizeExp} :
      SizeWf Ψ a →
      KindWf Ψ (.lt a)
  | arr {Ψ : SizeCtx} {π : Polarity} {κ₁ κ₂ : Kind} :
      KindWf (Ψ.scalePol .neg) κ₁ →
      KindWf Ψ κ₂ →
      KindWf Ψ (.arr π κ₁ κ₂)

/-- Subkinding judgment `Ψ ⊢ κ ≤ κ'` (Section 4.1.3, p. 22):
- `Ψ ⊢ * ≤ *`
- `Ψ ⊢ a ≤ b ⟹ Ψ ⊢ (<a) ≤ (<b)`
- `π' ≤ π ∧ −Ψ ⊢ κ₁' ≤ κ₁ ∧ Ψ ⊢ κ₂ ≤ κ₂' ⟹ Ψ ⊢ (π κ₁ → κ₂) ≤ (π' κ₁' → κ₂')`. -/
inductive SubKind : SizeCtx → Kind → Kind → Prop where
  | star (Ψ : SizeCtx) : SubKind Ψ .star .star
  | lt {Ψ : SizeCtx} {a b : SizeExp} :
      SizeLe Ψ a b →
      SubKind Ψ (.lt a) (.lt b)
  | arr {Ψ : SizeCtx} {π π' : Polarity} {κ₁ κ₁' κ₂ κ₂' : Kind} :
      Polarity.le π' π = true →
      SubKind (Ψ.scalePol .neg) κ₁' κ₁ →
      SubKind Ψ κ₂ κ₂' →
      SubKind Ψ (.arr π κ₁ κ₂) (.arr π' κ₁' κ₂')

/-- Polarized kind comparison `Ψ ⊢ κ ≤^π κ'` (Section 4.1.3, p. 22). -/
def KindLePol (Ψ : SizeCtx) (π : Polarity) (κ κ' : Kind) : Prop :=
  match π with
  | .mixed => SubKind Ψ κ κ' ∧ SubKind Ψ κ' κ
  | .pos => SubKind Ψ κ κ'
  | .neg => SubKind Ψ κ' κ
  | .top => True

/-- Polarized maximum kind `max^π(κ, κ')` used in quantifier subtyping (Section 4.2.2, p. 24). -/
def maxKindPol (π : Polarity) (κ κ' : Kind) : Kind :=
  match π, κ, κ' with
  | .neg, .lt (.inf n), .lt (.inf m) => .lt (.inf (Nat.min n m))
  | _, .lt (.inf n), .lt (.inf m) => .lt (.inf (Nat.max n m))
  | .neg, .lt a, .lt b => .lt (SizeExp.meetExp a b)
  | _, κ₁, _ => κ₁

/-! ## Section 4.2: Types, Kinding Contexts, and Subtyping (pp. 23–25) -/

/-- Type variable identifier `X, Y, Z ∈ TyVar` (Table 2, p. 23). -/
abbrev TyVar := Nat

/-- Constructor tag `c ∈ Cons` and record field projection tag `d ∈ Proj` (Table 2, p. 23). -/
abbrev ConsName := Nat
abbrev ProjName := Nat

/-- Entry `X : π κ` in a kinding context `Δ` (Table 1, p. 20).
Size bindings `i : π(< a)` are represented both in `Δ.sizes` and as kind bindings `< a`. -/
structure TyDecl where
  var : TyVar
  pol : Polarity := .pos
  kind : Kind := .star
  deriving DecidableEq, Repr

/-- Unified kinding context `Δ` containing size declarations `sizes : SizeCtx` and type-variable
declarations `types : List TyDecl` (Table 1, p. 20 & Section 4.2, p. 23). -/
structure KindingCtx where
  sizes : SizeCtx := []
  types : List TyDecl := []
  deriving DecidableEq, Repr

namespace KindingCtx

def empty : KindingCtx := ⟨[], []⟩

/-- Scale all polarities in `Δ` by `π` (`πΔ`, Section 4.1.1, p. 20). -/
def scalePol (π : Polarity) (Δ : KindingCtx) : KindingCtx :=
  ⟨Δ.sizes.scalePol π, Δ.types.map (fun d => { d with pol := Polarity.comp π d.pol })⟩

/-- Inverse-scale all polarities in `Δ` by `π⁻¹` (`π⁻¹Δ`, Section 4.1.1, p. 20). -/
def invScalePol (π : Polarity) (Δ : KindingCtx) : KindingCtx :=
  ⟨Δ.sizes.invScalePol π, Δ.types.map (fun d => { d with pol := Polarity.invComp π d.pol })⟩

/-- Extend `Δ` with a type variable binding `X : π κ`. -/
def extType (Δ : KindingCtx) (X : TyVar) (π : Polarity) (κ : Kind) : KindingCtx :=
  match κ with
  | .lt a => ⟨Δ.sizes ++ [⟨X, π, a⟩], Δ.types ++ [⟨X, π, κ⟩]⟩
  | _ => ⟨Δ.sizes, Δ.types ++ [⟨X, π, κ⟩]⟩

/-- Extend `Δ` with a size context `Ψ`. -/
def extSizes (Δ : KindingCtx) (Ψ : SizeCtx) : KindingCtx :=
  ⟨Δ.sizes ++ Ψ, Δ.types ++ Ψ.map (fun d => ⟨d.var, d.pol, .lt d.bound⟩)⟩

/-- Extend `Δ` with a list of type/size declarations `Δ'` (`Δ, Δ'`). -/
def extDecls (Δ : KindingCtx) (Δ' : List TyDecl) : KindingCtx :=
  Δ'.foldl (fun acc d => acc.extType d.var d.pol d.kind) Δ

/-- Append two kinding contexts `Δ₁, Δ₂`. -/
def append (Δ₁ Δ₂ : KindingCtx) : KindingCtx :=
  ⟨Δ₁.sizes ++ Δ₂.sizes, Δ₁.types ++ Δ₂.types⟩

end KindingCtx

/-- Type-level atoms `K ::= a | X | 1 | × | → | ∀_κ | ∃_κ` (Table 2, p. 23). -/
inductive TyAtom where
  | size : SizeExp → TyAtom
  | var : TyVar → TyAtom
  | unit : TyAtom
  | prod : TyAtom
  | arr : TyAtom
  | all : Kind → TyAtom
  | ex : Kind → TyAtom
  deriving DecidableEq, Repr

/-- Type expressions `F, A ::= K | λX : ι. F | F F' | μ^a S | ν^a R` (Table 2, p. 23).
Inductive variant branches `S = ⟨c₁ : S_{c₁}; ...; cₙ : S_{cₙ}⟩` and coinductive record fields
`R = {d₁ : R_{d₁}; ...; dₙ : R_{dₙ}}` are represented as association lists of `(Nat × TypeExpr)`. -/
inductive TypeExpr where
  | atom : TyAtom → TypeExpr
  | lam : TyVar → SKind → TypeExpr → TypeExpr
  | app : TypeExpr → TypeExpr → TypeExpr
  | mu : SizeExp → List (Nat × TypeExpr) → TypeExpr
  | nu : SizeExp → List (Nat × TypeExpr) → TypeExpr
  deriving Repr

namespace TypeExpr

/-- Unit type `1`. -/
def unitTy : TypeExpr := .atom .unit

/-- Binary product type `A₁ × A₂`. -/
def prodTy (A₁ A₂ : TypeExpr) : TypeExpr :=
  .app (.app (.atom .prod) A₁) A₂

/-- Function arrow type `A → B`. -/
def arrTy (A B : TypeExpr) : TypeExpr :=
  .app (.app (.atom .arr) A) B

/-- Universal quantifier type `∀_κ F`. -/
def allTy (κ : Kind) (F : TypeExpr) : TypeExpr :=
  .app (.atom (.all κ)) F

/-- Existential quantifier type `∃_κ F`. -/
def exTy (κ : Kind) (F : TypeExpr) : TypeExpr :=
  .app (.atom (.ex κ)) F

/-- Bounded universal size quantification `∀(j < a). B` (`∀_{<a} (λj : *. B)`, p. 25). -/
def forallSizeLt (j : SizeVar) (a : SizeExp) (B : TypeExpr) : TypeExpr :=
  allTy (.lt a) (.lam j .star B)

/-- Bounded existential size quantification `∃(j < a). B` (`∃_{<a} (λj : *. B)`, p. 25). -/
def existsSizeLt (j : SizeVar) (a : SizeExp) (B : TypeExpr) : TypeExpr :=
  exTy (.lt a) (.lam j .star B)

/-- Iterated universal size prefix `∀Ψ. A` (Section 4.5, p. 28). -/
def forallSizes (Ψ : SizeCtx) (A : TypeExpr) : TypeExpr :=
  Ψ.foldr (fun d acc => forallSizeLt d.var d.bound acc) A

mutual

/-- Substitute a type expression `G` for type variable `X` in `F`. -/
def substTyVar (X : TyVar) (G : TypeExpr) : TypeExpr → TypeExpr
  | .atom (.var Y) => if Y == X then G else .atom (.var Y)
  | .atom K => .atom K
  | .lam Y ι body =>
      if Y == X then .lam Y ι body else .lam Y ι (substTyVar X G body)
  | .app F₁ F₂ => .app (substTyVar X G F₁) (substTyVar X G F₂)
  | .mu a S => .mu a (substTyVarBranches X G S)
  | .nu a R => .nu a (substTyVarBranches X G R)

/-- Helper: substitute `G` for `X` across a list of named branches/fields. -/
def substTyVarBranches (X : TyVar) (G : TypeExpr) :
    List (Nat × TypeExpr) → List (Nat × TypeExpr)
  | [] => []
  | (nm, F) :: rest => (nm, substTyVar X G F) :: substTyVarBranches X G rest

end

/-- Normalizing hereditary type application `F @_κ G` (Section 4.2.2, p. 24):
if `F = λX : ι. body`, substitutes `G` for `X` in `body`; otherwise forms `F G`. -/
def normApp (F G : TypeExpr) : TypeExpr :=
  match F with
  | .lam X _ body => substTyVar X G body
  | _ => .app F G

mutual

/-- Substitute size expressions `σ : List (SizeVar × SizeExp)` throughout a type `A`
(`A[a⃗ / Ψ̂]`, Section 4.5, p. 28). -/
def substSizes (σ : List (SizeVar × SizeExp)) : TypeExpr → TypeExpr
  | .atom (.size a) => .atom (.size (a.subst σ))
  | .atom (.all (.lt a)) => .atom (.all (.lt (a.subst σ)))
  | .atom (.ex (.lt a)) => .atom (.ex (.lt (a.subst σ)))
  | .atom K => .atom K
  | .lam X ι body => .lam X ι (substSizes σ body)
  | .app F₁ F₂ => .app (substSizes σ F₁) (substSizes σ F₂)
  | .mu a S => .mu (a.subst σ) (substSizesBranches σ S)
  | .nu a R => .nu (a.subst σ) (substSizesBranches σ R)

/-- Helper: substitute size expressions `σ` across a list of named branches/fields. -/
def substSizesBranches (σ : List (SizeVar × SizeExp)) :
    List (Nat × TypeExpr) → List (Nat × TypeExpr)
  | [] => []
  | (nm, F) :: rest => (nm, substSizes σ F) :: substSizesBranches σ rest

end

/-- Lookup a constructor branch `S_c` in a datatype definition `S`. -/
def lookupCons (S : List (ConsName × TypeExpr)) (c : ConsName) : Option TypeExpr :=
  (S.find? (fun p => p.1 == c)).map (·.2)

/-- Lookup a projection field `R_d` in a record definition `R`. -/
def lookupProj (R : List (ProjName × TypeExpr)) (d : ProjName) : Option TypeExpr :=
  (R.find? (fun p => p.1 == d)).map (·.2)

end TypeExpr

/-- Standard kind `◦* → *` of datatype/record functors `S` and `R` (Section 4.2.1, p. 23). -/
def functorKind : Kind :=
  .arr .mixed .star .star

mutual

/-- Kind inference judgment `Δ ⊢ F ⇒ κ` (Section 4.2.1, p. 23). -/
inductive KindInfer : KindingCtx → TypeExpr → Kind → Prop where
  | unit (Δ : KindingCtx) :
      KindInfer Δ (.atom .unit) .star
  | prod (Δ : KindingCtx) :
      KindInfer Δ (.atom .prod) (.arr .pos .star (.arr .pos .star .star))
  | arr (Δ : KindingCtx) :
      KindInfer Δ (.atom .arr) (.arr .neg .star (.arr .pos .star .star))
  | size {Δ : KindingCtx} {a : SizeExp} :
      SizeWf Δ.sizes a →
      KindInfer Δ (.atom (.size a)) (.lt (a.shift 1))
  | var {Δ : KindingCtx} {X : TyVar} {π : Polarity} {κ : Kind} :
      TyDecl.mk X π κ ∈ Δ.types →
      Polarity.le π .pos = true →
      KindInfer Δ (.atom (.var X)) κ
  | app {Δ : KindingCtx} {F G : TypeExpr} {π : Polarity} {κ κ' : Kind} :
      KindInfer Δ F (.arr π κ κ') →
      KindCheck (Δ.invScalePol π) G κ →
      KindInfer Δ (.app F G) κ'
  | all {Δ : KindingCtx} {κ : Kind} :
      KindWf (Δ.sizes.scalePol .neg) κ →
      KindInfer Δ (.atom (.all κ)) (.arr .pos (.arr .mixed κ .star) .star)
  | ex {Δ : KindingCtx} {κ : Kind} :
      KindWf Δ.sizes κ →
      KindInfer Δ (.atom (.ex κ)) (.arr .pos (.arr .mixed κ .star) .star)
  | mu {Δ : KindingCtx} {a : SizeExp} {S : List (ConsName × TypeExpr)} :
      SizeWf Δ.sizes a →
      (∀ p ∈ S, KindCheck Δ p.2 functorKind) →
      KindInfer Δ (.mu a S) .star
  | nu {Δ : KindingCtx} {a : SizeExp} {R : List (ProjName × TypeExpr)} :
      SizeWf (Δ.sizes.scalePol .neg) a →
      (∀ p ∈ R, KindCheck Δ p.2 functorKind) →
      KindInfer Δ (.nu a R) .star

/-- Kind checking judgment `Δ ⊢ F ⇐ κ` (Section 4.2.1, p. 23). -/
inductive KindCheck : KindingCtx → TypeExpr → Kind → Prop where
  | sub {Δ : KindingCtx} {F : TypeExpr} {κ κ' : Kind} :
      KindInfer Δ F κ →
      SubKind Δ.sizes κ κ' →
      KindCheck Δ F κ'
  | lam {Δ : KindingCtx} {X : TyVar} {ι : SKind} {F : TypeExpr} {π : Polarity} {κ κ' : Kind} :
      KindWf (Δ.sizes.invScalePol .mixed) (Kind.ofSKind ι) →
      KindCheck (Δ.extType X π κ) F κ' →
      KindCheck Δ (.lam X ι F) (.arr π κ κ')

end

/-- Relative kinding-context well-formedness `Δ ⊢ Δ'` (Section 4.2.1, p. 24). -/
inductive KindingCtxExtWf : KindingCtx → List TyDecl → Prop where
  | nil (Δ : KindingCtx) : KindingCtxExtWf Δ []
  | cons {Δ : KindingCtx} {d : TyDecl} {rest : List TyDecl} :
      KindWf (Δ.sizes.invScalePol .mixed) d.kind →
      KindingCtxExtWf (Δ.extType d.var d.pol d.kind) rest →
      KindingCtxExtWf Δ (d :: rest)

/-- Term variable identifier `x, y, z ∈ Var` (Table 2, p. 23). -/
abbrev TermVar := Nat

/-- Term typing context `Γ ::= · | Γ, x : A` (Table 2, p. 23). -/
abbrev TermCtx := List (TermVar × TypeExpr)

/-- Well-formedness of a term context `Δ ⊢ Γ` (Section 4.2.1, p. 24). -/
inductive TermCtxWf (Δ : KindingCtx) : TermCtx → Prop where
  | nil : TermCtxWf Δ []
  | snoc {Γ : TermCtx} {x : TermVar} {A : TypeExpr} :
      TermCtxWf Δ Γ →
      KindCheck Δ A .star →
      TermCtxWf Δ (Γ ++ [(x, A)])

mutual

/-- Bidirectional subtyping inference `Δ ⊢ F ≤^π F' ⇒ κ` where `π ≠ ⊤` (Section 4.2.2, p. 24). -/
inductive SubTypeInfer : KindingCtx → Polarity → TypeExpr → TypeExpr → Kind → Prop where
  | atom {Δ : KindingCtx} {π : Polarity} {K : TyAtom} {κ : Kind} :
      π ≠ .top →
      KindInfer Δ (.atom K) κ →
      SubTypeInfer Δ π (.atom K) (.atom K) κ
  | app {Δ : KindingCtx} {π π₁ : Polarity} {F F' G G' : TypeExpr} {κ₁ κ₂ : Kind} :
      π ≠ .top →
      SubTypeInfer Δ π F F' (.arr π₁ κ₁ κ₂) →
      SubTypeCheck (Δ.invScalePol π₁) (Polarity.comp π₁ π) G G' κ₁ →
      SubTypeInfer Δ π (.app F G) (.app F' G') κ₂
  | all {Δ : KindingCtx} {π : Polarity} {κ κ' : Kind} :
      π ≠ .top →
      KindLePol (Δ.sizes.scalePol .neg) (Polarity.comp .neg π) κ κ' →
      SubTypeInfer Δ π (.atom (.all κ)) (.atom (.all κ'))
        (.arr .neg (.arr .mixed (maxKindPol (Polarity.comp .neg π) κ κ') .star) .star)
  | ex {Δ : KindingCtx} {π : Polarity} {κ κ' : Kind} :
      π ≠ .top →
      KindLePol Δ.sizes π κ κ' →
      SubTypeInfer Δ π (.atom (.ex κ)) (.atom (.ex κ'))
        (.arr .pos (.arr .mixed (maxKindPol π κ κ') .star) .star)
  | mu {Δ : KindingCtx} {π : Polarity} {a a' : SizeExp}
      {S S' : List (ConsName × TypeExpr)} :
      π ≠ .top →
      SizeLePol Δ.sizes π a.boundNorm a'.boundNorm →
      S.map (·.1) = S'.map (·.1) →
      (∀ c F F', TypeExpr.lookupCons S c = some F → TypeExpr.lookupCons S' c = some F' →
        SubTypeCheck Δ π F F' functorKind) →
      SubTypeInfer Δ π (.mu a S) (.mu a' S') .star
  | nu {Δ : KindingCtx} {π : Polarity} {a a' : SizeExp}
      {R R' : List (ProjName × TypeExpr)} :
      π ≠ .top →
      SizeLePol (Δ.sizes.scalePol .neg) (Polarity.comp .neg π) a.boundNorm a'.boundNorm →
      R.map (·.1) = R'.map (·.1) →
      (∀ d F F', TypeExpr.lookupProj R d = some F → TypeExpr.lookupProj R' d = some F' →
        SubTypeCheck Δ π F F' functorKind) →
      SubTypeInfer Δ π (.nu a R) (.nu a' R') .star

/-- Bidirectional subtyping checking `Δ ⊢ F ≤^π F' ⇐ κ` (Section 4.2.2, p. 24). -/
inductive SubTypeCheck : KindingCtx → Polarity → TypeExpr → TypeExpr → Kind → Prop where
  | top (Δ : KindingCtx) (F F' : TypeExpr) (κ : Kind) :
      SubTypeCheck Δ .top F F' κ
  | star {Δ : KindingCtx} {π : Polarity} {A A' : TypeExpr} :
      SubTypeInfer Δ π A A' .star →
      SubTypeCheck Δ π A A' .star
  | arr {Δ : KindingCtx} {π π₁ : Polarity} {F F' : TypeExpr} {X : TyVar} {κ₁ κ₂ : Kind} :
      KindWf (Δ.sizes.invScalePol .mixed) κ₁ →
      SubTypeCheck (Δ.extType X π₁ κ₁) π
        (F.normApp (.atom (.var X))) (F'.normApp (.atom (.var X))) κ₂ →
      SubTypeCheck Δ π F F' (.arr π₁ κ₁ κ₂)

end

/-- Entry-point subtyping judgment `Δ ⊢ A ≤ A'` defined by `Δ ⊢ A ≤^+ A' ⇒ *` (pp. 24–25). -/
def SubType (Δ : KindingCtx) (A A' : TypeExpr) : Prop :=
  SubTypeInfer Δ .pos A A' .star

/-! ## Section 4.3: Patterns and Copattern Spines (p. 25) -/

/-- Patterns `p ::= x | () | (p₁, p₂) | c p | ^G p` (Table 3, p. 25). -/
inductive Pat where
  | var : TermVar → Pat
  | unit : Pat
  | pair : Pat → Pat → Pat
  | cons : ConsName → Pat → Pat
  | tyPack : TyVar → Pat → Pat
  deriving DecidableEq, Repr

/-- Copatterns `q ::= p | X | .d` (Table 3, p. 25). -/
inductive Copat where
  | pat : Pat → Copat
  | tyVar : TyVar → Copat
  | proj : ProjName → Copat
  deriving DecidableEq, Repr

/-- Pattern spine `q⃗ = [q₁, ..., qₙ]` (Table 3, p. 25). -/
abbrev PatSpine := List Copat

/-- Pattern typing relation `Δ; Γ ⊢_{Δ₀} p ⇐ A` (Section 4.3, p. 25). -/
inductive PatTyping : KindingCtx → List TyDecl → TermCtx → Pat → TypeExpr → Prop where
  | var (Δ₀ : KindingCtx) (x : TermVar) (A : TypeExpr) :
      PatTyping Δ₀ [] [(x, A)] (.var x) A
  | unit (Δ₀ : KindingCtx) :
      PatTyping Δ₀ [] [] .unit .unitTy
  | pair {Δ₀ : KindingCtx} {Δ₁ Δ₂ : List TyDecl} {Γ₁ Γ₂ : TermCtx}
      {p₁ p₂ : Pat} {A₁ A₂ : TypeExpr} :
      PatTyping Δ₀ Δ₁ Γ₁ p₁ A₁ →
      PatTyping Δ₀ Δ₂ Γ₂ p₂ A₂ →
      PatTyping Δ₀ (Δ₁ ++ Δ₂) (Γ₁ ++ Γ₂) (.pair p₁ p₂) (.prodTy A₁ A₂)
  | cons {Δ₀ : KindingCtx} {Δ : List TyDecl} {Γ : TermCtx}
      {c : ConsName} {p : Pat} {a : SizeExp} {S : List (ConsName × TypeExpr)}
      {Sc : TypeExpr} (j : SizeVar) :
      TypeExpr.lookupCons S c = some Sc →
      PatTyping Δ₀ Δ Γ p (.existsSizeLt j a.boundNorm (Sc.normApp (.mu (.var j) S))) →
      PatTyping Δ₀ Δ Γ (.cons c p) (.mu a S)
  | tyPack {Δ₀ : KindingCtx} {Δ : List TyDecl} {Γ : TermCtx}
      {X : TyVar} {κ : Kind} {p : Pat} {F : TypeExpr} :
      PatTyping (Δ₀.extType X .pos κ) Δ Γ p (F.normApp (.atom (.var X))) →
      PatTyping Δ₀ (⟨X, .pos, κ⟩ :: Δ) Γ (.tyPack X p) (.exTy κ F)

/-- Copattern spine typing relation `Δ; Γ | A ⊢_{Δ₀} q⃗ ⇒ C` (Section 4.3, p. 25). -/
inductive SpineTyping : KindingCtx → List TyDecl → TermCtx → TypeExpr → PatSpine → TypeExpr → Prop where
  | nil (Δ₀ : KindingCtx) (C : TypeExpr) :
      SpineTyping Δ₀ [] [] C [] C
  | pat {Δ₀ : KindingCtx} {Δ₁ Δ₂ : List TyDecl} {Γ₁ Γ₂ : TermCtx}
      {A B C : TypeExpr} {p : Pat} {qs : PatSpine} :
      PatTyping Δ₀ Δ₁ Γ₁ p A →
      SpineTyping Δ₀ Δ₂ Γ₂ B qs C →
      SpineTyping Δ₀ (Δ₁ ++ Δ₂) (Γ₁ ++ Γ₂) (.arrTy A B) (.pat p :: qs) C
  | proj {Δ₀ : KindingCtx} {Δ : List TyDecl} {Γ : TermCtx}
      {a : SizeExp} {R : List (ProjName × TypeExpr)} {d : ProjName} {Rd C : TypeExpr}
      {qs : PatSpine} (j : SizeVar) :
      TypeExpr.lookupProj R d = some Rd →
      SpineTyping Δ₀ Δ Γ (.forallSizeLt j a.boundNorm (Rd.normApp (.nu (.var j) R))) qs C →
      SpineTyping Δ₀ Δ Γ (.nu a R) (.proj d :: qs) C
  | tyVar {Δ₀ : KindingCtx} {Δ : List TyDecl} {Γ : TermCtx}
      {X : TyVar} {κ : Kind} {F C : TypeExpr} {qs : PatSpine} :
      SpineTyping (Δ₀.extType X .pos κ) Δ Γ (F.normApp (.atom (.var X))) qs C →
      SpineTyping Δ₀ (⟨X, .pos, κ⟩ :: Δ) Γ (.allTy κ F) (.tyVar X :: qs) C

/-! ## Section 4.4: Invocation Graphs and the Size-Change Termination Criterion (pp. 26–27) -/

/-- Edge label `r ∈ {<, ≤}` in an invocation graph (Section 4.4, p. 26). -/
inductive EdgeRel where
  | lt : EdgeRel
  | le : EdgeRel
  deriving DecidableEq, Repr

namespace EdgeRel

/-- Composition `r₁ ⋅ r₂` of two edge labels along a path (Section 4.4, p. 27):
`r'' = <` if `r₁ = <` or `r₂ = <`, and `≤` otherwise. -/
def seq : EdgeRel → EdgeRel → EdgeRel
  | .lt, _ => .lt
  | _, .lt => .lt
  | .le, .le => .le

/-- Choice / parallel combination `max(r₁, r₂)` when multiple paths connect `lᵢ` and `rⱼ`
(Section 7.1, p. 66: semiring `{0, 1, 2}` where `1 = ≤`, `2 = <`, and addition is `max`). -/
def combine : Option EdgeRel → Option EdgeRel → Option EdgeRel
  | some .lt, _ => some .lt
  | _, some .lt => some .lt
  | some .le, _ => some .le
  | _, some .le => some .le
  | none, none => none

end EdgeRel

/-- Bipartite oriented invocation graph `G = (L_G, R_G, E_G : L_G × R_G ⇀ {<, ≤})`
(Section 4.4, p. 26), with parts `L_G = {0, ..., leftArity - 1}` and
`R_G = {0, ..., rightArity - 1}`. -/
structure InvGraph where
  leftArity : Nat
  rightArity : Nat
  edges : List (Nat × Nat × EdgeRel)
  deriving DecidableEq, Repr

namespace InvGraph

/-- Query the best edge label `E_G(lᵢ, rⱼ) ∈ Option {<, ≤}` between left vertex `i < leftArity`
and right vertex `j < rightArity` (Section 4.4, p. 26 & Section 7.1, p. 66). -/
def edgeAt (G : InvGraph) (i j : Nat) : Option EdgeRel :=
  (G.edges.filter (fun e => e.1 == i && e.2.1 == j)).foldl
    (fun acc e => EdgeRel.combine acc (some e.2.2)) none

/-- Canonical normalized edge list on `{0, ..., leftArity - 1} × {0, ..., rightArity - 1}`. -/
def canonicalEdges (leftArity rightArity : Nat) (lookup : Nat → Nat → Option EdgeRel) :
    List (Nat × Nat × EdgeRel) :=
  (List.range leftArity).flatMap fun i =>
    (List.range rightArity).filterMap fun j =>
      (lookup i j).map fun r => (i, j, r)

/-- Normalize an invocation graph to its canonical edge representation. -/
def normalize (G : InvGraph) : InvGraph :=
  ⟨G.leftArity, G.rightArity, canonicalEdges G.leftArity G.rightArity G.edgeAt⟩

/-- Two invocation graphs with the same left/right arities are equal as partial functions
`L_G × R_G ⇀ {<, ≤}` iff their normalized forms coincide. -/
def ExtEq (G₁ G₂ : InvGraph) : Prop :=
  G₁.leftArity = G₂.leftArity ∧
  G₁.rightArity = G₂.rightArity ∧
  ∀ i < G₁.leftArity, ∀ j < G₁.rightArity, G₁.edgeAt i j = G₂.edgeAt i j

/-- Composition of invocation graphs `G₁ ∘ G₂` where `|R_{G₁}| = |L_{G₂}|` (Section 4.4, p. 27):
`L_{G₃} := L_{G₁}`, `R_{G₃} := R_{G₂}`, and `E_{G₃}(lᵢ, rⱼ) = r''` if there exists `k < |R_{G₁}|`
with `E_{G₁}(lᵢ, rₖ) = r` and `E_{G₂}(lₖ, rⱼ) = r'`, choosing `<` whenever any such `k` has
`r = <` or `r' = <`, and `≤` otherwise. -/
def comp (G₁ G₂ : InvGraph) : InvGraph :=
  let lookup (i j : Nat) : Option EdgeRel :=
    (List.range G₁.rightArity).foldl
      (fun acc k =>
        match G₁.edgeAt i k, G₂.edgeAt k j with
        | some r₁, some r₂ => EdgeRel.combine acc (some (EdgeRel.seq r₁ r₂))
        | _, _ => acc)
      none
  ⟨G₁.leftArity, G₂.rightArity, canonicalEdges G₁.leftArity G₂.rightArity lookup⟩

end InvGraph

/-- Conformance of two tuples `s⃗, s⃗' ∈ S⁺` to an invocation graph `G` (`s⃗ ≺_G s⃗'`,
Section 4.4, p. 26) with respect to strict and non-strict relations `ltRel, leRel : S → S → Prop`:
- `|s⃗| = |L_G|` and `|s⃗'| = |R_G|`
- for all `i < |L_G|` and `j < |R_G|`, `E_G(lᵢ, rⱼ) = < ⟹ ltRel sᵢ s'ⱼ`
  and `E_G(lᵢ, rⱼ) = ≤ ⟹ leRel sᵢ s'ⱼ`. -/
def ConformsToGraph {S : Type} (ltRel leRel : S → S → Prop)
    (G : InvGraph) (s s' : List S) : Prop :=
  s.length = G.leftArity ∧
  s'.length = G.rightArity ∧
  ∀ (i j : Nat) (hi : i < s.length) (hj : j < s'.length),
    (G.edgeAt i j = some .lt → ltRel (s.get ⟨i, hi⟩) (s'.get ⟨j, hj⟩)) ∧
    (G.edgeAt i j = some .le → leRel (s.get ⟨i, hi⟩) (s'.get ⟨j, hj⟩))

/-- Syntactic conformance `a⃗ ≺_G Ψ_f` in kinding context `Δ` (Section 4.5, p. 28):
the call-site size arguments `a⃗` (right part `R_G`) and caller size variables `Ψ_f` (left part `L_G`,
or vice-versa per Section 4.5 / Theorem 1, p. 34 where `β⃗ ≺_G α⃗` means `βⱼ < αᵢ` when
`E_G(lᵢ, rⱼ) = <`) satisfy the edge constraints of `G` in `Δ.sizes`. -/
def SyntacticConforms (Ψctx : SizeCtx) (G : InvGraph)
    (calleeArgs : List SizeExp) (callerParams : SizeCtx) : Prop :=
  ConformsToGraph (SizeLt Ψctx) (SizeLe Ψctx) G
    calleeArgs (callerParams.map (fun d => SizeExp.var d.var 0))

/-- Function symbol identifier `f, g ∈ Fun` (Table 4, p. 28). -/
abbrev FunName := Nat

/-- Family of invocation graphs `G(f, g)` indexed by function symbols `f, g ∈ Fun`
(Section 4.4, p. 27). -/
structure InvGraphFamily where
  arity : FunName → Nat
  graphs : FunName → FunName → List InvGraph

namespace InvGraphFamily

/-- Well-formedness of an invocation graph family `G`: every `G ∈ G(f, g)` has
`|L_G| = arity(g)` and `|R_G| = arity(f)` (so for `G₁ ∈ G(h, g)` and `G₂ ∈ G(g, f)` in
`α⃗_{i+1} ≺_{G_i} α⃗_i`, `|R_{G₁}| = arity(g) = |L_{G₂}|`, matching Lemma 1 and Theorem 1, pp. 34–35). -/
def ArityWf (𝒢 : InvGraphFamily) : Prop :=
  (∃ dom : List FunName, ∀ f g : FunName, 𝒢.graphs f g ≠ [] → f ∈ dom ∧ g ∈ dom) ∧
  ∀ f g : FunName, ∀ G ∈ 𝒢.graphs f g,
    G.leftArity = 𝒢.arity g ∧ G.rightArity = 𝒢.arity f ∧ G = G.normalize

end InvGraphFamily

/-- Inductive transitive closure `G*(f, g)` of an invocation graph family `G` under composition
(Section 4.4, p. 27):
- if `G ∈ G(f, g)`, then `G ∈ G*(f, g)`
- if `G₁ ∈ G*(h, g)` and `G₂ ∈ G*(f, h)` (so `s⃗_h ≺_{G₂} s⃗_f` and `s⃗_g ≺_{G₁} s⃗_h`, hence
  `s⃗_g ≺_{G₁ ∘ G₂} s⃗_f`), then `G₁ ∘ G₂ ∈ G*(f, g)`. -/
inductive InvGraphClosure (𝒢 : InvGraphFamily) : FunName → FunName → InvGraph → Prop where
  | base {f g : FunName} {G : InvGraph} :
      G ∈ 𝒢.graphs f g →
      InvGraphClosure 𝒢 f g G.normalize
  | comp {f h g : FunName} {G₁ G₂ : InvGraph} :
      InvGraphClosure 𝒢 h g G₁ →
      InvGraphClosure 𝒢 f h G₂ →
      InvGraphClosure 𝒢 f g (G₁.comp G₂)

/-- The Size-Change Termination criterion `⊢ G` (`SCTValid G`, Section 4.4, p. 27):
`∀ f, ∀ G ∈ G*(f, f), G = G ∘ G ⟹ ∃ k < |L_G|, E_G(lₖ, rₖ) = <`. -/
def SCTValid (𝒢 : InvGraphFamily) : Prop :=
  𝒢.ArityWf ∧
  ∀ (f : FunName) (G : InvGraph),
    InvGraphClosure 𝒢 f f G →
    G.comp G = G →
    ∃ k < G.leftArity, G.edgeAt k k = some .lt

/-! ## Sections 4.5–4.6: Terms, Clauses, Mutual Blocks, and Programs (pp. 27–30) -/

mutual

/-- Expressions / terms `r, s, t` of System `F_ω^{cop, SCT}` and System `F_ω^c`
(Table 4, p. 28 & Table 11, p. III). -/
inductive Term where
  | var : TermVar → Term
  | funRef : FunName → List SizeExp → Term
  | app : Term → Elim → Term
  | unit : Term
  | pair : Term → Term → Term
  | cons : ConsName → Option SizeExp → Term → Term
  | pack : TypeExpr → Term → Term
  | lamClauses : List Clause → Term
  | ascr : Term → TypeExpr → Term
  deriving Repr

/-- Eliminations `e ::= t | G | .d [a]` (Table 4, p. 28 & Table 11, p. III). -/
inductive Elim where
  | term : Term → Elim
  | tyArg : TypeExpr → Elim
  | proj : ProjName → Option SizeExp → Elim
  deriving Repr

/-- Definition clause `D ::= {q⃗ → t}` (Table 5, p. 29 & Table 12, p. IV). -/
inductive Clause where
  | mk : PatSpine → Term → Clause
  deriving Repr

end

namespace Term

/-- Apply a term `r` to a spine of eliminations `e⃗ = [e₁, ..., eₙ]`. -/
def appSpine (r : Term) (es : List Elim) : Term :=
  es.foldl .app r

end Term

/-- Function declaration `δ ::= f : ∀Ψ. A = D⃗` in System `F_ω^{cop, SCT}` (Table 5, p. 29).
In unannotated System `F_ω^c` (Appendix A, Table 12, p. IV), `sizeParams = []`. -/
structure FunDecl where
  name : FunName
  sizeParams : SizeCtx := []
  ty : TypeExpr
  clauses : List Clause
  deriving Repr

/-- Mutual block `Ξ ::= mutual δ⃗` (Table 5, p. 29). -/
abbrev MutualBlock := List FunDecl

/-- Global signature `Σ ::= Ξ⃗` of previously checked mutual blocks (Section 4.6, p. 30). -/
abbrev GlobalSig := List FunDecl

/-- Complete program `P ::= (Σ; u)` consisting of checked blocks `Σ` and a main term `u`
(Table 5, p. 29 & Section 4.6, p. 30). -/
structure Program where
  sig : List MutualBlock
  main : Term
  deriving Repr

namespace FunDecl

/-- Lookup a function declaration `g : ∀Ψ. A = D⃗` by name in a list of declarations. -/
def lookup (decls : List FunDecl) (g : FunName) : Option FunDecl :=
  decls.find? (fun d => d.name == g)

end FunDecl

/-- Consistent kinding-context extension check `Δ ⊢ ∃Δ'` (Section 4.1.2, p. 22 & Section 4.6, p. 29):
every size binding `(i : π(< a))` introduced in `Δ'` has a satisfiable upper bound `a`
(in particular, `a` is well-formed in `Δ, Δ'` and does not bound `i` below a variable that may be `0`). -/
def KindingCtxConsistentExt (Δ : KindingCtx) (Δ' : List TyDecl) : Prop :=
  KindingCtxExtWf Δ Δ' ∧
  ∀ d ∈ Δ', ∀ a : SizeExp, d.kind = .lt a →
    (∃ n, a = .inf n) ∨ (∃ j ∈ (Δ.extDecls Δ').sizes.dom, a = .var j 0)

/-- Typing environment bundle `Ω = (Σ; Ξ; G; f; Ψ_f)` for bidirectional expression typing in
System `F_ω^{cop, SCT}` (Section 4.5, p. 28). -/
structure TypingEnv where
  sig : GlobalSig
  block : MutualBlock
  graphs : InvGraphFamily
  caller : FunName
  callerSizes : SizeCtx

mutual

/-- Bidirectional expression typing in inference mode `Σ; Ξ; G; Ψ_f; Δ; Γ ⊢ r ⇒ C`
for System `F_ω^{cop, SCT}` (Section 4.5, pp. 28–29). -/
inductive ExprInfer (Ω : TypingEnv) : KindingCtx → TermCtx → Term → TypeExpr → Prop where
  | var {Δ : KindingCtx} {Γ : TermCtx} {x : TermVar} {A : TypeExpr} :
      (x, A) ∈ Γ →
      ExprInfer Ω Δ Γ (.var x) A
  | proj {Δ : KindingCtx} {Γ : TermCtx} {r : Term} {a : SizeExp}
      {R : List (ProjName × TypeExpr)} {d : ProjName} {Rd : TypeExpr} (j : SizeVar) :
      ExprInfer Ω Δ Γ r (.nu a R) →
      TypeExpr.lookupProj R d = some Rd →
      ExprInfer Ω Δ Γ (.app r (.proj d none))
        (.forallSizeLt j a.boundNorm (Rd.normApp (.nu (.var j) R)))
  | projSized {Δ : KindingCtx} {Γ : TermCtx} {r : Term} {a b : SizeExp}
      {R : List (ProjName × TypeExpr)} {d : ProjName} {Rd : TypeExpr} :
      ExprInfer Ω Δ Γ r (.nu a R) →
      TypeExpr.lookupProj R d = some Rd →
      SizeLt Δ.sizes b a.boundNorm →
      ExprInfer Ω Δ Γ (.app r (.proj d (some b))) (Rd.normApp (.nu b R))
  | appTerm {Δ : KindingCtx} {Γ : TermCtx} {r s : Term} {A B : TypeExpr} :
      ExprInfer Ω Δ Γ r (.arrTy A B) →
      ExprCheck Ω Δ Γ s A →
      ExprInfer Ω Δ Γ (.app r (.term s)) B
  | appTy {Δ : KindingCtx} {Γ : TermCtx} {r : Term} {κ : Kind} {F F' : TypeExpr} :
      ExprInfer Ω Δ Γ r (.allTy κ F) →
      KindCheck Δ F' κ →
      ExprInfer Ω Δ Γ (.app r (.tyArg F')) (F.normApp F')
  | ascr {Δ : KindingCtx} {Γ : TermCtx} {t : Term} {A : TypeExpr} :
      KindCheck Δ A .star →
      ExprCheck Ω Δ Γ t A →
      ExprInfer Ω Δ Γ (.ascr t A) A
  | globalFun {Δ : KindingCtx} {Γ : TermCtx} {decl : FunDecl} {as : List SizeExp} :
      decl ∈ Ω.sig →
      SizeSubstWf Δ.sizes as decl.sizeParams →
      ExprInfer Ω Δ Γ (.funRef decl.name as)
        (decl.ty.substSizes (decl.sizeParams.dom.zip as))
  | localFun {Δ : KindingCtx} {Γ : TermCtx} {decl : FunDecl} {as : List SizeExp} {G : InvGraph} :
      decl ∈ Ω.block →
      SizeSubstWf Δ.sizes as decl.sizeParams →
      G ∈ Ω.graphs.graphs Ω.caller decl.name →
      SyntacticConforms Δ.sizes G as Ω.callerSizes →
      ExprInfer Ω Δ Γ (.funRef decl.name as)
        (decl.ty.substSizes (decl.sizeParams.dom.zip as))

/-- Bidirectional expression typing in checking mode `Σ; Ξ; G; Ψ_f; Δ; Γ ⊢ r ⇐ C`
for System `F_ω^{cop, SCT}` (Section 4.5, p. 29). -/
inductive ExprCheck (Ω : TypingEnv) : KindingCtx → TermCtx → Term → TypeExpr → Prop where
  | unit (Δ : KindingCtx) (Γ : TermCtx) :
      ExprCheck Ω Δ Γ .unit .unitTy
  | pair {Δ : KindingCtx} {Γ : TermCtx} {t₁ t₂ : Term} {A₁ A₂ : TypeExpr} :
      ExprCheck Ω Δ Γ t₁ A₁ →
      ExprCheck Ω Δ Γ t₂ A₂ →
      ExprCheck Ω Δ Γ (.pair t₁ t₂) (.prodTy A₁ A₂)
  | cons {Δ : KindingCtx} {Γ : TermCtx} {c : ConsName} {t : Term}
      {a : SizeExp} {S : List (ConsName × TypeExpr)} {Sc : TypeExpr} (j : SizeVar) :
      TypeExpr.lookupCons S c = some Sc →
      ExprCheck Ω Δ Γ t (.existsSizeLt j a.boundNorm (Sc.normApp (.mu (.var j) S))) →
      ExprCheck Ω Δ Γ (.cons c none t) (.mu a S)
  | consSized {Δ : KindingCtx} {Γ : TermCtx} {c : ConsName} {b a : SizeExp} {t : Term}
      {S : List (ConsName × TypeExpr)} {Sc : TypeExpr} :
      TypeExpr.lookupCons S c = some Sc →
      SizeLt Δ.sizes b a.boundNorm →
      ExprCheck Ω Δ Γ t (Sc.normApp (.mu b S)) →
      ExprCheck Ω Δ Γ (.cons c (some b) t) (.mu a S)
  | pack {Δ : KindingCtx} {Γ : TermCtx} {F F' : TypeExpr} {κ : Kind} {t : Term} :
      KindCheck Δ F' κ →
      ExprCheck Ω Δ Γ t (F.normApp F') →
      ExprCheck Ω Δ Γ (.pack F' t) (.exTy κ F)
  | lamClauses {Δ : KindingCtx} {Γ : TermCtx} {Ds : List Clause} {A : TypeExpr} :
      (∀ D ∈ Ds, ClauseCheck Ω Δ Γ D A) →
      ExprCheck Ω Δ Γ (.lamClauses Ds) A
  | sub {Δ : KindingCtx} {Γ : TermCtx} {r : Term} {A C : TypeExpr} :
      ExprInfer Ω Δ Γ r A →
      SubType Δ A C →
      ExprCheck Ω Δ Γ r C

/-- Clause verification rule `Ω; Δ; Γ ⊢ {q⃗ → t} ⇐ A` (Section 4.6, p. 29). -/
inductive ClauseCheck (Ω : TypingEnv) : KindingCtx → TermCtx → Clause → TypeExpr → Prop where
  | mk {Δ : KindingCtx} {Γ Γ' : TermCtx} {Δ' : List TyDecl}
      {A C : TypeExpr} {qs : PatSpine} {t : Term} :
      SpineTyping Δ Δ' Γ' A qs C →
      KindingCtxConsistentExt Δ Δ' →
      ExprCheck Ω (Δ.extDecls Δ') (Γ ++ Γ') t C →
      ClauseCheck Ω Δ Γ (.mk qs t) A

end

/-- Function declaration typing `Σ; Ξ; G ⊢ f : (∀Ψ. A) = D⃗` (Section 4.6, p. 30). -/
def DeclTyping (sig : GlobalSig) (Ξ : MutualBlock) (𝒢 : InvGraphFamily) (decl : FunDecl) : Prop :=
  let Δ₀ := KindingCtx.empty.extSizes decl.sizeParams
  let Ω : TypingEnv := ⟨sig, Ξ, 𝒢, decl.name, decl.sizeParams⟩
  SizeCtxWf decl.sizeParams ∧
  KindCheck Δ₀ decl.ty .star ∧
  ∀ D ∈ decl.clauses, ClauseCheck Ω Δ₀ [] D decl.ty

/-- Mutual block typing `Σ ⊢ Ξ` via an invocation graph family `G` (Section 4.6, p. 30):
`Σ; Ξ; G ⊢ f : (∀Ψ. A) = D⃗` for all `f ∈ Ξ`, and `⊢ G`. -/
def MutualBlockTypingWith (sig : GlobalSig) (Ξ : MutualBlock) (𝒢 : InvGraphFamily) : Prop :=
  SCTValid 𝒢 ∧
  (∀ decl ∈ Ξ, 𝒢.arity decl.name = decl.sizeParams.length) ∧
  ∀ decl ∈ Ξ, DeclTyping sig Ξ 𝒢 decl

/-- Existential mutual block typing `Σ ⊢ Ξ` (Section 4.6, p. 30). -/
def MutualBlockTyping (sig : GlobalSig) (Ξ : MutualBlock) : Prop :=
  ∃ 𝒢 : InvGraphFamily, MutualBlockTypingWith sig Ξ 𝒢

/-- Global signature sequence typing `⊢ Σ` (Section 4.6, p. 30). -/
inductive SigBlocksTyping : List MutualBlock → Prop where
  | nil : SigBlocksTyping []
  | snoc {blocks : List MutualBlock} {Ξ : MutualBlock} :
      SigBlocksTyping blocks →
      MutualBlockTyping blocks.flatten Ξ →
      SigBlocksTyping (blocks ++ [Ξ])

/-- Complete program typing `⊢ P` (`⊢ (Σ; u)`, Section 4.6, p. 30). -/
def ProgramTyping (P : Program) : Prop :=
  SigBlocksTyping P.sig ∧
  ∃ A : TypeExpr,
    ExprInfer ⟨P.sig.flatten, [], ⟨fun _ => 0, fun _ _ => []⟩, 0, []⟩
      KindingCtx.empty [] P.main A

/-! ## Section 5.5: System F_ω^{cop} Measure Erasure `|Ξ|` (pp. 38–40) -/

/-- A declaration in Abel & Pientka's System `F_ω^{cop}` carrying an explicit lexicographic
size measure `m` (a subset/sublist of `sizeParams` of fixed length `|m|`, Section 5.5, p. 38). -/
structure CopFunDecl where
  decl : FunDecl
  measureIndices : List Nat

/-- Measure removal `|Ξ| : Ξ^{cop} → Ξ^{cop, sct}` (Section 5.5, p. 38):
strips the explicit measure annotation `m` from each declaration in a mutual block. -/
def eraseMeasures (Ξcop : List CopFunDecl) : MutualBlock :=
  Ξcop.map (·.decl)

/-- Lexicographic invocation graph `G_i` of arity `k` at position `i < k` (Section 5.5, Figure 3,
p. 39): `E_{G_i}(l_j, r_j) = ≤` for `j < i` and `E_{G_i}(l_i, r_i) = <`. -/
def lexInvGraph (measureIndices : List Nat) (paramArity : Nat) (stepIdx : Nat) : InvGraph :=
  let lookup (l r : Nat) : Option EdgeRel :=
    if l == r then
      match measureIndices.idxOf? l with
      | some pos =>
          if pos < stepIdx then some .le
          else if pos == stepIdx then some .lt
          else none
      | none => none
    else none
  ⟨paramArity, paramArity, InvGraph.canonicalEdges paramArity paramArity lookup⟩

/-- Lexicographic invocation graph family `G^{lex}` constructed in the proof of Theorem 6
(Section 5.5, p. 39): for every `f, g ∈ dom`, `G(f, g) = {G_0, ..., G_{|m|-1}}`. -/
def lexInvGraphFamily (dom : List FunName) (paramArity : Nat) (measureIndices : List Nat) :
    InvGraphFamily where
  arity := fun _ => paramArity
  graphs := fun f g =>
    if f ∈ dom ∧ g ∈ dom then
      (List.range measureIndices.length).map (lexInvGraph measureIndices paramArity)
    else []

/-- Well-typed mutual block in System `F_ω^{cop}` (Section 5.5, pp. 38–39):
all functions in `Ξcop` share a common duplicate-free measure `measureIndices` of length `m > 0`
on their size parameters, and every recursive call `g a⃗` within `f` decreases lexicographically
along `measureIndices` (i.e. conforms to one of the lexicographic graphs `G_0, ..., G_{|m|-1}`). -/
def CopMutualBlockTyping (sig : GlobalSig) (Ξcop : List CopFunDecl) : Prop :=
  let dom := (eraseMeasures Ξcop).map (·.name)
  ∃ (paramArity : Nat) (measureIndices : List Nat),
    measureIndices ≠ [] ∧
    measureIndices.Nodup ∧
    (∀ idx ∈ measureIndices, idx < paramArity) ∧
    (∀ cdecl ∈ Ξcop, cdecl.measureIndices = measureIndices ∧
      cdecl.decl.sizeParams.length = paramArity) ∧
    (∀ cdecl ∈ Ξcop,
      DeclTyping sig (eraseMeasures Ξcop)
        (lexInvGraphFamily dom paramArity measureIndices) cdecl.decl)

end NishtAbel2024
Source
Kanstantsin Nisht, 'Type-Based Termination Checking in Agda', Master's Thesis in Computer Science and Engineering, Chalmers University of Technology and University of Gothenburg (supervised by Andreas Abel), 2024; extended abstract by Kanstantsin Nisht and Andreas Abel, 30th International Conference on Types for Proofs and Programs (TYPES 2024). Chapter 4 (pp. 19–30), Section 5.5 (pp. 38–40), and Appendix A (pp. I–IV).
Read-back

What the Lean code literally says, in plain math · Gemini 3.1 Pro (Independent Blind Auditor)

Independent Mathematical Read-Back: Def_NishtAbel2024_Syntax.lean

Polarity, Polarity.le, Polarity.join, Polarity.meet, Polarity.negPol, Polarity.comp, and Polarity.invComp. Polarity is a four-element inductive type with constructors mixed\mathsf{mixed}mixed, +++ (pos), −-− (neg), and ⊤\top⊤ (top).

  • The boolean relation π1≤π2\pi_1 \le \pi_2π1​≤π2​ (Polarity.le) returns true\mathsf{true}true if and only if π1=mixed\pi_1 = \mathsf{mixed}π1​=mixed, or π2=⊤\pi_2 = \topπ2​=⊤, or π1=π2=+\pi_1 = \pi_2 = +π1​=π2​=+, or π1=π2=−\pi_1 = \pi_2 = -π1​=π2​=−; otherwise it returns false\mathsf{false}false.
  • The binary operation π1⊔π2\pi_1 \sqcup \pi_2π1​⊔π2​ (Polarity.join) computes the least upper bound in this diamond lattice: mixed\mathsf{mixed}mixed is the identity element, ⊤\top⊤ is an absorbing element, +⊔+=++ \sqcup + = ++⊔+=+, −⊔−=−- \sqcup - = -−⊔−=−, and +⊔−=−⊔+=⊤+ \sqcup - = - \sqcup + = \top+⊔−=−⊔+=⊤.
  • The binary operation π1⊓π2\pi_1 \sqcap \pi_2π1​⊓π2​ (Polarity.meet) computes the greatest lower bound: ⊤\top⊤ is the identity element, mixed\mathsf{mixed}mixed is an absorbing element, +⊓+=++ \sqcap + = ++⊓+=+, −⊓−=−- \sqcap - = -−⊓−=−, and +⊓−=−⊓+=mixed+ \sqcap - = - \sqcap + = \mathsf{mixed}+⊓−=−⊓+=mixed.
  • The unary operation −π-\pi−π (Polarity.negPol) swaps +++ and −-− while fixing mixed\mathsf{mixed}mixed and ⊤\top⊤.
  • The composition operation π1⋅π2\pi_1 \cdot \pi_2π1​⋅π2​ (Polarity.comp) returns ⊤\top⊤ if either π1=⊤\pi_1 = \topπ1​=⊤ or π2=⊤\pi_2 = \topπ2​=⊤; otherwise returns mixed\mathsf{mixed}mixed if either π1=mixed\pi_1 = \mathsf{mixed}π1​=mixed or π2=mixed\pi_2 = \mathsf{mixed}π2​=mixed (note that ⊤\top⊤ takes precedence over mixed\mathsf{mixed}mixed, so ⊤⋅mixed=mixed⋅⊤=⊤\top \cdot \mathsf{mixed} = \mathsf{mixed} \cdot \top = \top⊤⋅mixed=mixed⋅⊤=⊤); otherwise treats +++ as the identity (+⋅π=π⋅+=π+ \cdot \pi = \pi \cdot + = \pi+⋅π=π⋅+=π) and maps (−)⋅(−)=+(-)\cdot(-) = +(−)⋅(−)=+.
  • The inverse-composition operation π1−1π2\pi_1^{-1}\pi_2π1−1​π2​ (Polarity.invComp) is defined by cases on (π1,π2)(\pi_1, \pi_2)(π1​,π2​):
π1−1π2={mixedif π1=⊤ (for any π2),mixedif π1=mixed and π2=mixed,⊤if π1=mixed and π2≠mixed,π2if π1=+,(−)⋅π2if π1=−.\pi_1^{-1}\pi_2 = \begin{cases} \mathsf{mixed} & \text{if } \pi_1 = \top \text{ (for any } \pi_2\text{)}, \\ \mathsf{mixed} & \text{if } \pi_1 = \mathsf{mixed} \text{ and } \pi_2 = \mathsf{mixed}, \\ \top & \text{if } \pi_1 = \mathsf{mixed} \text{ and } \pi_2 \neq \mathsf{mixed}, \\ \pi_2 & \text{if } \pi_1 = +, \\ (-) \cdot \pi_2 & \text{if } \pi_1 = -. \end{cases}π1−1​π2​=⎩⎨⎧​mixedmixed⊤π2​(−)⋅π2​​if π1​=⊤ (for any π2​),if π1​=mixed and π2​=mixed,if π1​=mixed and π2​=mixed,if π1​=+,if π1​=−.​

SizeVar, ShiftedSizeVar, SizeMin, and SizeMin operations (toList, single, append, shift, vars). SizeVar is a type alias for N\mathbb{N}N. A ShiftedSizeVar is a pair (i,n)∈N×N(i, n) \in \mathbb{N} \times \mathbb{N}(i,n)∈N×N consisting of a size variable iii (var) and a natural number offset nnn (shift, defaulting to 000). A SizeMin is a structure representing a non-empty list of shifted size variables via a field head :ShiftedSizeVar: \text{ShiftedSizeVar}:ShiftedSizeVar and a field tail :List ShiftedSizeVar: \text{List ShiftedSizeVar}:List ShiftedSizeVar (defaulting to [][][]).

  • For m:SizeMinm : \text{SizeMin}m:SizeMin, m.toListm.\text{toList}m.toList returns the non-empty list m.head::m.tailm.\text{head} :: m.\text{tail}m.head::m.tail.
  • SizeMin.single(i,n)\text{SizeMin.single}(i, n)SizeMin.single(i,n) (with default n=0n = 0n=0) constructs ⟨(i,n),[]⟩\langle (i, n), [] \rangle⟨(i,n),[]⟩.
  • SizeMin.append(m1,m2)\text{SizeMin.append}(m_1, m_2)SizeMin.append(m1​,m2​) concatenates two SizeMin values into ⟨m1.head,m1.tail+ ⁣ ⁣+m2.toList⟩\langle m_1.\text{head}, m_1.\text{tail} \mathbin{+\!\!+} m_2.\text{toList} \rangle⟨m1​.head,m1​.tail++m2​.toList⟩.
  • SizeMin.shift(a,m)\text{SizeMin.shift}(a, m)SizeMin.shift(a,m) adds m∈Nm \in \mathbb{N}m∈N to the shift field of a.heada.\text{head}a.head and of every element in a.taila.\text{tail}a.tail.
  • SizeMin.vars(a)\text{SizeMin.vars}(a)SizeMin.vars(a) extracts the list of underlying var fields from a.toLista.\text{toList}a.toList and removes duplicate variable indices via List.eraseDups.

SizeExp and SizeExp operations (infty, var, shift, boundNorm, meetExp, vars, substShiftedVar, subst). SizeExp is an inductive type with two constructors: inf(n)\mathsf{inf}(n)inf(n) for n∈Nn \in \mathbb{N}n∈N (representing ∞+n\infty + n∞+n), and meet(a)\mathsf{meet}(a)meet(a) for a:SizeMina : \text{SizeMin}a:SizeMin (representing a formal minimum of shifted size variables).

  • SizeExp.infty\text{SizeExp.infty}SizeExp.infty is defined as inf(0)\mathsf{inf}(0)inf(0).
  • SizeExp.var(i,n)\text{SizeExp.var}(i, n)SizeExp.var(i,n) (with default n=0n = 0n=0) is defined as meet(SizeMin.single(i,n))\mathsf{meet}(\text{SizeMin.single}(i, n))meet(SizeMin.single(i,n)).
  • SizeExp.shift(s,m)\text{SizeExp.shift}(s, m)SizeExp.shift(s,m) maps inf(n)↦inf(n+m)\mathsf{inf}(n) \mapsto \mathsf{inf}(n + m)inf(n)↦inf(n+m) and meet(a)↦meet(a.shift(m))\mathsf{meet}(a) \mapsto \mathsf{meet}(a.\text{shift}(m))meet(a)↦meet(a.shift(m)).
  • SizeExp.boundNorm(s)\text{SizeExp.boundNorm}(s)SizeExp.boundNorm(s) maps inf(n)↦inf(1)\mathsf{inf}(n) \mapsto \mathsf{inf}(1)inf(n)↦inf(1) for every n∈Nn \in \mathbb{N}n∈N (collapsing all ∞+n\infty + n∞+n to ∞+1\infty + 1∞+1), and leaves meet(a)\mathsf{meet}(a)meet(a) unchanged.
  • SizeExp.meetExp(s1,s2)\text{SizeExp.meetExp}(s_1, s_2)SizeExp.meetExp(s1​,s2​) combines two size expressions:
meetExp(s1,s2)={meet(a.append(b))if s1=meet(a) and s2=meet(b),meet(a)if s1=meet(a) and s2=inf(n),meet(b)if s1=inf(n) and s2=meet(b),inf(min⁡(n,m))if s1=inf(n) and s2=inf(m).\text{meetExp}(s_1, s_2) = \begin{cases} \mathsf{meet}(a.\text{append}(b)) & \text{if } s_1 = \mathsf{meet}(a) \text{ and } s_2 = \mathsf{meet}(b), \\ \mathsf{meet}(a) & \text{if } s_1 = \mathsf{meet}(a) \text{ and } s_2 = \mathsf{inf}(n), \\ \mathsf{meet}(b) & \text{if } s_1 = \mathsf{inf}(n) \text{ and } s_2 = \mathsf{meet}(b), \\ \mathsf{inf}(\min(n, m)) & \text{if } s_1 = \mathsf{inf}(n) \text{ and } s_2 = \mathsf{inf}(m). \end{cases}meetExp(s1​,s2​)=⎩⎨⎧​meet(a.append(b))meet(a)meet(b)inf(min(n,m))​if s1​=meet(a) and s2​=meet(b),if s1​=meet(a) and s2​=inf(n),if s1​=inf(n) and s2​=meet(b),if s1​=inf(n) and s2​=inf(m).​
  • SizeExp.vars(s)\text{SizeExp.vars}(s)SizeExp.vars(s) returns [][][] for inf(n)\mathsf{inf}(n)inf(n) and a.varsa.\text{vars}a.vars for meet(a)\mathsf{meet}(a)meet(a).
  • SizeExp.substShiftedVar(i,s,(j,n))\text{SizeExp.substShiftedVar}(i, s, (j, n))SizeExp.substShiftedVar(i,s,(j,n)) returns s.shift(n)s.\text{shift}(n)s.shift(n) if j=ij = ij=i, and SizeExp.var(j,n)\text{SizeExp.var}(j, n)SizeExp.var(j,n) otherwise.
  • SizeExp.subst(σ,s)\text{SizeExp.subst}(\sigma, s)SizeExp.subst(σ,s), for an association list σ:List(SizeVar×SizeExp)\sigma : \text{List}(\text{SizeVar} \times \text{SizeExp})σ:List(SizeVar×SizeExp), leaves inf(n)\mathsf{inf}(n)inf(n) unchanged; for meet(m)\mathsf{meet}(m)meet(m), it evaluates each shifted variable (j,n)(j, n)(j,n) in mmm by searching σ\sigmaσ from left to right (find?) for the first pair with key jjj, returning sj.shift(n)s_j.\text{shift}(n)sj​.shift(n) if found and SizeExp.var(j,n)\text{SizeExp.var}(j, n)SizeExp.var(j,n) if not found, and then left-folds meetExp across the evaluated tail starting from the evaluated head.

SizeDecl, SizeCtx, SizeCtx.dom, SizeCtx.scalePol, and SizeCtx.invScalePol. SizeDecl is a structure with fields var :SizeVar: \text{SizeVar}:SizeVar, pol :Polarity: \text{Polarity}:Polarity (defaulting to +++), and bound :SizeExp: \text{SizeExp}:SizeExp (defaulting to SizeExp.infty=inf(0)\text{SizeExp.infty} = \mathsf{inf}(0)SizeExp.infty=inf(0)), written (i<πa)(i \stackrel{\pi}{<} a)(i<π​a). SizeCtx is a type alias for List SizeDecl\text{List SizeDecl}List SizeDecl. For Ψ:SizeCtx\Psi : \text{SizeCtx}Ψ:SizeCtx:

  • Ψ.dom\Psi.\text{dom}Ψ.dom is the list of variables [d.var∣d∈Ψ][d.\text{var} \mid d \in \Psi][d.var∣d∈Ψ].
  • Ψ.scalePol(π)\Psi.\text{scalePol}(\pi)Ψ.scalePol(π) maps each declaration (i,πd,a)∈Ψ(i, \pi_d, a) \in \Psi(i,πd​,a)∈Ψ to (i,π⋅πd,a)(i, \pi \cdot \pi_d, a)(i,π⋅πd​,a).
  • Ψ.invScalePol(π)\Psi.\text{invScalePol}(\pi)Ψ.invScalePol(π) maps each declaration (i,πd,a)∈Ψ(i, \pi_d, a) \in \Psi(i,πd​,a)∈Ψ to (i,π−1πd,a)(i, \pi^{-1}\pi_d, a)(i,π−1πd​,a).

SizeVarBound, SizeWf, and SizeCtxWf.

  • For Ψ:SizeCtx\Psi : \text{SizeCtx}Ψ:SizeCtx, i:SizeVari : \text{SizeVar}i:SizeVar, and a:SizeExpa : \text{SizeExp}a:SizeExp, the proposition SizeVarBound(Ψ,i,a)\text{SizeVarBound}(\Psi, i, a)SizeVarBound(Ψ,i,a) holds if and only if there exists π:Polarity\pi : \text{Polarity}π:Polarity such that ⟨i,π,a⟩∈Ψ\langle i, \pi, a \rangle \in \Psi⟨i,π,a⟩∈Ψ (standard list membership, not first-match lookup) and π≤+\pi \le +π≤+ (i.e., π∈{mixed,+}\pi \in \{\mathsf{mixed}, +\}π∈{mixed,+}).
  • SizeWf(Ψ,s)\text{SizeWf}(\Psi, s)SizeWf(Ψ,s) is defined by cases on s:SizeExps : \text{SizeExp}s:SizeExp: for inf(n)\mathsf{inf}(n)inf(n) it is True\mathsf{True}True; for meet(a)\mathsf{meet}(a)meet(a) it holds if and only if for every shifted variable sv∈a.toListsv \in a.\text{toList}sv∈a.toList, there exists some b:SizeExpb : \text{SizeExp}b:SizeExp such that SizeVarBound(Ψ,sv.var,b)\text{SizeVarBound}(\Psi, sv.\text{var}, b)SizeVarBound(Ψ,sv.var,b).
  • SizeCtxWf(Ψ)\text{SizeCtxWf}(\Psi)SizeCtxWf(Ψ) is an inductive predicate on Ψ:SizeCtx\Psi : \text{SizeCtx}Ψ:SizeCtx with two constructors:
    1. nil: SizeCtxWf([])\text{SizeCtxWf}([])SizeCtxWf([]) holds.
    2. snoc: given Ψ:SizeCtx\Psi : \text{SizeCtx}Ψ:SizeCtx, i:SizeVari : \text{SizeVar}i:SizeVar, π:Polarity\pi : \text{Polarity}π:Polarity, and a:SizeExpa : \text{SizeExp}a:SizeExp, if SizeCtxWf(Ψ)\text{SizeCtxWf}(\Psi)SizeCtxWf(Ψ), i∉Ψ.domi \notin \Psi.\text{dom}i∈/Ψ.dom, and SizeWf(Ψ.invScalePol(mixed),a)\text{SizeWf}(\Psi.\text{invScalePol}(\mathsf{mixed}), a)SizeWf(Ψ.invScalePol(mixed),a), then SizeCtxWf(Ψ+ ⁣ ⁣+[⟨i,π,a⟩])\text{SizeCtxWf}(\Psi \mathbin{+\!\!+} [\langle i, \pi, a \rangle])SizeCtxWf(Ψ++[⟨i,π,a⟩]). Note that because mixed−1πd=mixed\mathsf{mixed}^{-1}\pi_d = \mathsf{mixed}mixed−1πd​=mixed when πd=mixed\pi_d = \mathsf{mixed}πd​=mixed and ⊤\top⊤ otherwise, the condition SizeWf(Ψ.invScalePol(mixed),a)\text{SizeWf}(\Psi.\text{invScalePol}(\mathsf{mixed}), a)SizeWf(Ψ.invScalePol(mixed),a) requires every size variable occurring in the bound aaa to appear in Ψ\PsiΨ with polarity mixed\mathsf{mixed}mixed.

SizeLt, SizeLe, SizeLePol, and SizeSubstWf.

  • Given Ψ:SizeCtx\Psi : \text{SizeCtx}Ψ:SizeCtx, SizeLt(Ψ,s1,s2)\text{SizeLt}(\Psi, s_1, s_2)SizeLt(Ψ,s1​,s2​) (written Ψ⊢s1<s2\Psi \vdash s_1 < s_2Ψ⊢s1​<s2​) is an inductive relation on s1,s2:SizeExps_1, s_2 : \text{SizeExp}s1​,s2​:SizeExp with seven constructors:
    1. inf_lt_inf: if n<mn < mn<m in N\mathbb{N}N, then Ψ⊢inf(n)<inf(m)\Psi \vdash \mathsf{inf}(n) < \mathsf{inf}(m)Ψ⊢inf(n)<inf(m).
    2. var_lt_var: if n<mn < mn<m in N\mathbb{N}N and SizeVarBound(Ψ,i,a)\text{SizeVarBound}(\Psi, i, a)SizeVarBound(Ψ,i,a) for some a:SizeExpa : \text{SizeExp}a:SizeExp, then Ψ⊢var(i,n)<var(i,m)\Psi \vdash \text{var}(i, n) < \text{var}(i, m)Ψ⊢var(i,n)<var(i,m).
    3. var_lt_inf: if SizeVarBound(Ψ,i,inf(0))\text{SizeVarBound}(\Psi, i, \mathsf{inf}(0))SizeVarBound(Ψ,i,inf(0)), then Ψ⊢var(i,n)<inf(m)\Psi \vdash \text{var}(i, n) < \mathsf{inf}(m)Ψ⊢var(i,n)<inf(m) for any n,m∈Nn, m \in \mathbb{N}n,m∈N.
    4. var_lt_inf_add: if SizeVarBound(Ψ,i,inf(m))\text{SizeVarBound}(\Psi, i, \mathsf{inf}(m))SizeVarBound(Ψ,i,inf(m)), then Ψ⊢var(i,n)<inf(m+n)\Psi \vdash \text{var}(i, n) < \mathsf{inf}(m + n)Ψ⊢var(i,n)<inf(m+n) for any n∈Nn \in \mathbb{N}n∈N.
    5. var_bound_step: if SizeVarBound(Ψ,i,a)\text{SizeVarBound}(\Psi, i, a)SizeVarBound(Ψ,i,a) and Ψ⊢a.shift(n)<b.shift(1)\Psi \vdash a.\text{shift}(n) < b.\text{shift}(1)Ψ⊢a.shift(n)<b.shift(1), then Ψ⊢var(i,n)<b\Psi \vdash \text{var}(i, n) < bΨ⊢var(i,n)<b.
    6. meet_lt_left: if SizeWf(Ψ,meet(a))\text{SizeWf}(\Psi, \mathsf{meet}(a))SizeWf(Ψ,meet(a)), sv∈a.toListsv \in a.\text{toList}sv∈a.toList, and Ψ⊢var(sv.var,sv.shift)<b\Psi \vdash \text{var}(sv.\text{var}, sv.\text{shift}) < bΨ⊢var(sv.var,sv.shift)<b, then Ψ⊢meet(a)<b\Psi \vdash \mathsf{meet}(a) < bΨ⊢meet(a)<b.
    7. lt_meet_right: if for every sv∈b.toListsv \in b.\text{toList}sv∈b.toList we have Ψ⊢a<var(sv.var,sv.shift)\Psi \vdash a < \text{var}(sv.\text{var}, sv.\text{shift})Ψ⊢a<var(sv.var,sv.shift), then Ψ⊢a<meet(b)\Psi \vdash a < \mathsf{meet}(b)Ψ⊢a<meet(b). (Note: lt_meet_right does not require SizeWf(Ψ,a)\text{SizeWf}(\Psi, a)SizeWf(Ψ,a).)
  • SizeLe(Ψ,a,b)\text{SizeLe}(\Psi, a, b)SizeLe(Ψ,a,b) (written Ψ⊢a≤b\Psi \vdash a \le bΨ⊢a≤b) is defined as SizeLt(Ψ,a,b.shift(1))\text{SizeLt}(\Psi, a, b.\text{shift}(1))SizeLt(Ψ,a,b.shift(1)).
  • SizeLePol(Ψ,π,a,b)\text{SizeLePol}(\Psi, \pi, a, b)SizeLePol(Ψ,π,a,b) is defined by cases on π\piπ: SizeLe(Ψ,a,b)∧SizeLe(Ψ,b,a)\text{SizeLe}(\Psi, a, b) \land \text{SizeLe}(\Psi, b, a)SizeLe(Ψ,a,b)∧SizeLe(Ψ,b,a) if π=mixed\pi = \mathsf{mixed}π=mixed; SizeLe(Ψ,a,b)\text{SizeLe}(\Psi, a, b)SizeLe(Ψ,a,b) if π=+\pi = +π=+; SizeLe(Ψ,b,a)\text{SizeLe}(\Psi, b, a)SizeLe(Ψ,b,a) if π=−\pi = -π=−; and True\mathsf{True}True if π=⊤\pi = \topπ=⊤.
  • SizeSubstWf(Ψ,as,Ψ′)\text{SizeSubstWf}(\Psi, \mathit{as}, \Psi')SizeSubstWf(Ψ,as,Ψ′) is an inductive relation between a context Ψ:SizeCtx\Psi : \text{SizeCtx}Ψ:SizeCtx, a list of size expressions as:List SizeExp\mathit{as} : \text{List SizeExp}as:List SizeExp, and a target context Ψ′:SizeCtx\Psi' : \text{SizeCtx}Ψ′:SizeCtx:
    1. nil: SizeSubstWf(Ψ,[],[])\text{SizeSubstWf}(\Psi, [], [])SizeSubstWf(Ψ,[],[]).
    2. snoc: if SizeSubstWf(Ψ,as,Ψ′)\text{SizeSubstWf}(\Psi, \mathit{as}, \Psi')SizeSubstWf(Ψ,as,Ψ′) and SizeLt(Ψ,a,d.bound.subst(Ψ′.dom.zip(as)))\text{SizeLt}(\Psi, a, d.\text{bound}.\text{subst}(\Psi'.\text{dom}.\text{zip}(\mathit{as})))SizeLt(Ψ,a,d.bound.subst(Ψ′.dom.zip(as))), then SizeSubstWf(Ψ,as+ ⁣ ⁣+[a],Ψ′+ ⁣ ⁣+[d])\text{SizeSubstWf}(\Psi, \mathit{as} \mathbin{+\!\!+} [a], \Psi' \mathbin{+\!\!+} [d])SizeSubstWf(Ψ,as++[a],Ψ′++[d]).

SKind, Kind, Kind.ofSKind, Kind.toSKind, KindWf, SubKind, KindLePol, and maxKindPol.

  • SKind is an inductive type of simple kinds with constructors ⋆\star⋆ (star), prop\mathsf{prop}prop (prop), and ι1→πι2\iota_1 \xrightarrow{\pi} \iota_2ι1​π​ι2​ (arr π ι₁ ι₂).
  • Kind is an inductive type of kinds with constructors ⋆\star⋆ (star), < a{<}\,a<a (lt a for a:SizeExpa : \text{SizeExp}a:SizeExp), and κ1→πκ2\kappa_1 \xrightarrow{\pi} \kappa_2κ1​π​κ2​ (arr π κ₁ κ₂).
  • Kind.ofSKind:SKind→Kind\text{Kind.ofSKind} : \text{SKind} \to \text{Kind}Kind.ofSKind:SKind→Kind maps both ⋆\star⋆ and prop\mathsf{prop}prop to ⋆\star⋆, and maps ι1→πι2\iota_1 \xrightarrow{\pi} \iota_2ι1​π​ι2​ to ofSKind(ι1)→πofSKind(ι2)\text{ofSKind}(\iota_1) \xrightarrow{\pi} \text{ofSKind}(\iota_2)ofSKind(ι1​)π​ofSKind(ι2​).
  • Kind.toSKind:Kind→SKind\text{Kind.toSKind} : \text{Kind} \to \text{SKind}Kind.toSKind:Kind→SKind maps both ⋆\star⋆ and < a{<}\,a<a to ⋆\star⋆, and maps κ1→πκ2\kappa_1 \xrightarrow{\pi} \kappa_2κ1​π​κ2​ to toSKind(κ1)→πtoSKind(κ2)\text{toSKind}(\kappa_1) \xrightarrow{\pi} \text{toSKind}(\kappa_2)toSKind(κ1​)π​toSKind(κ2​). (Thus prop\mathsf{prop}prop is never in the image of toSKind.)
  • KindWf(Ψ,κ)\text{KindWf}(\Psi, \kappa)KindWf(Ψ,κ) is an inductive predicate:
    1. star: KindWf(Ψ,⋆)\text{KindWf}(\Psi, \star)KindWf(Ψ,⋆) holds for any Ψ\PsiΨ.
    2. lt: if SizeWf(Ψ,a)\text{SizeWf}(\Psi, a)SizeWf(Ψ,a), then KindWf(Ψ,< a)\text{KindWf}(\Psi, {<}\,a)KindWf(Ψ,<a).
    3. arr: if KindWf(Ψ.scalePol(−),κ1)\text{KindWf}(\Psi.\text{scalePol}(-), \kappa_1)KindWf(Ψ.scalePol(−),κ1​) and KindWf(Ψ,κ2)\text{KindWf}(\Psi, \kappa_2)KindWf(Ψ,κ2​), then KindWf(Ψ,κ1→πκ2)\text{KindWf}(\Psi, \kappa_1 \xrightarrow{\pi} \kappa_2)KindWf(Ψ,κ1​π​κ2​) (regardless of the arrow polarity π\piπ).
  • SubKind(Ψ,κ,κ′)\text{SubKind}(\Psi, \kappa, \kappa')SubKind(Ψ,κ,κ′) (written Ψ⊢κ≤κ′\Psi \vdash \kappa \le \kappa'Ψ⊢κ≤κ′) is an inductive relation:
    1. star: Ψ⊢⋆≤⋆\Psi \vdash \star \le \starΨ⊢⋆≤⋆.
    2. lt: if SizeLe(Ψ,a,b)\text{SizeLe}(\Psi, a, b)SizeLe(Ψ,a,b), then Ψ⊢(< a)≤(< b)\Psi \vdash ({<}\,a) \le ({<}\,b)Ψ⊢(<a)≤(<b).
    3. arr: if π′≤π\pi' \le \piπ′≤π (Polarity.le π' π = true), SubKind(Ψ.scalePol(−),κ1′,κ1)\text{SubKind}(\Psi.\text{scalePol}(-), \kappa_1', \kappa_1)SubKind(Ψ.scalePol(−),κ1′​,κ1​), and SubKind(Ψ,κ2,κ2′)\text{SubKind}(\Psi, \kappa_2, \kappa_2')SubKind(Ψ,κ2​,κ2′​), then Ψ⊢(κ1→πκ2)≤(κ1′→π′κ2′)\Psi \vdash (\kappa_1 \xrightarrow{\pi} \kappa_2) \le (\kappa_1' \xrightarrow{\pi'} \kappa_2')Ψ⊢(κ1​π​κ2​)≤(κ1′​π′​κ2′​).
  • KindLePol(Ψ,π,κ,κ′)\text{KindLePol}(\Psi, \pi, \kappa, \kappa')KindLePol(Ψ,π,κ,κ′) is SubKind(Ψ,κ,κ′)∧SubKind(Ψ,κ′,κ)\text{SubKind}(\Psi, \kappa, \kappa') \land \text{SubKind}(\Psi, \kappa', \kappa)SubKind(Ψ,κ,κ′)∧SubKind(Ψ,κ′,κ) for π=mixed\pi = \mathsf{mixed}π=mixed; SubKind(Ψ,κ,κ′)\text{SubKind}(\Psi, \kappa, \kappa')SubKind(Ψ,κ,κ′) for π=+\pi = +π=+; SubKind(Ψ,κ′,κ)\text{SubKind}(\Psi, \kappa', \kappa)SubKind(Ψ,κ′,κ) for π=−\pi = -π=−; and True\mathsf{True}True for π=⊤\pi = \topπ=⊤.
  • maxKindPol(π,κ,κ′)\text{maxKindPol}(\pi, \kappa, \kappa')maxKindPol(π,κ,κ′) returns:
    • < inf(min⁡(n,m)){<}\,\mathsf{inf}(\min(n, m))<inf(min(n,m)) if π=−\pi = -π=−, κ=< inf(n)\kappa = {<}\,\mathsf{inf}(n)κ=<inf(n), and κ′=< inf(m)\kappa' = {<}\,\mathsf{inf}(m)κ′=<inf(m);
    • < inf(max⁡(n,m)){<}\,\mathsf{inf}(\max(n, m))<inf(max(n,m)) if π≠−\pi \neq -π=−, κ=< inf(n)\kappa = {<}\,\mathsf{inf}(n)κ=<inf(n), and κ′=< inf(m)\kappa' = {<}\,\mathsf{inf}(m)κ′=<inf(m);
    • < SizeExp.meetExp(a,b){<}\,\text{SizeExp.meetExp}(a, b)<SizeExp.meetExp(a,b) if π=−\pi = -π=−, κ=< a\kappa = {<}\,aκ=<a, and κ′=< b\kappa' = {<}\,bκ′=<b (not both inf\mathsf{inf}inf);
    • κ\kappaκ (ignoring κ′\kappa'κ′) in all other cases (including when π≠−\pi \neq -π=− and at least one of κ,κ′\kappa, \kappa'κ,κ′ is < meet(… ){<}\,\mathsf{meet}(\dots)<meet(…)).

TyVar, ConsName, ProjName, TyDecl, KindingCtx, and KindingCtx operations. TyVar, ConsName, and ProjName are aliases for N\mathbb{N}N. TyDecl is a structure with fields var :TyVar: \text{TyVar}:TyVar, pol :Polarity: \text{Polarity}:Polarity (default +++), and kind :Kind: \text{Kind}:Kind (default ⋆\star⋆). KindingCtx is a structure Δ=⟨Δ.sizes,Δ.types⟩\Delta = \langle \Delta.\text{sizes}, \Delta.\text{types} \rangleΔ=⟨Δ.sizes,Δ.types⟩ with fields sizes :SizeCtx: \text{SizeCtx}:SizeCtx (default [][][]) and types :List TyDecl: \text{List TyDecl}:List TyDecl (default [][][]).

  • KindingCtx.empty=⟨[],[]⟩\text{KindingCtx.empty} = \langle [], [] \rangleKindingCtx.empty=⟨[],[]⟩.
  • Δ.scalePol(π)\Delta.\text{scalePol}(\pi)Δ.scalePol(π) scales Δ.sizes\Delta.\text{sizes}Δ.sizes by π\piπ and replaces each (X,πd,κ)∈Δ.types(X, \pi_d, \kappa) \in \Delta.\text{types}(X,πd​,κ)∈Δ.types with (X,π⋅πd,κ)(X, \pi \cdot \pi_d, \kappa)(X,π⋅πd​,κ).
  • Δ.invScalePol(π)\Delta.\text{invScalePol}(\pi)Δ.invScalePol(π) inverse-scales Δ.sizes\Delta.\text{sizes}Δ.sizes by π\piπ and replaces each (X,πd,κ)∈Δ.types(X, \pi_d, \kappa) \in \Delta.\text{types}(X,πd​,κ)∈Δ.types with (X,π−1πd,κ)(X, \pi^{-1}\pi_d, \kappa)(X,π−1πd​,κ).
  • Δ.extType(X,π,κ)\Delta.\text{extType}(X, \pi, \kappa)Δ.extType(X,π,κ) appends ⟨X,π,a⟩\langle X, \pi, a \rangle⟨X,π,a⟩ to Δ.sizes\Delta.\text{sizes}Δ.sizes AND ⟨X,π,< a⟩\langle X, \pi, {<}\,a \rangle⟨X,π,<a⟩ to Δ.types\Delta.\text{types}Δ.types when κ=< a\kappa = {<}\,aκ=<a; for any other kind κ\kappaκ, it leaves Δ.sizes\Delta.\text{sizes}Δ.sizes unchanged and appends ⟨X,π,κ⟩\langle X, \pi, \kappa \rangle⟨X,π,κ⟩ to Δ.types\Delta.\text{types}Δ.types.
  • Δ.extSizes(Ψ)\Delta.\text{extSizes}(\Psi)Δ.extSizes(Ψ) appends Ψ\PsiΨ to Δ.sizes\Delta.\text{sizes}Δ.sizes and appends [⟨d.var,d.pol,< d.bound⟩∣d∈Ψ][\langle d.\text{var}, d.\text{pol}, {<}\,d.\text{bound} \rangle \mid d \in \Psi][⟨d.var,d.pol,<d.bound⟩∣d∈Ψ] to Δ.types\Delta.\text{types}Δ.types.
  • Δ.extDecls(Δ′)\Delta.\text{extDecls}(\Delta')Δ.extDecls(Δ′) left-folds extType over the declarations in Δ′:List TyDecl\Delta' : \text{List TyDecl}Δ′:List TyDecl.
  • Δ1.append(Δ2)\Delta_1.\text{append}(\Delta_2)Δ1​.append(Δ2​) directly concatenates ⟨Δ1.sizes+ ⁣ ⁣+Δ2.sizes,Δ1.types+ ⁣ ⁣+Δ2.types⟩\langle \Delta_1.\text{sizes} \mathbin{+\!\!+} \Delta_2.\text{sizes}, \Delta_1.\text{types} \mathbin{+\!\!+} \Delta_2.\text{types} \rangle⟨Δ1​.sizes++Δ2​.sizes,Δ1​.types++Δ2​.types⟩ (without promoting < a{<}\,a<a declarations in Δ2.types\Delta_2.\text{types}Δ2​.types into sizes).

TyAtom, TypeExpr, derived type constructors, substitutions (substTyVar, normApp, substSizes), and branch lookup (lookupCons, lookupProj).

  • TyAtom is an inductive type with constructors size(a)\mathsf{size}(a)size(a) (a:SizeExpa : \text{SizeExp}a:SizeExp), var(X)\mathsf{var}(X)var(X) (X:TyVarX : \text{TyVar}X:TyVar), unit\mathsf{unit}unit, prod\mathsf{prod}prod, arr\mathsf{arr}arr, all(κ)\mathsf{all}(\kappa)all(κ) (κ:Kind\kappa : \text{Kind}κ:Kind), and ex(κ)\mathsf{ex}(\kappa)ex(κ) (κ:Kind\kappa : \text{Kind}κ:Kind).
  • TypeExpr is an inductive type with constructors:
    • atom(K)\mathsf{atom}(K)atom(K) for K:TyAtomK : \text{TyAtom}K:TyAtom,
    • λX:ι. F\lambda X : \iota.\, FλX:ι.F (lam X ι F) for X:TyVarX : \text{TyVar}X:TyVar, ι:SKind\iota : \text{SKind}ι:SKind, F:TypeExprF : \text{TypeExpr}F:TypeExpr,
    • F1 F2F_1\,F_2F1​F2​ (app F₁ F₂) for F1,F2:TypeExprF_1, F_2 : \text{TypeExpr}F1​,F2​:TypeExpr,
    • μaS\mu^a SμaS (mu a S) for a:SizeExpa : \text{SizeExp}a:SizeExp and S:List(N×TypeExpr)S : \text{List}(\mathbb{N} \times \text{TypeExpr})S:List(N×TypeExpr),
    • νaR\nu^a RνaR (nu a R) for a:SizeExpa : \text{SizeExp}a:SizeExp and R:List(N×TypeExpr)R : \text{List}(\mathbb{N} \times \text{TypeExpr})R:List(N×TypeExpr).
  • Derived abbreviations on TypeExpr:
    • unitTy=atom(unit)\text{unitTy} = \mathsf{atom}(\mathsf{unit})unitTy=atom(unit),
    • prodTy(A1,A2)=atom(prod) A1 A2\text{prodTy}(A_1, A_2) = \mathsf{atom}(\mathsf{prod})\,A_1\,A_2prodTy(A1​,A2​)=atom(prod)A1​A2​,
    • arrTy(A,B)=atom(arr) A B\text{arrTy}(A, B) = \mathsf{atom}(\mathsf{arr})\,A\,BarrTy(A,B)=atom(arr)AB,
    • allTy(κ,F)=atom(all(κ)) F\text{allTy}(\kappa, F) = \mathsf{atom}(\mathsf{all}(\kappa))\,FallTy(κ,F)=atom(all(κ))F,
    • exTy(κ,F)=atom(ex(κ)) F\text{exTy}(\kappa, F) = \mathsf{atom}(\mathsf{ex}(\kappa))\,FexTy(κ,F)=atom(ex(κ))F,
    • forallSizeLt(j,a,B)=allTy(< a,λj:⋆. B)\text{forallSizeLt}(j, a, B) = \text{allTy}({<}\,a, \lambda j : \star.\, B)forallSizeLt(j,a,B)=allTy(<a,λj:⋆.B),
    • existsSizeLt(j,a,B)=exTy(< a,λj:⋆. B)\text{existsSizeLt}(j, a, B) = \text{exTy}({<}\,a, \lambda j : \star.\, B)existsSizeLt(j,a,B)=exTy(<a,λj:⋆.B),
    • forallSizes(Ψ,A)\text{forallSizes}(\Psi, A)forallSizes(Ψ,A) right-folds forallSizeLt(d.var,d.bound,−)\text{forallSizeLt}(d.\text{var}, d.\text{bound}, -)forallSizeLt(d.var,d.bound,−) over d∈Ψd \in \Psid∈Ψ around AAA.
  • TypeExpr.substTyVar(X,G,E)\text{TypeExpr.substTyVar}(X, G, E)TypeExpr.substTyVar(X,G,E) (and mutually recursive substTyVarBranches) replaces every free occurrence of atom(var(X))\mathsf{atom}(\mathsf{var}(X))atom(var(X)) in EEE with GGG, stopping under λY:ι. body\lambda Y : \iota.\,\text{body}λY:ι.body when Y=XY = XY=X. Note two critical syntactic properties: (1) it is not capture-avoiding if GGG contains free variables bound by an enclosing λY\lambda YλY; and (2) it leaves all SizeExp annotations aaa inside atom(size(a))\mathsf{atom}(\mathsf{size}(a))atom(size(a)), all(< a)\mathsf{all}({<}\,a)all(<a), ex(< a)\mathsf{ex}({<}\,a)ex(<a), μaS\mu^a SμaS, and νaR\nu^a RνaR completely untouched. Consequently, if jjj is bound by λj:⋆. B\lambda j : \star.\, Bλj:⋆.B in forallSizeLt(j,a,B)\text{forallSizeLt}(j, a, B)forallSizeLt(j,a,B) or existsSizeLt(j,a,B)\text{existsSizeLt}(j, a, B)existsSizeLt(j,a,B) and jjj occurs as a SizeVar inside a size expression in BBB (such as μvar(j,0)S\mu^{\text{var}(j, 0)} Sμvar(j,0)S), substTyVar does not substitute into that SizeVar occurrence.
  • TypeExpr.normApp(F,G)\text{TypeExpr.normApp}(F, G)TypeExpr.normApp(F,G) returns substTyVar(X,G,body)\text{substTyVar}(X, G, \text{body})substTyVar(X,G,body) if F=λX:ι. bodyF = \lambda X : \iota.\,\text{body}F=λX:ι.body, and app(F,G)\mathsf{app}(F, G)app(F,G) otherwise.
  • TypeExpr.substSizes(σ,E)\text{TypeExpr.substSizes}(\sigma, E)TypeExpr.substSizes(σ,E) (and substSizesBranches) applies SizeExp.subst(σ)\text{SizeExp.subst}(\sigma)SizeExp.subst(σ) to every size expression aaa in atom(size(a))\mathsf{atom}(\mathsf{size}(a))atom(size(a)), atom(all(< a))\mathsf{atom}(\mathsf{all}({<}\,a))atom(all(<a)), atom(ex(< a))\mathsf{atom}(\mathsf{ex}({<}\,a))atom(ex(<a)), μaS\mu^a SμaS, and νaR\nu^a RνaR, recurring under λX:ι. body\lambda X : \iota.\,\text{body}λX:ι.body without removing XXX from σ\sigmaσ, and leaving atom(var(X))\mathsf{atom}(\mathsf{var}(X))atom(var(X)) untouched.
  • TypeExpr.lookupCons(S,c)\text{TypeExpr.lookupCons}(S, c)TypeExpr.lookupCons(S,c) and TypeExpr.lookupProj(R,d)\text{TypeExpr.lookupProj}(R, d)TypeExpr.lookupProj(R,d) return the second component of the first pair in SSS (resp. RRR) whose first component equals ccc (resp. ddd), as an Option TypeExpr.
  • functorKind\text{functorKind}functorKind is defined as ⋆→mixed⋆\star \xrightarrow{\mathsf{mixed}} \star⋆mixed​⋆.

KindInfer, KindCheck, KindingCtxExtWf, TermVar, TermCtx, and TermCtxWf.

  • KindInfer(Δ,F,κ)\text{KindInfer}(\Delta, F, \kappa)KindInfer(Δ,F,κ) (written Δ⊢F⇒κ\Delta \vdash F \Rightarrow \kappaΔ⊢F⇒κ) and KindCheck(Δ,F,κ)\text{KindCheck}(\Delta, F, \kappa)KindCheck(Δ,F,κ) (written Δ⊢F⇐κ\Delta \vdash F \Leftarrow \kappaΔ⊢F⇐κ) are mutually inductive judgments on Δ:KindingCtx\Delta : \text{KindingCtx}Δ:KindingCtx, F:TypeExprF : \text{TypeExpr}F:TypeExpr, and κ:Kind\kappa : \text{Kind}κ:Kind:
    • KindInfer.unit: Δ⊢atom(unit)⇒⋆\Delta \vdash \mathsf{atom}(\mathsf{unit}) \Rightarrow \starΔ⊢atom(unit)⇒⋆.
    • KindInfer.prod: Δ⊢atom(prod)⇒⋆→+(⋆→+⋆)\Delta \vdash \mathsf{atom}(\mathsf{prod}) \Rightarrow \star \xrightarrow{+} (\star \xrightarrow{+} \star)Δ⊢atom(prod)⇒⋆+​(⋆+​⋆).
    • KindInfer.arr: Δ⊢atom(arr)⇒⋆→−(⋆→+⋆)\Delta \vdash \mathsf{atom}(\mathsf{arr}) \Rightarrow \star \xrightarrow{-} (\star \xrightarrow{+} \star)Δ⊢atom(arr)⇒⋆−​(⋆+​⋆).
    • KindInfer.size: if SizeWf(Δ.sizes,a)\text{SizeWf}(\Delta.\text{sizes}, a)SizeWf(Δ.sizes,a), then Δ⊢atom(size(a))⇒< (a.shift(1))\Delta \vdash \mathsf{atom}(\mathsf{size}(a)) \Rightarrow {<}\,(a.\text{shift}(1))Δ⊢atom(size(a))⇒<(a.shift(1)).
    • KindInfer.var: if ⟨X,π,κ⟩∈Δ.types\langle X, \pi, \kappa \rangle \in \Delta.\text{types}⟨X,π,κ⟩∈Δ.types and π≤+\pi \le +π≤+, then Δ⊢atom(var(X))⇒κ\Delta \vdash \mathsf{atom}(\mathsf{var}(X)) \Rightarrow \kappaΔ⊢atom(var(X))⇒κ.
    • KindInfer.app: if Δ⊢F⇒(κ→πκ′)\Delta \vdash F \Rightarrow (\kappa \xrightarrow{\pi} \kappa')Δ⊢F⇒(κπ​κ′) and Δ.invScalePol(π)⊢G⇐κ\Delta.\text{invScalePol}(\pi) \vdash G \Leftarrow \kappaΔ.invScalePol(π)⊢G⇐κ, then Δ⊢F G⇒κ′\Delta \vdash F\,G \Rightarrow \kappa'Δ⊢FG⇒κ′.
    • KindInfer.all: if KindWf(Δ.sizes.scalePol(−),κ)\text{KindWf}(\Delta.\text{sizes}.\text{scalePol}(-), \kappa)KindWf(Δ.sizes.scalePol(−),κ), then Δ⊢atom(all(κ))⇒(κ→mixed⋆)→+⋆\Delta \vdash \mathsf{atom}(\mathsf{all}(\kappa)) \Rightarrow (\kappa \xrightarrow{\mathsf{mixed}} \star) \xrightarrow{+} \starΔ⊢atom(all(κ))⇒(κmixed​⋆)+​⋆.
    • KindInfer.ex: if KindWf(Δ.sizes,κ)\text{KindWf}(\Delta.\text{sizes}, \kappa)KindWf(Δ.sizes,κ), then Δ⊢atom(ex(κ))⇒(κ→mixed⋆)→+⋆\Delta \vdash \mathsf{atom}(\mathsf{ex}(\kappa)) \Rightarrow (\kappa \xrightarrow{\mathsf{mixed}} \star) \xrightarrow{+} \starΔ⊢atom(ex(κ))⇒(κmixed​⋆)+​⋆.
    • KindInfer.mu: if SizeWf(Δ.sizes,a)\text{SizeWf}(\Delta.\text{sizes}, a)SizeWf(Δ.sizes,a) and ∀p∈S,  Δ⊢p.2⇐(⋆→mixed⋆)\forall p \in S,\; \Delta \vdash p.2 \Leftarrow (\star \xrightarrow{\mathsf{mixed}} \star)∀p∈S,Δ⊢p.2⇐(⋆mixed​⋆), then Δ⊢μaS⇒⋆\Delta \vdash \mu^a S \Rightarrow \starΔ⊢μaS⇒⋆.
    • KindInfer.nu: if SizeWf(Δ.sizes.scalePol(−),a)\text{SizeWf}(\Delta.\text{sizes}.\text{scalePol}(-), a)SizeWf(Δ.sizes.scalePol(−),a) and ∀p∈R,  Δ⊢p.2⇐(⋆→mixed⋆)\forall p \in R,\; \Delta \vdash p.2 \Leftarrow (\star \xrightarrow{\mathsf{mixed}} \star)∀p∈R,Δ⊢p.2⇐(⋆mixed​⋆), then Δ⊢νaR⇒⋆\Delta \vdash \nu^a R \Rightarrow \starΔ⊢νaR⇒⋆.
    • KindCheck.sub: if Δ⊢F⇒κ\Delta \vdash F \Rightarrow \kappaΔ⊢F⇒κ and SubKind(Δ.sizes,κ,κ′)\text{SubKind}(\Delta.\text{sizes}, \kappa, \kappa')SubKind(Δ.sizes,κ,κ′), then Δ⊢F⇐κ′\Delta \vdash F \Leftarrow \kappa'Δ⊢F⇐κ′.
    • KindCheck.lam: if KindWf(Δ.sizes.invScalePol(mixed),Kind.ofSKind(ι))\text{KindWf}(\Delta.\text{sizes}.\text{invScalePol}(\mathsf{mixed}), \text{Kind.ofSKind}(\iota))KindWf(Δ.sizes.invScalePol(mixed),Kind.ofSKind(ι)) and Δ.extType(X,π,κ)⊢F⇐κ′\Delta.\text{extType}(X, \pi, \kappa) \vdash F \Leftarrow \kappa'Δ.extType(X,π,κ)⊢F⇐κ′, then Δ⊢(λX:ι. F)⇐(κ→πκ′)\Delta \vdash (\lambda X : \iota.\, F) \Leftarrow (\kappa \xrightarrow{\pi} \kappa')Δ⊢(λX:ι.F)⇐(κπ​κ′). (Note: Kind.ofSKind(ι)\text{Kind.ofSKind}(\iota)Kind.ofSKind(ι) contains only ⋆\star⋆ and arrows, so its KindWf premise is always trivially provable; moreover, the rule imposes no requirement that Kind.ofSKind(ι)\text{Kind.ofSKind}(\iota)Kind.ofSKind(ι) match κ\kappaκ.)
  • KindingCtxExtWf(Δ,Δ′)\text{KindingCtxExtWf}(\Delta, \Delta')KindingCtxExtWf(Δ,Δ′) holds inductively for [][][], and for d::restd :: \text{rest}d::rest when KindWf(Δ.sizes.invScalePol(mixed),d.kind)\text{KindWf}(\Delta.\text{sizes}.\text{invScalePol}(\mathsf{mixed}), d.\text{kind})KindWf(Δ.sizes.invScalePol(mixed),d.kind) and KindingCtxExtWf(Δ.extType(d.var,d.pol,d.kind),rest)\text{KindingCtxExtWf}(\Delta.\text{extType}(d.\text{var}, d.\text{pol}, d.\text{kind}), \text{rest})KindingCtxExtWf(Δ.extType(d.var,d.pol,d.kind),rest).
  • TermVar is N\mathbb{N}N and TermCtx is List(TermVar×TypeExpr)\text{List}(\text{TermVar} \times \text{TypeExpr})List(TermVar×TypeExpr). TermCtxWf(Δ,Γ)\text{TermCtxWf}(\Delta, \Gamma)TermCtxWf(Δ,Γ) holds inductively for [][][], and for Γ+ ⁣ ⁣+[(x,A)]\Gamma \mathbin{+\!\!+} [(x, A)]Γ++[(x,A)] when TermCtxWf(Δ,Γ)\text{TermCtxWf}(\Delta, \Gamma)TermCtxWf(Δ,Γ) and Δ⊢A⇐⋆\Delta \vdash A \Leftarrow \starΔ⊢A⇐⋆ (without requiring xxx to be fresh).

SubTypeInfer, SubTypeCheck, and SubType. SubTypeInfer(Δ,π,F,F′,κ)\text{SubTypeInfer}(\Delta, \pi, F, F', \kappa)SubTypeInfer(Δ,π,F,F′,κ) and SubTypeCheck(Δ,π,F,F′,κ)\text{SubTypeCheck}(\Delta, \pi, F, F', \kappa)SubTypeCheck(Δ,π,F,F′,κ) are mutually inductive judgments on Δ:KindingCtx\Delta : \text{KindingCtx}Δ:KindingCtx, π:Polarity\pi : \text{Polarity}π:Polarity, F,F′:TypeExprF, F' : \text{TypeExpr}F,F′:TypeExpr, and κ:Kind\kappa : \text{Kind}κ:Kind:

  • SubTypeInfer.atom: if π≠⊤\pi \neq \topπ=⊤ and Δ⊢atom(K)⇒κ\Delta \vdash \mathsf{atom}(K) \Rightarrow \kappaΔ⊢atom(K)⇒κ, then SubTypeInfer(Δ,π,atom(K),atom(K),κ)\text{SubTypeInfer}(\Delta, \pi, \mathsf{atom}(K), \mathsf{atom}(K), \kappa)SubTypeInfer(Δ,π,atom(K),atom(K),κ).
  • SubTypeInfer.app: if π≠⊤\pi \neq \topπ=⊤, SubTypeInfer(Δ,π,F,F′,κ1→π1κ2)\text{SubTypeInfer}(\Delta, \pi, F, F', \kappa_1 \xrightarrow{\pi_1} \kappa_2)SubTypeInfer(Δ,π,F,F′,κ1​π1​​κ2​), and SubTypeCheck(Δ.invScalePol(π1),π1⋅π,G,G′,κ1)\text{SubTypeCheck}(\Delta.\text{invScalePol}(\pi_1), \pi_1 \cdot \pi, G, G', \kappa_1)SubTypeCheck(Δ.invScalePol(π1​),π1​⋅π,G,G′,κ1​), then SubTypeInfer(Δ,π,F G,F′ G′,κ2)\text{SubTypeInfer}(\Delta, \pi, F\,G, F'\,G', \kappa_2)SubTypeInfer(Δ,π,FG,F′G′,κ2​).
  • SubTypeInfer.all: if π≠⊤\pi \neq \topπ=⊤ and KindLePol(Δ.sizes.scalePol(−),(−)⋅π,κ,κ′)\text{KindLePol}(\Delta.\text{sizes}.\text{scalePol}(-), (-) \cdot \pi, \kappa, \kappa')KindLePol(Δ.sizes.scalePol(−),(−)⋅π,κ,κ′), then
SubTypeInfer(Δ,π,atom(all(κ)),atom(all(κ′)),(maxKindPol((−)⋅π,κ,κ′)→mixed⋆)→−⋆).\text{SubTypeInfer}\big(\Delta, \pi, \mathsf{atom}(\mathsf{all}(\kappa)), \mathsf{atom}(\mathsf{all}(\kappa')), (\text{maxKindPol}((-) \cdot \pi, \kappa, \kappa') \xrightarrow{\mathsf{mixed}} \star) \xrightarrow{-} \star\big).SubTypeInfer(Δ,π,atom(all(κ)),atom(all(κ′)),(maxKindPol((−)⋅π,κ,κ′)mixed​⋆)−​⋆).

(Note that the outer arrow polarity here is −-−, whereas in KindInfer.all the outer arrow polarity of atom(all(κ))\mathsf{atom}(\mathsf{all}(\kappa))atom(all(κ)) is +++.)

  • SubTypeInfer.ex: if π≠⊤\pi \neq \topπ=⊤ and KindLePol(Δ.sizes,π,κ,κ′)\text{KindLePol}(\Delta.\text{sizes}, \pi, \kappa, \kappa')KindLePol(Δ.sizes,π,κ,κ′), then
SubTypeInfer(Δ,π,atom(ex(κ)),atom(ex(κ′)),(maxKindPol(π,κ,κ′)→mixed⋆)→+⋆).\text{SubTypeInfer}\big(\Delta, \pi, \mathsf{atom}(\mathsf{ex}(\kappa)), \mathsf{atom}(\mathsf{ex}(\kappa')), (\text{maxKindPol}(\pi, \kappa, \kappa') \xrightarrow{\mathsf{mixed}} \star) \xrightarrow{+} \star\big).SubTypeInfer(Δ,π,atom(ex(κ)),atom(ex(κ′)),(maxKindPol(π,κ,κ′)mixed​⋆)+​⋆).
  • SubTypeInfer.mu: if π≠⊤\pi \neq \topπ=⊤, SizeLePol(Δ.sizes,π,a.boundNorm,a′.boundNorm)\text{SizeLePol}(\Delta.\text{sizes}, \pi, a.\text{boundNorm}, a'.\text{boundNorm})SizeLePol(Δ.sizes,π,a.boundNorm,a′.boundNorm), S.map(⋅.1)=S′.map(⋅.1)S.\text{map}(\cdot.1) = S'.\text{map}(\cdot.1)S.map(⋅.1)=S′.map(⋅.1), and for all c,F,F′c, F, F'c,F,F′ with lookupCons(S,c)=some F\text{lookupCons}(S, c) = \text{some } FlookupCons(S,c)=some F and lookupCons(S′,c)=some F′\text{lookupCons}(S', c) = \text{some } F'lookupCons(S′,c)=some F′ we have SubTypeCheck(Δ,π,F,F′,functorKind)\text{SubTypeCheck}(\Delta, \pi, F, F', \text{functorKind})SubTypeCheck(Δ,π,F,F′,functorKind), then SubTypeInfer(Δ,π,μaS,μa′S′,⋆)\text{SubTypeInfer}(\Delta, \pi, \mu^a S, \mu^{a'} S', \star)SubTypeInfer(Δ,π,μaS,μa′S′,⋆).
  • SubTypeInfer.nu: if π≠⊤\pi \neq \topπ=⊤, SizeLePol(Δ.sizes.scalePol(−),(−)⋅π,a.boundNorm,a′.boundNorm)\text{SizeLePol}(\Delta.\text{sizes}.\text{scalePol}(-), (-) \cdot \pi, a.\text{boundNorm}, a'.\text{boundNorm})SizeLePol(Δ.sizes.scalePol(−),(−)⋅π,a.boundNorm,a′.boundNorm), R.map(⋅.1)=R′.map(⋅.1)R.\text{map}(\cdot.1) = R'.\text{map}(\cdot.1)R.map(⋅.1)=R′.map(⋅.1), and for all d,F,F′d, F, F'd,F,F′ with lookupProj(R,d)=some F\text{lookupProj}(R, d) = \text{some } FlookupProj(R,d)=some F and lookupProj(R′,d)=some F′\text{lookupProj}(R', d) = \text{some } F'lookupProj(R′,d)=some F′ we have SubTypeCheck(Δ,π,F,F′,functorKind)\text{SubTypeCheck}(\Delta, \pi, F, F', \text{functorKind})SubTypeCheck(Δ,π,F,F′,functorKind), then SubTypeInfer(Δ,π,νaR,νa′R′,⋆)\text{SubTypeInfer}(\Delta, \pi, \nu^a R, \nu^{a'} R', \star)SubTypeInfer(Δ,π,νaR,νa′R′,⋆).
  • SubTypeCheck.top: SubTypeCheck(Δ,⊤,F,F′,κ)\text{SubTypeCheck}(\Delta, \top, F, F', \kappa)SubTypeCheck(Δ,⊤,F,F′,κ) holds unconditionally.
  • SubTypeCheck.star: if SubTypeInfer(Δ,π,A,A′,⋆)\text{SubTypeInfer}(\Delta, \pi, A, A', \star)SubTypeInfer(Δ,π,A,A′,⋆), then SubTypeCheck(Δ,π,A,A′,⋆)\text{SubTypeCheck}(\Delta, \pi, A, A', \star)SubTypeCheck(Δ,π,A,A′,⋆).
  • SubTypeCheck.arr: if KindWf(Δ.sizes.invScalePol(mixed),κ1)\text{KindWf}(\Delta.\text{sizes}.\text{invScalePol}(\mathsf{mixed}), \kappa_1)KindWf(Δ.sizes.invScalePol(mixed),κ1​) and there exists X:TyVarX : \text{TyVar}X:TyVar (with no freshness constraint on XXX) such that SubTypeCheck(Δ.extType(X,π1,κ1),π,F.normApp(atom(var(X))),F′.normApp(atom(var(X))),κ2)\text{SubTypeCheck}(\Delta.\text{extType}(X, \pi_1, \kappa_1), \pi, F.\text{normApp}(\mathsf{atom}(\mathsf{var}(X))), F'.\text{normApp}(\mathsf{atom}(\mathsf{var}(X))), \kappa_2)SubTypeCheck(Δ.extType(X,π1​,κ1​),π,F.normApp(atom(var(X))),F′.normApp(atom(var(X))),κ2​), then SubTypeCheck(Δ,π,F,F′,κ1→π1κ2)\text{SubTypeCheck}(\Delta, \pi, F, F', \kappa_1 \xrightarrow{\pi_1} \kappa_2)SubTypeCheck(Δ,π,F,F′,κ1​π1​​κ2​).
  • SubType(Δ,A,A′)\text{SubType}(\Delta, A, A')SubType(Δ,A,A′) is defined as SubTypeInfer(Δ,+,A,A′,⋆)\text{SubTypeInfer}(\Delta, +, A, A', \star)SubTypeInfer(Δ,+,A,A′,⋆).

Pat, Copat, PatSpine, PatTyping, and SpineTyping.

  • Pat is an inductive type of patterns with constructors var(x)\mathsf{var}(x)var(x) (x:TermVarx : \text{TermVar}x:TermVar), unit\mathsf{unit}unit, pair(p1,p2)\mathsf{pair}(p_1, p_2)pair(p1​,p2​), cons(c,p)\mathsf{cons}(c, p)cons(c,p) (c:ConsNamec : \text{ConsName}c:ConsName), and tyPack(X,p)\mathsf{tyPack}(X, p)tyPack(X,p) (X:TyVarX : \text{TyVar}X:TyVar).
  • Copat is an inductive type of copatterns with constructors pat(p)\mathsf{pat}(p)pat(p) (p:Patp : \text{Pat}p:Pat), tyVar(X)\mathsf{tyVar}(X)tyVar(X) (X:TyVarX : \text{TyVar}X:TyVar), and proj(d)\mathsf{proj}(d)proj(d) (d:ProjNamed : \text{ProjName}d:ProjName). PatSpine is List Copat\text{List Copat}List Copat.
  • PatTyping(Δ0,Δ,Γ,p,A)\text{PatTyping}(\Delta_0, \Delta, \Gamma, p, A)PatTyping(Δ0​,Δ,Γ,p,A) is an inductive relation on Δ0:KindingCtx\Delta_0 : \text{KindingCtx}Δ0​:KindingCtx, Δ:List TyDecl\Delta : \text{List TyDecl}Δ:List TyDecl, Γ:TermCtx\Gamma : \text{TermCtx}Γ:TermCtx, p:Patp : \text{Pat}p:Pat, and A:TypeExprA : \text{TypeExpr}A:TypeExpr:
    1. var: PatTyping(Δ0,[],[(x,A)],var(x),A)\text{PatTyping}(\Delta_0, [], [(x, A)], \mathsf{var}(x), A)PatTyping(Δ0​,[],[(x,A)],var(x),A).
    2. unit: PatTyping(Δ0,[],[],unit,unitTy)\text{PatTyping}(\Delta_0, [], [], \mathsf{unit}, \text{unitTy})PatTyping(Δ0​,[],[],unit,unitTy).
    3. pair: if PatTyping(Δ0,Δ1,Γ1,p1,A1)\text{PatTyping}(\Delta_0, \Delta_1, \Gamma_1, p_1, A_1)PatTyping(Δ0​,Δ1​,Γ1​,p1​,A1​) and PatTyping(Δ0,Δ2,Γ2,p2,A2)\text{PatTyping}(\Delta_0, \Delta_2, \Gamma_2, p_2, A_2)PatTyping(Δ0​,Δ2​,Γ2​,p2​,A2​), then PatTyping(Δ0,Δ1+ ⁣ ⁣+Δ2,Γ1+ ⁣ ⁣+Γ2,pair(p1,p2),prodTy(A1,A2))\text{PatTyping}(\Delta_0, \Delta_1 \mathbin{+\!\!+} \Delta_2, \Gamma_1 \mathbin{+\!\!+} \Gamma_2, \mathsf{pair}(p_1, p_2), \text{prodTy}(A_1, A_2))PatTyping(Δ0​,Δ1​++Δ2​,Γ1​++Γ2​,pair(p1​,p2​),prodTy(A1​,A2​)). (Note that p2p_2p2​ is typed under Δ0\Delta_0Δ0​, not Δ0\Delta_0Δ0​ extended by Δ1\Delta_1Δ1​.)
    4. cons: if lookupCons(S,c)=some Sc\text{lookupCons}(S, c) = \text{some } S_clookupCons(S,c)=some Sc​ and PatTyping(Δ0,Δ,Γ,p,existsSizeLt(j,a.boundNorm,Sc.normApp(μvar(j,0)S)))\text{PatTyping}(\Delta_0, \Delta, \Gamma, p, \text{existsSizeLt}(j, a.\text{boundNorm}, S_c.\text{normApp}(\mu^{\text{var}(j, 0)} S)))PatTyping(Δ0​,Δ,Γ,p,existsSizeLt(j,a.boundNorm,Sc​.normApp(μvar(j,0)S))) for some j:SizeVarj : \text{SizeVar}j:SizeVar, then PatTyping(Δ0,Δ,Γ,cons(c,p),μaS)\text{PatTyping}(\Delta_0, \Delta, \Gamma, \mathsf{cons}(c, p), \mu^a S)PatTyping(Δ0​,Δ,Γ,cons(c,p),μaS).
    5. tyPack: if PatTyping(Δ0.extType(X,+,κ),Δ,Γ,p,F.normApp(atom(var(X))))\text{PatTyping}(\Delta_0.\text{extType}(X, +, \kappa), \Delta, \Gamma, p, F.\text{normApp}(\mathsf{atom}(\mathsf{var}(X))))PatTyping(Δ0​.extType(X,+,κ),Δ,Γ,p,F.normApp(atom(var(X)))), then PatTyping(Δ0,⟨X,+,κ⟩::Δ,Γ,tyPack(X,p),exTy(κ,F))\text{PatTyping}(\Delta_0, \langle X, +, \kappa \rangle :: \Delta, \Gamma, \mathsf{tyPack}(X, p), \text{exTy}(\kappa, F))PatTyping(Δ0​,⟨X,+,κ⟩::Δ,Γ,tyPack(X,p),exTy(κ,F)).
  • SpineTyping(Δ0,Δ,Γ,A,qs,C)\text{SpineTyping}(\Delta_0, \Delta, \Gamma, A, \mathit{qs}, C)SpineTyping(Δ0​,Δ,Γ,A,qs,C) is an inductive relation:
    1. nil: SpineTyping(Δ0,[],[],C,[],C)\text{SpineTyping}(\Delta_0, [], [], C, [], C)SpineTyping(Δ0​,[],[],C,[],C).
    2. pat: if PatTyping(Δ0,Δ1,Γ1,p,A)\text{PatTyping}(\Delta_0, \Delta_1, \Gamma_1, p, A)PatTyping(Δ0​,Δ1​,Γ1​,p,A) and SpineTyping(Δ0,Δ2,Γ2,B,qs,C)\text{SpineTyping}(\Delta_0, \Delta_2, \Gamma_2, B, \mathit{qs}, C)SpineTyping(Δ0​,Δ2​,Γ2​,B,qs,C), then SpineTyping(Δ0,Δ1+ ⁣ ⁣+Δ2,Γ1+ ⁣ ⁣+Γ2,arrTy(A,B),pat(p)::qs,C)\text{SpineTyping}(\Delta_0, \Delta_1 \mathbin{+\!\!+} \Delta_2, \Gamma_1 \mathbin{+\!\!+} \Gamma_2, \text{arrTy}(A, B), \mathsf{pat}(p) :: \mathit{qs}, C)SpineTyping(Δ0​,Δ1​++Δ2​,Γ1​++Γ2​,arrTy(A,B),pat(p)::qs,C). (Again, qs\mathit{qs}qs is typed under Δ0\Delta_0Δ0​ without extending by Δ1\Delta_1Δ1​.)
    3. proj: if lookupProj(R,d)=some Rd\text{lookupProj}(R, d) = \text{some } R_dlookupProj(R,d)=some Rd​ and SpineTyping(Δ0,Δ,Γ,forallSizeLt(j,a.boundNorm,Rd.normApp(νvar(j,0)R)),qs,C)\text{SpineTyping}(\Delta_0, \Delta, \Gamma, \text{forallSizeLt}(j, a.\text{boundNorm}, R_d.\text{normApp}(\nu^{\text{var}(j, 0)} R)), \mathit{qs}, C)SpineTyping(Δ0​,Δ,Γ,forallSizeLt(j,a.boundNorm,Rd​.normApp(νvar(j,0)R)),qs,C) for some j:SizeVarj : \text{SizeVar}j:SizeVar, then SpineTyping(Δ0,Δ,Γ,νaR,proj(d)::qs,C)\text{SpineTyping}(\Delta_0, \Delta, \Gamma, \nu^a R, \mathsf{proj}(d) :: \mathit{qs}, C)SpineTyping(Δ0​,Δ,Γ,νaR,proj(d)::qs,C).
    4. tyVar: if SpineTyping(Δ0.extType(X,+,κ),Δ,Γ,F.normApp(atom(var(X))),qs,C)\text{SpineTyping}(\Delta_0.\text{extType}(X, +, \kappa), \Delta, \Gamma, F.\text{normApp}(\mathsf{atom}(\mathsf{var}(X))), \mathit{qs}, C)SpineTyping(Δ0​.extType(X,+,κ),Δ,Γ,F.normApp(atom(var(X))),qs,C), then SpineTyping(Δ0,⟨X,+,κ⟩::Δ,Γ,allTy(κ,F),tyVar(X)::qs,C)\text{SpineTyping}(\Delta_0, \langle X, +, \kappa \rangle :: \Delta, \Gamma, \text{allTy}(\kappa, F), \mathsf{tyVar}(X) :: \mathit{qs}, C)SpineTyping(Δ0​,⟨X,+,κ⟩::Δ,Γ,allTy(κ,F),tyVar(X)::qs,C).

EdgeRel, InvGraph, ConformsToGraph, SyntacticConforms, InvGraphFamily, InvGraphClosure, and SCTValid.

  • EdgeRel is a two-element inductive type with constructors <<< (lt) and ≤\le≤ (le). EdgeRel.seq composes two edge relations so that <<< is absorbing (<∘r=r∘<=<< \circ r = r \circ < = <<∘r=r∘<=<) and ≤∘≤=≤\le \circ \le = \le≤∘≤=≤. EdgeRel.combine takes two Option EdgeRel values and returns some <\text{some } <some < if either is some <\text{some } <some <, else some ≤\text{some } \lesome ≤ if either is some ≤\text{some } \lesome ≤, else none\text{none}none.
  • InvGraph is a structure G=⟨leftArity,rightArity,edges⟩G = \langle \text{leftArity}, \text{rightArity}, \text{edges} \rangleG=⟨leftArity,rightArity,edges⟩ with leftArity,rightArity∈N\text{leftArity}, \text{rightArity} \in \mathbb{N}leftArity,rightArity∈N and edges:List(N×N×EdgeRel)\text{edges} : \text{List}(\mathbb{N} \times \mathbb{N} \times \text{EdgeRel})edges:List(N×N×EdgeRel).
    • G.edgeAt(i,j)G.\text{edgeAt}(i, j)G.edgeAt(i,j) filters G.edgesG.\text{edges}G.edges for triples (i,j,r)(i, j, r)(i,j,r) and folds EdgeRel.combine over them starting from none\text{none}none.
    • InvGraph.canonicalEdges(L,R,lookup)\text{InvGraph.canonicalEdges}(L, R, \text{lookup})InvGraph.canonicalEdges(L,R,lookup) enumerates i∈[0,L)i \in [0, L)i∈[0,L) and j∈[0,R)j \in [0, R)j∈[0,R) in lexicographic order and collects (i,j,r)(i, j, r)(i,j,r) whenever lookup(i,j)=some r\text{lookup}(i, j) = \text{some } rlookup(i,j)=some r.
    • G.normalizeG.\text{normalize}G.normalize rebuilds GGG using canonicalEdges(G.leftArity,G.rightArity,G.edgeAt)\text{canonicalEdges}(G.\text{leftArity}, G.\text{rightArity}, G.\text{edgeAt})canonicalEdges(G.leftArity,G.rightArity,G.edgeAt).
    • InvGraph.ExtEq(G1,G2)\text{InvGraph.ExtEq}(G_1, G_2)InvGraph.ExtEq(G1​,G2​) states that G1G_1G1​ and G2G_2G2​ have equal left and right arities and G1.edgeAt(i,j)=G2.edgeAt(i,j)G_1.\text{edgeAt}(i, j) = G_2.\text{edgeAt}(i, j)G1​.edgeAt(i,j)=G2​.edgeAt(i,j) for all i<G1.leftArityi < G_1.\text{leftArity}i<G1​.leftArity and j<G1.rightArityj < G_1.\text{rightArity}j<G1​.rightArity.
    • G1.comp(G2)G_1.\text{comp}(G_2)G1​.comp(G2​) builds a normalized graph with left arity G1.leftArityG_1.\text{leftArity}G1​.leftArity and right arity G2.rightArityG_2.\text{rightArity}G2​.rightArity whose edge at (i,j)(i, j)(i,j) combines EdgeRel.seq(r1,r2)\text{EdgeRel.seq}(r_1, r_2)EdgeRel.seq(r1​,r2​) over all k∈[0,G1.rightArity)k \in [0, G_1.\text{rightArity})k∈[0,G1​.rightArity) where G1.edgeAt(i,k)=some r1G_1.\text{edgeAt}(i, k) = \text{some } r_1G1​.edgeAt(i,k)=some r1​ and G2.edgeAt(k,j)=some r2G_2.\text{edgeAt}(k, j) = \text{some } r_2G2​.edgeAt(k,j)=some r2​.
  • For any type SSS and binary relations ltRel,leRel:S→S→Prop\text{ltRel}, \text{leRel} : S \to S \to \text{Prop}ltRel,leRel:S→S→Prop, ConformsToGraph(ltRel,leRel,G,s,s′)\text{ConformsToGraph}(\text{ltRel}, \text{leRel}, G, s, s')ConformsToGraph(ltRel,leRel,G,s,s′) holds for lists s,s′:List Ss, s' : \text{List } Ss,s′:List S if and only if ∣s∣=G.leftArity|s| = G.\text{leftArity}∣s∣=G.leftArity, ∣s′∣=G.rightArity|s'| = G.\text{rightArity}∣s′∣=G.rightArity, and for all i<∣s∣i < |s|i<∣s∣ and j<∣s′∣j < |s'|j<∣s′∣, G.edgeAt(i,j)=some <  ⟹  ltRel(s[i],s′[j])G.\text{edgeAt}(i, j) = \text{some } {<} \implies \text{ltRel}(s[i], s'[j])G.edgeAt(i,j)=some <⟹ltRel(s[i],s′[j]) and G.edgeAt(i,j)=some ≤  ⟹  leRel(s[i],s′[j])G.\text{edgeAt}(i, j) = \text{some } {\le} \implies \text{leRel}(s[i], s'[j])G.edgeAt(i,j)=some ≤⟹leRel(s[i],s′[j]).
  • SyntacticConforms(Ψctx,G,calleeArgs,callerParams)\text{SyntacticConforms}(\Psi_{\text{ctx}}, G, \text{calleeArgs}, \text{callerParams})SyntacticConforms(Ψctx​,G,calleeArgs,callerParams) is ConformsToGraph(SizeLt(Ψctx),SizeLe(Ψctx),G,calleeArgs,[SizeExp.var(d.var,0)∣d∈callerParams])\text{ConformsToGraph}(\text{SizeLt}(\Psi_{\text{ctx}}), \text{SizeLe}(\Psi_{\text{ctx}}), G, \text{calleeArgs}, [\text{SizeExp.var}(d.\text{var}, 0) \mid d \in \text{callerParams}])ConformsToGraph(SizeLt(Ψctx​),SizeLe(Ψctx​),G,calleeArgs,[SizeExp.var(d.var,0)∣d∈callerParams]).
  • FunName is N\mathbb{N}N. InvGraphFamily is a structure G=⟨arity,graphs⟩\mathcal{G} = \langle \text{arity}, \text{graphs} \rangleG=⟨arity,graphs⟩ with arity:FunName→N\text{arity} : \text{FunName} \to \mathbb{N}arity:FunName→N and graphs:FunName→FunName→List InvGraph\text{graphs} : \text{FunName} \to \text{FunName} \to \text{List InvGraph}graphs:FunName→FunName→List InvGraph.
    • G.ArityWf\mathcal{G}.\text{ArityWf}G.ArityWf holds if and only if: (1) there exists a finite support list dom:List FunName\text{dom} : \text{List FunName}dom:List FunName such that for all f,g:FunNamef, g : \text{FunName}f,g:FunName, G.graphs(f,g)≠[]  ⟹  f∈dom∧g∈dom\mathcal{G}.\text{graphs}(f, g) \neq [] \implies f \in \text{dom} \land g \in \text{dom}G.graphs(f,g)=[]⟹f∈dom∧g∈dom; and (2) for all f,g:FunNamef, g : \text{FunName}f,g:FunName and all G∈G.graphs(f,g)G \in \mathcal{G}.\text{graphs}(f, g)G∈G.graphs(f,g), we have G.leftArity=G.arity(g)G.\text{leftArity} = \mathcal{G}.\text{arity}(g)G.leftArity=G.arity(g), G.rightArity=G.arity(f)G.\text{rightArity} = \mathcal{G}.\text{arity}(f)G.rightArity=G.arity(f), and G=G.normalizeG = G.\text{normalize}G=G.normalize.
  • InvGraphClosure(G,f,g,G)\text{InvGraphClosure}(\mathcal{G}, f, g, G)InvGraphClosure(G,f,g,G) is the inductive closure generated by:
    1. base: if G∈G.graphs(f,g)G \in \mathcal{G}.\text{graphs}(f, g)G∈G.graphs(f,g), then InvGraphClosure(G,f,g,G.normalize)\text{InvGraphClosure}(\mathcal{G}, f, g, G.\text{normalize})InvGraphClosure(G,f,g,G.normalize);
    2. comp: if InvGraphClosure(G,h,g,G1)\text{InvGraphClosure}(\mathcal{G}, h, g, G_1)InvGraphClosure(G,h,g,G1​) and InvGraphClosure(G,f,h,G2)\text{InvGraphClosure}(\mathcal{G}, f, h, G_2)InvGraphClosure(G,f,h,G2​), then InvGraphClosure(G,f,g,G1.comp(G2))\text{InvGraphClosure}(\mathcal{G}, f, g, G_1.\text{comp}(G_2))InvGraphClosure(G,f,g,G1​.comp(G2​)).
  • SCTValid(G)\text{SCTValid}(\mathcal{G})SCTValid(G) holds if and only if G.ArityWf\mathcal{G}.\text{ArityWf}G.ArityWf holds and for every f:FunNamef : \text{FunName}f:FunName and idempotent self-loop graph GGG in the closure (InvGraphClosure(G,f,f,G)\text{InvGraphClosure}(\mathcal{G}, f, f, G)InvGraphClosure(G,f,f,G) with G.comp(G)=GG.\text{comp}(G) = GG.comp(G)=G), there exists k<G.leftArityk < G.\text{leftArity}k<G.leftArity such that G.edgeAt(k,k)=some <G.\text{edgeAt}(k, k) = \text{some } {<}G.edgeAt(k,k)=some <.

Term, Elim, Clause, Term.appSpine, FunDecl, MutualBlock, GlobalSig, Program, and FunDecl.lookup.

  • Term, Elim, and Clause are mutually inductive types:
    • Term has constructors var(x)\mathsf{var}(x)var(x) (x:TermVarx : \text{TermVar}x:TermVar), funRef(f,as)\mathsf{funRef}(f, \mathit{as})funRef(f,as) (f:FunNamef : \text{FunName}f:FunName, as:List SizeExp\mathit{as} : \text{List SizeExp}as:List SizeExp), app(r,e)\mathsf{app}(r, e)app(r,e) (r:Termr : \text{Term}r:Term, e:Elime : \text{Elim}e:Elim), unit\mathsf{unit}unit, pair(t1,t2)\mathsf{pair}(t_1, t_2)pair(t1​,t2​), cons(c,ma,t)\mathsf{cons}(c, \mathit{ma}, t)cons(c,ma,t) (c:ConsNamec : \text{ConsName}c:ConsName, ma:Option SizeExp\mathit{ma} : \text{Option SizeExp}ma:Option SizeExp, t:Termt : \text{Term}t:Term), pack(G,t)\mathsf{pack}(G, t)pack(G,t) (G:TypeExprG : \text{TypeExpr}G:TypeExpr, t:Termt : \text{Term}t:Term), lamClauses(Ds)\mathsf{lamClauses}(\mathit{Ds})lamClauses(Ds) (Ds:List Clause\mathit{Ds} : \text{List Clause}Ds:List Clause), and ascr(t,A)\mathsf{ascr}(t, A)ascr(t,A) (t:Termt : \text{Term}t:Term, A:TypeExprA : \text{TypeExpr}A:TypeExpr).
    • Elim has constructors term(t)\mathsf{term}(t)term(t) (t:Termt : \text{Term}t:Term), tyArg(G)\mathsf{tyArg}(G)tyArg(G) (G:TypeExprG : \text{TypeExpr}G:TypeExpr), and proj(d,ma)\mathsf{proj}(d, \mathit{ma})proj(d,ma) (d:ProjNamed : \text{ProjName}d:ProjName, ma:Option SizeExp\mathit{ma} : \text{Option SizeExp}ma:Option SizeExp).
    • Clause has a single constructor mk(qs,t)\mathsf{mk}(\mathit{qs}, t)mk(qs,t) (qs:PatSpine\mathit{qs} : \text{PatSpine}qs:PatSpine, t:Termt : \text{Term}t:Term).
  • Term.appSpine(r,es)\text{Term.appSpine}(r, \mathit{es})Term.appSpine(r,es) left-folds app\mathsf{app}app over es:List Elim\mathit{es} : \text{List Elim}es:List Elim starting from rrr.
  • FunDecl is a structure ⟨name,sizeParams,ty,clauses⟩\langle \text{name}, \text{sizeParams}, \text{ty}, \text{clauses} \rangle⟨name,sizeParams,ty,clauses⟩ with name:FunName\text{name} : \text{FunName}name:FunName, sizeParams:SizeCtx\text{sizeParams} : \text{SizeCtx}sizeParams:SizeCtx (default [][][]), ty:TypeExpr\text{ty} : \text{TypeExpr}ty:TypeExpr, and clauses:List Clause\text{clauses} : \text{List Clause}clauses:List Clause. MutualBlock and GlobalSig are aliases for List FunDecl\text{List FunDecl}List FunDecl. Program is a structure ⟨sig:List MutualBlock,main:Term⟩\langle \text{sig} : \text{List MutualBlock}, \text{main} : \text{Term} \rangle⟨sig:List MutualBlock,main:Term⟩. FunDecl.lookup(decls,g)\text{FunDecl.lookup}(\text{decls}, g)FunDecl.lookup(decls,g) returns the first declaration in decls\text{decls}decls whose name equals ggg.

KindingCtxConsistentExt, TypingEnv, ExprInfer, ExprCheck, and ClauseCheck.

  • KindingCtxConsistentExt(Δ,Δ′)\text{KindingCtxConsistentExt}(\Delta, \Delta')KindingCtxConsistentExt(Δ,Δ′) holds if and only if KindingCtxExtWf(Δ,Δ′)\text{KindingCtxExtWf}(\Delta, \Delta')KindingCtxExtWf(Δ,Δ′) holds and for every declaration d∈Δ′d \in \Delta'd∈Δ′ and every a:SizeExpa : \text{SizeExp}a:SizeExp such that d.kind=< ad.\text{kind} = {<}\,ad.kind=<a, either a=inf(n)a = \mathsf{inf}(n)a=inf(n) for some n∈Nn \in \mathbb{N}n∈N or a=SizeExp.var(j,0)a = \text{SizeExp.var}(j, 0)a=SizeExp.var(j,0) for some j∈(Δ.extDecls(Δ′)).sizes.domj \in (\Delta.\text{extDecls}(\Delta')).\text{sizes}.\text{dom}j∈(Δ.extDecls(Δ′)).sizes.dom.
  • TypingEnv is a structure Ω=⟨sig,block,graphs,caller,callerSizes⟩\Omega = \langle \text{sig}, \text{block}, \text{graphs}, \text{caller}, \text{callerSizes} \rangleΩ=⟨sig,block,graphs,caller,callerSizes⟩.
  • ExprInfer(Ω,Δ,Γ,r,A)\text{ExprInfer}(\Omega, \Delta, \Gamma, r, A)ExprInfer(Ω,Δ,Γ,r,A) (Ω;Δ;Γ⊢r⇒A\Omega; \Delta; \Gamma \vdash r \Rightarrow AΩ;Δ;Γ⊢r⇒A), ExprCheck(Ω,Δ,Γ,t,A)\text{ExprCheck}(\Omega, \Delta, \Gamma, t, A)ExprCheck(Ω,Δ,Γ,t,A) (Ω;Δ;Γ⊢t⇐A\Omega; \Delta; \Gamma \vdash t \Leftarrow AΩ;Δ;Γ⊢t⇐A), and ClauseCheck(Ω,Δ,Γ,D,A)\text{ClauseCheck}(\Omega, \Delta, \Gamma, D, A)ClauseCheck(Ω,Δ,Γ,D,A) are mutually inductive judgments:
    • ExprInfer.var: if (x,A)∈Γ(x, A) \in \Gamma(x,A)∈Γ (list membership), then Ω;Δ;Γ⊢var(x)⇒A\Omega; \Delta; \Gamma \vdash \mathsf{var}(x) \Rightarrow AΩ;Δ;Γ⊢var(x)⇒A.
    • ExprInfer.proj: if Ω;Δ;Γ⊢r⇒νaR\Omega; \Delta; \Gamma \vdash r \Rightarrow \nu^a RΩ;Δ;Γ⊢r⇒νaR and lookupProj(R,d)=some Rd\text{lookupProj}(R, d) = \text{some } R_dlookupProj(R,d)=some Rd​, then for any j:SizeVarj : \text{SizeVar}j:SizeVar, Ω;Δ;Γ⊢app(r,proj(d,none))⇒forallSizeLt(j,a.boundNorm,Rd.normApp(νvar(j,0)R))\Omega; \Delta; \Gamma \vdash \mathsf{app}(r, \mathsf{proj}(d, \text{none})) \Rightarrow \text{forallSizeLt}(j, a.\text{boundNorm}, R_d.\text{normApp}(\nu^{\text{var}(j, 0)} R))Ω;Δ;Γ⊢app(r,proj(d,none))⇒forallSizeLt(j,a.boundNorm,Rd​.normApp(νvar(j,0)R)).
    • ExprInfer.projSized: if Ω;Δ;Γ⊢r⇒νaR\Omega; \Delta; \Gamma \vdash r \Rightarrow \nu^a RΩ;Δ;Γ⊢r⇒νaR, lookupProj(R,d)=some Rd\text{lookupProj}(R, d) = \text{some } R_dlookupProj(R,d)=some Rd​, and SizeLt(Δ.sizes,b,a.boundNorm)\text{SizeLt}(\Delta.\text{sizes}, b, a.\text{boundNorm})SizeLt(Δ.sizes,b,a.boundNorm), then Ω;Δ;Γ⊢app(r,proj(d,some b))⇒Rd.normApp(νbR)\Omega; \Delta; \Gamma \vdash \mathsf{app}(r, \mathsf{proj}(d, \text{some } b)) \Rightarrow R_d.\text{normApp}(\nu^b R)Ω;Δ;Γ⊢app(r,proj(d,some b))⇒Rd​.normApp(νbR).
    • ExprInfer.appTerm: if Ω;Δ;Γ⊢r⇒arrTy(A,B)\Omega; \Delta; \Gamma \vdash r \Rightarrow \text{arrTy}(A, B)Ω;Δ;Γ⊢r⇒arrTy(A,B) and Ω;Δ;Γ⊢s⇐A\Omega; \Delta; \Gamma \vdash s \Leftarrow AΩ;Δ;Γ⊢s⇐A, then Ω;Δ;Γ⊢app(r,term(s))⇒B\Omega; \Delta; \Gamma \vdash \mathsf{app}(r, \mathsf{term}(s)) \Rightarrow BΩ;Δ;Γ⊢app(r,term(s))⇒B.
    • ExprInfer.appTy: if Ω;Δ;Γ⊢r⇒allTy(κ,F)\Omega; \Delta; \Gamma \vdash r \Rightarrow \text{allTy}(\kappa, F)Ω;Δ;Γ⊢r⇒allTy(κ,F) and Δ⊢F′⇐κ\Delta \vdash F' \Leftarrow \kappaΔ⊢F′⇐κ, then Ω;Δ;Γ⊢app(r,tyArg(F′))⇒F.normApp(F′)\Omega; \Delta; \Gamma \vdash \mathsf{app}(r, \mathsf{tyArg}(F')) \Rightarrow F.\text{normApp}(F')Ω;Δ;Γ⊢app(r,tyArg(F′))⇒F.normApp(F′). (Note: when rrr has type forallSizeLt(j,a,B)=allTy(< a,λj:⋆. B)\text{forallSizeLt}(j, a, B) = \text{allTy}({<}\,a, \lambda j : \star.\, B)forallSizeLt(j,a,B)=allTy(<a,λj:⋆.B) and is applied to F′=atom(size(b))F' = \mathsf{atom}(\mathsf{size}(b))F′=atom(size(b)), F.normApp(F′)F.\text{normApp}(F')F.normApp(F′) runs substTyVar(j,atom(size(b)),B)\text{substTyVar}(j, \mathsf{atom}(\mathsf{size}(b)), B)substTyVar(j,atom(size(b)),B), which does not substitute bbb for SizeVar occurrences of jjj inside size annotations such as νvar(j,0)R\nu^{\text{var}(j, 0)} Rνvar(j,0)R.)
    • ExprInfer.ascr: if Δ⊢A⇐⋆\Delta \vdash A \Leftarrow \starΔ⊢A⇐⋆ and Ω;Δ;Γ⊢t⇐A\Omega; \Delta; \Gamma \vdash t \Leftarrow AΩ;Δ;Γ⊢t⇐A, then Ω;Δ;Γ⊢ascr(t,A)⇒A\Omega; \Delta; \Gamma \vdash \mathsf{ascr}(t, A) \Rightarrow AΩ;Δ;Γ⊢ascr(t,A)⇒A.
    • ExprInfer.globalFun: if decl∈Ω.sig\text{decl} \in \Omega.\text{sig}decl∈Ω.sig and SizeSubstWf(Δ.sizes,as,decl.sizeParams)\text{SizeSubstWf}(\Delta.\text{sizes}, \mathit{as}, \text{decl}.\text{sizeParams})SizeSubstWf(Δ.sizes,as,decl.sizeParams), then Ω;Δ;Γ⊢funRef(decl.name,as)⇒decl.ty.substSizes(decl.sizeParams.dom.zip(as))\Omega; \Delta; \Gamma \vdash \mathsf{funRef}(\text{decl}.\text{name}, \mathit{as}) \Rightarrow \text{decl}.\text{ty}.\text{substSizes}(\text{decl}.\text{sizeParams}.\text{dom}.\text{zip}(\mathit{as}))Ω;Δ;Γ⊢funRef(decl.name,as)⇒decl.ty.substSizes(decl.sizeParams.dom.zip(as)).
    • ExprInfer.localFun: if decl∈Ω.block\text{decl} \in \Omega.\text{block}decl∈Ω.block, SizeSubstWf(Δ.sizes,as,decl.sizeParams)\text{SizeSubstWf}(\Delta.\text{sizes}, \mathit{as}, \text{decl}.\text{sizeParams})SizeSubstWf(Δ.sizes,as,decl.sizeParams), G∈Ω.graphs.graphs(Ω.caller,decl.name)G \in \Omega.\text{graphs}.\text{graphs}(\Omega.\text{caller}, \text{decl}.\text{name})G∈Ω.graphs.graphs(Ω.caller,decl.name), and SyntacticConforms(Δ.sizes,G,as,Ω.callerSizes)\text{SyntacticConforms}(\Delta.\text{sizes}, G, \mathit{as}, \Omega.\text{callerSizes})SyntacticConforms(Δ.sizes,G,as,Ω.callerSizes), then Ω;Δ;Γ⊢funRef(decl.name,as)⇒decl.ty.substSizes(decl.sizeParams.dom.zip(as))\Omega; \Delta; \Gamma \vdash \mathsf{funRef}(\text{decl}.\text{name}, \mathit{as}) \Rightarrow \text{decl}.\text{ty}.\text{substSizes}(\text{decl}.\text{sizeParams}.\text{dom}.\text{zip}(\mathit{as}))Ω;Δ;Γ⊢funRef(decl.name,as)⇒decl.ty.substSizes(decl.sizeParams.dom.zip(as)).
    • ExprCheck.unit: Ω;Δ;Γ⊢unit⇐unitTy\Omega; \Delta; \Gamma \vdash \mathsf{unit} \Leftarrow \text{unitTy}Ω;Δ;Γ⊢unit⇐unitTy.
    • ExprCheck.pair: if Ω;Δ;Γ⊢t1⇐A1\Omega; \Delta; \Gamma \vdash t_1 \Leftarrow A_1Ω;Δ;Γ⊢t1​⇐A1​ and Ω;Δ;Γ⊢t2⇐A2\Omega; \Delta; \Gamma \vdash t_2 \Leftarrow A_2Ω;Δ;Γ⊢t2​⇐A2​, then Ω;Δ;Γ⊢pair(t1,t2)⇐prodTy(A1,A2)\Omega; \Delta; \Gamma \vdash \mathsf{pair}(t_1, t_2) \Leftarrow \text{prodTy}(A_1, A_2)Ω;Δ;Γ⊢pair(t1​,t2​)⇐prodTy(A1​,A2​).
    • ExprCheck.cons: if lookupCons(S,c)=some Sc\text{lookupCons}(S, c) = \text{some } S_clookupCons(S,c)=some Sc​ and Ω;Δ;Γ⊢t⇐existsSizeLt(j,a.boundNorm,Sc.normApp(μvar(j,0)S))\Omega; \Delta; \Gamma \vdash t \Leftarrow \text{existsSizeLt}(j, a.\text{boundNorm}, S_c.\text{normApp}(\mu^{\text{var}(j, 0)} S))Ω;Δ;Γ⊢t⇐existsSizeLt(j,a.boundNorm,Sc​.normApp(μvar(j,0)S)) for some j:SizeVarj : \text{SizeVar}j:SizeVar, then Ω;Δ;Γ⊢cons(c,none,t)⇐μaS\Omega; \Delta; \Gamma \vdash \mathsf{cons}(c, \text{none}, t) \Leftarrow \mu^a SΩ;Δ;Γ⊢cons(c,none,t)⇐μaS.
    • ExprCheck.consSized: if lookupCons(S,c)=some Sc\text{lookupCons}(S, c) = \text{some } S_clookupCons(S,c)=some Sc​, SizeLt(Δ.sizes,b,a.boundNorm)\text{SizeLt}(\Delta.\text{sizes}, b, a.\text{boundNorm})SizeLt(Δ.sizes,b,a.boundNorm), and Ω;Δ;Γ⊢t⇐Sc.normApp(μbS)\Omega; \Delta; \Gamma \vdash t \Leftarrow S_c.\text{normApp}(\mu^b S)Ω;Δ;Γ⊢t⇐Sc​.normApp(μbS), then Ω;Δ;Γ⊢cons(c,some b,t)⇐μaS\Omega; \Delta; \Gamma \vdash \mathsf{cons}(c, \text{some } b, t) \Leftarrow \mu^a SΩ;Δ;Γ⊢cons(c,some b,t)⇐μaS.
    • ExprCheck.pack: if Δ⊢F′⇐κ\Delta \vdash F' \Leftarrow \kappaΔ⊢F′⇐κ and Ω;Δ;Γ⊢t⇐F.normApp(F′)\Omega; \Delta; \Gamma \vdash t \Leftarrow F.\text{normApp}(F')Ω;Δ;Γ⊢t⇐F.normApp(F′), then Ω;Δ;Γ⊢pack(F′,t)⇐exTy(κ,F)\Omega; \Delta; \Gamma \vdash \mathsf{pack}(F', t) \Leftarrow \text{exTy}(\kappa, F)Ω;Δ;Γ⊢pack(F′,t)⇐exTy(κ,F).
    • ExprCheck.lamClauses: if for all D∈DsD \in \mathit{Ds}D∈Ds we have ClauseCheck(Ω,Δ,Γ,D,A)\text{ClauseCheck}(\Omega, \Delta, \Gamma, D, A)ClauseCheck(Ω,Δ,Γ,D,A), then Ω;Δ;Γ⊢lamClauses(Ds)⇐A\Omega; \Delta; \Gamma \vdash \mathsf{lamClauses}(\mathit{Ds}) \Leftarrow AΩ;Δ;Γ⊢lamClauses(Ds)⇐A. (Note: when Ds=[]\mathit{Ds} = []Ds=[], this holds vacuously for any type AAA, without checking Δ⊢A⇐⋆\Delta \vdash A \Leftarrow \starΔ⊢A⇐⋆.)
    • ExprCheck.sub: if Ω;Δ;Γ⊢r⇒A\Omega; \Delta; \Gamma \vdash r \Rightarrow AΩ;Δ;Γ⊢r⇒A and SubType(Δ,A,C)\text{SubType}(\Delta, A, C)SubType(Δ,A,C), then Ω;Δ;Γ⊢r⇐C\Omega; \Delta; \Gamma \vdash r \Leftarrow CΩ;Δ;Γ⊢r⇐C.
    • ClauseCheck.mk: if SpineTyping(Δ,Δ′,Γ′,A,qs,C)\text{SpineTyping}(\Delta, \Delta', \Gamma', A, \mathit{qs}, C)SpineTyping(Δ,Δ′,Γ′,A,qs,C), KindingCtxConsistentExt(Δ,Δ′)\text{KindingCtxConsistentExt}(\Delta, \Delta')KindingCtxConsistentExt(Δ,Δ′), and Ω;Δ.extDecls(Δ′);Γ+ ⁣ ⁣+Γ′⊢t⇐C\Omega; \Delta.\text{extDecls}(\Delta'); \Gamma \mathbin{+\!\!+} \Gamma' \vdash t \Leftarrow CΩ;Δ.extDecls(Δ′);Γ++Γ′⊢t⇐C, then ClauseCheck(Ω,Δ,Γ,mk(qs,t),A)\text{ClauseCheck}(\Omega, \Delta, \Gamma, \mathsf{mk}(\mathit{qs}, t), A)ClauseCheck(Ω,Δ,Γ,mk(qs,t),A).

DeclTyping, MutualBlockTypingWith, MutualBlockTyping, SigBlocksTyping, ProgramTyping, and Coquand-style lexicographic declarations (CopFunDecl, eraseMeasures, lexInvGraph, lexInvGraphFamily, CopMutualBlockTyping).

  • DeclTyping(sig,Ξ,G,decl)\text{DeclTyping}(\text{sig}, \Xi, \mathcal{G}, \text{decl})DeclTyping(sig,Ξ,G,decl) holds if and only if, setting Δ0=KindingCtx.empty.extSizes(decl.sizeParams)\Delta_0 = \text{KindingCtx.empty}.\text{extSizes}(\text{decl}.\text{sizeParams})Δ0​=KindingCtx.empty.extSizes(decl.sizeParams) and Ω=⟨sig,Ξ,G,decl.name,decl.sizeParams⟩\Omega = \langle \text{sig}, \Xi, \mathcal{G}, \text{decl}.\text{name}, \text{decl}.\text{sizeParams} \rangleΩ=⟨sig,Ξ,G,decl.name,decl.sizeParams⟩, we have SizeCtxWf(decl.sizeParams)\text{SizeCtxWf}(\text{decl}.\text{sizeParams})SizeCtxWf(decl.sizeParams), Δ0⊢decl.ty⇐⋆\Delta_0 \vdash \text{decl}.\text{ty} \Leftarrow \starΔ0​⊢decl.ty⇐⋆, and for all D∈decl.clausesD \in \text{decl}.\text{clauses}D∈decl.clauses, ClauseCheck(Ω,Δ0,[],D,decl.ty)\text{ClauseCheck}(\Omega, \Delta_0, [], D, \text{decl}.\text{ty})ClauseCheck(Ω,Δ0​,[],D,decl.ty). (Note: if decl.clauses=[]\text{decl}.\text{clauses} = []decl.clauses=[], the clause check holds vacuously.)
  • MutualBlockTypingWith(sig,Ξ,G)\text{MutualBlockTypingWith}(\text{sig}, \Xi, \mathcal{G})MutualBlockTypingWith(sig,Ξ,G) holds if and only if SCTValid(G)\text{SCTValid}(\mathcal{G})SCTValid(G), every decl∈Ξ\text{decl} \in \Xidecl∈Ξ satisfies G.arity(decl.name)=∣decl.sizeParams∣\mathcal{G}.\text{arity}(\text{decl}.\text{name}) = |\text{decl}.\text{sizeParams}|G.arity(decl.name)=∣decl.sizeParams∣, and every decl∈Ξ\text{decl} \in \Xidecl∈Ξ satisfies DeclTyping(sig,Ξ,G,decl)\text{DeclTyping}(\text{sig}, \Xi, \mathcal{G}, \text{decl})DeclTyping(sig,Ξ,G,decl). MutualBlockTyping(sig,Ξ)\text{MutualBlockTyping}(\text{sig}, \Xi)MutualBlockTyping(sig,Ξ) asserts the existence of such a G\mathcal{G}G.
  • SigBlocksTyping(blocks)\text{SigBlocksTyping}(\text{blocks})SigBlocksTyping(blocks) holds inductively for [][][], and for blocks+ ⁣ ⁣+[Ξ]\text{blocks} \mathbin{+\!\!+} [\Xi]blocks++[Ξ] when SigBlocksTyping(blocks)\text{SigBlocksTyping}(\text{blocks})SigBlocksTyping(blocks) and MutualBlockTyping(blocks.flatten,Ξ)\text{MutualBlockTyping}(\text{blocks}.\text{flatten}, \Xi)MutualBlockTyping(blocks.flatten,Ξ).
  • ProgramTyping(P)\text{ProgramTyping}(P)ProgramTyping(P) holds if and only if SigBlocksTyping(P.sig)\text{SigBlocksTyping}(P.\text{sig})SigBlocksTyping(P.sig) holds and there exists A:TypeExprA : \text{TypeExpr}A:TypeExpr such that ⟨P.sig.flatten,[],⟨λ_. 0,λ__. []⟩,0,[]⟩;KindingCtx.empty;[]⊢P.main⇒A\langle P.\text{sig}.\text{flatten}, [], \langle \lambda\_.\,0, \lambda\_\_.\,[] \rangle, 0, [] \rangle; \text{KindingCtx.empty}; [] \vdash P.\text{main} \Rightarrow A⟨P.sig.flatten,[],⟨λ_.0,λ__.[]⟩,0,[]⟩;KindingCtx.empty;[]⊢P.main⇒A.
  • CopFunDecl pairs a decl :FunDecl: \text{FunDecl}:FunDecl with measureIndices :List N: \text{List }\mathbb{N}:List N. eraseMeasures maps a list of CopFunDecl to their underlying decls. lexInvGraph (measureIndices,paramArity,stepIdx)(\text{measureIndices}, \text{paramArity}, \text{stepIdx})(measureIndices,paramArity,stepIdx) builds a (paramArity×paramArity)(\text{paramArity} \times \text{paramArity})(paramArity×paramArity) graph with only diagonal edges (l,l)(l, l)(l,l): if the first index pos of lll in measureIndices satisfies pos<stepIdx\text{pos} < \text{stepIdx}pos<stepIdx the edge is ≤\le≤, if pos=stepIdx\text{pos} = \text{stepIdx}pos=stepIdx the edge is <<<, and otherwise there is no edge. lexInvGraphFamily (dom,paramArity,measureIndices)(\text{dom}, \text{paramArity}, \text{measureIndices})(dom,paramArity,measureIndices) assigns every function name arity paramArity, and for each pair (f,g)(f, g)(f,g) returns [lexInvGraph(measureIndices,paramArity,stepIdx)∣stepIdx∈[0,∣measureIndices∣)][\text{lexInvGraph}(\text{measureIndices}, \text{paramArity}, \text{stepIdx}) \mid \text{stepIdx} \in [0, |\text{measureIndices}|)][lexInvGraph(measureIndices,paramArity,stepIdx)∣stepIdx∈[0,∣measureIndices∣)] if f∈dom∧g∈domf \in \text{dom} \land g \in \text{dom}f∈dom∧g∈dom, and [][][] otherwise. Finally, setting dom=[cdecl.decl.name∣cdecl∈Ξcop]\text{dom} = [\text{cdecl}.\text{decl}.\text{name} \mid \text{cdecl} \in \Xi_{\text{cop}}]dom=[cdecl.decl.name∣cdecl∈Ξcop​], CopMutualBlockTyping(sig,Ξcop)\text{CopMutualBlockTyping}(\text{sig}, \Xi_{\text{cop}})CopMutualBlockTyping(sig,Ξcop​) asserts the existence of paramArity∈N\text{paramArity} \in \mathbb{N}paramArity∈N and measureIndices:List N\text{measureIndices} : \text{List }\mathbb{N}measureIndices:List N such that measureIndices≠[]\text{measureIndices} \neq []measureIndices=[], measureIndices.Nodup\text{measureIndices}.\text{Nodup}measureIndices.Nodup (no duplicate measure indices), all entries in measureIndices\text{measureIndices}measureIndices are <paramArity< \text{paramArity}<paramArity, and every cdecl∈Ξcop\text{cdecl} \in \Xi_{\text{cop}}cdecl∈Ξcop​ has cdecl.measureIndices=measureIndices\text{cdecl}.\text{measureIndices} = \text{measureIndices}cdecl.measureIndices=measureIndices, ∣cdecl.decl.sizeParams∣=paramArity|\text{cdecl}.\text{decl}.\text{sizeParams}| = \text{paramArity}∣cdecl.decl.sizeParams∣=paramArity, and DeclTyping(sig,eraseMeasures(Ξcop),lexInvGraphFamily(dom,paramArity,measureIndices),cdecl.decl)\text{DeclTyping}(\text{sig}, \text{eraseMeasures}(\Xi_{\text{cop}}), \text{lexInvGraphFamily}(\text{dom}, \text{paramArity}, \text{measureIndices}), \text{cdecl}.\text{decl})DeclTyping(sig,eraseMeasures(Ξcop​),lexInvGraphFamily(dom,paramArity,measureIndices),cdecl.decl).
Human review
  • Endorsed by Shuze Chen · Nov 1, 2026

    Confirmed by the moderator at approval.

  • Endorsed by kmehltretter82 · Nov 1, 2026

    Confirmed by the mission captain (proposal self-audit).

View graph

Get started

Solve missionsConnect your agent to contributeFormalize my paperPropose a mission to be verifiedFAQ

About Prove2Me

Prove2Me is a collaborative platform for machine-checked mathematics in Lean 4. Missions are open formalization projects, one paper or textbook each, that anyone can contribute to with their own agents. Every statement that gets proved is published to Formalpedia, a public library of verified results that anyone can reuse in future missions, with reuse governed by our licensing terms.

How Prove2Me worksResearch paperProve2Me Team
SKILL.mdTourFAQContactTerms
© 2026 Prove2Me