Prove2Me
Navigate
DiscoverCollectionsFormalpediaGalaxyBlogsUsersMomentumMy Missions+
Prove2Me
Log in
← Formalpedia

Chapter 6: Unannotated System F_ω^c, Polarized Signature Encoding, Spine Inference, Constraint Generation, and Algorithms 1 & 2

Definition
NishtAbel2024_Inference

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

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

Formalizes Chapter 6 (pp. 41–60) and Appendix A (pp. I–V) of Nisht & Abel (2024): unannotated System F_ω^c kinding and pattern/spine typing, fixpoint polarity occurrences (SizeOccursFixPol), polarized signature encoding (EncodeType), pattern and copattern-spine rigid variable gathering (InferPat, InferSpine), fixpoint hygiene predicates (PositiveFixpointHygiene, SignatureFixpointHygiene), flexible size variable contexts (FlexVars), subtype constraint generation (CompareTypes), bidirectional call-site constraint inference (InferTerm, CheckTerm), closest next bounds (closestNextBound), least upper bounds (lubSizes), Algorithm 1 (solveConstraintGraph), call-graph construction (buildCallGraph), and Algorithm 2 (Algorithm2Accepts).

Definition code
import Mathlib
import Definitions.Def_NishtAbel2024_Syntax
import Definitions.Def_NishtAbel2024_Semantics

/-!
# Chapter 6 & Appendix A of Nisht & Abel (2024): Size Inference, Constraint Solving, and Termination Checking

This module formalizes the type-based termination inference pipeline of Chapter 6 (pp. 41–60)
and the unannotated source calculus System `F_ω^c` of Appendix A (pp. I–V) of
Kanstantsin Nisht and Andreas Abel, *"Type-Based Termination Checking in Agda"* (2024):

1. **Appendix A (pp. I–V): Unannotated System `F_ω^c`**:
   - Kind checking `Δ ⊢_{F_ω} A ⇒ ι` and `Δ ⊢_{F_ω} A ⇐ ι` (`FwKindInfer`, `FwKindCheck`)
   - Pattern and copattern-spine typing `Δ; Γ ⊢^{Δ'}_{F_ω} p ⇐ A` and
     `Δ; Γ | A ⊢^{Δ'}_{F_ω} q⃗ ⇒ C` (`FwPatTyping`, `FwSpineTyping`)
2. **Section 6.1 (pp. 41–44): Function Signature Encoding**:
   - Polarized type encoding `π; Δ ⊢_{SCT}^{π*} A ⇒ Ψ; A'` (`EncodeType`)
   - Fixpoint kind tag `FixKind` (`μ` vs. `ν`) and polarized size-variable occurrence
     `Δ ⊢ i ∈_π F` (`SizeOccursFixPol`, `SizeOccursPol`)
3. **Section 6.2 (pp. 44–47): Pattern & Copattern-Spine Rigid Variable Gathering**:
   - Pattern rigid-variable gathering `Δ₀ ⊢_{SCT} p : A ⇒ Γ; Δ; Ψ; p'` (`InferPat`)
   - Copattern-spine rigid-variable gathering `Δ₀ ⊢_{SCT} q⃗ : A ⇒ C; Γ; Δ; Ψ; q⃗'` (`InferSpine`)
4. **Section 6.3 (pp. 48–56): Call-Site Inference, Checking, and Type Comparison**:
   - Flexible variable context `Φ` (`FlexVars`), size constraints `C` (`SizeConstraint`),
     and non-recursive constructor size variables `T`
   - Call-site inference `Φ; Γ; Δ ⊢_{SCT} t ⇒ A; Φ'; C; T; t'` (`InferTerm`)
   - Call-site checking `Φ; Γ; Δ | A ⊢_{SCT} t ⇒ Φ'; C; T; t'` (`CheckTerm`)
   - Context trivialization `Φ ⊢_↓ Ψ₁ ⇒ Ψ₂` (`TrivializeCtx`) and clause checking
     `Φ; Γ; Δ | C ⊢_{SCT} D ⇒ Φ'; C_out; T; D'` (`CheckClauseInfer`, `CheckClausesInfer`)
   - Polarized type comparison `Φ; Δ; ι ⊢_{SCT} A ≤^π B ⇒ C` (`CompareTypes`)
5. **Sections 6.4–6.5 (pp. 56–60): Constraint Solving (Algorithm 1) & Termination Checker (Algorithm 2)**:
   - Flexible substitution `φ`, functorial term application `φ(t)`, and coherence `Ψ; C ⊢ φ`
     (`CoherentSubst`)
   - Closest next bound `Ψ ⊢ R a ⇒ b` (`ClosestNextBound`, `closestNextBound`) and least upper
     bound `Ψ ⊢ LUB(b₁, ..., bₘ) ⇒ c` (`IsLubSize`, `lubSizes`)
   - **Algorithm 1** (`solveConstraintGraph` computing `φ*`)
   - Recursive-call invocation graph conformance (`LocalCallsConform`, `buildCallGraph`) and
     **Algorithm 2** (`Algorithm2Accepts`)
-/

namespace NishtAbel2024

/-! ## Appendix A: Unannotated Source Calculus System `F_ω^c` (pp. I–V) -/

/-- Simple functor kind `◦* → *` in System `F_ω^c` (Appendix A, p. II). -/
def fwFunctorSKind : SKind :=
  .arr .mixed .star .star

mutual

/-- Check whether a `TypeExpr` belongs to the unannotated System `F_ω^c` fragment
(i.e. contains no size atoms `.size`, no bounded size quantifiers `.lt`, and all fixpoints
`μ` and `ν` carry the unannotated size `.infty`). -/
def TypeExpr.isUnannotated : TypeExpr → Prop
  | .atom (.size _) => False
  | .atom (.all (.lt _)) => False
  | .atom (.ex (.lt _)) => False
  | .atom _ => True
  | .lam _ _ body => body.isUnannotated
  | .app F G => F.isUnannotated ∧ G.isUnannotated
  | .mu a S => a = .infty ∧ isUnannotatedBranches S
  | .nu a R => a = .infty ∧ isUnannotatedBranches R

/-- Helper: check whether all branches/fields in a list are unannotated. -/
def isUnannotatedBranches : List (Nat × TypeExpr) → Prop
  | [] => True
  | (_, F) :: rest => F.isUnannotated ∧ isUnannotatedBranches rest

end

mutual

/-- Unannotated kind inference `Δ ⊢_{F_ω} F ⇒ ι` in System `F_ω^c` (Appendix A, Section A.1.2, p. II). -/
inductive FwKindInfer : KindingCtx → TypeExpr → SKind → Prop where
  | unit (Δ : KindingCtx) :
      FwKindInfer Δ (.atom .unit) .star
  | prod (Δ : KindingCtx) :
      FwKindInfer Δ (.atom .prod) (.arr .pos .star (.arr .pos .star .star))
  | arr (Δ : KindingCtx) :
      FwKindInfer Δ (.atom .arr) (.arr .neg .star (.arr .pos .star .star))
  | var {Δ : KindingCtx} {X : TyVar} {π : Polarity} {ι : SKind} :
      TyDecl.mk X π (Kind.ofSKind ι) ∈ Δ.types →
      Polarity.le π .pos = true →
      FwKindInfer Δ (.atom (.var X)) ι
  | app {Δ : KindingCtx} {F G : TypeExpr} {π : Polarity} {ι ι' : SKind} :
      FwKindInfer Δ F (.arr π ι ι') →
      FwKindCheck (Δ.invScalePol π) G ι →
      FwKindInfer Δ (.app F G) ι'
  | all {Δ : KindingCtx} {ι : SKind} :
      FwKindInfer Δ (.atom (.all (Kind.ofSKind ι)))
        (.arr .pos (.arr .mixed ι .star) .star)
  | ex {Δ : KindingCtx} {ι : SKind} :
      FwKindInfer Δ (.atom (.ex (Kind.ofSKind ι)))
        (.arr .pos (.arr .mixed ι .star) .star)
  | mu {Δ : KindingCtx} {S : List (ConsName × TypeExpr)} :
      (∀ p ∈ S, FwKindCheck Δ p.2 fwFunctorSKind) →
      FwKindInfer Δ (.mu .infty S) .star
  | nu {Δ : KindingCtx} {R : List (ProjName × TypeExpr)} :
      (∀ p ∈ R, FwKindCheck Δ p.2 fwFunctorSKind) →
      FwKindInfer Δ (.nu .infty R) .star

/-- Unannotated kind checking `Δ ⊢_{F_ω} F ⇐ ι` in System `F_ω^c` (Appendix A, Section A.1.2, p. II). -/
inductive FwKindCheck : KindingCtx → TypeExpr → SKind → Prop where
  | infer {Δ : KindingCtx} {F : TypeExpr} {ι : SKind} :
      FwKindInfer Δ F ι →
      FwKindCheck Δ F ι
  | lam {Δ : KindingCtx} {X : TyVar} {ι ι' : SKind} {F : TypeExpr} {π : Polarity} :
      FwKindCheck (Δ.extType X π (Kind.ofSKind ι)) F ι' →
      FwKindCheck Δ (.lam X ι F) (.arr π ι ι')

end

/-- Unannotated pattern typing `Δ; Γ ⊢^{Δ'}_{F_ω} p ⇐ A` in System `F_ω^c`
(Appendix A, Section A.2, p. II). -/
inductive FwPatTyping : KindingCtx → List TyDecl → TermCtx → Pat → TypeExpr → Prop where
  | var (Δ : KindingCtx) (x : TermVar) {A : TypeExpr} :
      FwKindCheck Δ A .star →
      FwPatTyping Δ [] [(x, A)] (.var x) A
  | unit (Δ : KindingCtx) :
      FwPatTyping Δ [] [] .unit .unitTy
  | pair {Δ : KindingCtx} {Δ₁ Δ₂ : List TyDecl} {Γ₁ Γ₂ : TermCtx}
      {p₁ p₂ : Pat} {A₁ A₂ : TypeExpr} :
      FwPatTyping Δ Δ₁ Γ₁ p₁ A₁ →
      FwPatTyping (Δ.append ⟨[], Δ₁⟩) Δ₂ Γ₂ p₂ A₂ →
      FwPatTyping Δ (Δ₁ ++ Δ₂) (Γ₁ ++ Γ₂) (.pair p₁ p₂) (.prodTy A₁ A₂)
  | cons {Δ : KindingCtx} {Δ' : List TyDecl} {Γ : TermCtx} {c : ConsName} {p : Pat}
      {S : List (ConsName × TypeExpr)} {Sc : TypeExpr} :
      TypeExpr.lookupCons S c = some Sc →
      FwPatTyping Δ Δ' Γ p (Sc.normApp (.mu .infty S)) →
      FwPatTyping Δ Δ' Γ (.cons c p) (.mu .infty S)
  | tyPack {Δ : KindingCtx} {Δ' : List TyDecl} {Γ : TermCtx} {X : TyVar} {ι : SKind}
      {p : Pat} {F : TypeExpr} :
      X ∉ (Δ.types ++ Δ').map (·.var) →
      FwPatTyping (Δ.extType X .pos (Kind.ofSKind ι)) Δ' Γ p (F.normApp (.atom (.var X))) →
      FwPatTyping Δ (⟨X, .pos, Kind.ofSKind ι⟩ :: Δ') Γ (.tyPack X p) (.exTy (Kind.ofSKind ι) F)

/-- Unannotated copattern-spine typing `Δ; Γ | A ⊢^{Δ'}_{F_ω} q⃗ ⇒ C` in System `F_ω^c`
(Appendix A, Section A.2, p. III). -/
inductive FwSpineTyping :
    KindingCtx → List TyDecl → TermCtx → TypeExpr → PatSpine → TypeExpr → Prop where
  | nil (Δ : KindingCtx) (A : TypeExpr) :
      FwSpineTyping Δ [] [] A [] A
  | pat {Δ : KindingCtx} {Δ₁ Δ₂ : List TyDecl} {Γ₁ Γ₂ : TermCtx}
      {p : Pat} {qs : PatSpine} {A B C : TypeExpr} :
      FwPatTyping Δ Δ₁ Γ₁ p A →
      FwSpineTyping (Δ.append ⟨[], Δ₁⟩) Δ₂ Γ₂ B qs C →
      FwSpineTyping Δ (Δ₁ ++ Δ₂) (Γ₁ ++ Γ₂) (.arrTy A B) (.pat p :: qs) C
  | tyApp {Δ : KindingCtx} {Δ' : List TyDecl} {Γ : TermCtx} {X : TyVar} {ι : SKind}
      {F C : TypeExpr} {qs : PatSpine} :
      X ∉ (Δ.types ++ Δ').map (·.var) →
      FwSpineTyping (Δ.extType X .pos (Kind.ofSKind ι)) Δ' Γ
        (F.normApp (.atom (.var X))) qs C →
      FwSpineTyping Δ (⟨X, .pos, Kind.ofSKind ι⟩ :: Δ') Γ
        (.allTy (Kind.ofSKind ι) F) (.tyVar X :: qs) C
  | proj {Δ : KindingCtx} {Δ' : List TyDecl} {Γ : TermCtx} {d : ProjName}
      {R : List (ProjName × TypeExpr)} {Rd C : TypeExpr} {qs : PatSpine} :
      TypeExpr.lookupProj R d = some Rd →
      FwSpineTyping Δ Δ' Γ (Rd.normApp (.nu .infty R)) qs C →
      FwSpineTyping Δ Δ' Γ (.nu .infty R) (.proj d :: qs) C

/-! ## Section 6.1: Function Signature Encoding & Polarized Size Occurrences (pp. 41–44) -/

/-- Tag distinguishing inductive (`μ`) and coinductive (`ν`) fixpoint operators
(Section 6.1, Lemma 3, p. 43). -/
inductive FixKind where
  | mu : FixKind
  | nu : FixKind
  deriving DecidableEq, Repr

mutual

/-- Collect all size variables mentioned in a `TypeExpr`. -/
def TypeExpr.allSizeVars : TypeExpr → List SizeVar
  | .atom (.size a) => a.vars
  | .atom (.all (.lt a)) => a.vars
  | .atom (.ex (.lt a)) => a.vars
  | .atom _ => []
  | .lam _ _ body => body.allSizeVars
  | .app F G => F.allSizeVars ++ G.allSizeVars
  | .mu a S => a.vars ++ allSizeVarsBranches S
  | .nu a R => a.vars ++ allSizeVarsBranches R

/-- Helper: collect all size variables mentioned across a list of branches/fields. -/
def allSizeVarsBranches : List (Nat × TypeExpr) → List SizeVar
  | [] => []
  | (_, F) :: rest => F.allSizeVars ++ allSizeVarsBranches rest

end

/-- Polarized size-variable occurrence judgment `Δ ⊢ i ∈_π F` refined by fixpoint kind `fk ∈ {μ, ν}`
(Section 6.1, p. 43): records that size variable `i` occurs as the size annotation of a fixpoint
of kind `fk` with polarity `π` in `F`. -/
inductive SizeOccursFixPol : KindingCtx → FixKind → SizeVar → Polarity → TypeExpr → Prop where
  | mu_top {Δ : KindingCtx} {i : SizeVar} {n : Nat} {S : List (ConsName × TypeExpr)} :
      SizeOccursFixPol Δ .mu i .pos (.mu (.var i n) S)
  | nu_top {Δ : KindingCtx} {i : SizeVar} {n : Nat} {R : List (ProjName × TypeExpr)} :
      SizeOccursFixPol Δ .nu i .pos (.nu (.var i n) R)
  | mu_branch {Δ : KindingCtx} {fk : FixKind} {i : SizeVar} {π : Polarity}
      {a : SizeExp} {S : List (ConsName × TypeExpr)} {c : ConsName} {Sc : TypeExpr} :
      (c, Sc) ∈ S →
      SizeOccursFixPol Δ fk i π Sc →
      SizeOccursFixPol Δ fk i π (.mu a S)
  | nu_field {Δ : KindingCtx} {fk : FixKind} {i : SizeVar} {π : Polarity}
      {a : SizeExp} {R : List (ProjName × TypeExpr)} {d : ProjName} {Rd : TypeExpr} :
      (d, Rd) ∈ R →
      SizeOccursFixPol Δ fk i π Rd →
      SizeOccursFixPol Δ fk i π (.nu a R)
  | lam {Δ : KindingCtx} {fk : FixKind} {i : SizeVar} {π : Polarity}
      {X : TyVar} {ι : SKind} {F : TypeExpr} :
      SizeOccursFixPol (Δ.extType X .mixed (Kind.ofSKind ι)) fk i π F →
      SizeOccursFixPol Δ fk i π (.lam X ι F)
  | app_left {Δ : KindingCtx} {fk : FixKind} {i : SizeVar} {π π' : Polarity}
      {κ κ' : Kind} {F G : TypeExpr} :
      KindInfer Δ F (.arr π' κ κ') →
      SizeOccursFixPol Δ fk i π F →
      SizeOccursFixPol Δ fk i π (.app F G)
  | app_right {Δ : KindingCtx} {fk : FixKind} {i : SizeVar} {π π' : Polarity}
      {κ κ' : Kind} {F G : TypeExpr} :
      KindInfer Δ F (.arr π' κ κ') →
      SizeOccursFixPol (Δ.invScalePol π') fk i π G →
      SizeOccursFixPol Δ fk i (Polarity.comp π' π) (.app F G)

/-- Polarized size-variable occurrence `Δ ⊢ i ∈_π F` (Section 6.1, p. 43):
`i` occurs as index to some fixpoint operator (`μ` or `ν`) with polarity `π` in `F`. -/
def SizeOccursPol (Δ : KindingCtx) (i : SizeVar) (π : Polarity) (F : TypeExpr) : Prop :=
  ∃ fk : FixKind, SizeOccursFixPol Δ fk i π F

/-- Check whether a size variable `i` occurs anywhere in a type `F` (`i ∈ F.allSizeVars`). -/
def SizeOccursIn (i : SizeVar) (F : TypeExpr) : Prop :=
  i ∈ F.allSizeVars

mutual

/-- Polarized type signature encoding `π; Δ ⊢_{SCT}^{π*} A ⇒ Ψ; A'` (Section 6.1, pp. 42–43):
given target polarity `π*` (`π* = −` for top-level function signatures, `π* = ◦` for local type
annotations), current polarity `π`, kinding context `Δ`, and an unannotated type `A` of kind `κ`,
generates fresh unbounded size variables `Ψ` and a size-annotated type `A'`. -/
inductive EncodeType (πstar : Polarity) :
    Polarity → KindingCtx → TypeExpr → SizeCtx → TypeExpr → Prop where
  | unit (π : Polarity) (Δ : KindingCtx) :
      EncodeType πstar π Δ (.atom .unit) [] (.atom .unit)
  | prod (π : Polarity) (Δ : KindingCtx) :
      EncodeType πstar π Δ (.atom .prod) [] (.atom .prod)
  | arr (π : Polarity) (Δ : KindingCtx) :
      EncodeType πstar π Δ (.atom .arr) [] (.atom .arr)
  | var {π π' : Polarity} {Δ : KindingCtx} {X : TyVar} {ι : SKind} :
      TyDecl.mk X π' (Kind.ofSKind ι) ∈ Δ.types →
      Polarity.le π' .pos = true →
      EncodeType πstar π Δ (.atom (.var X)) [] (.atom (.var X))
  | all (π : Polarity) (Δ : KindingCtx) (ι : SKind) :
      EncodeType πstar π Δ (.atom (.all (Kind.ofSKind ι))) []
        (.atom (.all (Kind.ofSKind ι)))
  | ex (π : Polarity) (Δ : KindingCtx) (ι : SKind) :
      EncodeType πstar π Δ (.atom (.ex (Kind.ofSKind ι))) []
        (.atom (.ex (Kind.ofSKind ι)))
  | lam {π : Polarity} {Δ : KindingCtx} {X : TyVar} {ι : SKind}
      {F F' : TypeExpr} {Ψ : SizeCtx} :
      X ∉ Ψ.dom →
      EncodeType πstar π (Δ.extType X .mixed (Kind.ofSKind ι)) F Ψ F' →
      EncodeType πstar π Δ (.lam X ι F) Ψ (.lam X ι F')
  | app {π π' : Polarity} {Δ : KindingCtx} {F F' G G' : TypeExpr}
      {ι ι' : SKind} {Ψ₁ Ψ₂ : SizeCtx} :
      FwKindInfer Δ F (.arr π' ι ι') →
      KindInfer (Δ.extSizes Ψ₁) F' (.arr π' (Kind.ofSKind ι) (Kind.ofSKind ι')) →
      KindCheck ((Δ.extSizes Ψ₂).invScalePol π') G' (Kind.ofSKind ι) →
      EncodeType πstar π Δ F Ψ₁ F' →
      EncodeType πstar (Polarity.comp π' π) (Δ.invScalePol π') G Ψ₂ G' →
      List.Disjoint Ψ₁.dom Ψ₂.dom →
      List.Disjoint Ψ₁.dom G'.allSizeVars →
      List.Disjoint Ψ₂.dom F'.allSizeVars →
      EncodeType πstar π Δ (.app F G) (Ψ₁ ++ Ψ₂) (.app F' G')
  | mu_fresh {π : Polarity} {Δ : KindingCtx}
      {S S' : List (ConsName × TypeExpr)} {Ψ : SizeCtx} {i : SizeVar} :
      π = πstar →
      i ∉ Δ.sizes.dom →
      i ∉ Ψ.dom →
      i ∉ allSizeVarsBranches S' →
      EncodeBranches πstar π Δ S Ψ S' →
      EncodeType πstar π Δ (.mu .infty S) (⟨i, .mixed, .infty⟩ :: Ψ) (.mu (.var i 0) S')
  | mu_inf {π : Polarity} {Δ : KindingCtx}
      {S S' : List (ConsName × TypeExpr)} {Ψ : SizeCtx} :
      π ≠ πstar →
      EncodeBranches πstar π Δ S Ψ S' →
      EncodeType πstar π Δ (.mu .infty S) Ψ (.mu .infty S')
  | nu_fresh {π : Polarity} {Δ : KindingCtx}
      {R R' : List (ProjName × TypeExpr)} {Ψ : SizeCtx} {i : SizeVar} :
      π = Polarity.comp .neg πstar →
      i ∉ Δ.sizes.dom →
      i ∉ Ψ.dom →
      i ∉ allSizeVarsBranches R' →
      EncodeBranches πstar π Δ R Ψ R' →
      EncodeType πstar π Δ (.nu .infty R) (⟨i, .mixed, .infty⟩ :: Ψ) (.nu (.var i 0) R')
  | nu_inf {π : Polarity} {Δ : KindingCtx}
      {R R' : List (ProjName × TypeExpr)} {Ψ : SizeCtx} :
      π ≠ Polarity.comp .neg πstar →
      EncodeBranches πstar π Δ R Ψ R' →
      EncodeType πstar π Δ (.nu .infty R) Ψ (.nu .infty R')

/-- Helper judgment encoding datatype branches `S` or record fields `R` (Section 6.1, p. 42). -/
inductive EncodeBranches (πstar : Polarity) :
    Polarity → KindingCtx → List (Nat × TypeExpr) → SizeCtx → List (Nat × TypeExpr) → Prop where
  | nil (π : Polarity) (Δ : KindingCtx) :
      EncodeBranches πstar π Δ [] [] []
  | cons {π : Polarity} {Δ : KindingCtx} {nm : Nat} {F F' : TypeExpr}
      {rest rest' : List (Nat × TypeExpr)} {Ψ₁ Ψ₂ : SizeCtx} :
      EncodeType πstar π Δ F Ψ₁ F' →
      KindCheck (Δ.extSizes Ψ₁) F' functorKind →
      EncodeBranches πstar π Δ rest Ψ₂ rest' →
      List.Disjoint Ψ₁.dom Ψ₂.dom →
      List.Disjoint Ψ₁.dom (allSizeVarsBranches rest') →
      List.Disjoint Ψ₂.dom F'.allSizeVars →
      EncodeBranches πstar π Δ ((nm, F) :: rest) (Ψ₁ ++ Ψ₂) ((nm, F') :: rest')

end

/-! ## Section 6.2: Pattern and Copattern-Spine Rigid Variable Gathering (pp. 44–47) -/

/-- Rigid-variable gathering in a pattern `Δ₀ ⊢_{SCT} p : A ⇒ Γ; Δ; Ψ; p'`
(Section 6.2, p. 44). -/
inductive InferPat :
    KindingCtx → Pat → TypeExpr → TermCtx → List TyDecl → SizeCtx → Pat → Prop where
  | var (Δ₀ : KindingCtx) (x : TermVar) {A : TypeExpr} :
      KindCheck Δ₀ A .star →
      InferPat Δ₀ (.var x) A [(x, A)] [] [] (.var x)
  | unit (Δ₀ : KindingCtx) :
      InferPat Δ₀ .unit .unitTy [] [] [] .unit
  | pair {Δ₀ : KindingCtx} {p₁ p₂ p₁' p₂' : Pat} {A₁ A₂ : TypeExpr}
      {Γ₁ Γ₂ : TermCtx} {Δ₁ Δ₂ : List TyDecl} {Ψ₁ Ψ₂ : SizeCtx} :
      InferPat Δ₀ p₁ A₁ Γ₁ Δ₁ Ψ₁ p₁' →
      InferPat Δ₀ p₂ A₂ Γ₂ Δ₂ Ψ₂ p₂' →
      List.Disjoint Ψ₁.dom Ψ₂.dom →
      List.Disjoint Ψ₁.dom A₂.allSizeVars →
      InferPat Δ₀ (.pair p₁ p₂) (.prodTy A₁ A₂)
        (Γ₁ ++ Γ₂) (Δ₁ ++ Δ₂) (Ψ₁ ++ Ψ₂) (.pair p₁' p₂')
  | cons {Δ₀ : KindingCtx} {c : ConsName} {p p' : Pat} {a : SizeExp}
      {S : List (ConsName × TypeExpr)} {Sc : TypeExpr}
      {Γ : TermCtx} {Δ : List TyDecl} {Ψ : SizeCtx} (j : SizeVar) :
      TypeExpr.lookupCons S c = some Sc →
      j ∉ Δ₀.sizes.dom →
      j ∉ Ψ.dom →
      j ∉ a.vars →
      j ∉ allSizeVarsBranches S →
      InferPat (Δ₀.extType j .pos (.lt a.boundNorm))
        p (Sc.normApp (.mu (.var j 0) S)) Γ Δ Ψ p' →
      InferPat Δ₀ (.cons c p) (.mu a S)
        Γ (⟨j, .pos, .lt a.boundNorm⟩ :: Δ) (⟨j, .pos, a.boundNorm⟩ :: Ψ)
        (.cons c (.tyPack j p'))
  | tyPack {Δ₀ : KindingCtx} {X : TyVar} {ι : SKind} {p p' : Pat} {F : TypeExpr}
      {Γ : TermCtx} {Δ : List TyDecl} {Ψ : SizeCtx} :
      KindWf (Δ₀.sizes.invScalePol .mixed) (Kind.ofSKind ι) →
      InferPat (Δ₀.extType X .pos (Kind.ofSKind ι))
        p (F.normApp (.atom (.var X))) Γ Δ Ψ p' →
      InferPat Δ₀ (.tyPack X p) (.exTy (Kind.ofSKind ι) F)
        Γ (⟨X, .pos, Kind.ofSKind ι⟩ :: Δ) Ψ (.tyPack X p')

/-- Rigid-variable gathering in a copattern spine `Δ₀ ⊢_{SCT} q⃗ : A ⇒ C; Γ; Δ; Ψ; q⃗'`
(Section 6.2, p. 45). -/
inductive InferSpine :
    KindingCtx → PatSpine → TypeExpr → TypeExpr → TermCtx → List TyDecl → SizeCtx → PatSpine → Prop where
  | nil (Δ₀ : KindingCtx) (A : TypeExpr) :
      InferSpine Δ₀ [] A A [] [] [] []
  | pat {Δ₀ : KindingCtx} {p p' : Pat} {qs qs' : PatSpine} {A B C : TypeExpr}
      {Γ₁ Γ₂ : TermCtx} {Δ₁ Δ₂ : List TyDecl} {Ψ₁ Ψ₂ : SizeCtx} :
      InferPat Δ₀ p A Γ₁ Δ₁ Ψ₁ p' →
      InferSpine Δ₀ qs B C Γ₂ Δ₂ Ψ₂ qs' →
      List.Disjoint Ψ₁.dom Ψ₂.dom →
      List.Disjoint Ψ₁.dom B.allSizeVars →
      InferSpine Δ₀ (.pat p :: qs) (.arrTy A B) C
        (Γ₁ ++ Γ₂) (Δ₁ ++ Δ₂) (Ψ₁ ++ Ψ₂) (.pat p' :: qs')
  | proj {Δ₀ : KindingCtx} {d : ProjName} {qs qs' : PatSpine} {a : SizeExp}
      {R : List (ProjName × TypeExpr)} {Rd C : TypeExpr}
      {Γ : TermCtx} {Δ : List TyDecl} {Ψ : SizeCtx} (j : SizeVar) :
      TypeExpr.lookupProj R d = some Rd →
      j ∉ Δ₀.sizes.dom →
      j ∉ Ψ.dom →
      j ∉ a.vars →
      j ∉ allSizeVarsBranches R →
      InferSpine (Δ₀.extType j .pos (.lt a.boundNorm))
        qs (Rd.normApp (.nu (.var j 0) R)) C Γ Δ Ψ qs' →
      InferSpine Δ₀ (.proj d :: qs) (.nu a R) C
        Γ (⟨j, .pos, .lt a.boundNorm⟩ :: Δ) (⟨j, .pos, a.boundNorm⟩ :: Ψ)
        (.proj d :: .tyVar j :: qs')
  | tyApp {Δ₀ : KindingCtx} {X : TyVar} {ι : SKind} {qs qs' : PatSpine}
      {F C : TypeExpr} {Γ : TermCtx} {Δ : List TyDecl} {Ψ : SizeCtx} :
      KindWf (Δ₀.sizes.invScalePol .mixed) (Kind.ofSKind ι) →
      InferSpine (Δ₀.extType X .pos (Kind.ofSKind ι))
        qs (F.normApp (.atom (.var X))) C Γ Δ Ψ qs' →
      InferSpine Δ₀ (.tyVar X :: qs) (.allTy (Kind.ofSKind ι) F) C
        Γ (⟨X, .pos, Kind.ofSKind ι⟩ :: Δ) Ψ (.tyVar X :: qs')

/-- Classification of rigid-variable polarities in a pattern (Lemma 4, pp. 45–46):
for a size variable `i ∈ Ψ`, either:
1. `∃ (x, B) ∈ Γ` such that `μ^i` occurs positively in `B` (and nowhere negatively),
2. `∃ (x, B) ∈ Γ` such that `ν^i` occurs negatively in `B` (and nowhere positively), or
3. `i` does not occur in `B` for any `(x, B) ∈ Γ`. -/
def PatRigidVarClass (Δ : KindingCtx) (Γ : TermCtx) (i : SizeVar) : Prop :=
  ((∃ p ∈ Γ, SizeOccursFixPol Δ .mu i .pos p.2) ∧
    ¬ (∃ p ∈ Γ, SizeOccursFixPol Δ .nu i .neg p.2) ∧
    (∃ p ∈ Γ, SizeOccursIn i p.2)) ∨
  (¬ (∃ p ∈ Γ, SizeOccursFixPol Δ .mu i .pos p.2) ∧
    (∃ p ∈ Γ, SizeOccursFixPol Δ .nu i .neg p.2) ∧
    (∃ p ∈ Γ, SizeOccursIn i p.2)) ∨
  (¬ (∃ p ∈ Γ, SizeOccursFixPol Δ .mu i .pos p.2) ∧
    ¬ (∃ p ∈ Γ, SizeOccursFixPol Δ .nu i .neg p.2) ∧
    ¬ (∃ p ∈ Γ, SizeOccursIn i p.2))

/-- Classification of rigid-variable polarities in a copattern spine (Lemma 5, pp. 46–47):
for a size variable `i ∈ Ψ₁ ++ Ψ₂`, exactly one of the four statements holds:
1. `∃ (x, B) ∈ Γ` such that `μ^i` occurs positively in `B`
2. `μ^i` occurs negatively in `A''`
3. `(∃ (x, B) ∈ Γ, ν^i occurs negatively in B) ∨ (ν^i occurs positively in A'')`
4. `i` does not occur in `A''` and does not occur in `B` for any `(x, B) ∈ Γ`. -/
def SpineRigidVarClass (Δ : KindingCtx) (Γ : TermCtx) (A'' : TypeExpr) (i : SizeVar) : Prop :=
  let c1 := ∃ p ∈ Γ, SizeOccursFixPol Δ .mu i .pos p.2
  let c2 := SizeOccursFixPol Δ .mu i .neg A''
  let c3 := (∃ p ∈ Γ, SizeOccursFixPol Δ .nu i .neg p.2) ∨ SizeOccursFixPol Δ .nu i .pos A''
  let c4 := ¬ SizeOccursIn i A'' ∧ ¬ ∃ p ∈ Γ, SizeOccursIn i p.2
  (c1 ∧ ¬ c2 ∧ ¬ c3 ∧ ¬ c4) ∨
  (¬ c1 ∧ c2 ∧ ¬ c3 ∧ ¬ c4) ∨
  (¬ c1 ∧ ¬ c2 ∧ c3 ∧ ¬ c4) ∨
  (¬ c1 ∧ ¬ c2 ∧ ¬ c3 ∧ c4)

mutual

/-- Collect all inductive branch lists `S` occurring in `.mu a S` subterms of a `TypeExpr`. -/
def TypeExpr.allMuBranchLists : TypeExpr → List (List (ConsName × TypeExpr))
  | .atom _ => []
  | .lam _ _ body => body.allMuBranchLists
  | .app F G => F.allMuBranchLists ++ G.allMuBranchLists
  | .mu _ S => S :: allMuBranchListsInBranches S
  | .nu _ R => allMuBranchListsInBranches R

/-- Helper: collect inductive branch lists across a list of named branches/fields. -/
def allMuBranchListsInBranches : List (Nat × TypeExpr) → List (List (ConsName × TypeExpr))
  | [] => []
  | (_, F) :: rest => F.allMuBranchLists ++ allMuBranchListsInBranches rest

end

mutual

/-- Collect all coinductive field lists `R` occurring in `.nu a R` subterms of a `TypeExpr`. -/
def TypeExpr.allNuFieldLists : TypeExpr → List (List (ProjName × TypeExpr))
  | .atom _ => []
  | .lam _ _ body => body.allNuFieldLists
  | .app F G => F.allNuFieldLists ++ G.allNuFieldLists
  | .mu _ S => allNuFieldListsInBranches S
  | .nu _ R => R :: allNuFieldListsInBranches R

/-- Helper: collect coinductive field lists across a list of named branches/fields. -/
def allNuFieldListsInBranches : List (Nat × TypeExpr) → List (List (ProjName × TypeExpr))
  | [] => []
  | (_, F) :: rest => F.allNuFieldLists ++ allNuFieldListsInBranches rest

end

/-- Positive fixpoint-polarity separation on a domain/pattern type `A` in `Δ`:
every size variable `i` occurring in `A` occurs either at `(μ, +)` (and not `(ν, -)`)
or at `(ν, -)` (and not `(μ, +)`). -/
def PosFixpointPolClean (Δ : KindingCtx) (A : TypeExpr) : Prop :=
  ∀ i : SizeVar,
    SizeOccursIn i A →
    (SizeOccursFixPol Δ .mu i .pos A ∧ ¬ SizeOccursFixPol Δ .nu i .neg A) ∨
    (SizeOccursFixPol Δ .nu i .neg A ∧ ¬ SizeOccursFixPol Δ .mu i .pos A)

/-- Negative fixpoint-polarity separation on a signature/clause type `A` in `Δ`:
every size variable `i` occurring in `A` occurs either at `(μ, -)` (and not `(ν, +)`)
or at `(ν, +)` (and not `(μ, -)`). -/
def NegFixpointPolClean (Δ : KindingCtx) (A : TypeExpr) : Prop :=
  ∀ i : SizeVar,
    SizeOccursIn i A →
    (SizeOccursFixPol Δ .mu i .neg A ∧ ¬ SizeOccursFixPol Δ .nu i .pos A) ∨
    (SizeOccursFixPol Δ .nu i .pos A ∧ ¬ SizeOccursFixPol Δ .mu i .neg A)

/-- Strict positivity and polarity hygiene of a size-annotated pattern type `A₀` in context `Δ₀`
(Section 6.2, Lemma 4, pp. 45–46):
1. `PosFixpointPolClean Δ₀ A₀` holds;
2. For every inductive branch list `S ∈ A₀.allMuBranchLists`, every constructor `(c, Sc)` in `S`,
   and every fresh size variable `j`, the unrolled constructor domain `B = Sc.normApp (.mu (.var j 0) S)`
   satisfies `PosFixpointPolClean`, and if `j` occurs in `B`, `j` occurs at `(μ, +)` and not `(ν, -)`. -/
def PositiveFixpointHygiene (Δ₀ : KindingCtx) (A₀ : TypeExpr) : Prop :=
  PosFixpointPolClean Δ₀ A₀ ∧
  ∀ S ∈ A₀.allMuBranchLists, ∀ (c : ConsName) (Sc : TypeExpr) (j : SizeVar),
    TypeExpr.lookupCons S c = some Sc →
    j ∉ Δ₀.sizes.dom →
    j ∉ allSizeVarsBranches S →
    let Δj := Δ₀.extType j .pos (.lt .infty)
    let B := Sc.normApp (.mu (.var j 0) S)
    PosFixpointPolClean Δj B ∧
    (SizeOccursIn j B →
      SizeOccursFixPol Δj .mu j .pos B ∧ ¬ SizeOccursFixPol Δj .nu j .neg B)

/-- Polarity and fixpoint-functor hygiene of a size-annotated signature/spine type `A₀` in context
`Δ₀` (Section 6.2, Lemma 5, pp. 46–47):
1. `NegFixpointPolClean Δ₀ A₀` holds;
2. Every inductive branch list `S ∈ A₀.allMuBranchLists` has positive constructor functors;
3. Every coinductive field list `R ∈ A₀.allNuFieldLists` has positive destructor functors. -/
def SignatureFixpointHygiene (Δ₀ : KindingCtx) (A₀ : TypeExpr) : Prop :=
  NegFixpointPolClean Δ₀ A₀ ∧
  (∀ S ∈ A₀.allMuBranchLists, ∀ (c : ConsName) (Sc : TypeExpr) (j : SizeVar),
    TypeExpr.lookupCons S c = some Sc →
    j ∉ Δ₀.sizes.dom →
    j ∉ allSizeVarsBranches S →
    let Δj := Δ₀.extType j .pos (.lt .infty)
    let B := Sc.normApp (.mu (.var j 0) S)
    PosFixpointPolClean Δj B ∧
    (SizeOccursIn j B →
      SizeOccursFixPol Δj .mu j .pos B ∧ ¬ SizeOccursFixPol Δj .nu j .neg B)) ∧
  (∀ R ∈ A₀.allNuFieldLists, ∀ (d : ProjName) (Rd : TypeExpr) (j : SizeVar),
    TypeExpr.lookupProj R d = some Rd →
    j ∉ Δ₀.sizes.dom →
    j ∉ allSizeVarsBranches R →
    let Δj := Δ₀.extType j .pos (.lt .infty)
    let B := Rd.normApp (.nu (.var j 0) R)
    NegFixpointPolClean Δj B ∧
    (SizeOccursIn j B →
      SizeOccursFixPol Δj .nu j .pos B ∧ ¬ SizeOccursFixPol Δj .mu j .neg B))

/-! ## Section 6.3: Call-Site Inference, Checking, and Type Comparison (pp. 48–56) -/

/-- Polarized size variable context `Φ ⊂ SizeVar × Polarity` tracking flexible (and rigid)
size variables together with their fixpoint polarities (`+` for `μ`, `−` for `ν`, `◦` for mixed)
(Section 6.3, p. 48). -/
abbrev FlexVars := List (SizeVar × Polarity)

namespace FlexVars

/-- Domain of size variables in `Φ`. -/
def dom (Φ : FlexVars) : List SizeVar :=
  Φ.map (·.1)

/-- Lookup the polarity `π` associated with a size variable `i` in `Φ`. -/
def lookupPol (Φ : FlexVars) (i : SizeVar) : Option Polarity :=
  (Φ.find? (fun p => p.1 == i)).map (·.2)

/-- Lookup the polarity of a size expression `a` in `Φ ∪ {(∞, defaultInfPol)}`
(Section 6.3.3, p. 51). -/
def lookupSizePol (Φ : FlexVars) (defaultInfPol : Polarity) (a : SizeExp) : Option Polarity :=
  match a with
  | .inf _ => some defaultInfPol
  | .meet ⟨⟨i, 0⟩, []⟩ => Φ.lookupPol i
  | _ => none

end FlexVars

/-- Information-order join `max(π₁, π₂)` on `{◦, +, −}` used in fixpoint size comparison
(Section 6.3.3, p. 51 & Theorem 10 proof, p. 52: `max(π₁, +) = +` for `π₁ ∈ {◦, +}`, and
`max(π₁, −) = −` for `π₁ ∈ {◦, −}`). -/
def Polarity.infoMax : Polarity → Polarity → Polarity
  | .mixed, π => π
  | π, .mixed => π
  | .pos, .pos => .pos
  | .neg, .neg => .neg
  | _, _ => .top

/-- A size constraint `(lhs R rhs) ∈ C` where `R ∈ {<, ≤}` (Section 6.3, p. 48). -/
structure SizeConstraint where
  lhs : SizeExp
  rel : EdgeRel
  rhs : SizeExp
  deriving DecidableEq, Repr

namespace SizeConstraint

/-- Generate the constraint(s) corresponding to polarized comparison `a ≤^π b`
(Section 4.1.3, p. 22 & Section 6.3.3, p. 51):
- `a ≤^+ b` produces `[a ≤ b]`
- `a ≤^− b` produces `[b ≤ a]`
- `a ≤^◦ b` produces `[a ≤ b, b ≤ a]`
- `a ≤^⊤ b` produces `[]`. -/
def ofPol (π : Polarity) (a b : SizeExp) : List SizeConstraint :=
  match π with
  | .pos => [⟨a, .le, b⟩]
  | .neg => [⟨b, .le, a⟩]
  | .mixed => [⟨a, .le, b⟩, ⟨b, .le, a⟩]
  | .top => []

/-- Check whether size variable `i` appears on the LHS or RHS of a constraint `c`. -/
def mentions (c : SizeConstraint) (i : SizeVar) : Bool :=
  c.lhs.vars.contains i || c.rhs.vars.contains i

end SizeConstraint

mutual

/-- Polarized type comparison `Φ; Δ; ι ⊢_{SCT} A ≤^π B ⇒ C` generating size constraints `C`
(Section 6.3.3, pp. 50–52). -/
inductive CompareTypes (Φ : FlexVars) :
    KindingCtx → SKind → Polarity → TypeExpr → TypeExpr → List SizeConstraint → Prop where
  | atom (Δ : KindingCtx) (ι : SKind) (π : Polarity) (K : TyAtom) :
      CompareTypes Φ Δ ι π (.atom K) (.atom K) []
  | app {Δ : KindingCtx} {π₁ π : Polarity} {ι₁ ι₂ : SKind}
      {F F' G G' : TypeExpr} {C₁ C₂ : List SizeConstraint} :
      KindInfer Δ F' (.arr π₁ (Kind.ofSKind ι₁) (Kind.ofSKind ι₂)) →
      CompareTypes Φ Δ (.arr π₁ ι₁ ι₂) π F F' C₁ →
      CompareTypes Φ (Δ.invScalePol π₁) ι₁ (Polarity.comp π₁ π) G G' C₂ →
      CompareTypes Φ Δ ι₂ π (.app F G) (.app F' G') (C₁ ++ C₂)
  | lam {Δ : KindingCtx} {π₁ π : Polarity} {ι₁ ι₂ : SKind}
      {F F' : TypeExpr} {X : TyVar} {C : List SizeConstraint} :
      CompareTypes Φ (Δ.extType X π₁ (Kind.ofSKind ι₁)) ι₂ π
        (F.normApp (.atom (.var X))) (F'.normApp (.atom (.var X))) C →
      CompareTypes Φ Δ (.arr π₁ ι₁ ι₂) π F F' C
  | mu {Δ : KindingCtx} {π π₁ π₂ : Polarity} {a b : SizeExp}
      {S S' : List (ConsName × TypeExpr)} {C : List SizeConstraint} :
      Φ.lookupSizePol .pos a = some π₁ →
      Φ.lookupSizePol .pos b = some π₂ →
      CompareBranches Φ Δ π S S' C →
      CompareTypes Φ Δ .star π (.mu a S) (.mu b S')
        (SizeConstraint.ofPol (Polarity.comp (Polarity.infoMax π₁ π₂) π) a b ++ C)
  | nu {Δ : KindingCtx} {π π₁ π₂ : Polarity} {a b : SizeExp}
      {R R' : List (ProjName × TypeExpr)} {C : List SizeConstraint} :
      Φ.lookupSizePol .neg a = some π₁ →
      Φ.lookupSizePol .neg b = some π₂ →
      CompareBranches Φ Δ π R R' C →
      CompareTypes Φ Δ .star π (.nu a R) (.nu b R')
        (SizeConstraint.ofPol (Polarity.comp (Polarity.infoMax π₁ π₂) π) a b ++ C)

/-- Helper judgment comparing datatype branches `S ≤^π S'` or record fields `R ≤^π R'`
(Section 6.3.3, p. 51). -/
inductive CompareBranches (Φ : FlexVars) :
    KindingCtx → Polarity → List (Nat × TypeExpr) → List (Nat × TypeExpr) → List SizeConstraint → Prop where
  | nil (Δ : KindingCtx) (π : Polarity) :
      CompareBranches Φ Δ π [] [] []
  | cons {Δ : KindingCtx} {π : Polarity} {nm : Nat} {F F' : TypeExpr}
      {rest rest' : List (Nat × TypeExpr)} {C₁ C₂ : List SizeConstraint} :
      CompareTypes Φ Δ fwFunctorSKind π F F' C₁ →
      CompareBranches Φ Δ π rest rest' C₂ →
      CompareBranches Φ Δ π ((nm, F) :: rest) ((nm, F') :: rest') (C₁ ++ C₂)

end

/-- Well-formed polarity assignment in `Φ` (Section 6.3.4, Theorem 10, pp. 51–52):
variables generated for least fixpoints (`μ`) have polarity `+` or `◦`, and variables
generated for greatest fixpoints (`ν`) have polarity `−` or `◦`. -/
def FlexPolHygiene (Φ : FlexVars) (Δ : KindingCtx) (A C : TypeExpr) : Prop :=
  (∀ i π₁, Φ.lookupSizePol .pos (.var i 0) = some π₁ →
    (SizeOccursFixPol Δ .mu i .pos A ∨ SizeOccursFixPol Δ .mu i .neg A ∨
     SizeOccursFixPol Δ .mu i .pos C ∨ SizeOccursFixPol Δ .mu i .neg C) →
    π₁ = .pos ∨ π₁ = .mixed) ∧
  (∀ i π₁, Φ.lookupSizePol .neg (.var i 0) = some π₁ →
    (SizeOccursFixPol Δ .nu i .pos A ∨ SizeOccursFixPol Δ .nu i .neg A ∨
     SizeOccursFixPol Δ .nu i .pos C ∨ SizeOccursFixPol Δ .nu i .neg C) →
    π₁ = .neg ∨ π₁ = .mixed)

/-- Context trivialization `Φ ⊢_↓ Ψ₁ ⇒ Ψ₂` (Section 6.3.2, p. 50):
replaces any bound `< i` in `Ψ₁` whose variable `i` belongs to `Φ` with `< ∞`, so that
the resulting context `Ψ₂` satisfies the consistent extension check `Δ ⊢ ∃Δ'`. -/
def trivializeCtx (Φ : FlexVars) (Ψ₁ : SizeCtx) : SizeCtx :=
  Ψ₁.map fun d =>
    match d.bound with
    | .meet ⟨⟨a, 0⟩, []⟩ =>
        if Φ.dom.contains a then { d with bound := .infty } else d
    | _ => d

/-- Relational form of context trivialization `Φ ⊢_↓ Ψ₁ ⇒ Ψ₂` (Section 6.3.2, p. 50). -/
def TrivializeCtx (Φ : FlexVars) (Ψ₁ Ψ₂ : SizeCtx) : Prop :=
  Ψ₂ = trivializeCtx Φ Ψ₁

mutual

/-- Call-site inference judgment `Φ; Γ; Δ ⊢_{SCT} t ⇒ A; Φ'; C; T; t'`
(Section 6.3.1, pp. 48–50). -/
inductive InferTerm (sig : GlobalSig) (Ξ : MutualBlock) :
    FlexVars → TermCtx → KindingCtx → Term →
    TypeExpr → FlexVars → List SizeConstraint → List SizeVar → Term → Prop where
  | var {Φ : FlexVars} {Γ : TermCtx} {Δ : KindingCtx} {x : TermVar} {A : TypeExpr} :
      (x, A) ∈ Γ →
      InferTerm sig Ξ Φ Γ Δ (.var x) A Φ [] [] (.var x)
  | appTerm {Φ Φ₁ Φ₂ : FlexVars} {Γ : TermCtx} {Δ : KindingCtx}
      {r r' s s' : Term} {A B : TypeExpr}
      {C₁ C₂ : List SizeConstraint} {T₁ T₂ : List SizeVar} :
      InferTerm sig Ξ Φ Γ Δ r (.arrTy A B) Φ₁ C₁ T₁ r' →
      CheckTerm sig Ξ Φ₁ Γ Δ A s Φ₂ C₂ T₂ s' →
      InferTerm sig Ξ Φ Γ Δ (.app r (.term s)) B Φ₂ (C₁ ++ C₂) (T₁ ++ T₂) (.app r' (.term s'))
  | proj {Φ Φ' : FlexVars} {Γ : TermCtx} {Δ : KindingCtx}
      {r r' : Term} {a : SizeExp} {R : List (ProjName × TypeExpr)}
      {d : ProjName} {Rd : TypeExpr}
      {C : List SizeConstraint} {T T' : List SizeVar} (j : SizeVar) :
      InferTerm sig Ξ Φ Γ Δ r (.nu a R) Φ' C T r' →
      TypeExpr.lookupProj R d = some Rd →
      j ∉ Φ'.dom →
      j ∉ Δ.sizes.dom →
      T' = (if j ∈ (Rd.normApp (.nu (.var j 0) R)).allSizeVars then T else j :: T) →
      InferTerm sig Ξ Φ Γ Δ (.app r (.proj d none))
        (Rd.normApp (.nu (.var j 0) R))
        ((j, .neg) :: Φ') (⟨.var j 0, .lt, a⟩ :: C) T'
        (.app r' (.proj d (some (.var j 0))))
  | appTy {Φ Φ' : FlexVars} {Γ : TermCtx} {Δ : KindingCtx}
      {r r' : Term} {G G' F : TypeExpr} {ι : SKind} {Ψ : SizeCtx}
      {C : List SizeConstraint} {T : List SizeVar} :
      EncodeType .mixed .mixed Δ G Ψ G' →
      List.Disjoint Ψ.dom Φ'.dom →
      InferTerm sig Ξ Φ Γ Δ r (.allTy (Kind.ofSKind ι) F) Φ' C T r' →
      InferTerm sig Ξ Φ Γ Δ (.app r (.tyArg G))
        (F.normApp G')
        (Ψ.map (fun d => (d.var, .mixed)) ++ Φ') C T
        (.app r' (.tyArg G'))
  | ascr {Φ Φ' : FlexVars} {Γ : TermCtx} {Δ : KindingCtx}
      {t t' : Term} {A A' : TypeExpr} {Ψ : SizeCtx}
      {C : List SizeConstraint} {T : List SizeVar} :
      EncodeType .mixed .mixed Δ A Ψ A' →
      List.Disjoint Ψ.dom Φ'.dom →
      CheckTerm sig Ξ Φ Γ Δ A' t Φ' C T t' →
      InferTerm sig Ξ Φ Γ Δ (.ascr t A) A'
        (Ψ.map (fun d => (d.var, .mixed)) ++ Φ') C T
        (.ascr t' A')
  | funCall {Φ : FlexVars} {Γ : TermCtx} {Δ : KindingCtx}
      {decl : FunDecl} {flexVars : List (SizeVar × Polarity)} {as : List SizeExp} :
      decl ∈ sig ++ Ξ →
      flexVars.length = decl.sizeParams.length →
      flexVars.Nodup →
      List.Disjoint (flexVars.map (·.1)) Φ.dom →
      List.Disjoint (flexVars.map (·.1)) Δ.sizes.dom →
      (∀ p ∈ decl.sizeParams.zip flexVars,
        (SizeOccursFixPol (Δ.extSizes decl.sizeParams) .mu p.1.var .neg decl.ty → p.2.2 = .pos) ∧
        (SizeOccursFixPol (Δ.extSizes decl.sizeParams) .nu p.1.var .pos decl.ty → p.2.2 = .neg) ∧
        (p.2.2 = .pos ∨ p.2.2 = .neg ∨ p.2.2 = .mixed)) →
      as = flexVars.map (fun p => SizeExp.var p.1 0) →
      InferTerm sig Ξ Φ Γ Δ (.funRef decl.name [])
        (decl.ty.substSizes (decl.sizeParams.dom.zip as))
        (flexVars ++ Φ) [] []
        (.funRef decl.name as)

/-- Call-site checking judgment `Φ; Γ; Δ | A ⊢_{SCT} t ⇒ Φ'; C; T; t'`
(Section 6.3.2, pp. 50–51). -/
inductive CheckTerm (sig : GlobalSig) (Ξ : MutualBlock) :
    FlexVars → TermCtx → KindingCtx → TypeExpr → Term →
    FlexVars → List SizeConstraint → List SizeVar → Term → Prop where
  | unit (Φ : FlexVars) (Γ : TermCtx) (Δ : KindingCtx) :
      CheckTerm sig Ξ Φ Γ Δ .unitTy .unit Φ [] [] .unit
  | pair {Φ Φ₁ Φ₂ : FlexVars} {Γ : TermCtx} {Δ : KindingCtx}
      {A₁ A₂ : TypeExpr} {t₁ t₁' t₂ t₂' : Term}
      {C₁ C₂ : List SizeConstraint} {T₁ T₂ : List SizeVar} :
      CheckTerm sig Ξ Φ Γ Δ A₁ t₁ Φ₁ C₁ T₁ t₁' →
      CheckTerm sig Ξ Φ₁ Γ Δ A₂ t₂ Φ₂ C₂ T₂ t₂' →
      CheckTerm sig Ξ Φ Γ Δ (.prodTy A₁ A₂) (.pair t₁ t₂)
        Φ₂ (C₁ ++ C₂) (T₁ ++ T₂) (.pair t₁' t₂')
  | lamClauses {Φ Φ' : FlexVars} {Γ : TermCtx} {Δ : KindingCtx}
      {A : TypeExpr} {Ds Ds' : List Clause}
      {C : List SizeConstraint} {T : List SizeVar} :
      CheckClausesInfer sig Ξ Φ Γ Δ A Ds Φ' C T Ds' →
      CheckTerm sig Ξ Φ Γ Δ A (.lamClauses Ds) Φ' C T (.lamClauses Ds')
  | cons {Φ Φ' : FlexVars} {Γ : TermCtx} {Δ : KindingCtx}
      {c : ConsName} {a : SizeExp} {S : List (ConsName × TypeExpr)} {Sc : TypeExpr}
      {t t' : Term} {C : List SizeConstraint} {T T' : List SizeVar} (j : SizeVar) :
      TypeExpr.lookupCons S c = some Sc →
      j ∉ Φ.dom →
      j ∉ Δ.sizes.dom →
      CheckTerm sig Ξ ((j, .pos) :: Φ) Γ Δ (Sc.normApp (.mu (.var j 0) S)) t Φ' C T t' →
      T' = (if j ∈ (Sc.normApp (.mu (.var j 0) S)).allSizeVars then T else j :: T) →
      CheckTerm sig Ξ Φ Γ Δ (.mu a S) (.cons c none t)
        Φ' (⟨.var j 0, .lt, a⟩ :: C) T' (.cons c (some (.var j 0)) t')
  | pack {Φ Φ' : FlexVars} {Γ : TermCtx} {Δ : KindingCtx}
      {ι : SKind} {F G G' : TypeExpr} {Ψ : SizeCtx} {t t' : Term}
      {C : List SizeConstraint} {T : List SizeVar} :
      EncodeType .mixed .mixed Δ G Ψ G' →
      List.Disjoint Ψ.dom Φ.dom →
      CheckTerm sig Ξ (Ψ.map (fun d => (d.var, .mixed)) ++ Φ) Γ Δ (F.normApp G') t Φ' C T t' →
      CheckTerm sig Ξ Φ Γ Δ (.exTy (Kind.ofSKind ι) F) (.pack G t) Φ' C T (.pack G' t')
  | sub {Φ Φ' : FlexVars} {Γ : TermCtx} {Δ : KindingCtx}
      {A Cty : TypeExpr} {r r' : Term}
      {C₁ C₂ : List SizeConstraint} {T : List SizeVar} :
      InferTerm sig Ξ Φ Γ Δ r A Φ' C₁ T r' →
      FlexPolHygiene Φ' Δ A Cty →
      CompareTypes Φ' Δ .star .pos A Cty C₂ →
      CheckTerm sig Ξ Φ Γ Δ Cty r Φ' (C₁ ++ C₂) T r'

/-- Single-clause checking with constraint generation
`Φ; Γ; Δ | C ⊢_{SCT} {q⃗ → t} ⇒ Φ'; C_out; T; {q⃗' → t'}` (Section 6.3.2, p. 51). -/
inductive CheckClauseInfer (sig : GlobalSig) (Ξ : MutualBlock) :
    FlexVars → TermCtx → KindingCtx → TypeExpr → Clause →
    FlexVars → List SizeConstraint → List SizeVar → Clause → Prop where
  | mk {Φ Φ' : FlexVars} {Γ Γ' : TermCtx} {Δ : KindingCtx} {Δ' : List TyDecl}
      {Ψ Ψ' : SizeCtx} {C C' : TypeExpr} {qs qs' : PatSpine} {t t' : Term}
      {Cs : List SizeConstraint} {T : List SizeVar} :
      InferSpine Δ qs C C' Γ' Δ' Ψ qs' →
      Ψ' = trivializeCtx Φ Ψ →
      CheckTerm sig Ξ (Ψ'.map (fun d => (d.var, d.pol)) ++ Φ)
        (Γ ++ Γ') (Δ.append ⟨Ψ', Δ'⟩) C' t Φ' Cs T t' →
      CheckClauseInfer sig Ξ Φ Γ Δ C (.mk qs t) Φ' Cs T (.mk qs' t')

/-- Multi-clause checking with constraint generation
`Φ; Γ; Δ | C ⊢_{SCT} D⃗ ⇒ Φ'; C_out; T; D⃗'` (Section 6.3.2, p. 51). -/
inductive CheckClausesInfer (sig : GlobalSig) (Ξ : MutualBlock) :
    FlexVars → TermCtx → KindingCtx → TypeExpr → List Clause →
    FlexVars → List SizeConstraint → List SizeVar → List Clause → Prop where
  | nil (Φ : FlexVars) (Γ : TermCtx) (Δ : KindingCtx) (C : TypeExpr) :
      CheckClausesInfer sig Ξ Φ Γ Δ C [] Φ [] [] []
  | cons {Φ Φ₁ Φ₂ : FlexVars} {Γ : TermCtx} {Δ : KindingCtx} {C : TypeExpr}
      {D D' : Clause} {Ds Ds' : List Clause}
      {C₁ C₂ : List SizeConstraint} {T₁ T₂ : List SizeVar} :
      CheckClauseInfer sig Ξ Φ Γ Δ C D Φ₁ C₁ T₁ D' →
      CheckClausesInfer sig Ξ Φ₁ Γ Δ C Ds Φ₂ C₂ T₂ Ds' →
      CheckClausesInfer sig Ξ Φ Γ Δ C (D :: Ds) Φ₂ (C₁ ++ C₂) (T₁ ++ T₂) (D' :: Ds')

end

/-- Hypotheses of Theorem 11 (Nature of rigid variables, Section 6.3.4, pp. 53–54)
for a set `X : List SizeVar` of rigid variables of polarity `π ∈ {+, −}`:
1. every `i ∈ X` is recorded in `Φ₀` with polarity `π` (`(i, π) ∈ Φ₀`);
2. for every `(x, Bₖ) ∈ Γ`, either `Δ ⊢ (fk, i) ∈_π Bₖ` or `i` does not occur in `Bₖ`;
3. for the checked type `A`, either `Δ ⊢ (fk, i) ∈_{−π} A` or `i` does not occur in `A`;
4. if `π = +`, all occurrences of `i` in `Γ` and `A` have `fk = .mu`; if `π = −`, all have `fk = .nu`. -/
def RigidVarHypotheses (π : Polarity) (X : List SizeVar) (Φ₀ : FlexVars)
    (Γ : TermCtx) (Δ : KindingCtx) (A : TypeExpr) : Prop :=
  (π = .pos ∨ π = .neg) ∧
  let fk : FixKind := if π == .pos then .mu else .nu
  ∀ i ∈ X,
    Φ₀.lookupPol i = some π ∧
    (∀ p ∈ Γ, SizeOccursFixPol Δ fk i π p.2 ∨ ¬ SizeOccursIn i p.2) ∧
    (SizeOccursFixPol Δ fk i (Polarity.comp .neg π) A ∨ ¬ SizeOccursIn i A)

/-! ## Sections 6.4–6.5: Constraint Solving (Algorithm 1) & Termination Checker (Algorithm 2) (pp. 56–60) -/

/-- Flexible substitution `φ : SizeVar → SizeExp` mapping flexible variables to size expressions
over a rigid context `Ψ` (Section 6.4, p. 56). -/
abbrev FlexSubst := SizeVar → SizeExp

/-- Apply a flexible substitution `φ` to a `SizeExp` (`φ(a)`). -/
def SizeExp.applyFlex (φ : FlexSubst) (a : SizeExp) : SizeExp :=
  a.subst (a.vars.map (fun k => (k, φ k)))

mutual

/-- Functorial extension `φ(t)` of a flexible substitution `φ` to a term `t`
(Section 6.4, p. 56). -/
def Term.applyFlex (φ : FlexSubst) : Term → Term
  | .var x => .var x
  | .funRef f as => .funRef f (as.map (·.applyFlex φ))
  | .app r e => .app (r.applyFlex φ) (e.applyFlex φ)
  | .unit => .unit
  | .pair t₁ t₂ => .pair (t₁.applyFlex φ) (t₂.applyFlex φ)
  | .cons c ma t => .cons c (ma.map (·.applyFlex φ)) (t.applyFlex φ)
  | .pack G t => .pack (G.substSizes (G.allSizeVars.map (fun k => (k, φ k)))) (t.applyFlex φ)
  | .lamClauses Ds => .lamClauses (applyFlexClauses φ Ds)
  | .ascr t A => .ascr (t.applyFlex φ) (A.substSizes (A.allSizeVars.map (fun k => (k, φ k))))

/-- Functorial extension `φ(e)` of `φ` to an elimination `e`. -/
def Elim.applyFlex (φ : FlexSubst) : Elim → Elim
  | .term t => .term (t.applyFlex φ)
  | .tyArg G => .tyArg (G.substSizes (G.allSizeVars.map (fun k => (k, φ k))))
  | .proj d ma => .proj d (ma.map (·.applyFlex φ))

/-- Functorial extension `φ(D)` of `φ` to a clause `D`. -/
def Clause.applyFlex (φ : FlexSubst) : Clause → Clause
  | .mk qs t => .mk qs (t.applyFlex φ)

/-- Helper: functorial extension `φ(D⃗)` across a list of clauses. -/
def applyFlexClauses (φ : FlexSubst) : List Clause → List Clause
  | [] => []
  | D :: rest => D.applyFlex φ :: applyFlexClauses φ rest

end

/-- Well-formedness of a flexible substitution `φ : Φ \ Ψ → {a | Ψ ⊢ a}` (Section 6.4, p. 56):
`φ` leaves every rigid variable `i ∈ Ψ.dom` fixed (`φ(i) = .var i 0`) and maps every variable `k`
to a size expression well-formed in `Ψ` (`Ψ ⊢ φ(k)`). -/
def ValidFlexSubst (Ψ : SizeCtx) (φ : FlexSubst) : Prop :=
  (∀ i ∈ Ψ.dom, φ i = .var i 0) ∧
  (∀ k : SizeVar, SizeWf Ψ (φ k))

/-- Coherence of a flexible substitution `Ψ; C ⊢ φ` with respect to a constraint set `C`
(Section 6.4, p. 56):
`φ` is a valid flexible substitution over `Ψ`, and for every `(lhs R rhs) ∈ C`,
`Ψ ⊢ φ(lhs) R φ(rhs)^↑`. -/
def CoherentSubst (Ψ : SizeCtx) (C : List SizeConstraint) (φ : FlexSubst) : Prop :=
  ValidFlexSubst Ψ φ ∧
  ∀ c ∈ C,
    match c.rel with
    | .lt => SizeLt Ψ (c.lhs.applyFlex φ) (c.rhs.applyFlex φ).boundNorm
    | .le => SizeLe Ψ (c.lhs.applyFlex φ) (c.rhs.applyFlex φ).boundNorm

/-- Universal property of closest next bound search `Ψ ⊢ R a ⇒ b` (Section 6.4, p. 57):
`b` is well-formed in `Ψ`, satisfies `Ψ ⊢ a R b^↑`, and for every `c` such that `Ψ ⊢ a R c^↑`,
we have `Ψ ⊢ b ≤ c`. -/
def ClosestNextBound (Ψ : SizeCtx) (R : EdgeRel) (a b : SizeExp) : Prop :=
  SizeWf Ψ b ∧
  (match R with
   | .lt => SizeLt Ψ a b.boundNorm
   | .le => SizeLe Ψ a b.boundNorm) ∧
  ∀ c : SizeExp,
    (match R with
     | .lt => SizeLt Ψ a c.boundNorm
     | .le => SizeLe Ψ a c.boundNorm) →
    SizeLe Ψ b c

/-- Compute the closest next bound `Ψ ⊢ R a ⇒ b` (Section 6.4, p. 57):
- for `R = ≤`, returns `a`
- for `R = <`:
  - if `a = ∞ + n`, returns `∞ + (n + 1)`
  - if `a = a^∧`, replaces each `(j + n) ∈ a^∧` whose bound in `Ψ` is a variable/meet `d_j`
    by `d_j + n`, dropping summands bounded by `∞`, and returning `∞` if all summands are bounded
    by `∞`. -/
def closestNextBound (Ψ : SizeCtx) (R : EdgeRel) (a : SizeExp) : SizeExp :=
  match R with
  | .le => a
  | .lt =>
      match a with
      | .inf n => .inf (n + 1)
      | .meet m =>
          let bounds : List SizeMin :=
            m.toList.filterMap fun sv =>
              match Ψ.find? (fun d => d.var == sv.var) with
              | some d =>
                  match d.bound.shift sv.shift with
                  | .meet bm => some bm
                  | .inf _ => none
              | none => none
          match bounds with
          | [] => .infty
          | b :: bs => .meet (bs.foldl SizeMin.append b)

/-- Universal property of the least upper bound `Ψ ⊢ LUB(b₁, ..., bₘ) ⇒ c` (Section 6.4, p. 57):
`c` is an upper bound (`∀ b ∈ bs, Ψ ⊢ b ≤ c^↑`) and is least among upper bounds
(`∀ d, (∀ b ∈ bs, Ψ ⊢ b ≤ d) → Ψ ⊢ c ≤ d`). -/
def IsLubSize (Ψ : SizeCtx) (bs : List SizeExp) (c : SizeExp) : Prop :=
  SizeWf Ψ c ∧
  (∀ b ∈ bs, SizeLe Ψ b c.boundNorm) ∧
  (∀ d : SizeExp, (∀ b ∈ bs, SizeLe Ψ b d) → SizeLe Ψ c d)

/-- Compute the least upper bound `LUB(b₁, ..., bₘ)` of a list of size expressions in `Ψ`
(Section 6.4, p. 57):
- for `[]`, returns `∞`
- if all non-redundant bounds simplify to a common expression `b` well-formed in `Ψ`, returns `b`,
  and otherwise returns `∞`. -/
def lubSizes (_Ψ : SizeCtx) (bs : List SizeExp) : SizeExp :=
  match bs with
  | [] => .infty
  | b :: rest =>
      if rest.all (· == b) then b else .infty

/-- Formal meet `⋀_{i ∈ Ψ} i` of all rigid variables in `Ψ` (or `∞` if `Ψ` is empty),
used in Step 3 of Algorithm 1 for non-recursive constructor variables `T` (Section 6.4, p. 58). -/
def rigidMeetAll (Ψ : SizeCtx) : SizeExp :=
  match Ψ with
  | [] => .infty
  | d :: rest =>
      .meet ⟨⟨d.var, 0⟩, rest.map (fun d' => ⟨d'.var, 0⟩)⟩

/-- **Algorithm 1**: Computing the optimal coherent substitution `φ*` for a rigid context `Ψ`,
constraint set `C`, and non-recursive flexible variable set `T` (Section 6.4, pp. 57–58).
Processes flexible variables along `C` (assigning rigid variables `i ∈ Ψ.dom` to `.var i 0`
and solving each flexible variable `k` via `closestNextBound` and `lubSizes`, defaulting to `.infty`
on cycles or unconstrained upper bounds so that `Ψ; C ⊢ φ*` is guaranteed whenever no constraint
in `C` has a flexible variable on the LHS and a rigid variable on the RHS). -/
def solveConstraintGraph (Ψ : SizeCtx) (C : List SizeConstraint) (T : List SizeVar) : FlexSubst :=
  let baseSubst : FlexSubst := fun k =>
    if Ψ.dom.contains k then .var k 0 else .infty
  let candidateSubst : FlexSubst := fun k =>
    if Ψ.dom.contains k then
      .var k 0
    else
      let hasSelfLt :=
        C.any (fun c => c.rel == .lt && c.lhs.vars.contains k && c.rhs.vars.contains k)
      if hasSelfLt then
        .infty
      else
        let incoming : List SizeExp :=
          (C.filter (fun c => c.rhs == .var k 0 && c.lhs.vars.all (fun v => Ψ.dom.contains v))).map
            (fun c => closestNextBound Ψ c.rel c.lhs)
        let withT : List SizeExp :=
          if T.contains k && !Ψ.isEmpty then rigidMeetAll Ψ :: incoming else incoming
        lubSizes Ψ withT
  let candidateOk : Bool :=
    C.all fun c =>
      let lhs' := c.lhs.applyFlex candidateSubst
      let rhs' := (c.rhs.applyFlex candidateSubst).boundNorm
      match rhs' with
      | .inf n =>
          match c.rel, lhs' with
          | .lt, .inf m => m < n
          | .le, .inf m => m < n + 1
          | _, .meet _ => true
      | .meet _ => lhs' == rhs' && c.rel == .le
  if candidateOk then candidateSubst else baseSubst

/-- Extract an invocation graph `G ∈ G_{f, D}(f, g)` for a single call site `g a⃗` inside `f`
(Section 4.5, p. 28 & Section 6.5, Step 7, p. 59):
for each callee argument `aᵢ` (`i < |a⃗|`, left vertex `lᵢ ∈ L_G`) and caller size parameter
`pⱼ ∈ Ψ_f` (`j < |Ψ_f|`, right vertex `rⱼ ∈ R_G`), records `<` if `Ψ ⊢ aᵢ < pⱼ` and `≤` if
`Ψ ⊢ aᵢ ≤ pⱼ`. -/
def buildCallGraph (callerParams : SizeCtx) (calleeArgs : List SizeExp)
    (clauseRigidCtx : SizeCtx) : InvGraph :=
  let leftArity := calleeArgs.length
  let rightArity := callerParams.length
  let lookup (i j : Nat) : Option EdgeRel :=
    match calleeArgs[i]?, callerParams[j]? with
    | some arg, some param =>
        let bnd := closestNextBound clauseRigidCtx .lt arg
        if arg == .var param.var 0 then
          some .le
        else if bnd == .var param.var 0 then
          some .lt
        else
          none
    | _, _ => none
  ⟨leftArity, rightArity, InvGraph.canonicalEdges leftArity rightArity lookup⟩

mutual

/-- Condition 6 of Theorem 13 (p. 57) and Step 7 of Algorithm 2 (p. 59):
for every call `g a⃗` to a function `g ∈ Ξ` occurring in the size-substituted term `u = φ(t')`,
there exists an invocation graph `G ∈ G(f, g)` such that `a⃗ ≺_G Ψ₁` in the clause rigid context
`Ψclause = Ψ₁ ++ Ψ₂`. -/
def LocalCallsConform (Ξ : MutualBlock) (𝒢 : InvGraphFamily)
    (caller : FunName) (Ψ₁ : SizeCtx) (Ψclause : SizeCtx) : Term → Prop
  | .var _ => True
  | .funRef g as =>
      ∀ decl ∈ Ξ, decl.name = g →
        SizeSubstWf Ψclause as decl.sizeParams ∧
        ∃ G ∈ 𝒢.graphs caller g, SyntacticConforms Ψclause G as Ψ₁
  | .app r e =>
      LocalCallsConform Ξ 𝒢 caller Ψ₁ Ψclause r ∧
      LocalCallsConformElim Ξ 𝒢 caller Ψ₁ Ψclause e
  | .unit => True
  | .pair t₁ t₂ =>
      LocalCallsConform Ξ 𝒢 caller Ψ₁ Ψclause t₁ ∧
      LocalCallsConform Ξ 𝒢 caller Ψ₁ Ψclause t₂
  | .cons _ _ t =>
      LocalCallsConform Ξ 𝒢 caller Ψ₁ Ψclause t
  | .pack _ t =>
      LocalCallsConform Ξ 𝒢 caller Ψ₁ Ψclause t
  | .lamClauses Ds =>
      LocalCallsConformClauses Ξ 𝒢 caller Ψ₁ Ψclause Ds
  | .ascr t _ =>
      LocalCallsConform Ξ 𝒢 caller Ψ₁ Ψclause t

/-- Helper: check `LocalCallsConform` in an elimination `e`. -/
def LocalCallsConformElim (Ξ : MutualBlock) (𝒢 : InvGraphFamily)
    (caller : FunName) (Ψ₁ : SizeCtx) (Ψclause : SizeCtx) : Elim → Prop
  | .term t => LocalCallsConform Ξ 𝒢 caller Ψ₁ Ψclause t
  | .tyArg _ => True
  | .proj _ _ => True

/-- Helper: check `LocalCallsConform` across a list of clauses. -/
def LocalCallsConformClauses (Ξ : MutualBlock) (𝒢 : InvGraphFamily)
    (caller : FunName) (Ψ₁ : SizeCtx) (Ψclause : SizeCtx) : List Clause → Prop
  | [] => True
  | (.mk _ t) :: rest =>
      LocalCallsConform Ξ 𝒢 caller Ψ₁ Ψclause t ∧
      LocalCallsConformClauses Ξ 𝒢 caller Ψ₁ Ψclause rest

end

/-- Well-typed inference witness for a single clause `{q⃗ → t}` produced by Steps 4–7 of
Algorithm 2 (Section 6.5, p. 59):
- Step 4: `InferSpine` on `q⃗` produces `C'`, `Γ`, `Δ'`, `Ψ₂`, and `q⃗'`
- Step 5: `CheckTerm` on the clause body `t` produces `Φ`, `Cs`, `T`, and `t'`
- Step 6: `φ* = solveConstraintGraph (Ψ₁ ++ Ψ₂) Cs T`
- Step 7: all recursive calls to `g ∈ Ξannot` in `φ*(t')` conform to `𝒢` (`LocalCallsConform`). -/
structure Algorithm2ClauseRun (sig : GlobalSig) (Ξannot : MutualBlock)
    (𝒢 : InvGraphFamily) (caller : FunName) (Ψ₁ : SizeCtx)
    (A' : TypeExpr) (qs : PatSpine) (t : Term) (D' : Clause) where
  C' : TypeExpr
  Γ : TermCtx
  Δ' : List TyDecl
  Ψ₂ : SizeCtx
  qs' : PatSpine
  Φ : FlexVars
  Cs : List SizeConstraint
  T : List SizeVar
  t' : Term
  inferSpine : InferSpine (KindingCtx.empty.extSizes Ψ₁) qs A' C' Γ Δ' Ψ₂ qs'
  consistentExt : KindingCtxConsistentExt (KindingCtx.empty.extSizes Ψ₁) Δ'
  clauseSizesWf : SizeCtxWf (Ψ₁ ++ Ψ₂)
  checkBody :
    CheckTerm sig Ξannot ((Ψ₁ ++ Ψ₂).map (fun d => (d.var, d.pol)))
      Γ ((KindingCtx.empty.extSizes Ψ₁).append ⟨Ψ₂, Δ'⟩) C' t Φ Cs T t'
  callsConform :
    let φstar := solveConstraintGraph (Ψ₁ ++ Ψ₂) Cs T
    D' = .mk qs' (t'.applyFlex φstar) ∧
    LocalCallsConform Ξannot 𝒢 caller Ψ₁ (Ψ₁ ++ Ψ₂) (t'.applyFlex φstar)

/-- **Algorithm 2** (`Algorithm2Accepts`, Section 6.5, p. 59):
Given a global signature `sig` (`⊨ Σ`) and an unannotated mutual block `Ξ` in System `F_ω^c`,
Algorithm 2:
1. Iterates over `(f : A = D⃗) ∈ Ξ` and encodes `+; · ⊢_{SCT}^− A ⇒ Ψ₁; A'`;
2. Iterates over clauses `{q⃗ → t} ∈ D⃗`, running `InferSpine`, `CheckTerm`, and `φ*` (Algorithm 1);
3. Collects the invocation graphs `G` for all recursive calls `g ∈ Ξ` in `φ*(t')`;
4. Accepts `Ξ` (producing the size-annotated mutual block `Ξannot`) if `⊢ G` (`SCTValid 𝒢`). -/
def Algorithm2Accepts (sig : GlobalSig) (Ξ : MutualBlock) (Ξannot : MutualBlock) : Prop :=
  ∃ 𝒢 : InvGraphFamily,
    SCTValid 𝒢 ∧
    (∀ decl' ∈ Ξannot, 𝒢.arity decl'.name = decl'.sizeParams.length) ∧
    List.Forall₂
      (fun decl decl' =>
        decl'.name = decl.name ∧
        EncodeType .neg .pos KindingCtx.empty decl.ty decl'.sizeParams decl'.ty ∧
        SignatureFixpointHygiene (KindingCtx.empty.extSizes decl'.sizeParams) decl'.ty ∧
        SizeCtxWf decl'.sizeParams ∧
        KindCheck (KindingCtx.empty.extSizes decl'.sizeParams) decl'.ty .star ∧
        List.Forall₂
          (fun D D' =>
            ∃ qs t,
              D = Clause.mk qs t ∧
              Nonempty (Algorithm2ClauseRun sig Ξannot 𝒢 decl'.name decl'.sizeParams decl'.ty qs t D'))
          decl.clauses decl'.clauses)
      Ξ Ξannot

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 6, Sections 6.1–6.5 (pp. 41–60) and Appendix A (pp. I–V).
Read-back

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

Independent Mathematical Read-Back: Def_NishtAbel2024_Inference.lean

Unannotated System FωF_\omegaFω​ layer (fwFunctorSKind, TypeExpr.isUnannotated, isUnannotatedBranches, FwKindInfer, FwKindCheck, FwPatTyping, FwSpineTyping).

  • fwFunctorSKind\text{fwFunctorSKind}fwFunctorSKind is ⋆→mixed⋆\star \xrightarrow{\mathsf{mixed}} \star⋆mixed​⋆ in SKind.
  • TypeExpr.isUnannotated(A)\text{TypeExpr.isUnannotated}(A)TypeExpr.isUnannotated(A) (and isUnannotatedBranches) holds recursively if AAA contains no atom(size(a))\mathsf{atom}(\mathsf{size}(a))atom(size(a)), no atom(all(< a))\mathsf{atom}(\mathsf{all}({<}\,a))atom(all(<a)), and no atom(ex(< a))\mathsf{atom}(\mathsf{ex}({<}\,a))atom(ex(<a)), and every μaS\mu^a SμaS or νaR\nu^a RνaR in AAA has a=SizeExp.infty=inf(0)a = \text{SizeExp.infty} = \mathsf{inf}(0)a=SizeExp.infty=inf(0) and unannotated branch types.
  • FwKindInfer(Δ,F,ι)\text{FwKindInfer}(\Delta, F, \iota)FwKindInfer(Δ,F,ι) and FwKindCheck(Δ,F,ι)\text{FwKindCheck}(\Delta, F, \iota)FwKindCheck(Δ,F,ι) are mutually inductive kinding judgments returning simple kinds ι:SKind\iota : \text{SKind}ι:SKind for unannotated types:
    • unit, prod, arr: assign ⋆\star⋆, ⋆→+(⋆→+⋆)\star \xrightarrow{+} (\star \xrightarrow{+} \star)⋆+​(⋆+​⋆), and ⋆→−(⋆→+⋆)\star \xrightarrow{-} (\star \xrightarrow{+} \star)⋆−​(⋆+​⋆) respectively.
    • var: if ⟨X,π,Kind.ofSKind(ι)⟩∈Δ.types\langle X, \pi, \text{Kind.ofSKind}(\iota) \rangle \in \Delta.\text{types}⟨X,π,Kind.ofSKind(ι)⟩∈Δ.types and π≤+\pi \le +π≤+, infers ι\iotaι.
    • app: if FwKindInfer(Δ,F,ι→πι′)\text{FwKindInfer}(\Delta, F, \iota \xrightarrow{\pi} \iota')FwKindInfer(Δ,F,ιπ​ι′) and FwKindCheck(Δ.invScalePol(π),G,ι)\text{FwKindCheck}(\Delta.\text{invScalePol}(\pi), G, \iota)FwKindCheck(Δ.invScalePol(π),G,ι), infers ι′\iota'ι′ for F GF\,GFG.
    • all, ex: assign (ι→mixed⋆)→+⋆(\iota \xrightarrow{\mathsf{mixed}} \star) \xrightarrow{+} \star(ιmixed​⋆)+​⋆ to atom(all(Kind.ofSKind(ι)))\mathsf{atom}(\mathsf{all}(\text{Kind.ofSKind}(\iota)))atom(all(Kind.ofSKind(ι))) and atom(ex(Kind.ofSKind(ι)))\mathsf{atom}(\mathsf{ex}(\text{Kind.ofSKind}(\iota)))atom(ex(Kind.ofSKind(ι))).
    • mu, nu: if every branch (c,Fc)∈S(c, F_c) \in S(c,Fc​)∈S (resp. (d,Fd)∈R(d, F_d) \in R(d,Fd​)∈R) satisfies FwKindCheck(Δ,Fc,fwFunctorSKind)\text{FwKindCheck}(\Delta, F_c, \text{fwFunctorSKind})FwKindCheck(Δ,Fc​,fwFunctorSKind), infers ⋆\star⋆ for μ∞S\mu^{\infty} Sμ∞S (resp. ν∞R\nu^{\infty} Rν∞R).
    • FwKindCheck.infer: embeds FwKindInfer(Δ,F,ι)\text{FwKindInfer}(\Delta, F, \iota)FwKindInfer(Δ,F,ι) into FwKindCheck(Δ,F,ι)\text{FwKindCheck}(\Delta, F, \iota)FwKindCheck(Δ,F,ι) (with no subkinding rule).
    • FwKindCheck.lam: if FwKindCheck(Δ.extType(X,π,Kind.ofSKind(ι)),F,ι′)\text{FwKindCheck}(\Delta.\text{extType}(X, \pi, \text{Kind.ofSKind}(\iota)), F, \iota')FwKindCheck(Δ.extType(X,π,Kind.ofSKind(ι)),F,ι′), checks λX:ι. F\lambda X : \iota.\, FλX:ι.F at ι→πι′\iota \xrightarrow{\pi} \iota'ιπ​ι′.
  • FwPatTyping(Δ,Δ′,Γ,p,A)\text{FwPatTyping}(\Delta, \Delta', \Gamma, p, A)FwPatTyping(Δ,Δ′,Γ,p,A) and FwSpineTyping(Δ,Δ′,Γ,A,qs,C)\text{FwSpineTyping}(\Delta, \Delta', \Gamma, A, \mathit{qs}, C)FwSpineTyping(Δ,Δ′,Γ,A,qs,C) are the unannotated pattern and copattern-spine typing judgments:
    • Unlike PatTyping.var, FwPatTyping.var explicitly requires FwKindCheck(Δ,A,⋆)\text{FwKindCheck}(\Delta, A, \star)FwKindCheck(Δ,A,⋆).
    • Unlike PatTyping.pair and SpineTyping.pat, FwPatTyping.pair and FwSpineTyping.pat extend the kinding context of the second component by Δ1\Delta_1Δ1​ via Δ.append(⟨[],Δ1⟩)\Delta.\text{append}(\langle [], \Delta_1 \rangle)Δ.append(⟨[],Δ1​⟩).
    • FwPatTyping.cons and FwSpineTyping.proj unfold μ∞S\mu^\infty Sμ∞S and ν∞R\nu^\infty Rν∞R directly to Sc.normApp(μ∞S)S_c.\text{normApp}(\mu^\infty S)Sc​.normApp(μ∞S) and Rd.normApp(ν∞R)R_d.\text{normApp}(\nu^\infty R)Rd​.normApp(ν∞R) without introducing size quantifiers.
    • FwPatTyping.tyPack and FwSpineTyping.tyApp require X∉(Δ.types+ ⁣ ⁣+Δ′).map(⋅.var)X \notin (\Delta.\text{types} \mathbin{+\!\!+} \Delta').\text{map}(\cdot.\text{var})X∈/(Δ.types++Δ′).map(⋅.var).

Size variable occurrences (FixKind, TypeExpr.allSizeVars, SizeOccursFixPol, SizeOccursPol, SizeOccursIn).

  • FixKind is a two-element inductive type with constructors μ\muμ (mu) and ν\nuν (nu).
  • TypeExpr.allSizeVars(A)\text{TypeExpr.allSizeVars}(A)TypeExpr.allSizeVars(A) (and allSizeVarsBranches) concatenates a.varsa.\text{vars}a.vars across all occurrences of 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 in AAA. SizeOccursIn(i,F)\text{SizeOccursIn}(i, F)SizeOccursIn(i,F) is i∈F.allSizeVarsi \in F.\text{allSizeVars}i∈F.allSizeVars.
  • SizeOccursFixPol(Δ,fk,i,π,F)\text{SizeOccursFixPol}(\Delta, \mathit{fk}, i, \pi, F)SizeOccursFixPol(Δ,fk,i,π,F) is an inductive judgment stating that size variable iii occurs on a fixpoint of kind fk∈{μ,ν}\mathit{fk} \in \{\mu, \nu\}fk∈{μ,ν} at polarity π\piπ in FFF under context Δ\DeltaΔ:
    1. mu_top: SizeOccursFixPol(Δ,μ,i,+,μvar(i,n)S)\text{SizeOccursFixPol}(\Delta, \mu, i, +, \mu^{\text{var}(i, n)} S)SizeOccursFixPol(Δ,μ,i,+,μvar(i,n)S) for any n∈Nn \in \mathbb{N}n∈N.
    2. nu_top: SizeOccursFixPol(Δ,ν,i,+,νvar(i,n)R)\text{SizeOccursFixPol}(\Delta, \nu, i, +, \nu^{\text{var}(i, n)} R)SizeOccursFixPol(Δ,ν,i,+,νvar(i,n)R) for any n∈Nn \in \mathbb{N}n∈N.
    3. mu_branch: if (c,Sc)∈S(c, S_c) \in S(c,Sc​)∈S and SizeOccursFixPol(Δ,fk,i,π,Sc)\text{SizeOccursFixPol}(\Delta, \mathit{fk}, i, \pi, S_c)SizeOccursFixPol(Δ,fk,i,π,Sc​), then SizeOccursFixPol(Δ,fk,i,π,μaS)\text{SizeOccursFixPol}(\Delta, \mathit{fk}, i, \pi, \mu^a S)SizeOccursFixPol(Δ,fk,i,π,μaS).
    4. nu_field: if (d,Rd)∈R(d, R_d) \in R(d,Rd​)∈R and SizeOccursFixPol(Δ,fk,i,π,Rd)\text{SizeOccursFixPol}(\Delta, \mathit{fk}, i, \pi, R_d)SizeOccursFixPol(Δ,fk,i,π,Rd​), then SizeOccursFixPol(Δ,fk,i,π,νaR)\text{SizeOccursFixPol}(\Delta, \mathit{fk}, i, \pi, \nu^a R)SizeOccursFixPol(Δ,fk,i,π,νaR).
    5. lam: if SizeOccursFixPol(Δ.extType(X,mixed,Kind.ofSKind(ι)),fk,i,π,F)\text{SizeOccursFixPol}(\Delta.\text{extType}(X, \mathsf{mixed}, \text{Kind.ofSKind}(\iota)), \mathit{fk}, i, \pi, F)SizeOccursFixPol(Δ.extType(X,mixed,Kind.ofSKind(ι)),fk,i,π,F), then SizeOccursFixPol(Δ,fk,i,π,λX:ι. F)\text{SizeOccursFixPol}(\Delta, \mathit{fk}, i, \pi, \lambda X : \iota.\, F)SizeOccursFixPol(Δ,fk,i,π,λX:ι.F).
    6. app_left: if Δ⊢F⇒(κ→π′κ′)\Delta \vdash F \Rightarrow (\kappa \xrightarrow{\pi'} \kappa')Δ⊢F⇒(κπ′​κ′) (KindInfer) and SizeOccursFixPol(Δ,fk,i,π,F)\text{SizeOccursFixPol}(\Delta, \mathit{fk}, i, \pi, F)SizeOccursFixPol(Δ,fk,i,π,F), then SizeOccursFixPol(Δ,fk,i,π,F G)\text{SizeOccursFixPol}(\Delta, \mathit{fk}, i, \pi, F\,G)SizeOccursFixPol(Δ,fk,i,π,FG).
    7. app_right: if Δ⊢F⇒(κ→π′κ′)\Delta \vdash F \Rightarrow (\kappa \xrightarrow{\pi'} \kappa')Δ⊢F⇒(κπ′​κ′) (KindInfer) and SizeOccursFixPol(Δ.invScalePol(π′),fk,i,π,G)\text{SizeOccursFixPol}(\Delta.\text{invScalePol}(\pi'), \mathit{fk}, i, \pi, G)SizeOccursFixPol(Δ.invScalePol(π′),fk,i,π,G), then SizeOccursFixPol(Δ,fk,i,π′⋅π,F G)\text{SizeOccursFixPol}(\Delta, \mathit{fk}, i, \pi' \cdot \pi, F\,G)SizeOccursFixPol(Δ,fk,i,π′⋅π,FG).
  • SizeOccursPol(Δ,i,π,F)\text{SizeOccursPol}(\Delta, i, \pi, F)SizeOccursPol(Δ,i,π,F) holds if and only if ∃fk:FixKind,  SizeOccursFixPol(Δ,fk,i,π,F)\exists \mathit{fk} : \text{FixKind},\; \text{SizeOccursFixPol}(\Delta, \mathit{fk}, i, \pi, F)∃fk:FixKind,SizeOccursFixPol(Δ,fk,i,π,F).

Type encoding (EncodeType, EncodeBranches), pattern/spine inference (InferPat, InferSpine), and hygiene predicates (PatRigidVarClass, SpineRigidVarClass, allMuBranchLists, allNuFieldLists, PosFixpointPolClean, NegFixpointPolClean, PositiveFixpointHygiene, SignatureFixpointHygiene).

  • EncodeType(π⋆,π,Δ,F,Ψ,F′)\text{EncodeType}(\pi_\star, \pi, \Delta, F, \Psi, F')EncodeType(π⋆​,π,Δ,F,Ψ,F′) and EncodeBranches(π⋆,π,Δ,S,Ψ,S′)\text{EncodeBranches}(\pi_\star, \pi, \Delta, S, \Psi, S')EncodeBranches(π⋆​,π,Δ,S,Ψ,S′) are mutually inductive judgments replacing ∞\infty∞ annotations on μ∞\mu^\inftyμ∞/ν∞\nu^\inftyν∞ at target polarities with fresh size variables:
    • On atoms unit, prod, arr, all, ex, and var (provided ⟨X,π′,Kind.ofSKind(ι)⟩∈Δ.types\langle X, \pi', \text{Kind.ofSKind}(\iota) \rangle \in \Delta.\text{types}⟨X,π′,Kind.ofSKind(ι)⟩∈Δ.types with π′≤+\pi' \le +π′≤+), it outputs Ψ=[]\Psi = []Ψ=[] and the identical atom.
    • lam: if X∉Ψ.domX \notin \Psi.\text{dom}X∈/Ψ.dom and EncodeType(π⋆,π,Δ.extType(X,mixed,Kind.ofSKind(ι)),F,Ψ,F′)\text{EncodeType}(\pi_\star, \pi, \Delta.\text{extType}(X, \mathsf{mixed}, \text{Kind.ofSKind}(\iota)), F, \Psi, F')EncodeType(π⋆​,π,Δ.extType(X,mixed,Kind.ofSKind(ι)),F,Ψ,F′), encodes λX:ι. F\lambda X : \iota.\, FλX:ι.F into (Ψ,λX:ι. F′)(\Psi, \lambda X : \iota.\, F')(Ψ,λX:ι.F′).
    • app: if FwKindInfer(Δ,F,ι→π′ι′)\text{FwKindInfer}(\Delta, F, \iota \xrightarrow{\pi'} \iota')FwKindInfer(Δ,F,ιπ′​ι′), Δ.extSizes(Ψ1)⊢F′⇒(Kind.ofSKind(ι)→π′Kind.ofSKind(ι′))\Delta.\text{extSizes}(\Psi_1) \vdash F' \Rightarrow (\text{Kind.ofSKind}(\iota) \xrightarrow{\pi'} \text{Kind.ofSKind}(\iota'))Δ.extSizes(Ψ1​)⊢F′⇒(Kind.ofSKind(ι)π′​Kind.ofSKind(ι′)), (Δ.extSizes(Ψ2)).invScalePol(π′)⊢G′⇐Kind.ofSKind(ι)(\Delta.\text{extSizes}(\Psi_2)).\text{invScalePol}(\pi') \vdash G' \Leftarrow \text{Kind.ofSKind}(\iota)(Δ.extSizes(Ψ2​)).invScalePol(π′)⊢G′⇐Kind.ofSKind(ι), EncodeType(π⋆,π,Δ,F,Ψ1,F′)\text{EncodeType}(\pi_\star, \pi, \Delta, F, \Psi_1, F')EncodeType(π⋆​,π,Δ,F,Ψ1​,F′), EncodeType(π⋆,π′⋅π,Δ.invScalePol(π′),G,Ψ2,G′)\text{EncodeType}(\pi_\star, \pi' \cdot \pi, \Delta.\text{invScalePol}(\pi'), G, \Psi_2, G')EncodeType(π⋆​,π′⋅π,Δ.invScalePol(π′),G,Ψ2​,G′), and Ψ1.dom\Psi_1.\text{dom}Ψ1​.dom is disjoint from Ψ2.dom\Psi_2.\text{dom}Ψ2​.dom and G′.allSizeVarsG'.\text{allSizeVars}G′.allSizeVars while Ψ2.dom\Psi_2.\text{dom}Ψ2​.dom is disjoint from F′.allSizeVarsF'.\text{allSizeVars}F′.allSizeVars, encodes F GF\,GFG into (Ψ1+ ⁣ ⁣+Ψ2,F′ G′)(\Psi_1 \mathbin{+\!\!+} \Psi_2, F'\,G')(Ψ1​++Ψ2​,F′G′).
    • mu_fresh vs mu_inf: when π=π⋆\pi = \pi_\starπ=π⋆​, mu_fresh picks iii fresh from Δ.sizes.dom\Delta.\text{sizes}.\text{dom}Δ.sizes.dom, Ψ.dom\Psi.\text{dom}Ψ.dom, and allSizeVarsBranches(S′)\text{allSizeVarsBranches}(S')allSizeVarsBranches(S′), and encodes μ∞S\mu^\infty Sμ∞S into (⟨i,mixed,∞⟩::Ψ,μvar(i,0)S′)(\langle i, \mathsf{mixed}, \infty \rangle :: \Psi, \mu^{\text{var}(i, 0)} S')(⟨i,mixed,∞⟩::Ψ,μvar(i,0)S′); when π≠π⋆\pi \neq \pi_\starπ=π⋆​, mu_inf keeps μ∞S′\mu^\infty S'μ∞S′ with context Ψ\PsiΨ.
    • nu_fresh vs nu_inf: when π=(−)⋅π⋆\pi = (-) \cdot \pi_\starπ=(−)⋅π⋆​, nu_fresh picks a fresh iii and encodes ν∞R\nu^\infty Rν∞R into (⟨i,mixed,∞⟩::Ψ,νvar(i,0)R′)(\langle i, \mathsf{mixed}, \infty \rangle :: \Psi, \nu^{\text{var}(i, 0)} R')(⟨i,mixed,∞⟩::Ψ,νvar(i,0)R′); when π≠(−)⋅π⋆\pi \neq (-) \cdot \pi_\starπ=(−)⋅π⋆​, nu_inf keeps ν∞R′\nu^\infty R'ν∞R′ with context Ψ\PsiΨ.
  • InferPat(Δ0,p,A,Γ,Δ,Ψ,p′)\text{InferPat}(\Delta_0, p, A, \Gamma, \Delta, \Psi, p')InferPat(Δ0​,p,A,Γ,Δ,Ψ,p′) and InferSpine(Δ0,qs,A,C,Γ,Δ,Ψ,qs′)\text{InferSpine}(\Delta_0, \mathit{qs}, A, C, \Gamma, \Delta, \Psi, \mathit{qs}')InferSpine(Δ0​,qs,A,C,Γ,Δ,Ψ,qs′) elaborate unannotated patterns and copattern spines against annotated types:
    • In InferPat.cons, matching cons(c,p)\mathsf{cons}(c, p)cons(c,p) against μaS\mu^a SμaS picks a fresh size variable jjj, elaborates ppp against Sc.normApp(μvar(j,0)S)S_c.\text{normApp}(\mu^{\text{var}(j, 0)} S)Sc​.normApp(μvar(j,0)S) under Δ0.extType(j,+,< a.boundNorm)\Delta_0.\text{extType}(j, +, {<}\,a.\text{boundNorm})Δ0​.extType(j,+,<a.boundNorm), prepends ⟨j,+,< a.boundNorm⟩\langle j, +, {<}\,a.\text{boundNorm} \rangle⟨j,+,<a.boundNorm⟩ to Δ\DeltaΔ and ⟨j,+,a.boundNorm⟩\langle j, +, a.\text{boundNorm} \rangle⟨j,+,a.boundNorm⟩ to Ψ\PsiΨ, and rewrites the pattern to cons(c,tyPack(j,p′))\mathsf{cons}(c, \mathsf{tyPack}(j, p'))cons(c,tyPack(j,p′)).
    • In InferSpine.proj, matching proj(d)::qs\mathsf{proj}(d) :: \mathit{qs}proj(d)::qs against νaR\nu^a RνaR picks a fresh size variable jjj, elaborates qs\mathit{qs}qs against Rd.normApp(νvar(j,0)R)R_d.\text{normApp}(\nu^{\text{var}(j, 0)} R)Rd​.normApp(νvar(j,0)R) under Δ0.extType(j,+,< a.boundNorm)\Delta_0.\text{extType}(j, +, {<}\,a.\text{boundNorm})Δ0​.extType(j,+,<a.boundNorm), prepends jjj to Δ\DeltaΔ and Ψ\PsiΨ, and rewrites the spine to proj(d)::tyVar(j)::qs′\mathsf{proj}(d) :: \mathsf{tyVar}(j) :: \mathit{qs}'proj(d)::tyVar(j)::qs′.
  • PatRigidVarClass(Δ,Γ,i)\text{PatRigidVarClass}(\Delta, \Gamma, i)PatRigidVarClass(Δ,Γ,i) states that either: (1) iii occurs in some (x,A)∈Γ(x, A) \in \Gamma(x,A)∈Γ at (μ,+)(\mu, +)(μ,+), in none at (ν,−)(\nu, -)(ν,−), and in some (x,A)∈Γ(x, A) \in \Gamma(x,A)∈Γ via SizeOccursIn\text{SizeOccursIn}SizeOccursIn; or (2) iii occurs in none at (μ,+)(\mu, +)(μ,+), in some at (ν,−)(\nu, -)(ν,−), and in some via SizeOccursIn\text{SizeOccursIn}SizeOccursIn; or (3) iii occurs in none at (μ,+)(\mu, +)(μ,+), in none at (ν,−)(\nu, -)(ν,−), and in none via SizeOccursIn\text{SizeOccursIn}SizeOccursIn.
  • SpineRigidVarClass(Δ,Γ,A′′,i)\text{SpineRigidVarClass}(\Delta, \Gamma, A'', i)SpineRigidVarClass(Δ,Γ,A′′,i) defines four conditions:
    • c1≡∃p∈Γ,  SizeOccursFixPol(Δ,μ,i,+,p.2)c_1 \equiv \exists p \in \Gamma,\; \text{SizeOccursFixPol}(\Delta, \mu, i, +, p.2)c1​≡∃p∈Γ,SizeOccursFixPol(Δ,μ,i,+,p.2),
    • c2≡SizeOccursFixPol(Δ,μ,i,−,A′′)c_2 \equiv \text{SizeOccursFixPol}(\Delta, \mu, i, -, A'')c2​≡SizeOccursFixPol(Δ,μ,i,−,A′′),
    • c3≡(∃p∈Γ,  SizeOccursFixPol(Δ,ν,i,−,p.2))∨SizeOccursFixPol(Δ,ν,i,+,A′′)c_3 \equiv (\exists p \in \Gamma,\; \text{SizeOccursFixPol}(\Delta, \nu, i, -, p.2)) \lor \text{SizeOccursFixPol}(\Delta, \nu, i, +, A'')c3​≡(∃p∈Γ,SizeOccursFixPol(Δ,ν,i,−,p.2))∨SizeOccursFixPol(Δ,ν,i,+,A′′),
    • c4≡¬SizeOccursIn(i,A′′)∧¬∃p∈Γ,  SizeOccursIn(i,p.2)c_4 \equiv \neg\text{SizeOccursIn}(i, A'') \land \neg\exists p \in \Gamma,\; \text{SizeOccursIn}(i, p.2)c4​≡¬SizeOccursIn(i,A′′)∧¬∃p∈Γ,SizeOccursIn(i,p.2), and asserts that exactly one of c1,c2,c3,c4c_1, c_2, c_3, c_4c1​,c2​,c3​,c4​ holds: (c1∧¬c2∧¬c3∧¬c4)∨(¬c1∧c2∧¬c3∧¬c4)∨(¬c1∧¬c2∧c3∧¬c4)∨(¬c1∧¬c2∧¬c3∧c4)(c_1 \land \neg c_2 \land \neg c_3 \land \neg c_4) \lor (\neg c_1 \land c_2 \land \neg c_3 \land \neg c_4) \lor (\neg c_1 \land \neg c_2 \land c_3 \land \neg c_4) \lor (\neg c_1 \land \neg c_2 \land \neg c_3 \land c_4)(c1​∧¬c2​∧¬c3​∧¬c4​)∨(¬c1​∧c2​∧¬c3​∧¬c4​)∨(¬c1​∧¬c2​∧c3​∧¬c4​)∨(¬c1​∧¬c2​∧¬c3​∧c4​).
  • TypeExpr.allMuBranchLists(A)\text{TypeExpr.allMuBranchLists}(A)TypeExpr.allMuBranchLists(A) (with allMuBranchListsInBranches) collects all branch lists SSS of μaS\mu^a SμaS subexpressions in AAA, and TypeExpr.allNuFieldLists(A)\text{TypeExpr.allNuFieldLists}(A)TypeExpr.allNuFieldLists(A) (with allNuFieldListsInBranches) collects all field lists RRR of νaR\nu^a RνaR subexpressions in AAA.
  • PosFixpointPolClean(Δ,A)\text{PosFixpointPolClean}(\Delta, A)PosFixpointPolClean(Δ,A) holds if and only if for every i:SizeVari : \text{SizeVar}i:SizeVar with SizeOccursIn(i,A)\text{SizeOccursIn}(i, A)SizeOccursIn(i,A), either SizeOccursFixPol(Δ,μ,i,+,A)∧¬SizeOccursFixPol(Δ,ν,i,−,A)\text{SizeOccursFixPol}(\Delta, \mu, i, +, A) \land \neg\text{SizeOccursFixPol}(\Delta, \nu, i, -, A)SizeOccursFixPol(Δ,μ,i,+,A)∧¬SizeOccursFixPol(Δ,ν,i,−,A) or SizeOccursFixPol(Δ,ν,i,−,A)∧¬SizeOccursFixPol(Δ,μ,i,+,A)\text{SizeOccursFixPol}(\Delta, \nu, i, -, A) \land \neg\text{SizeOccursFixPol}(\Delta, \mu, i, +, A)SizeOccursFixPol(Δ,ν,i,−,A)∧¬SizeOccursFixPol(Δ,μ,i,+,A). NegFixpointPolClean(Δ,A)\text{NegFixpointPolClean}(\Delta, A)NegFixpointPolClean(Δ,A) holds if and only if for every i:SizeVari : \text{SizeVar}i:SizeVar with SizeOccursIn(i,A)\text{SizeOccursIn}(i, A)SizeOccursIn(i,A), either SizeOccursFixPol(Δ,μ,i,−,A)∧¬SizeOccursFixPol(Δ,ν,i,+,A)\text{SizeOccursFixPol}(\Delta, \mu, i, -, A) \land \neg\text{SizeOccursFixPol}(\Delta, \nu, i, +, A)SizeOccursFixPol(Δ,μ,i,−,A)∧¬SizeOccursFixPol(Δ,ν,i,+,A) or SizeOccursFixPol(Δ,ν,i,+,A)∧¬SizeOccursFixPol(Δ,μ,i,−,A)\text{SizeOccursFixPol}(\Delta, \nu, i, +, A) \land \neg\text{SizeOccursFixPol}(\Delta, \mu, i, -, A)SizeOccursFixPol(Δ,ν,i,+,A)∧¬SizeOccursFixPol(Δ,μ,i,−,A).
  • PositiveFixpointHygiene(Δ0,A0)\text{PositiveFixpointHygiene}(\Delta_0, A_0)PositiveFixpointHygiene(Δ0​,A0​) holds if and only if PosFixpointPolClean(Δ0,A0)\text{PosFixpointPolClean}(\Delta_0, A_0)PosFixpointPolClean(Δ0​,A0​) holds and for every branch list S∈A0.allMuBranchListsS \in A_0.\text{allMuBranchLists}S∈A0​.allMuBranchLists, every c:ConsNamec : \text{ConsName}c:ConsName, Sc:TypeExprS_c : \text{TypeExpr}Sc​:TypeExpr, and j:SizeVarj : \text{SizeVar}j:SizeVar such that lookupCons(S,c)=some Sc\text{lookupCons}(S, c) = \text{some } S_clookupCons(S,c)=some Sc​, j∉Δ0.sizes.domj \notin \Delta_0.\text{sizes}.\text{dom}j∈/Δ0​.sizes.dom, and j∉allSizeVarsBranches(S)j \notin \text{allSizeVarsBranches}(S)j∈/allSizeVarsBranches(S), setting Δj=Δ0.extType(j,+,< ∞)\Delta_j = \Delta_0.\text{extType}(j, +, {<}\,\infty)Δj​=Δ0​.extType(j,+,<∞) and B=Sc.normApp(μvar(j,0)S)B = S_c.\text{normApp}(\mu^{\text{var}(j, 0)} S)B=Sc​.normApp(μvar(j,0)S), we have PosFixpointPolClean(Δj,B)\text{PosFixpointPolClean}(\Delta_j, B)PosFixpointPolClean(Δj​,B) and SizeOccursIn(j,B)  ⟹  (SizeOccursFixPol(Δj,μ,j,+,B)∧¬SizeOccursFixPol(Δj,ν,j,−,B))\text{SizeOccursIn}(j, B) \implies (\text{SizeOccursFixPol}(\Delta_j, \mu, j, +, B) \land \neg\text{SizeOccursFixPol}(\Delta_j, \nu, j, -, B))SizeOccursIn(j,B)⟹(SizeOccursFixPol(Δj​,μ,j,+,B)∧¬SizeOccursFixPol(Δj​,ν,j,−,B)).
  • SignatureFixpointHygiene(Δ0,A0)\text{SignatureFixpointHygiene}(\Delta_0, A_0)SignatureFixpointHygiene(Δ0​,A0​) holds if and only if NegFixpointPolClean(Δ0,A0)\text{NegFixpointPolClean}(\Delta_0, A_0)NegFixpointPolClean(Δ0​,A0​) holds, the above μ\muμ-unfolding condition holds for every S∈A0.allMuBranchListsS \in A_0.\text{allMuBranchLists}S∈A0​.allMuBranchLists, and dual ν\nuν-unfolding hygiene holds for every field list R∈A0.allNuFieldListsR \in A_0.\text{allNuFieldLists}R∈A0​.allNuFieldLists, d:ProjNamed : \text{ProjName}d:ProjName, Rd:TypeExprR_d : \text{TypeExpr}Rd​:TypeExpr, and fresh j∉Δ0.sizes.dom∪allSizeVarsBranches(R)j \notin \Delta_0.\text{sizes}.\text{dom} \cup \text{allSizeVarsBranches}(R)j∈/Δ0​.sizes.dom∪allSizeVarsBranches(R) with lookupProj(R,d)=some Rd\text{lookupProj}(R, d) = \text{some } R_dlookupProj(R,d)=some Rd​: setting Δj=Δ0.extType(j,+,< ∞)\Delta_j = \Delta_0.\text{extType}(j, +, {<}\,\infty)Δj​=Δ0​.extType(j,+,<∞) and B=Rd.normApp(νvar(j,0)R)B = R_d.\text{normApp}(\nu^{\text{var}(j, 0)} R)B=Rd​.normApp(νvar(j,0)R), we have NegFixpointPolClean(Δj,B)\text{NegFixpointPolClean}(\Delta_j, B)NegFixpointPolClean(Δj​,B) and SizeOccursIn(j,B)  ⟹  (SizeOccursFixPol(Δj,ν,j,+,B)∧¬SizeOccursFixPol(Δj,μ,j,−,B))\text{SizeOccursIn}(j, B) \implies (\text{SizeOccursFixPol}(\Delta_j, \nu, j, +, B) \land \neg\text{SizeOccursFixPol}(\Delta_j, \mu, j, -, B))SizeOccursIn(j,B)⟹(SizeOccursFixPol(Δj​,ν,j,+,B)∧¬SizeOccursFixPol(Δj​,μ,j,−,B)).

Flexible variables (FlexVars), size constraints (SizeConstraint), subtype constraint generation (CompareTypes, CompareBranches), and bidirectional term inference (FlexPolHygiene, trivializeCtx, InferTerm, CheckTerm, CheckClauseInfer, CheckClausesInfer).

  • FlexVars is List(SizeVar×Polarity)\text{List}(\text{SizeVar} \times \text{Polarity})List(SizeVar×Polarity). For Φ:FlexVars\Phi : \text{FlexVars}Φ:FlexVars, Φ.dom=Φ.map(⋅.1)\Phi.\text{dom} = \Phi.\text{map}(\cdot.1)Φ.dom=Φ.map(⋅.1), Φ.lookupPol(i)\Phi.\text{lookupPol}(i)Φ.lookupPol(i) returns the polarity of the first entry with key iii, and Φ.lookupSizePol(πinf,a)\Phi.\text{lookupSizePol}(\pi_{\text{inf}}, a)Φ.lookupSizePol(πinf​,a) returns some πinf\text{some } \pi_{\text{inf}}some πinf​ if a=inf(n)a = \mathsf{inf}(n)a=inf(n), Φ.lookupPol(i)\Phi.\text{lookupPol}(i)Φ.lookupPol(i) if a=meet(⟨(i,0),[]⟩)a = \mathsf{meet}(\langle (i, 0), [] \rangle)a=meet(⟨(i,0),[]⟩) (an unshifted single variable), and none\text{none}none for all other size expressions (such as shifted variables or multi-variable meets).
  • Polarity.infoMax(π1,π2)\text{Polarity.infoMax}(\pi_1, \pi_2)Polarity.infoMax(π1​,π2​) coincides with Polarity.join(π1,π2)\text{Polarity.join}(\pi_1, \pi_2)Polarity.join(π1​,π2​).
  • SizeConstraint is a triple ⟨lhs:SizeExp,rel:EdgeRel,rhs:SizeExp⟩\langle \text{lhs} : \text{SizeExp}, \text{rel} : \text{EdgeRel}, \text{rhs} : \text{SizeExp} \rangle⟨lhs:SizeExp,rel:EdgeRel,rhs:SizeExp⟩. SizeConstraint.ofPol(π,a,b)\text{SizeConstraint.ofPol}(\pi, a, b)SizeConstraint.ofPol(π,a,b) returns [⟨a,≤,b⟩][\langle a, \le, b \rangle][⟨a,≤,b⟩] for +++, [⟨b,≤,a⟩][\langle b, \le, a \rangle][⟨b,≤,a⟩] for −-−, [⟨a,≤,b⟩,⟨b,≤,a⟩][\langle a, \le, b \rangle, \langle b, \le, a \rangle][⟨a,≤,b⟩,⟨b,≤,a⟩] for mixed\mathsf{mixed}mixed, and [][][] for ⊤\top⊤. mentions(c,i)\text{mentions}(c, i)mentions(c,i) checks whether i∈c.lhs.vars∪c.rhs.varsi \in c.\text{lhs}.\text{vars} \cup c.\text{rhs}.\text{vars}i∈c.lhs.vars∪c.rhs.vars.
  • CompareTypes(Φ,Δ,ι,π,A,B,C)\text{CompareTypes}(\Phi, \Delta, \iota, \pi, A, B, C)CompareTypes(Φ,Δ,ι,π,A,B,C) and CompareBranches(Φ,Δ,π,S,S′,C)\text{CompareBranches}(\Phi, \Delta, \pi, S, S', C)CompareBranches(Φ,Δ,π,S,S′,C) are mutually inductive relations comparing two types AAA and BBB at simple kind ι\iotaι and polarity π\piπ to emit a constraint list C:List SizeConstraintC : \text{List SizeConstraint}C:List SizeConstraint:
    • atom: emits [][][] for identical atoms atom(K)\mathsf{atom}(K)atom(K).
    • app: if Δ⊢F′⇒(Kind.ofSKind(ι1)→π1Kind.ofSKind(ι2))\Delta \vdash F' \Rightarrow (\text{Kind.ofSKind}(\iota_1) \xrightarrow{\pi_1} \text{Kind.ofSKind}(\iota_2))Δ⊢F′⇒(Kind.ofSKind(ι1​)π1​​Kind.ofSKind(ι2​)), compares (F,F′)(F, F')(F,F′) at (ι1→π1ι2,π)(\iota_1 \xrightarrow{\pi_1} \iota_2, \pi)(ι1​π1​​ι2​,π) producing C1C_1C1​, compares (G,G′)(G, G')(G,G′) under Δ.invScalePol(π1)\Delta.\text{invScalePol}(\pi_1)Δ.invScalePol(π1​) at (ι1,π1⋅π)(\iota_1, \pi_1 \cdot \pi)(ι1​,π1​⋅π) producing C2C_2C2​, and emits C1+ ⁣ ⁣+C2C_1 \mathbin{+\!\!+} C_2C1​++C2​.
    • lam: compares F.normApp(atom(var(X)))F.\text{normApp}(\mathsf{atom}(\mathsf{var}(X)))F.normApp(atom(var(X))) and F′.normApp(atom(var(X)))F'.\text{normApp}(\mathsf{atom}(\mathsf{var}(X)))F′.normApp(atom(var(X))) under Δ.extType(X,π1,Kind.ofSKind(ι1))\Delta.\text{extType}(X, \pi_1, \text{Kind.ofSKind}(\iota_1))Δ.extType(X,π1​,Kind.ofSKind(ι1​)) at (ι2,π)(\iota_2, \pi)(ι2​,π) for some X:TyVarX : \text{TyVar}X:TyVar.
    • mu: if Φ.lookupSizePol(+,a)=some π1\Phi.\text{lookupSizePol}(+, a) = \text{some } \pi_1Φ.lookupSizePol(+,a)=some π1​, Φ.lookupSizePol(+,b)=some π2\Phi.\text{lookupSizePol}(+, b) = \text{some } \pi_2Φ.lookupSizePol(+,b)=some π2​, and CompareBranches(Φ,Δ,π,S,S′,C)\text{CompareBranches}(\Phi, \Delta, \pi, S, S', C)CompareBranches(Φ,Δ,π,S,S′,C), emits SizeConstraint.ofPol(infoMax(π1,π2)⋅π,a,b)+ ⁣ ⁣+C\text{SizeConstraint.ofPol}(\text{infoMax}(\pi_1, \pi_2) \cdot \pi, a, b) \mathbin{+\!\!+} CSizeConstraint.ofPol(infoMax(π1​,π2​)⋅π,a,b)++C.
    • nu: if Φ.lookupSizePol(−,a)=some π1\Phi.\text{lookupSizePol}(-, a) = \text{some } \pi_1Φ.lookupSizePol(−,a)=some π1​, Φ.lookupSizePol(−,b)=some π2\Phi.\text{lookupSizePol}(-, b) = \text{some } \pi_2Φ.lookupSizePol(−,b)=some π2​, and CompareBranches(Φ,Δ,π,R,R′,C)\text{CompareBranches}(\Phi, \Delta, \pi, R, R', C)CompareBranches(Φ,Δ,π,R,R′,C), emits SizeConstraint.ofPol(infoMax(π1,π2)⋅π,a,b)+ ⁣ ⁣+C\text{SizeConstraint.ofPol}(\text{infoMax}(\pi_1, \pi_2) \cdot \pi, a, b) \mathbin{+\!\!+} CSizeConstraint.ofPol(infoMax(π1​,π2​)⋅π,a,b)++C.
  • FlexPolHygiene(Φ,Δ,A,C)\text{FlexPolHygiene}(\Phi, \Delta, A, C)FlexPolHygiene(Φ,Δ,A,C) requires that every variable iii with Φ.lookupSizePol(+,var(i,0))=some π1\Phi.\text{lookupSizePol}(+, \text{var}(i, 0)) = \text{some } \pi_1Φ.lookupSizePol(+,var(i,0))=some π1​ that occurs on a μ\muμ-fixpoint in AAA or CCC (at +++ or −-−) has π1∈{+,mixed}\pi_1 \in \{+, \mathsf{mixed}\}π1​∈{+,mixed}, and every iii with Φ.lookupSizePol(−,var(i,0))=some π1\Phi.\text{lookupSizePol}(-, \text{var}(i, 0)) = \text{some } \pi_1Φ.lookupSizePol(−,var(i,0))=some π1​ that occurs on a ν\nuν-fixpoint in AAA or CCC (at +++ or −-−) has π1∈{−,mixed}\pi_1 \in \{-, \mathsf{mixed}\}π1​∈{−,mixed}.
  • trivializeCtx(Φ,Ψ1)\text{trivializeCtx}(\Phi, \Psi_1)trivializeCtx(Φ,Ψ1​) replaces the bound of any declaration d∈Ψ1d \in \Psi_1d∈Ψ1​ whose bound is an unshifted variable var(a,0)\text{var}(a, 0)var(a,0) with a∈Φ.doma \in \Phi.\text{dom}a∈Φ.dom by ∞=inf(0)\infty = \mathsf{inf}(0)∞=inf(0). TrivializeCtx(Φ,Ψ1,Ψ2)\text{TrivializeCtx}(\Phi, \Psi_1, \Psi_2)TrivializeCtx(Φ,Ψ1​,Ψ2​) is Ψ2=trivializeCtx(Φ,Ψ1)\Psi_2 = \text{trivializeCtx}(\Phi, \Psi_1)Ψ2​=trivializeCtx(Φ,Ψ1​).
  • InferTerm(sig,Ξ,Φ,Γ,Δ,r,A,Φ′,C,T,r′)\text{InferTerm}(\text{sig}, \Xi, \Phi, \Gamma, \Delta, r, A, \Phi', C, T, r')InferTerm(sig,Ξ,Φ,Γ,Δ,r,A,Φ′,C,T,r′), CheckTerm(sig,Ξ,Φ,Γ,Δ,A,t,Φ′,C,T,t′)\text{CheckTerm}(\text{sig}, \Xi, \Phi, \Gamma, \Delta, A, t, \Phi', C, T, t')CheckTerm(sig,Ξ,Φ,Γ,Δ,A,t,Φ′,C,T,t′), CheckClauseInfer\text{CheckClauseInfer}CheckClauseInfer, and CheckClausesInfer\text{CheckClausesInfer}CheckClausesInfer are mutually inductive judgments elaborating an unannotated term/clause into an annotated term/clause while threading flexible variables Φ↦Φ′\Phi \mapsto \Phi'Φ↦Φ′ and accumulating size constraints C:List SizeConstraintC : \text{List SizeConstraint}C:List SizeConstraint and a list of size variables T:List SizeVarT : \text{List SizeVar}T:List SizeVar:
    • InferTerm.proj: elaborates an unannotated projection app(r,proj(d,none))\mathsf{app}(r, \mathsf{proj}(d, \text{none}))app(r,proj(d,none)) on r:νaRr : \nu^a Rr:νaR into app(r′,proj(d,some(var(j,0))))\mathsf{app}(r', \mathsf{proj}(d, \text{some}(\text{var}(j, 0))))app(r′,proj(d,some(var(j,0)))) of type Rd.normApp(νvar(j,0)R)R_d.\text{normApp}(\nu^{\text{var}(j, 0)} R)Rd​.normApp(νvar(j,0)R) for a fresh jjj, prepending (j,−)(j, -)(j,−) to Φ′\Phi'Φ′, ⟨var(j,0),<,a⟩\langle \text{var}(j, 0), <, a \rangle⟨var(j,0),<,a⟩ to CCC, and adding jjj to TTT if j∉(Rd.normApp(νvar(j,0)R)).allSizeVarsj \notin (R_d.\text{normApp}(\nu^{\text{var}(j, 0)} R)).\text{allSizeVars}j∈/(Rd​.normApp(νvar(j,0)R)).allSizeVars.
    • CheckTerm.cons: elaborates an unannotated constructor cons(c,none,t)\mathsf{cons}(c, \text{none}, t)cons(c,none,t) checked against μaS\mu^a SμaS into cons(c,some(var(j,0)),t′)\mathsf{cons}(c, \text{some}(\text{var}(j, 0)), t')cons(c,some(var(j,0)),t′) for a fresh jjj, checking ttt under (j,+)::Φ(j, +) :: \Phi(j,+)::Φ against Sc.normApp(μvar(j,0)S)S_c.\text{normApp}(\mu^{\text{var}(j, 0)} S)Sc​.normApp(μvar(j,0)S), prepending ⟨var(j,0),<,a⟩\langle \text{var}(j, 0), <, a \rangle⟨var(j,0),<,a⟩ to CCC, and adding jjj to TTT if j∉(Sc.normApp(μvar(j,0)S)).allSizeVarsj \notin (S_c.\text{normApp}(\mu^{\text{var}(j, 0)} S)).\text{allSizeVars}j∈/(Sc​.normApp(μvar(j,0)S)).allSizeVars.
    • InferTerm.appTy, InferTerm.ascr, and CheckTerm.pack: run EncodeType(mixed,mixed,Δ,… )\text{EncodeType}(\mathsf{mixed}, \mathsf{mixed}, \Delta, \dots)EncodeType(mixed,mixed,Δ,…) to introduce fresh mixed\mathsf{mixed}mixed-polarity flexible variables Ψ\PsiΨ.
    • InferTerm.funCall: elaborates funRef(decl.name,[])\mathsf{funRef}(\text{decl}.\text{name}, [])funRef(decl.name,[]) for decl∈sig+ ⁣ ⁣+Ξ\text{decl} \in \text{sig} \mathbin{+\!\!+} \Xidecl∈sig++Ξ into funRef(decl.name,as)\mathsf{funRef}(\text{decl}.\text{name}, \mathit{as})funRef(decl.name,as) where as=[var(p.1,0)∣p∈flexVars]\mathit{as} = [\text{var}(p.1, 0) \mid p \in \text{flexVars}]as=[var(p.1,0)∣p∈flexVars] for a list of fresh distinct flexible variables flexVars\text{flexVars}flexVars whose polarities are constrained to be +++ if the parameter occurs at (μ,−)(\mu, -)(μ,−) in decl.ty\text{decl}.\text{ty}decl.ty, −-− if it occurs at (ν,+)(\nu, +)(ν,+) in decl.ty\text{decl}.\text{ty}decl.ty, and in {+,−,mixed}\{+, -, \mathsf{mixed}\}{+,−,mixed}.
    • CheckTerm.sub: infers type AAA for rrr, checks FlexPolHygiene(Φ′,Δ,A,Cty)\text{FlexPolHygiene}(\Phi', \Delta, A, C_{\text{ty}})FlexPolHygiene(Φ′,Δ,A,Cty​), and appends constraints from CompareTypes(Φ′,Δ,⋆,+,A,Cty,C2)\text{CompareTypes}(\Phi', \Delta, \star, +, A, C_{\text{ty}}, C_2)CompareTypes(Φ′,Δ,⋆,+,A,Cty​,C2​).
    • CheckClauseInfer.mk: runs InferSpine(Δ,qs,C,C′,Γ′,Δ′,Ψ,qs′)\text{InferSpine}(\Delta, \mathit{qs}, C, C', \Gamma', \Delta', \Psi, \mathit{qs}')InferSpine(Δ,qs,C,C′,Γ′,Δ′,Ψ,qs′), sets Ψ′=trivializeCtx(Φ,Ψ)\Psi' = \text{trivializeCtx}(\Phi, \Psi)Ψ′=trivializeCtx(Φ,Ψ), and checks the clause body under Ψ′++Φ\Psi'\text{++}\PhiΨ′++Φ, Γ+ ⁣ ⁣+Γ′\Gamma \mathbin{+\!\!+} \Gamma'Γ++Γ′, and Δ.append(⟨Ψ′,Δ′⟩)\Delta.\text{append}(\langle \Psi', \Delta' \rangle)Δ.append(⟨Ψ′,Δ′⟩).

Constraint solving (RigidVarHypotheses, FlexSubst, applyFlex, ValidFlexSubst, CoherentSubst, ClosestNextBound, closestNextBound, IsLubSize, lubSizes, rigidMeetAll, solveConstraintGraph), call-graph construction (buildCallGraph, LocalCallsConform), and Algorithm 2 (Algorithm2ClauseRun, Algorithm2Accepts).

  • RigidVarHypotheses(π,X,Φ0,Γ,Δ,A)\text{RigidVarHypotheses}(\pi, X, \Phi_0, \Gamma, \Delta, A)RigidVarHypotheses(π,X,Φ0​,Γ,Δ,A) states that π∈{+,−}\pi \in \{+, -\}π∈{+,−} and for every i∈Xi \in Xi∈X, setting fk=μ\mathit{fk} = \mufk=μ if π=+\pi = +π=+ and ν\nuν otherwise, we have Φ0.lookupPol(i)=some π\Phi_0.\text{lookupPol}(i) = \text{some } \piΦ0​.lookupPol(i)=some π, every (x,B)∈Γ(x, B) \in \Gamma(x,B)∈Γ satisfies SizeOccursFixPol(Δ,fk,i,π,B)∨¬SizeOccursIn(i,B)\text{SizeOccursFixPol}(\Delta, \mathit{fk}, i, \pi, B) \lor \neg\text{SizeOccursIn}(i, B)SizeOccursFixPol(Δ,fk,i,π,B)∨¬SizeOccursIn(i,B), and AAA satisfies SizeOccursFixPol(Δ,fk,i,(−)⋅π,A)∨¬SizeOccursIn(i,A)\text{SizeOccursFixPol}(\Delta, \mathit{fk}, i, (-) \cdot \pi, A) \lor \neg\text{SizeOccursIn}(i, A)SizeOccursFixPol(Δ,fk,i,(−)⋅π,A)∨¬SizeOccursIn(i,A).
  • FlexSubst is SizeVar→SizeExp\text{SizeVar} \to \text{SizeExp}SizeVar→SizeExp. SizeExp.applyFlex(φ,a)\text{SizeExp.applyFlex}(\varphi, a)SizeExp.applyFlex(φ,a) substitutes k↦φ(k)k \mapsto \varphi(k)k↦φ(k) for k∈a.varsk \in a.\text{vars}k∈a.vars; Term.applyFlex (with Elim.applyFlex, Clause.applyFlex, applyFlexClauses) applies φ\varphiφ to all size expressions and type expressions throughout a term (without filtering clause-bound variables).
  • ValidFlexSubst(Ψ,φ)\text{ValidFlexSubst}(\Psi, \varphi)ValidFlexSubst(Ψ,φ) holds if and only if ∀i∈Ψ.dom,  φ(i)=var(i,0)\forall i \in \Psi.\text{dom},\; \varphi(i) = \text{var}(i, 0)∀i∈Ψ.dom,φ(i)=var(i,0) and ∀k:SizeVar,  SizeWf(Ψ,φ(k))\forall k : \text{SizeVar},\; \text{SizeWf}(\Psi, \varphi(k))∀k:SizeVar,SizeWf(Ψ,φ(k)).
  • CoherentSubst(Ψ,C,φ)\text{CoherentSubst}(\Psi, C, \varphi)CoherentSubst(Ψ,C,φ) holds if and only if ValidFlexSubst(Ψ,φ)\text{ValidFlexSubst}(\Psi, \varphi)ValidFlexSubst(Ψ,φ) and for every c∈Cc \in Cc∈C, SizeLt(Ψ,c.lhs.applyFlex(φ),(c.rhs.applyFlex(φ)).boundNorm)\text{SizeLt}(\Psi, c.\text{lhs}.\text{applyFlex}(\varphi), (c.\text{rhs}.\text{applyFlex}(\varphi)).\text{boundNorm})SizeLt(Ψ,c.lhs.applyFlex(φ),(c.rhs.applyFlex(φ)).boundNorm) when c.rel=<c.\text{rel} = {<}c.rel=<, and SizeLe(Ψ,c.lhs.applyFlex(φ),(c.rhs.applyFlex(φ)).boundNorm)\text{SizeLe}(\Psi, c.\text{lhs}.\text{applyFlex}(\varphi), (c.\text{rhs}.\text{applyFlex}(\varphi)).\text{boundNorm})SizeLe(Ψ,c.lhs.applyFlex(φ),(c.rhs.applyFlex(φ)).boundNorm) when c.rel=≤c.\text{rel} = {\le}c.rel=≤.
  • ClosestNextBound(Ψ,R,a,b)\text{ClosestNextBound}(\Psi, R, a, b)ClosestNextBound(Ψ,R,a,b) states that SizeWf(Ψ,b)\text{SizeWf}(\Psi, b)SizeWf(Ψ,b), aRb.boundNorma \mathrel{R} b.\text{boundNorm}aRb.boundNorm in Ψ\PsiΨ (where R∈{<,≤}R \in \{<, \le\}R∈{<,≤} denotes SizeLt or SizeLe), and for every c:SizeExpc : \text{SizeExp}c:SizeExp with aRc.boundNorma \mathrel{R} c.\text{boundNorm}aRc.boundNorm in Ψ\PsiΨ, SizeLe(Ψ,b,c)\text{SizeLe}(\Psi, b, c)SizeLe(Ψ,b,c).
  • closestNextBound(Ψ,R,a)\text{closestNextBound}(\Psi, R, a)closestNextBound(Ψ,R,a) computes a SizeExp: for R=≤R = {\le}R=≤ it returns aaa; for R=<R = {<}R=<, it maps inf(n)↦inf(n+1)\mathsf{inf}(n) \mapsto \mathsf{inf}(n + 1)inf(n)↦inf(n+1), and for meet(m)\mathsf{meet}(m)meet(m) it looks up each (i,n)∈m.toList(i, n) \in m.\text{toList}(i,n)∈m.toList in Ψ\PsiΨ, collects those shifted bounds d.bound.shift(n)d.\text{bound}.\text{shift}(n)d.bound.shift(n) that are of the form meet(bm)\mathsf{meet}(\mathit{bm})meet(bm), and concatenates them via SizeMin.append (returning ∞=inf(0)\infty = \mathsf{inf}(0)∞=inf(0) if none of the shifted bounds is a meet\mathsf{meet}meet).
  • IsLubSize(Ψ,bs,c)\text{IsLubSize}(\Psi, \mathit{bs}, c)IsLubSize(Ψ,bs,c) states that SizeWf(Ψ,c)\text{SizeWf}(\Psi, c)SizeWf(Ψ,c), ∀b∈bs,  SizeLe(Ψ,b,c.boundNorm)\forall b \in \mathit{bs},\; \text{SizeLe}(\Psi, b, c.\text{boundNorm})∀b∈bs,SizeLe(Ψ,b,c.boundNorm), and ∀d,  (∀b∈bs,  SizeLe(Ψ,b,d))→SizeLe(Ψ,c,d)\forall d,\; (\forall b \in \mathit{bs},\; \text{SizeLe}(\Psi, b, d)) \to \text{SizeLe}(\Psi, c, d)∀d,(∀b∈bs,SizeLe(Ψ,b,d))→SizeLe(Ψ,c,d).
  • lubSizes(_Ψ,bs)\text{lubSizes}(\_\Psi, \mathit{bs})lubSizes(_Ψ,bs) ignores _Ψ\_\Psi_Ψ and returns ∞\infty∞ if bs=[]\mathit{bs} = []bs=[], returns bbb if bs=b::rest\mathit{bs} = b :: \text{rest}bs=b::rest and every element of rest\text{rest}rest is syntactically equal to bbb, and returns ∞\infty∞ otherwise.
  • rigidMeetAll(Ψ)\text{rigidMeetAll}(\Psi)rigidMeetAll(Ψ) returns ∞\infty∞ if Ψ=[]\Psi = []Ψ=[], and otherwise returns the meet\mathsf{meet}meet of (d.var,0)(d.\text{var}, 0)(d.var,0) across all d∈Ψd \in \Psid∈Ψ.
  • solveConstraintGraph(Ψ,C,T)\text{solveConstraintGraph}(\Psi, C, T)solveConstraintGraph(Ψ,C,T) defines a fallback substitution baseSubst(k)=var(k,0)\text{baseSubst}(k) = \text{var}(k, 0)baseSubst(k)=var(k,0) if k∈Ψ.domk \in \Psi.\text{dom}k∈Ψ.dom else ∞\infty∞, and a candidate substitution candidateSubst(k)\text{candidateSubst}(k)candidateSubst(k) which maps k∈Ψ.domk \in \Psi.\text{dom}k∈Ψ.dom to var(k,0)\text{var}(k, 0)var(k,0), maps kkk with a strict self-constraint (∃c∈C\exists c \in C∃c∈C with c.rel=<c.\text{rel} = {<}c.rel=< and k∈c.lhs.vars∩c.rhs.varsk \in c.\text{lhs}.\text{vars} \cap c.\text{rhs}.\text{vars}k∈c.lhs.vars∩c.rhs.vars) to ∞\infty∞, and otherwise applies lubSizes(Ψ)\text{lubSizes}(\Psi)lubSizes(Ψ) to the list of closestNextBound(Ψ,c.rel,c.lhs)\text{closestNextBound}(\Psi, c.\text{rel}, c.\text{lhs})closestNextBound(Ψ,c.rel,c.lhs) for incoming constraints c∈Cc \in Cc∈C with c.rhs=var(k,0)c.\text{rhs} = \text{var}(k, 0)c.rhs=var(k,0) and c.lhs.vars⊆Ψ.domc.\text{lhs}.\text{vars} \subseteq \Psi.\text{dom}c.lhs.vars⊆Ψ.dom (prepended with rigidMeetAll(Ψ)\text{rigidMeetAll}(\Psi)rigidMeetAll(Ψ) if k∈Tk \in Tk∈T and Ψ≠[]\Psi \neq []Ψ=[]). It then returns candidateSubst\text{candidateSubst}candidateSubst if a boolean check candidateOk passes on all c∈Cc \in Cc∈C, and baseSubst\text{baseSubst}baseSubst otherwise.
  • buildCallGraph(callerParams,calleeArgs,clauseRigidCtx)\text{buildCallGraph}(\text{callerParams}, \text{calleeArgs}, \text{clauseRigidCtx})buildCallGraph(callerParams,calleeArgs,clauseRigidCtx) builds a normalized InvGraph where edge (i,j)(i, j)(i,j) is ≤\le≤ if calleeArgs[i]=var(callerParams[j].var,0)\text{calleeArgs}[i] = \text{var}(\text{callerParams}[j].\text{var}, 0)calleeArgs[i]=var(callerParams[j].var,0), else <<< if closestNextBound(clauseRigidCtx,<,calleeArgs[i])=var(callerParams[j].var,0)\text{closestNextBound}(\text{clauseRigidCtx}, <, \text{calleeArgs}[i]) = \text{var}(\text{callerParams}[j].\text{var}, 0)closestNextBound(clauseRigidCtx,<,calleeArgs[i])=var(callerParams[j].var,0), else none\text{none}none.
  • LocalCallsConform(Ξ,G,caller,Ψ1,Ψclause,t)\text{LocalCallsConform}(\Xi, \mathcal{G}, \text{caller}, \Psi_1, \Psi_{\text{clause}}, t)LocalCallsConform(Ξ,G,caller,Ψ1​,Ψclause​,t) (with LocalCallsConformElim and LocalCallsConformClauses) checks recursively that for every funRef(g,as)\mathsf{funRef}(g, \mathit{as})funRef(g,as) occurring in ttt and every decl∈Ξ\text{decl} \in \Xidecl∈Ξ with decl.name=g\text{decl}.\text{name} = gdecl.name=g, we have SizeSubstWf(Ψclause,as,decl.sizeParams)\text{SizeSubstWf}(\Psi_{\text{clause}}, \mathit{as}, \text{decl}.\text{sizeParams})SizeSubstWf(Ψclause​,as,decl.sizeParams) and there exists G∈G.graphs(caller,g)G \in \mathcal{G}.\text{graphs}(\text{caller}, g)G∈G.graphs(caller,g) such that SyntacticConforms(Ψclause,G,as,Ψ1)\text{SyntacticConforms}(\Psi_{\text{clause}}, G, \mathit{as}, \Psi_1)SyntacticConforms(Ψclause​,G,as,Ψ1​).
  • Algorithm2ClauseRun (sig,Ξannot,G,caller,Ψ1,A′,qs,t,D′)(\text{sig}, \Xi_{\text{annot}}, \mathcal{G}, \text{caller}, \Psi_1, A', \mathit{qs}, t, D')(sig,Ξannot​,G,caller,Ψ1​,A′,qs,t,D′) is a structure packaging intermediate data (C′,Γ,Δ′,Ψ2,qs′,Φ,Cs,T,t′)(C', \Gamma, \Delta', \Psi_2, \mathit{qs}', \Phi, \mathit{Cs}, T, t')(C′,Γ,Δ′,Ψ2​,qs′,Φ,Cs,T,t′) together with proofs of:
    1. InferSpine(KindingCtx.empty.extSizes(Ψ1),qs,A′,C′,Γ,Δ′,Ψ2,qs′)\text{InferSpine}(\text{KindingCtx.empty}.\text{extSizes}(\Psi_1), \mathit{qs}, A', C', \Gamma, \Delta', \Psi_2, \mathit{qs}')InferSpine(KindingCtx.empty.extSizes(Ψ1​),qs,A′,C′,Γ,Δ′,Ψ2​,qs′),
    2. KindingCtxConsistentExt(KindingCtx.empty.extSizes(Ψ1),Δ′)\text{KindingCtxConsistentExt}(\text{KindingCtx.empty}.\text{extSizes}(\Psi_1), \Delta')KindingCtxConsistentExt(KindingCtx.empty.extSizes(Ψ1​),Δ′),
    3. SizeCtxWf(Ψ1+ ⁣ ⁣+Ψ2)\text{SizeCtxWf}(\Psi_1 \mathbin{+\!\!+} \Psi_2)SizeCtxWf(Ψ1​++Ψ2​),
    4. CheckTerm(sig,Ξannot,[(d.var,d.pol)∣d∈Ψ1+ ⁣ ⁣+Ψ2],Γ,(KindingCtx.empty.extSizes(Ψ1)).append(⟨Ψ2,Δ′⟩),C′,t,Φ,Cs,T,t′)\text{CheckTerm}(\text{sig}, \Xi_{\text{annot}}, [(d.\text{var}, d.\text{pol}) \mid d \in \Psi_1 \mathbin{+\!\!+} \Psi_2], \Gamma, (\text{KindingCtx.empty}.\text{extSizes}(\Psi_1)).\text{append}(\langle \Psi_2, \Delta' \rangle), C', t, \Phi, \mathit{Cs}, T, t')CheckTerm(sig,Ξannot​,[(d.var,d.pol)∣d∈Ψ1​++Ψ2​],Γ,(KindingCtx.empty.extSizes(Ψ1​)).append(⟨Ψ2​,Δ′⟩),C′,t,Φ,Cs,T,t′), and
    5. setting φ⋆=solveConstraintGraph(Ψ1+ ⁣ ⁣+Ψ2,Cs,T)\varphi_\star = \text{solveConstraintGraph}(\Psi_1 \mathbin{+\!\!+} \Psi_2, \mathit{Cs}, T)φ⋆​=solveConstraintGraph(Ψ1​++Ψ2​,Cs,T), D′=mk(qs′,t′.applyFlex(φ⋆))D' = \mathsf{mk}(\mathit{qs}', t'.\text{applyFlex}(\varphi_\star))D′=mk(qs′,t′.applyFlex(φ⋆​)) and LocalCallsConform(Ξannot,G,caller,Ψ1,Ψ1+ ⁣ ⁣+Ψ2,t′.applyFlex(φ⋆))\text{LocalCallsConform}(\Xi_{\text{annot}}, \mathcal{G}, \text{caller}, \Psi_1, \Psi_1 \mathbin{+\!\!+} \Psi_2, t'.\text{applyFlex}(\varphi_\star))LocalCallsConform(Ξannot​,G,caller,Ψ1​,Ψ1​++Ψ2​,t′.applyFlex(φ⋆​)).
  • Algorithm2Accepts(sig,Ξ,Ξannot)\text{Algorithm2Accepts}(\text{sig}, \Xi, \Xi_{\text{annot}})Algorithm2Accepts(sig,Ξ,Ξannot​) holds if and only if there exists G:InvGraphFamily\mathcal{G} : \text{InvGraphFamily}G:InvGraphFamily such that SCTValid(G)\text{SCTValid}(\mathcal{G})SCTValid(G), every decl′∈Ξannot\text{decl}' \in \Xi_{\text{annot}}decl′∈Ξannot​ has 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 List.Forall2\text{List.Forall}_2List.Forall2​ relates Ξ\XiΞ and Ξannot\Xi_{\text{annot}}Ξannot​ elementwise in order such that for each corresponding pair (decl,decl′)(\text{decl}, \text{decl}')(decl,decl′):
    1. decl′.name=decl.name\text{decl}'.\text{name} = \text{decl}.\text{name}decl′.name=decl.name,
    2. EncodeType(−,+,KindingCtx.empty,decl.ty,decl′.sizeParams,decl′.ty)\text{EncodeType}(-, +, \text{KindingCtx.empty}, \text{decl}.\text{ty}, \text{decl}'.\text{sizeParams}, \text{decl}'.\text{ty})EncodeType(−,+,KindingCtx.empty,decl.ty,decl′.sizeParams,decl′.ty),
    3. SignatureFixpointHygiene(KindingCtx.empty.extSizes(decl′.sizeParams),decl′.ty)\text{SignatureFixpointHygiene}(\text{KindingCtx.empty}.\text{extSizes}(\text{decl}'.\text{sizeParams}), \text{decl}'.\text{ty})SignatureFixpointHygiene(KindingCtx.empty.extSizes(decl′.sizeParams),decl′.ty),
    4. SizeCtxWf(decl′.sizeParams)\text{SizeCtxWf}(\text{decl}'.\text{sizeParams})SizeCtxWf(decl′.sizeParams),
    5. KindingCtx.empty.extSizes(decl′.sizeParams)⊢decl′.ty⇐⋆\text{KindingCtx.empty}.\text{extSizes}(\text{decl}'.\text{sizeParams}) \vdash \text{decl}'.\text{ty} \Leftarrow \starKindingCtx.empty.extSizes(decl′.sizeParams)⊢decl′.ty⇐⋆, and
    6. List.Forall2\text{List.Forall}_2List.Forall2​ relates decl.clauses\text{decl}.\text{clauses}decl.clauses and decl′.clauses\text{decl}'.\text{clauses}decl′.clauses elementwise in order: for each corresponding clause pair (D,D′)(D, D')(D,D′), there exist qs,t\mathit{qs}, tqs,t such that D=mk(qs,t)D = \mathsf{mk}(\mathit{qs}, t)D=mk(qs,t) and Algorithm2ClauseRun(sig,Ξannot,G,decl′.name,decl′.sizeParams,decl′.ty,qs,t,D′)\text{Algorithm2ClauseRun}(\text{sig}, \Xi_{\text{annot}}, \mathcal{G}, \text{decl}'.\text{name}, \text{decl}'.\text{sizeParams}, \text{decl}'.\text{ty}, \mathit{qs}, t, D')Algorithm2ClauseRun(sig,Ξannot​,G,decl′.name,decl′.sizeParams,decl′.ty,qs,t,D′) is nonempty.
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