85 Foundations as Instances of Parameters: Logics, Sets, Categories, Toposes and Types

The seven operations and parameter values are one chart, not a privileged frame; every point is reached from the chart and also joined to its neighbours by translations, so the map can be redrawn with any point as origin; CIC (T99) is the checking language in the same sense that a computation uses some coordinates, and Cubical Agda (T127) checks the same items independently.

Status of the points

149 points: 149 proved, 0 proved with cited parts remaining, 0 remaining, 0 not formalized. All re-exported general theorems are collected in found/Lines.lean (253 theorems, no axioms).

Item

File

Status

T59

Core

proved

T65

Minimal

proved

T66

Classical

proved

T73

HigherOrder

proved

T114

HOIL

proved

T142

SecondOrder2

proved

T71

ManyValued

proved

T67

Modal

proved

T113

ModalExt

proved

T137

GL

proved

T72

TemporalEpistemic

proved

T138

Dynamic

proved

T68

Linear

proved

T69

Relevant

proved

T112

Lambek

proved

T70

Paracons

proved

T139

DaCosta

proved

T140

Kleene3

proved

T111

Quantum

proved

T141

FreeInfHybrid

proved

T170

ManySorted

proved

T171

ModalMu

proved

T172

Conditional

proved

T173

NonMono

proved

T174

ProbLogic

proved

T175

Dependence

proved

T176

Description

proved

T177

FixpointLogic

proved

T178

Justification

proved

T143

Hilbert

proved

T74

ND

proved

T75

Sequent

proved

T76

CHL

proved

T77

DNTrans

proved

T179

ProofNets

proved

T180

Dialectica

proved

T78

Lambda

proved

T79

STLC_F

proved

T144

TypedCalculi

proved

T80

SK

proved

T81

Recursive

proved

T145

Register

proved

T82

ChurchTuring

proved

T181

PTS

proved

T182

Automata

proved

T183

Process

proved

T184

QuantumCirc

proved

T185

Fagin

proved

T83

PAHA

proved

T84

SecondOrder

proved

T86

NNO

proved

T85

Goedel

proved

T124

Ordinal

proved

T186

Presburger

proved

T187

HAomega

proved

T146

Zermelo

proved

T89

ZF

proved

T91

NBG

proved

T90

KP

proved

T88

IZF

proved

T87

Setoid

proved

T106

NF

proved

T107

ETCS

proved

T147

SEAR

proved

T105

AFA

proved

T109

Mostowski

proved

T125

WellFounded

proved

T110

Nominal

proved

T104

Grothendieck

proved

T92

SetTopos

proved

T162

TG

proved

T163

MacLane

proved

T164

GPK

proved

T165

IST

proved

T166

AST

proved

T167

Ackermann

proved

T168

AD

proved

T169

VeqL

proved

T188

LargeCardinals

proved

T189

MartinAxiom

proved

T64

Internal

proved

T148

Beth

proved

T93

Completeness

proved

T94

Compactness

proved

T108

Forcing

proved

T96

Effective

proved

T96b

EffectiveK1

proved

T190

Ultraproduct

proved

T191

AlgebraicLogic

proved

T192

Truth

proved

T60

Base

proved

T61

Cat

proved

T149

KanExt

proved

T62

CCC

proved

T150

MonoidalClosed

proved

T151

Fibration

proved

T193

Higher2

proved

T63

Topos

proved

T95

Sheaf

proved

T97

Classifier

proved

T115

Locale

proved

T119

SDG

proved

T194

GeometricLogic

proved

T98

MLTT

proved

T99

CIC

proved

T120

MLTTVariants

proved

T127

OrtonPitts

proved

T152

CwF

proved

T121

OTT

proved

T122

TwoLevel

proved

T195

TypeVariants

proved

T134

Simplicial

proved

T133

ModelCat

proved

T135

Homotopy

proved

T153

InfCat

proved

T154

Presentable

proved

T155

LocalUniverse

proved

T136

ShulmanPath

proved

T196

InfN

proved

T118

Bishop

proved

T116

Domain

proved

T117

Game

proved

T156

Coalgebra

proved

T197

Brouwer

proved

T198

Markov

proved

T199

Predicative

proved

T200

Finitism

proved

T201

Mereology

proved

T202

Condensed

proved

T157

Institutions

proved

T158

MMT

proved

T159

Dedukti

proved

T160

LF

proved

T161

IsabellePure

proved

T203

Metamath

proved

T204

Mizar

proved

T205

HOL

proved

T206

UniversalLogic

proved

T207

ChurchTuring2

proved

T208

FOCompleteness

proved

T209

ETCSZF

proved

T210

Schanuel

proved

T211

Frege

proved

T212

Ramified

proved

T213

ETCC

proved

T214

Epsilon

proved

T215

Plural

proved

T216

Krivine

proved

T126

Lines

proved

Item

Content

Status
T60

A=A chain, E-categories, Fun \(\to \) Rel

proved
T61

functors, Yoneda, limits, adjunctions, monads

proved
T62

CCC, \((-\times b)\dashv (b\Rightarrow -)\), setoids CCC, Fun CCC \(\Leftrightarrow \) funext, \(f^*\dashv \Pi _f\)

proved
T63

\(\Omega =(\mathrm {Prop},\leftrightarrow )\), Heyting, classifier on setoids, \(P X=X\Rightarrow \Omega \)

proved
T64

internal language: first-order intuitionistic ND sound in setoids

proved
T65

minimal vs intuitionistic: Heyting soundness, \(\vdash _{int}\iff \vdash _{min}+\mathrm {EFQ}\), separations

proved
T66

classical = Boolean \(\Omega \); Gödel–Gentzen \(\Gamma \vdash _c\varphi \iff gg\,\Gamma \vdash _i gg\,\varphi \)

proved
T67

K, T, S4, S5: frame correspondence; GMT translation into S4

proved
T68

linear: residuated lattices with \(!\); wk+ct \(\Leftrightarrow \) Heyting; Girard via co-Kleisli

proved
T69

relevant/affine square: contraction, weakening on residuated models

proved
T70

paraconsistent = order dual of \(\Omega \) (co-Heyting); LP

proved
T71

Gödel = prelinear Heyting; MV + idempotent = Boolean; \(\L _3\)

proved
T72

tense \(P\dashv G,\ F\dashv H\); common knowledge = greatest fixed point

proved
T73

quantifiers \(\exists _f\dashv f^*\dashv \forall _f\); Frobenius, Beck–Chevalley; higher order via \(P X\)

proved
T74

natural deduction \(\to ,\wedge \): normalization by evaluation; consistency

proved
T75

sequent calculus LJ: cut elimination via ND normalization

proved
T76

Curry–Howard–Lambek: terms = derivations; \(\beta \eta \) sound in every CCC

proved
T77

Gödel–Gentzen \(\equiv \) Kuroda; Glivenko; Friedman A-translation

proved
T78

untyped \(\lambda \): Church–Rosser (Takahashi), unique normal forms

proved
T105

AFA: graphs + bisimulation (no quotient), strong extensionality, unique decorations, \(\Omega =\{\Omega \}\), streams

proved
T108

forcing = nucleus on \(\Omega \); \(\neg \neg \)-sheaves Boolean, complete; Cohen-style example

proved
T96

realizability Heyting algebra over any combinatory algebra; collapses to \(\Omega \) on one point

proved
T87

setoid model: quotients, funext, choice \(\Rightarrow \) LEM (Diaconescu)

proved
T109

Mostowski collapse injective; Aczel’s \(V\): extensionality, \(\in \)-induction, \(x\notin x\)

proved
T95

presheaf topos: sieves Heyting, \(\Omega \) classifies subpresheaves (unique); sheaf truth values = fixed sieves

proved
T86

NNO for any category parameter; unique up to iso; \(\mathbb {N}\) in setoids; bridge to arithmetic

proved
T133

model structures on the category parameter; trivial model structure on every C

proved
T107

ETCS = setoid coordinate + well-pointed + NNO + Boolean + choice (choice alone suffices)

proved
T88

IZF in Aczel’s \(V\): pairing, union, separation, power set, infinity, collection (\(\Sigma \))

proved
T89

ZF = IZF point + LEM condition: classical foundation; ZFC condition = choice

proved
T90

KP = \(\Delta _0\) fragment: \(\Delta _0\) formulas respect \(\approx \); \(\Delta _0\)-separation as an instance

proved
T91

NBG/MK: classes = respecting predicates on \(V\); subclass of a set is a set; universe proper

proved
T113

deontic D \(\Leftrightarrow \) serial \(R\); reflexive \(\Rightarrow \) serial

proved
T119

SDG: Kock–Lawvere + field condition + LEM on \(D\) \(\Rightarrow 0=1\) (minimal ring conditions)

proved
T111

quantum: ortholattices; distributive \(\Rightarrow \) Boolean Heyting; MO2 orthomodular, not distributive

proved
T59

core: setoid stem closed under the seven operations (Lean + Cubical Agda)

proved
T137

GL: Löb \(\Leftrightarrow \) transitive + conversely well-founded (constructive)

proved
T140

strong Kleene K3: no tautologies, explosive; K3 \(\leftrightarrow \) LP duality

proved
T143

Hilbert systems: deduction theorem; Hilbert \(\Leftrightarrow \) natural deduction

proved
T150

closed structure = adjunctions \((-\otimes b)\dashv (b\multimap -)\); instances: CCCs, residuated orders

proved
T112

Lambek: residuated monoids with two residuals; languages model; exchange \(\Rightarrow \) residuals coincide

proved
T138

PDL box laws (\(;,\cup ,{}^*\) fixed point, induction); LTL unfoldings on paths

proved
T116

Scott: \(\omega \)CPO parameter; Kleene least fixed point

proved
T156

coalgebras on the category parameter: final unique up to iso; Lambek’s lemma

proved
T115

locales: frames \(\Rightarrow \) Heyting algebras; opens of any topology form a frame

proved
T141

free logic (existence predicate), \(L_{\omega _1\omega }\) (countable \(\wedge ,\vee \)), hybrid logic (nominals, @)

proved
T139

da Costa \(C_\omega \): bivaluations; LEM valid, explosion fails

proved
T97

subobject classifiers: core \(\Omega \) is one; any two are isomorphic

proved
T104

Grothendieck universe \(U=\{\mathrm {lift}\,a\}\in V_{1}\): transitive, closed under pairing, union, power

proved
T171

modal \(\mu \)-calculus: Knaster–Tarski lfp/gfp on \(\Omega ^W\); \(EF\,p=\mu X.p\vee \Diamond X\) = reachability

proved
T177

LFP logic: transitive closure \(=\mu T.\,E\vee E;T\)

proved
T176

ALC = modal K (Schild translation preserves extensions)

proved
T172

conditional logic: selection functions; identity holds, antecedent strengthening fails

proved
T173

preferential (KLM) nonmonotonic consequence; monotonicity fails; empty preference = classical

proved
T175

team semantics: dependence atom, downward closure, not flat

proved
T178

justification logic: Fitting models; application, sum, reflection; forgetful projection to S4

proved
T182

automata: subset construction (states = power of states) accepts the NFA language

proved
T183

processes: LTS bisimilarity is an equivalence; Hennessy–Milner invariance

proved
T198

Markov’s principle as a truth-value condition; LEM \(\Rightarrow \) MP; MP \(\Leftrightarrow \) \(\Sigma ^0_1\) stability

proved
T201

mereology: parthood parameter; inhabited predicates satisfy strong supplementation and fusion

proved
T191

Lindenbaum–Tarski algebra is Heyting; algebraic completeness \(\vdash _i\varphi \iff \) valid in all Heyting algebras

proved
T192

Lawvere’s fixed-point theorem; Cantor; Tarski-style undefinability

proved
T142

second-order: standard vs Henkin (\(D_2\) parameter); comprehension fails in a Henkin model

proved
T170

many-sorted: relativization to the total space; Henkin second-order = two-sorted

proved
T125

foundation vs AFA: WF+extensional \(\Rightarrow \) no self-membership; a loop \(\Rightarrow \ \Omega \)

proved
T163

Mac Lane, Zermelo and Tarski–Grothendieck points assembled on \(V\)

proved
T81

primitive recursive terms evaluate (total); addition; \(\mu \)-graph deterministic

proved
T145

two-counter machines: small-step semantics; addition program reaches halt with \(r_0=x+y\)

proved
T186

Presburger/Skolem fragments; \(\Delta _0\) truth in \(\mathbb {N}\) decidable (bounded search)

proved
T93

completeness: intuitionistic \(\iff \) Heyting-valid; classical \(\iff \) Boolean-valid (Lindenbaum)

proved
T94

finite hypotheses; strong completeness; compactness of Heyting consequence

proved
T83

arithmetic structures: Q, induction; \(\mathbb {N}\) is a PA/HA structure; one point fails Q

proved
T84

\(\omega \)-models \((\mathbb {N},D)\): comprehension per class; chain decidable \(\subseteq \Sigma ^0_1\subseteq \) all

proved
T151

hyperdoctrines on the category parameter; setoid instance; monotonicity from adjunctions

proved
T110

nominal sets: permutation actions with finite support; atoms and products nominal

proved
T197

Brouwer: weak continuity WC-N refutes LEM for \(\Pi ^0_1\)

proved
T164

positive set theory: positive comprehension gives \(V\in V\), unions, intersections

proved
T180

Dialectica category as a category instance; morphisms = Gödel’s implication shape

proved
T99

CIC as a point: impredicative Prop, definitional proof irrelevance, UIP, subsingleton elimination, universes

proved
T200

finitism: PR closure; multiplication is PR with correct values

proved
T122

two-level: outer strict Eq \(\Rightarrow \) inner paths; inner paths finer

proved
T121

observational type theory = setoid stem: funext and propext definitional

proved
T148

Beth: bar closure is a nucleus on upsets of the binary tree; Beth truth values Heyting; soundness

proved
T92

setoids form an elementary topos with NNO (equalizers + CCC + \(\Omega \) + NNO)

proved
T147

SEAR: relations on setoids; tabulation with jointly monic projections; power sets

proved
T206

universal logic: Tarskian consequence; ND and every semantic consequence Tarskian; preferential not monotone

proved
T157

institutions: satisfaction condition; propositional logic is an institution

proved
T80

SK: weak reduction simulated by \(\beta \) in \(\lambda \); bracket abstraction (T96) the converse

proved
T205

HOL: simple types in the setoid stem; extensionality; classical = LEM condition

proved
T174

probability logic: counting measure on a finite outcome list; inclusion–exclusion, complement, monotonicity

proved
T193

2-category of E-categories: horizontal composition, naturality, interchange law

proved
T187

Gödel’s T: finite types over \(\mathbb {N}\); standard evaluation; recursor equations; addition

proved
T152

CwF parameter; family model with laws by rfl; \(\Pi ,\Sigma \) \(\beta \eta \); Id reflects (extensional MLTT)

proved
T120

extensional MLTT = UIP (family model); intensional = groupoid universe where UIP fails

proved
T160

meta-frameworks as points: LF adequacy, Dedukti rewriting, Pure rules, MMT composition, Metamath substitution, Mizar = TG + classical

proved
T168

determinacy: finite Bool games determined (constructive Zermelo); AD as a condition (clashes with AC)

proved
T117

game semantics: verifier wins \(\iff \) true, falsifier wins \(\iff \) false; determined

proved
T165

IST: standardness predicate; idealization for \(<\) gives a nonstandard number

proved
T188

tower of universes \(U_u\in V_{u+1}\), \(\mathrm {lift}\,U_u\in U_{u+1}\)

proved
T114

HOIL = HOL’s type model without the Boolean condition; Boolean \(\Omega \iff \) LEM

proved
T134

simplicial sets: \(\Delta \) as a category value; sSet = setoid presheaves; nerve of a preorder; inner 2-horn fills

proved
T149

Kan extensions (order-enriched): \(\mathrm {Lan}_f g=\bigvee \{g p\mid f p\le q\}\), universal property

proved
T135

homotopy theory: \(\pi _0\) = localization of objects at weak equivalences; trivial model: identified objects isomorphic

proved
T194

geometric formulas (\(\top ,\wedge ,\bigvee \)) preserved by frame homomorphisms

proved
T153

quasi-categories: inner 2-horn condition on any simplicial set; nerves satisfy it

proved
T190

reduced products over a filter as setoids; operations respect \(\sim \); Łoś for equations and conjunctions

proved
T195

session types: duality is an involution swapping send/receive and choice/offer

proved
T167

Ackermann: every class of level-0 sets is a set of level 1 (separation inside \(U\))

proved
T185

descriptive complexity (certificate side): ESO 2-colourability = guessed colouring + correct Boolean check

proved
T184

quantum circuits: CNOT involution, three CNOTs = SWAP, Toffoli involution; \(H^2=2I\), \(XZ=-ZX\)

proved
T166

AST: proper semisets contradict full separation (every semiset is a set in \(V\))

proved
T202

condensed sets (finite shadow): \(S\mapsto X^S\) sends finite coproducts to products

proved
T189

Martin’s axiom, countable case: Rasiowa–Sikorski generic filter meeting countably many dense sets

proved
T199

predicativism: arithmetical comprehension; Weyl’s impredicative \(\mathbb N\) equals the predicative one

proved
T179

MLL proofs: linear negation involutive; Euler invariant atoms \(=2(\#\otimes +1)\)

proved
T196

globular sets; the iterated-identity globular set of a type is an \((\infty ,0)\)-category; in CIC higher cells collapse

proved
T136

Shulman as a corollary: the Orton–Pitts core at a Grothendieck \(\infty \)-topos over the classical point (also: universes in \(V\) → Glivenko → model structure on setoids → interval paths)

proved
T155

local universes: types as maps into \((U,\mathrm {El})\); substitution strictly functorial; comprehension laws by rfl

proved
T154

presentability: subsets are directed unions of finite ones; Bousfield localization as a closure operator with its reflection property

proved
T169

constructibility: \(\mathrm {Def}(x)\subseteq \mathcal P(x)\), and \(x\subseteq \mathrm {Def}(x)\) for transitive \(x\)

proved
T144

PCF: environment semantics with fuel, a type checker; factorial via fix evaluates to 120 and has type \(\mathbb N\to \mathbb N\)

proved
T181

pure type systems over a parametric specification; derivability monotone in the specification; the λ-cube from λ→ to λC

proved
T79

STLC normalization by evaluation: every closed typed term’s output is \(\beta \)-normal (Tait logical predicate)

proved
T85

Gödel I/II and Löb (user’s NoSelfVerify, linked); Löb on both sides of provability logic

proved
T208

first-order logic: Heyting-valued soundness/completeness, Löwenheim–Skolem (domain \(\mathbb N\)), compactness for theories of sentences

proved
T127

HoTT as an interval value: paths = equality iff the interval is connected; univalence holds in Cubical Agda and fails at the CIC point

proved
T209

ETCS ↔ Mac Lane (instance level, both ways): El preserves power/products/exponentials; the core W-type of trees satisfies the Mac Lane axioms

proved
T210

nominal sets ↔ Schanuel topos: supports, gluing, colimit of a local presheaf is nominal, round trip

proved
T126

all lines in one Lean file: 197 general theorems re-exported, status table

proved
T118

Bishop reals: regular integer sequences over \(n+1\), \(\approx \) an equivalence (Bishop’s argument), negation and integers

proved
T96b

realizability over K1 (μ-recursive programs): a numbering, determinism, Church’s thesis realized, no realizer for decidability of halting

proved
T211

Frege: Basic Law V is inconsistent (Russell = Cantor diagonal); Hume’s principle, zero, predecessor, ancestral induction

proved
T212

ramified types: orders over simple types, erasure; reducibility collapses the hierarchy; a strict hierarchy without it

proved
T213

ETCC: objects = functors from 1, arrows = functors from 2, composition from 3, products, discrete categories = sets

proved
T214

Hilbert epsilon-calculus: critical axiom, quantifiers, choice, Diaconescu

proved
T215

Plural logic (Boolos): plural comprehension, Boolos translation, pluralities as parts

proved
T216

Krivine classical realizability: modus ponens, cc realizes Peirce, empty pole

proved
–T126

see TODO

remaining

85.1 The base: the A=A chain and RelFunCat

The path groupoid, setoids, functions and relations form categories with setoid hom-sets; the graph functor \(\mathrm {Fun}\to \mathrm {Rel}\) is faithful and its image is the total single-valued relations. \(\Gamma :\mathbf {Fun}\to \mathbf {Rel},\ f\mapsto \{(a,b)\mid f a=b\};\quad R\ \text {single-valued}+\text {witness }w\ \Rightarrow \ \Gamma (w)\simeq R\).

found/Base.lean

/-
  T60. found/Base — the base of the one frame.

  * The A = A chain (OneChain C0–C6): rule, join, rev, ap, Iso.
  * E-categories: categories whose hom-sets carry an equivalence relation
    (a setoid), so that no quotient (Quot.sound) and no funext is needed.
  * Three instances: the path groupoid of a type (the A = A chain is a
    groupoid), the category of setoids, the category of types and functions
    (pointwise equality), the category of types and relations.
  * RelFunCat: the graph functor Fun → Rel, faithful, and the functions are
    exactly the total single-valued relations (one direction constructive,
    the other with a unique-choice witness given as data).

  Lean 4 core only, hand-written proofs, no axioms.

  CIC dependence: proof irrelevance of Eq (path equivalence in PathCat set to True = UIP), structure eta.
-/

namespace Found

universe u v w

/-! ## The A = A chain -/

section Chain
variable {A : Type u} {B : Type v}

theorem rule {a : A} (G : (x : A) → a = x → Prop) (h : G a rfl) :
    ∀ (x : A) (p : a = x), G x p := by
  intro x p
  cases p
  exact h

theorem join {a x y : A} (p : a = x) (q : x = y) : a = y := by
  cases q
  exact p

theorem rev {a x : A} (p : a = x) : x = a := by
  cases p
  rfl

theorem ap (f : A → B) {a x : A} (p : a = x) : f a = f x := by
  cases p
  rfl

theorem join_id {a x : A} (p : a = x) : join p rfl = p := rfl
theorem id_join {a x : A} (p : a = x) : join rfl p = p := rfl
theorem join_assoc {a x y z : A} (p : a = x) (q : x = y) (r : y = z) :
    join (join p q) r = join p (join q r) := rfl
theorem join_rev {a x : A} (p : a = x) : join p (rev p) = rfl := rfl
theorem ap_join (f : A → B) {a x y : A} (p : a = x) (q : x = y) :
    ap f (join p q) = join (ap f p) (ap f q) := rfl

structure Iso (α : Type u) (β : Type v) where
  fwd : α → β
  bwd : β → α
  left : ∀ a, bwd (fwd a) = a
  right : ∀ b, fwd (bwd b) = b

def Iso.refl (α : Type u) : Iso α α := ⟨fun a => a, fun a => a, fun _ => rfl, fun _ => rfl⟩

def Iso.symm {α : Type u} {β : Type v} (e : Iso α β) : Iso β α :=
  ⟨e.bwd, e.fwd, e.right, e.left⟩

def Iso.trans {α : Type u} {β : Type v} {γ : Type w} (e : Iso α β) (f : Iso β γ) : Iso α γ :=
  ⟨fun a => f.fwd (e.fwd a), fun c => e.bwd (f.bwd c),
   fun a => join (ap e.bwd (f.left (e.fwd a))) (e.left a),
   fun c => join (ap f.fwd (e.right (f.bwd c))) (f.right c)⟩

end Chain

/-! ## Setoids and E-categories -/

structure Setd where
  car : Type u
  eqv : car → car → Prop
  refl : ∀ a, eqv a a
  symm : ∀ {a b}, eqv a b → eqv b a
  trans : ∀ {a b c}, eqv a b → eqv b c → eqv a c

/-- A category whose hom-sets are setoids. -/
structure ECat where
  Ob : Type u
  Hom : Ob → Ob → Type v
  heq : {a b : Ob} → Hom a b → Hom a b → Prop
  hrefl : ∀ {a b} (f : Hom a b), heq f f
  hsymm : ∀ {a b} {f g : Hom a b}, heq f g → heq g f
  htrans : ∀ {a b} {f g h : Hom a b}, heq f g → heq g h → heq f h
  id : (a : Ob) → Hom a a
  comp : {a b c : Ob} → Hom a b → Hom b c → Hom a c
  comp_resp : ∀ {a b c} {f f' : Hom a b} {g g' : Hom b c},
    heq f f' → heq g g' → heq (comp f g) (comp f' g')
  id_comp : ∀ {a b} (f : Hom a b), heq (comp (id a) f) f
  comp_id : ∀ {a b} (f : Hom a b), heq (comp f (id b)) f
  assoc : ∀ {a b c d} (f : Hom a b) (g : Hom b c) (h : Hom c d),
    heq (comp (comp f g) h) (comp f (comp g h))

/-- A functor between E-categories, respecting the hom equivalences. -/
structure EFun (C : ECat.{u, v}) (D : ECat.{u', v'}) where
  obj : C.Ob → D.Ob
  map : {a b : C.Ob} → C.Hom a b → D.Hom (obj a) (obj b)
  map_resp : ∀ {a b} {f g : C.Hom a b}, C.heq f g → D.heq (map f) (map g)
  map_id : ∀ a, D.heq (map (C.id a)) (D.id (obj a))
  map_comp : ∀ {a b c} (f : C.Hom a b) (g : C.Hom b c),
    D.heq (map (C.comp f g)) (D.comp (map f) (map g))

def EFun.Faithful {C : ECat.{u, v}} {D : ECat.{u', v'}} (F : EFun C D) : Prop :=
  ∀ {a b} (f g : C.Hom a b), D.heq (F.map f) (F.map g) → C.heq f g

/-! ## Instance 1: the A = A chain is a groupoid -/

def PathCat (A : Type u) : ECat.{u, 0} where
  Ob := A
  Hom a b := PLift (a = b)
  heq _ _ := True
  hrefl _ := trivial
  hsymm _ := trivial
  htrans _ _ := trivial
  id _ := ⟨rfl⟩
  comp p q := ⟨join p.down q.down⟩
  comp_resp _ _ := trivial
  id_comp _ := trivial
  comp_id _ := trivial
  assoc _ _ _ := trivial

/-- every path has an inverse: the groupoid law, from `rev` -/
theorem PathCat.inv {A : Type u} {a b : A} (p : (PathCat A).Hom a b) :
    ∃ q : (PathCat A).Hom b a, (PathCat A).heq ((PathCat A).comp p q) ((PathCat A).id a) :=
  ⟨⟨rev p.down⟩, trivial⟩

/-- `ap` is a functor between path groupoids -/
def PathCat.apF {A : Type u} {B : Type v} (f : A → B) : EFun (PathCat A) (PathCat B) where
  obj := f
  map p := ⟨ap f p.down⟩
  map_resp _ := trivial
  map_id _ := trivial
  map_comp _ _ := trivial

/-! ## Instance 2: setoids -/

structure SHom (X Y : Setd.{u}) where
  fn : X.car → Y.car
  resp : ∀ {a a'}, X.eqv a a' → Y.eqv (fn a) (fn a')

def SetdCat : ECat.{u+1, u} where
  Ob := Setd.{u}
  Hom := SHom
  heq {_ b} f g := ∀ x, b.eqv (f.fn x) (g.fn x)
  hrefl {_ b} f x := b.refl (f.fn x)
  hsymm {_ b} _ _ h x := b.symm (h x)
  htrans {_ b} _ _ _ h k x := b.trans (h x) (k x)
  id _ := ⟨fun x => x, fun h => h⟩
  comp f g := ⟨fun x => g.fn (f.fn x), fun h => g.resp (f.resp h)⟩
  comp_resp {_ _ c} _ _ g _ hf hg x := c.trans (g.resp (hf x)) (hg _)
  id_comp {_ b} f x := b.refl (f.fn x)
  comp_id {_ b} f x := b.refl (f.fn x)
  assoc {_ _ _ d} _ _ h _ := d.refl (h.fn _)

/-! ## Instance 3: types and functions (pointwise equality, no funext) -/

def FunCat : ECat.{u+1, u} where
  Ob := Type u
  Hom A B := A → B
  heq f g := ∀ x, f x = g x
  hrefl _ _ := rfl
  hsymm h x := rev (h x)
  htrans h k x := join (h x) (k x)
  id _ := fun x => x
  comp f g := fun x => g (f x)
  comp_resp {_ _ _} _ f' g _ hf hg x := join (ap g (hf x)) (hg (f' x))
  id_comp _ _ := rfl
  comp_id _ _ := rfl
  assoc _ _ _ _ := rfl

/-! ## Instance 4: types and relations (pointwise ↔, no propext) -/

def RelCat : ECat.{u+1, u} where
  Ob := Type u
  Hom A B := A → B → Prop
  heq R S := ∀ a b, R a b ↔ S a b
  hrefl _ _ _ := Iff.rfl
  hsymm h a b := (h a b).symm
  htrans h k a b := (h a b).trans (k a b)
  id _ := fun a b => a = b
  comp R S := fun a c => ∃ b, R a b ∧ S b c
  comp_resp hR hS a c :=
    ⟨fun ⟨b, r, s⟩ => ⟨b, (hR a b).mp r, (hS b c).mp s⟩,
     fun ⟨b, r, s⟩ => ⟨b, (hR a b).mpr r, (hS b c).mpr s⟩⟩
  id_comp _ a b :=
    ⟨fun ⟨_, e, r⟩ => by cases e; exact r, fun r => ⟨a, rfl, r⟩⟩
  comp_id _ a b :=
    ⟨fun ⟨_, r, e⟩ => by cases e; exact r, fun r => ⟨b, r, rfl⟩⟩
  assoc _ _ _ a d :=
    ⟨fun ⟨c, ⟨b, r, s⟩, t⟩ => ⟨b, r, c, s, t⟩,
     fun ⟨b, r, c, s, t⟩ => ⟨c, ⟨b, r, s⟩, t⟩⟩

/-! ## RelFunCat: functions are the total single-valued relations -/

def graph {A : Type u} {B : Type u} (f : A → B) : A → B → Prop := fun a b => f a = b

def Graph : EFun FunCat.{u} RelCat.{u} where
  obj A := A
  map f := graph f
  map_resp {_ _} _ _ h a _ :=
    ⟨fun e => join (rev (h a)) e, fun e => join (h a) e⟩
  map_id _ _ _ := Iff.rfl
  map_comp f g a _ :=
    ⟨fun e => ⟨f a, rfl, e⟩, fun ⟨_, e1, e2⟩ => join (ap g e1) e2⟩

theorem Graph_faithful : EFun.Faithful Graph.{u} :=
  fun _ g h x => (h x (g x)).mpr rfl

def Total {A B : Type u} (R : A → B → Prop) : Prop := ∀ a, ∃ b, R a b
def SingleValued {A B : Type u} (R : A → B → Prop) : Prop :=
  ∀ a b b', R a b → R a b' → b = b'

theorem graph_total {A B : Type u} (f : A → B) : Total (graph f) := fun a => ⟨f a, rfl⟩

theorem graph_single {A B : Type u} (f : A → B) : SingleValued (graph f) :=
  fun _ _ _ e e' => join (rev e) e'

/-- the converse: a single-valued relation with a chosen witness (data, i.e. a
  `Σ`-type rather than `∃`, so no choice) is the graph of a function -/
theorem rel_is_graph {A B : Type u} (R : A → B → Prop) (hs : SingleValued R)
    (w : (a : A) → {b : B // R a b}) :
    RelCat.heq (graph (fun a => (w a).val)) R :=
  fun a b => ⟨fun e => by cases e; exact (w a).property,
              fun r => hs a _ _ (w a).property r⟩

/-- the map back and forth is the identity up to the hom equivalence -/
theorem graph_witness_roundtrip {A B : Type u} (f : A → B) :
    FunCat.heq (fun a => (⟨f a, rfl⟩ : {b : B // graph f a b}).val) f :=
  fun _ => rfl

end Found

#print axioms Found.rule
#print axioms Found.join
#print axioms Found.rev
#print axioms Found.ap
#print axioms Found.join_assoc
#print axioms Found.Iso.trans
#print axioms Found.PathCat
#print axioms Found.PathCat.inv
#print axioms Found.PathCat.apF
#print axioms Found.SetdCat
#print axioms Found.FunCat
#print axioms Found.RelCat
#print axioms Found.Graph
#print axioms Found.Graph_faithful
#print axioms Found.graph_total
#print axioms Found.graph_single
#print axioms Found.rel_is_graph
#print axioms Found.graph_witness_roundtrip

#print axioms: 18 theorems, no axioms.

85.2 Categories, Yoneda, adjunctions, monads

Natural transformations, the Yoneda lemma for setoid presheaves (full and faithful), uniqueness of terminals and products, triangle identities from a hom-set adjunction, and the monad of an adjunction. \(\mathrm {Nat}(\mathbf {y}c,P)\simeq P(c);\quad F\dashv G\ \Rightarrow \ (G F,\eta ,\ k\mapsto G(\psi k))\ \text {is a monad}\).

found/Cat.lean

/-
  T61. found/Cat — category theory inside the frame (setoid hom-sets).

  * identity and composite functors, natural transformations, vertical composite
  * setoid-valued presheaves, representables, the Yoneda lemma, Yoneda is
    full (every natural map between representables is composition with a map)
  * terminal objects (unique up to iso), binary products; Fun has both
  * adjunctions in hom-set form: unit, counit, triangle identities
  * Kleisli monads; every adjunction gives a monad; Option is a monad on Fun

  Lean 4 core only, hand-written proofs, no axioms.

  CIC dependence: definitional structure eta (Prod, PUnit: the rfl proofs in funProduct, funTerminal).
-/
import found.Base

namespace Found

universe u v u' v' u'' v'' w

namespace ECat
variable (C : ECat.{u, v})

theorem lcong {a b c : C.Ob} {f f' : C.Hom a b} (h : C.heq f f') (g : C.Hom b c) :
    C.heq (C.comp f g) (C.comp f' g) := C.comp_resp h (C.hrefl g)

theorem rcong {a b c : C.Ob} (f : C.Hom a b) {g g' : C.Hom b c} (h : C.heq g g') :
    C.heq (C.comp f g) (C.comp f g') := C.comp_resp (C.hrefl f) h

/-- the hom-set of `a` and `b` as a setoid -/
def homS (a b : C.Ob) : Setd.{v} :=
  ⟨C.Hom a b, C.heq, C.hrefl, fun h => C.hsymm h, fun h k => C.htrans h k⟩

end ECat

/-! ## Functors and natural transformations -/

def EFun.idF (C : ECat.{u, v}) : EFun C C where
  obj a := a
  map f := f
  map_resp h := h
  map_id a := C.hrefl (C.id a)
  map_comp f g := C.hrefl (C.comp f g)

def EFun.compF {C : ECat.{u, v}} {D : ECat.{u', v'}} {E : ECat.{u'', v''}}
    (F : EFun C D) (G : EFun D E) : EFun C E where
  obj a := G.obj (F.obj a)
  map f := G.map (F.map f)
  map_resp h := G.map_resp (F.map_resp h)
  map_id a := E.htrans (G.map_resp (F.map_id a)) (G.map_id _)
  map_comp f g := E.htrans (G.map_resp (F.map_comp f g)) (G.map_comp _ _)

structure NatTr {C : ECat.{u, v}} {D : ECat.{u', v'}} (F G : EFun C D) where
  app : (a : C.Ob) → D.Hom (F.obj a) (G.obj a)
  nat : ∀ {a b} (f : C.Hom a b),
    D.heq (D.comp (F.map f) (app b)) (D.comp (app a) (G.map f))

section NT
variable {C : ECat.{u, v}} {D : ECat.{u', v'}}

def NatTr.idT (F : EFun C D) : NatTr F F where
  app a := D.id (F.obj a)
  nat f := D.htrans (D.comp_id (F.map f)) (D.hsymm (D.id_comp (F.map f)))

def NatTr.vcomp {F G H : EFun C D} (α : NatTr F G) (β : NatTr G H) : NatTr F H where
  app a := D.comp (α.app a) (β.app a)
  nat {a b} f :=
    D.htrans (D.hsymm (D.assoc (F.map f) (α.app b) (β.app b)))
    (D.htrans (D.lcong (α.nat f) (β.app b))
    (D.htrans (D.assoc (α.app a) (G.map f) (β.app b))
    (D.htrans (D.rcong (α.app a) (β.nat f))
      (D.hsymm (D.assoc (α.app a) (β.app a) (H.map f))))))

theorem NatTr.idT_vcomp {F G : EFun C D} (α : NatTr F G) (a : C.Ob) :
    D.heq ((NatTr.vcomp (NatTr.idT F) α).app a) (α.app a) := D.id_comp (α.app a)

theorem NatTr.vcomp_assoc {F G H K : EFun C D} (α : NatTr F G) (β : NatTr G H)
    (γ : NatTr H K) (a : C.Ob) :
    D.heq ((NatTr.vcomp (NatTr.vcomp α β) γ).app a) ((NatTr.vcomp α (NatTr.vcomp β γ)).app a) :=
  D.assoc _ _ _

end NT

/-! ## Presheaves of setoids and the Yoneda lemma -/

structure Psh (C : ECat.{u, v}) where
  obj : C.Ob → Setd.{w}
  map : {a b : C.Ob} → C.Hom a b → (obj b).car → (obj a).car
  map_eqv : ∀ {a b} (f : C.Hom a b) {x y}, (obj b).eqv x y → (obj a).eqv (map f x) (map f y)
  map_resp : ∀ {a b} {f g : C.Hom a b} (x : (obj b).car), C.heq f g → (obj a).eqv (map f x) (map g x)
  map_id : ∀ a x, (obj a).eqv (map (C.id a) x) x
  map_comp : ∀ {a b c} (f : C.Hom a b) (g : C.Hom b c) x,
    (obj a).eqv (map (C.comp f g) x) (map f (map g x))

structure PNat {C : ECat.{u, v}} (P Q : Psh.{u, v, w} C) where
  app : (a : C.Ob) → (P.obj a).car → (Q.obj a).car
  app_eqv : ∀ a {x y}, (P.obj a).eqv x y → (Q.obj a).eqv (app a x) (app a y)
  nat : ∀ {a b} (f : C.Hom a b) x, (Q.obj a).eqv (app a (P.map f x)) (Q.map f (app b x))

section Yoneda
variable {C : ECat.{u, v}}

/-- the representable presheaf `Hom(-, c)` -/
def yo (C : ECat.{u, v}) (c : C.Ob) : Psh.{u, v, v} C where
  obj a := C.homS a c
  map f g := C.comp f g
  map_eqv f _ _ h := C.rcong f h
  map_resp x h := C.lcong h x
  map_id _ x := C.id_comp x
  map_comp f g x := C.assoc f g x

variable {c : C.Ob} {P : Psh.{u, v, v} C}

def yoFwd (α : PNat (yo C c) P) : (P.obj c).car := α.app c (C.id c)

def yoBwd (x : (P.obj c).car) : PNat (yo C c) P where
  app _ g := P.map g x
  app_eqv _ _ _ h := P.map_resp x h
  nat f g := P.map_comp f g x

/-- Yoneda, one way round -/
theorem yoneda_fwd_bwd (x : (P.obj c).car) : (P.obj c).eqv (yoFwd (yoBwd (P := P) x)) x :=
  P.map_id c x

/-- Yoneda, the other way round -/
theorem yoneda_bwd_fwd (α : PNat (yo C c) P) (a : C.Ob) (g : C.Hom a c) :
    (P.obj a).eqv ((yoBwd (yoFwd α)).app a g) (α.app a g) :=
  (P.obj a).trans ((P.obj a).symm (α.nat g (C.id c))) (α.app_eqv a (C.comp_id g))

theorem yoFwd_resp {α β : PNat (yo C c) P}
    (h : ∀ a g, (P.obj a).eqv (α.app a g) (β.app a g)) :
    (P.obj c).eqv (yoFwd α) (yoFwd β) := h c (C.id c)

theorem yoBwd_resp {x y : (P.obj c).car} (h : (P.obj c).eqv x y) (a : C.Ob) (g : C.Hom a c) :
    (P.obj a).eqv ((yoBwd (P := P) x).app a g) ((yoBwd (P := P) y).app a g) :=
  P.map_eqv g h

/-- the Yoneda embedding is full -/
theorem yoneda_full {a c : C.Ob} (α : PNat (yo C a) (yo C c)) :
    ∃ f : C.Hom a c, ∀ b (g : C.Hom b a), C.heq (α.app b g) (C.comp g f) :=
  ⟨yoFwd α, fun b g => C.hsymm (yoneda_bwd_fwd α b g)⟩

/-- the Yoneda embedding is faithful -/
theorem yoneda_faithful {a c : C.Ob} (f f' : C.Hom a c)
    (h : ∀ b (g : C.Hom b a), C.heq (C.comp g f) (C.comp g f')) : C.heq f f' :=
  C.htrans (C.hsymm (C.id_comp f)) (C.htrans (h a (C.id a)) (C.id_comp f'))

end Yoneda

/-! ## Limits: terminal objects and binary products -/

structure Terminal (C : ECat.{u, v}) where
  one : C.Ob
  bang : (a : C.Ob) → C.Hom a one
  uniq : ∀ {a} (f : C.Hom a one), C.heq f (bang a)

theorem Terminal.unique_iso {C : ECat.{u, v}} (T S : Terminal C) :
    C.heq (C.comp (S.bang T.one) (T.bang S.one)) (C.id T.one) :=
  C.htrans (T.uniq _) (C.hsymm (T.uniq (C.id T.one)))

structure Product (C : ECat.{u, v}) (a b : C.Ob) where
  P : C.Ob
  p1 : C.Hom P a
  p2 : C.Hom P b
  pair : {x : C.Ob} → C.Hom x a → C.Hom x b → C.Hom x P
  beta1 : ∀ {x} (f : C.Hom x a) (g : C.Hom x b), C.heq (C.comp (pair f g) p1) f
  beta2 : ∀ {x} (f : C.Hom x a) (g : C.Hom x b), C.heq (C.comp (pair f g) p2) g
  eta : ∀ {x} (h : C.Hom x P), C.heq h (pair (C.comp h p1) (C.comp h p2))
  pair_resp : ∀ {x} {f f' : C.Hom x a} {g g' : C.Hom x b},
    C.heq f f' → C.heq g g' → C.heq (pair f g) (pair f' g')

/-- two products of the same pair are isomorphic -/
theorem Product.unique_iso {C : ECat.{u, v}} {a b : C.Ob} (X Y : Product C a b) :
    C.heq (C.comp (Y.pair X.p1 X.p2) (X.pair Y.p1 Y.p2)) (C.id X.P) := by
  have k1 : C.heq (C.comp (C.comp (Y.pair X.p1 X.p2) (X.pair Y.p1 Y.p2)) X.p1) X.p1 :=
    C.htrans (C.assoc _ _ _) (C.htrans (C.rcong _ (X.beta1 _ _)) (Y.beta1 _ _))
  have k2 : C.heq (C.comp (C.comp (Y.pair X.p1 X.p2) (X.pair Y.p1 Y.p2)) X.p2) X.p2 :=
    C.htrans (C.assoc _ _ _) (C.htrans (C.rcong _ (X.beta2 _ _)) (Y.beta2 _ _))
  have e1 := X.eta (C.comp (Y.pair X.p1 X.p2) (X.pair Y.p1 Y.p2))
  have e2 := X.eta (C.id X.P)
  exact C.htrans e1 (C.htrans (X.pair_resp k1 k2)
    (C.hsymm (C.htrans e2 (X.pair_resp (C.id_comp X.p1) (C.id_comp X.p2)))))

def funTerminal : Terminal FunCat.{u} where
  one := PUnit
  bang _ := fun _ => PUnit.unit
  uniq _ _ := rfl

def funProduct (A B : Type u) : Product FunCat.{u} A B where
  P := A × B
  p1 := Prod.fst
  p2 := Prod.snd
  pair f g := fun x => (f x, g x)
  beta1 _ _ _ := rfl
  beta2 _ _ _ := rfl
  eta _ _ := rfl
  pair_resp hf hg x := join (ap (fun y => (y, _)) (hf x)) (ap (fun z => (_, z)) (hg x))

/-! ## Adjunctions -/

structure Adj {C : ECat.{u, v}} {D : ECat.{u', v'}} (F : EFun C D) (G : EFun D C) where
  phi : {a : C.Ob} → {b : D.Ob} → D.Hom (F.obj a) b → C.Hom a (G.obj b)
  psi : {a : C.Ob} → {b : D.Ob} → C.Hom a (G.obj b) → D.Hom (F.obj a) b
  phi_resp : ∀ {a b} {k k' : D.Hom (F.obj a) b}, D.heq k k' → C.heq (phi k) (phi k')
  psi_resp : ∀ {a b} {g g' : C.Hom a (G.obj b)}, C.heq g g' → D.heq (psi g) (psi g')
  phi_psi : ∀ {a b} (g : C.Hom a (G.obj b)), C.heq (phi (psi g)) g
  psi_phi : ∀ {a b} (k : D.Hom (F.obj a) b), D.heq (psi (phi k)) k
  nat_l : ∀ {a a' b} (f : C.Hom a' a) (k : D.Hom (F.obj a) b),
    C.heq (phi (D.comp (F.map f) k)) (C.comp f (phi k))
  nat_r : ∀ {a b b'} (k : D.Hom (F.obj a) b) (g : D.Hom b b'),
    C.heq (phi (D.comp k g)) (C.comp (phi k) (G.map g))

namespace Adj
variable {C : ECat.{u, v}} {D : ECat.{u', v'}} {F : EFun C D} {G : EFun D C} (A : Adj F G)

def unit (a : C.Ob) : C.Hom a (G.obj (F.obj a)) := A.phi (D.id (F.obj a))
def counit (b : D.Ob) : D.Hom (F.obj (G.obj b)) b := A.psi (C.id (G.obj b))

theorem phi_eq {a b} (k : D.Hom (F.obj a) b) : C.heq (A.phi k) (C.comp (A.unit a) (G.map k)) :=
  C.htrans (A.phi_resp (D.hsymm (D.id_comp k))) (A.nat_r _ k)

theorem psi_nat_l {a a' b} (f : C.Hom a' a) (h : C.Hom a (G.obj b)) :
    D.heq (A.psi (C.comp f h)) (D.comp (F.map f) (A.psi h)) := by
  have e : C.heq (A.phi (D.comp (F.map f) (A.psi h))) (C.comp f h) :=
    C.htrans (A.nat_l f (A.psi h)) (C.rcong f (A.phi_psi h))
  exact D.htrans (A.psi_resp (C.hsymm e)) (A.psi_phi _)

theorem psi_nat_r {a b b'} (g : C.Hom a (G.obj b)) (k : D.Hom b b') :
    D.heq (A.psi (C.comp g (G.map k))) (D.comp (A.psi g) k) := by
  have e : C.heq (A.phi (D.comp (A.psi g) k)) (C.comp g (G.map k)) :=
    C.htrans (A.nat_r (A.psi g) k) (C.lcong (A.phi_psi g) (G.map k))
  exact D.htrans (A.psi_resp (C.hsymm e)) (A.psi_phi _)

theorem psi_eq {a b} (g : C.Hom a (G.obj b)) : D.heq (A.psi g) (D.comp (F.map g) (A.counit b)) :=
  D.htrans (A.psi_resp (C.hsymm (C.comp_id g))) (A.psi_nat_l g _)

/-- first triangle identity -/
theorem triangle_F (a : C.Ob) :
    D.heq (D.comp (F.map (A.unit a)) (A.counit (F.obj a))) (D.id (F.obj a)) :=
  D.htrans (D.hsymm (A.psi_eq (A.unit a))) (A.psi_phi _)

/-- second triangle identity -/
theorem triangle_G (b : D.Ob) :
    C.heq (C.comp (A.unit (G.obj b)) (G.map (A.counit b))) (C.id (G.obj b)) :=
  C.htrans (C.hsymm (A.phi_eq (A.counit b))) (A.phi_psi _)

end Adj

/-! ## Monads -/

structure KMonad (C : ECat.{u, v}) where
  T : C.Ob → C.Ob
  ret : (a : C.Ob) → C.Hom a (T a)
  bind : {a b : C.Ob} → C.Hom a (T b) → C.Hom (T a) (T b)
  bind_resp : ∀ {a b} {k k' : C.Hom a (T b)}, C.heq k k' → C.heq (bind k) (bind k')
  left : ∀ {a b} (k : C.Hom a (T b)), C.heq (C.comp (ret a) (bind k)) k
  right : ∀ a, C.heq (bind (ret a)) (C.id (T a))
  assoc : ∀ {a b c} (k : C.Hom a (T b)) (l : C.Hom b (T c)),
    C.heq (C.comp (bind k) (bind l)) (bind (C.comp k (bind l)))

/-- every adjunction gives a monad `G ∘ F` -/
def Adj.monad {C : ECat.{u, v}} {D : ECat.{u', v'}} {F : EFun C D} {G : EFun D C}
    (A : Adj F G) : KMonad C where
  T a := G.obj (F.obj a)
  ret := A.unit
  bind k := G.map (A.psi k)
  bind_resp h := G.map_resp (A.psi_resp h)
  left k := C.htrans (C.hsymm (A.phi_eq (A.psi k))) (A.phi_psi k)
  right _ := C.htrans (G.map_resp (A.psi_phi _)) (G.map_id _)
  assoc k l := C.htrans (C.hsymm (G.map_comp _ _)) (G.map_resp (D.hsymm (A.psi_nat_r k (A.psi l))))

def optionBind {A B : Type u} (k : A → Option B) : Option A → Option B
  | none => none
  | some a => k a

/-- `Option` is a monad on the category of functions -/
def optionMonad : KMonad FunCat.{u} where
  T := Option
  ret _ := some
  bind := optionBind
  bind_resp h x := by
    cases x with
    | none => rfl
    | some a => exact h a
  left _ _ := rfl
  right _ x := by
    cases x with
    | none => rfl
    | some _ => rfl
  assoc _ _ x := by
    cases x with
    | none => rfl
    | some _ => rfl

end Found

#print axioms Found.EFun.idF
#print axioms Found.EFun.compF
#print axioms Found.NatTr.idT
#print axioms Found.NatTr.vcomp
#print axioms Found.NatTr.idT_vcomp
#print axioms Found.NatTr.vcomp_assoc
#print axioms Found.yo
#print axioms Found.yoneda_fwd_bwd
#print axioms Found.yoneda_bwd_fwd
#print axioms Found.yoFwd_resp
#print axioms Found.yoBwd_resp
#print axioms Found.yoneda_full
#print axioms Found.yoneda_faithful
#print axioms Found.Terminal.unique_iso
#print axioms Found.Product.unique_iso
#print axioms Found.funTerminal
#print axioms Found.funProduct
#print axioms Found.Adj.phi_eq
#print axioms Found.Adj.psi_nat_l
#print axioms Found.Adj.psi_nat_r
#print axioms Found.Adj.psi_eq
#print axioms Found.Adj.triangle_F
#print axioms Found.Adj.triangle_G
#print axioms Found.Adj.monad
#print axioms Found.optionMonad

#print axioms: 25 theorems, no axioms.

85.3 Cartesian closed and locally cartesian closed

Every CCC has \((-\times b)\dashv (b\Rightarrow -)\); setoids form a CCC; currying on types respects pointwise equality iff funext; reindexing of setoid families has the right adjoint \(\Pi _f\). \(\mathrm {Hom}(a\times b,c)\simeq \mathrm {Hom}(a,b\Rightarrow c);\quad \mathrm {FunCurryResp}\leftrightarrow \mathrm {FunExt};\quad f^*\dashv \Pi _f\).

found/CCC.lean

/-
  T62. found/CCC — cartesian closed and locally cartesian closed categories.

  * CCC as an E-category with terminal, products, exponentials (curry/eval).
  * In any CCC: (- × b) and (b ⇒ -) are functors and (- × b) ⊣ (b ⇒ -);
    hence a monad b ⇒ (- × b) (the state monad).
  * Condition: setoids form a CCC (no axioms); for types with pointwise
    equality the standard currying respects equality iff funext holds,
    so "Fun is a CCC" is exactly the funext condition.
  * LCCC in family form: for f : I → J, the reindexing f* on families of
    setoids has a right adjoint Π_f (the dependent product ∀).

  Lean 4 core only, hand-written proofs, no axioms.

  CIC dependence: definitional structure eta (beta/eta of setdCCC are refl); not impredicative Prop.
-/
import found.Cat

namespace Found

universe u v

/-! ## Cartesian closed E-categories -/

structure CCC (C : ECat.{u, v}) where
  term : Terminal C
  prod : (a b : C.Ob) → Product C a b
  exp : C.Ob → C.Ob → C.Ob
  ev : (b c : C.Ob) → C.Hom (prod (exp b c) b).P c
  curry : {a b c : C.Ob} → C.Hom (prod a b).P c → C.Hom a (exp b c)
  curry_resp : ∀ {a b c} {h h' : C.Hom (prod a b).P c}, C.heq h h' → C.heq (curry h) (curry h')
  beta : ∀ {a b c} (h : C.Hom (prod a b).P c),
    C.heq (C.comp ((prod (exp b c) b).pair (C.comp (prod a b).p1 (curry h)) (prod a b).p2) (ev b c)) h
  eta : ∀ {a b c} (g : C.Hom a (exp b c)),
    C.heq (curry (C.comp ((prod (exp b c) b).pair (C.comp (prod a b).p1 g) (prod a b).p2) (ev b c))) g

namespace CCC
variable {C : ECat.{u, v}} (K : CCC C)

/-- `f × b` -/
def times {a a' : C.Ob} (b : C.Ob) (f : C.Hom a a') : C.Hom (K.prod a b).P (K.prod a' b).P :=
  (K.prod a' b).pair (C.comp (K.prod a b).p1 f) (K.prod a b).p2

theorem times_resp {a a' : C.Ob} (b : C.Ob) {f f' : C.Hom a a'} (h : C.heq f f') :
    C.heq (K.times b f) (K.times b f') :=
  (K.prod a' b).pair_resp (C.rcong _ h) (C.hrefl _)

theorem times_id (a b : C.Ob) : C.heq (K.times b (C.id a)) (C.id (K.prod a b).P) :=
  C.htrans ((K.prod a b).pair_resp
      (C.htrans (C.comp_id _) (C.hsymm (C.id_comp _))) (C.hsymm (C.id_comp _)))
    (C.hsymm ((K.prod a b).eta (C.id _)))

theorem times_comp {a a' a'' : C.Ob} (b : C.Ob) (f : C.Hom a a') (g : C.Hom a' a'') :
    C.heq (K.times b (C.comp f g)) (C.comp (K.times b f) (K.times b g)) := by
  have r1 : C.heq (C.comp (C.comp (K.times b f) (K.times b g)) (K.prod a'' b).p1)
      (C.comp (K.prod a b).p1 (C.comp f g)) :=
    C.htrans (C.assoc _ _ _) (C.htrans (C.rcong _ ((K.prod a'' b).beta1 _ _))
      (C.htrans (C.hsymm (C.assoc _ _ _)) (C.htrans (C.lcong ((K.prod a' b).beta1 _ _) g)
        (C.assoc _ _ _))))
  have r2 : C.heq (C.comp (C.comp (K.times b f) (K.times b g)) (K.prod a'' b).p2)
      (K.prod a b).p2 :=
    C.htrans (C.assoc _ _ _) (C.htrans (C.rcong _ ((K.prod a'' b).beta2 _ _))
      ((K.prod a' b).beta2 _ _))
  exact C.htrans ((K.prod a'' b).pair_resp (C.hsymm r1) (C.hsymm r2))
    (C.hsymm ((K.prod a'' b).eta _))

/-- the exponential transpose is unique -/
theorem curry_uniq {a b c : C.Ob} (k : C.Hom a (K.exp b c)) (h : C.Hom (K.prod a b).P c)
    (e : C.heq (C.comp (K.times b k) (K.ev b c)) h) : C.heq k (K.curry h) :=
  C.htrans (C.hsymm (K.eta k)) (K.curry_resp e)

/-- `b ⇒ g` -/
def expMap (b : C.Ob) {c c' : C.Ob} (g : C.Hom c c') : C.Hom (K.exp b c) (K.exp b c') :=
  K.curry (C.comp (K.ev b c) g)

theorem expMap_id (b c : C.Ob) : C.heq (K.expMap b (C.id c)) (C.id (K.exp b c)) :=
  C.hsymm (K.curry_uniq _ _
    (C.htrans (C.lcong (K.times_id _ b) _)
      (C.htrans (C.id_comp _) (C.hsymm (C.comp_id _)))))

theorem expMap_comp (b : C.Ob) {c c' c'' : C.Ob} (g : C.Hom c c') (g' : C.Hom c' c'') :
    C.heq (K.expMap b (C.comp g g')) (C.comp (K.expMap b g) (K.expMap b g')) :=
  C.hsymm (K.curry_uniq _ _
    (C.htrans (C.lcong (K.times_comp b _ _) _)
    (C.htrans (C.assoc _ _ _)
    (C.htrans (C.rcong _ (K.beta _))
    (C.htrans (C.hsymm (C.assoc _ _ _))
    (C.htrans (C.lcong (K.beta _) g') (C.assoc _ _ _)))))))

def prodF (b : C.Ob) : EFun C C where
  obj a := (K.prod a b).P
  map f := K.times b f
  map_resp h := K.times_resp b h
  map_id a := K.times_id a b
  map_comp f g := K.times_comp b f g

def expF (b : C.Ob) : EFun C C where
  obj c := K.exp b c
  map g := K.expMap b g
  map_resp h := K.curry_resp (C.rcong _ h)
  map_id c := K.expMap_id b c
  map_comp g g' := K.expMap_comp b g g'

/-- the defining adjunction of a CCC: `(- × b) ⊣ (b ⇒ -)` -/
def adj (b : C.Ob) : Adj (K.prodF b) (K.expF b) where
  phi h := K.curry h
  psi g := C.comp (K.times b g) (K.ev b _)
  phi_resp h := K.curry_resp h
  psi_resp h := C.lcong (K.times_resp b h) _
  phi_psi g := K.eta g
  psi_phi h := K.beta h
  nat_l _ h := C.hsymm (K.curry_uniq _ _
    (C.htrans (C.lcong (K.times_comp b _ _) _)
    (C.htrans (C.assoc _ _ _) (C.rcong _ (K.beta h)))))
  nat_r h g := C.hsymm (K.curry_uniq _ _
    (C.htrans (C.lcong (K.times_comp b _ _) _)
    (C.htrans (C.assoc _ _ _)
    (C.htrans (C.rcong _ (K.beta _))
    (C.htrans (C.hsymm (C.assoc _ _ _)) (C.lcong (K.beta h) g))))))

/-- the state monad `b ⇒ (- × b)` of any CCC -/
def stateMonad (b : C.Ob) : KMonad C := (K.adj b).monad

end CCC

/-! ## Setoids form a CCC -/

def unitS : Setd.{u} := ⟨PUnit, fun _ _ => True, fun _ => trivial, fun _ => trivial, fun _ _ => trivial⟩

def prodS (X Y : Setd.{u}) : Setd.{u} where
  car := X.car × Y.car
  eqv p q := X.eqv p.1 q.1 ∧ Y.eqv p.2 q.2
  refl p := ⟨X.refl p.1, Y.refl p.2⟩
  symm h := ⟨X.symm h.1, Y.symm h.2⟩
  trans h k := ⟨X.trans h.1 k.1, Y.trans h.2 k.2⟩

def expS (X Y : Setd.{u}) : Setd.{u} where
  car := SHom X Y
  eqv f g := ∀ x, Y.eqv (f.fn x) (g.fn x)
  refl f x := Y.refl (f.fn x)
  symm h x := Y.symm (h x)
  trans h k x := Y.trans (h x) (k x)

def setdTerminal : Terminal SetdCat.{u} where
  one := unitS
  bang _ := ⟨fun _ => PUnit.unit, fun _ => trivial⟩
  uniq _ _ := trivial

def setdProduct (X Y : Setd.{u}) : Product SetdCat.{u} X Y where
  P := prodS X Y
  p1 := ⟨Prod.fst, fun h => h.1⟩
  p2 := ⟨Prod.snd, fun h => h.2⟩
  pair f g := ⟨fun z => (f.fn z, g.fn z), fun h => ⟨f.resp h, g.resp h⟩⟩
  beta1 f _ z := X.refl (f.fn z)
  beta2 _ g z := Y.refl (g.fn z)
  eta h z := ⟨X.refl (h.fn z).1, Y.refl (h.fn z).2⟩
  pair_resp hf hg z := ⟨hf z, hg z⟩

def setdCCC : CCC SetdCat.{u} where
  term := setdTerminal
  prod := setdProduct
  exp := expS
  ev _ Z := ⟨fun p => p.1.fn p.2, fun {p q} h => Z.trans (p.1.resp h.2) (h.1 q.2)⟩
  curry {X Y _} h :=
    ⟨fun x => ⟨fun y => h.fn (x, y), fun e => h.resp ⟨X.refl x, e⟩⟩,
     fun e y => h.resp ⟨e, Y.refl y⟩⟩
  curry_resp hh x y := hh (x, y)
  beta {_ _ c} h p := c.refl (h.fn p)
  eta {_ _ c} g x y := c.refl ((g.fn x).fn y)

/-- the state monad on setoids -/
def setdState (S : Setd.{u}) : KMonad SetdCat.{u} := setdCCC.stateMonad S

/-! ## Types with pointwise equality: CCC ⇔ funext -/

def FunExt : Prop := ∀ {B C : Type u} (f g : B → C), (∀ x, f x = g x) → f = g

/-- the standard currying on `FunCat` respects the hom equivalence -/
def FunCurryResp : Prop :=
  ∀ {A B C : Type u} (h h' : A × B → C), (∀ p, h p = h' p) →
    ∀ a, (fun b => h (a, b)) = (fun b => h' (a, b))

theorem funCurryResp_iff_funext : FunCurryResp.{u} ↔ FunExt.{u} :=
  ⟨fun H _ _ f g e => H (fun p => f p.2) (fun p => g p.2) (fun p => e p.2) PUnit.unit,
   fun F _ _ _ _ _ e a => F _ _ (fun b => e (a, b))⟩

/-! ## LCCC in family form: reindexing has a right adjoint Π -/

/-- families of setoids over a type, with pointwise maps -/
def Fam (I : Type u) : ECat.{u+1, u} where
  Ob := I → Setd.{u}
  Hom X Y := (i : I) → SHom (X i) (Y i)
  heq {_ Y} f g := ∀ i x, (Y i).eqv ((f i).fn x) ((g i).fn x)
  hrefl {_ Y} f i x := (Y i).refl ((f i).fn x)
  hsymm {_ Y _ _} h i x := (Y i).symm (h i x)
  htrans {_ Y _ _ _} h k i x := (Y i).trans (h i x) (k i x)
  id _ _ := ⟨fun x => x, fun h => h⟩
  comp f g i := ⟨fun x => (g i).fn ((f i).fn x), fun h => (g i).resp ((f i).resp h)⟩
  comp_resp {_ _ Z} _ _ g _ hf hg i x := (Z i).trans ((g i).resp (hf i x)) (hg i _)
  id_comp {_ Y} f i x := (Y i).refl ((f i).fn x)
  comp_id {_ Y} f i x := (Y i).refl ((f i).fn x)
  assoc {_ _ _ W} _ _ h i _ := (W i).refl ((h i).fn _)

section Reindex
variable {I J : Type u} (f : I → J)

/-- reindexing `f*` -/
def pullF : EFun (Fam J) (Fam I) where
  obj Y i := Y (f i)
  map g i := g (f i)
  map_resp h i x := h (f i) x
  map_id Y i x := (Y (f i)).refl x
  map_comp {_ _ Z} _ g i _ := (Z (f i)).refl ((g (f i)).fn _)

/-- the dependent product `Π_f X` at `j`: sections over the fibre of `j` -/
def piS (X : I → Setd.{u}) (j : J) : Setd.{u} where
  car := (i : I) → f i = j → (X i).car
  eqv s t := ∀ i e, (X i).eqv (s i e) (t i e)
  refl s i e := (X i).refl (s i e)
  symm h i e := (X i).symm (h i e)
  trans h k i e := (X i).trans (h i e) (k i e)

def piF : EFun (Fam I) (Fam J) where
  obj X j := piS f X j
  map g _ := ⟨fun s i e => (g i).fn (s i e), fun h i e => (g i).resp (h i e)⟩
  map_resp h _ s i e := h i (s i e)
  map_id X _ s i e := (X i).refl (s i e)
  map_comp {_ _ Z} _ g _ _ i _ := (Z i).refl ((g i).fn _)

/-- transport along a fibre equation -/
def tr (Y : J → Setd.{u}) {j j' : J} (e : j = j') (y : (Y j).car) : (Y j').car := by
  cases e
  exact y

theorem tr_resp (Y : J → Setd.{u}) {j j' : J} (e : j = j') {y y' : (Y j).car}
    (h : (Y j).eqv y y') : (Y j').eqv (tr Y e y) (tr Y e y') := by
  cases e
  exact h

/-- `f* ⊣ Π_f` : reindexing has a right adjoint, the dependent product -/
def pullPiAdj : Adj (pullF f) (piF f) where
  phi {Y _} k j := ⟨fun y i e => (k i).fn (tr Y e.symm y),
                    fun h i e => (k i).resp (tr_resp Y e.symm h)⟩
  psi g i := ⟨fun y => (g (f i)).fn y i rfl, fun h => (g (f i)).resp h i rfl⟩
  phi_resp hk _ _ i _ := hk i _
  psi_resp hg i y := hg (f i) y i rfl
  phi_psi {Y X} g j y i e := by
    cases e
    exact (X i).refl _
  psi_phi {_ X} k i y := (X i).refl _
  nat_l {_ _ X} a k j y i e := by
    cases e
    exact (X i).refl _
  nat_r {_ _ X'} k g j y i e := by
    cases e
    exact (X' i).refl _

end Reindex

end Found

#print axioms Found.CCC.times_id
#print axioms Found.CCC.times_comp
#print axioms Found.CCC.curry_uniq
#print axioms Found.CCC.expMap_id
#print axioms Found.CCC.expMap_comp
#print axioms Found.CCC.prodF
#print axioms Found.CCC.expF
#print axioms Found.CCC.adj
#print axioms Found.CCC.stateMonad
#print axioms Found.setdTerminal
#print axioms Found.setdProduct
#print axioms Found.setdCCC
#print axioms Found.setdState
#print axioms Found.funCurryResp_iff_funext
#print axioms Found.Fam
#print axioms Found.pullF
#print axioms Found.piF
#print axioms Found.tr_resp
#print axioms Found.pullPiAdj

#print axioms: 19 theorems, no axioms.

85.4 Subobject classifier and Heyting algebras

\(\Omega =(\mathrm {Prop},\leftrightarrow )\) and \(\mathrm {Sub}(X)\) are Heyting algebras; predicate subsetoids are pullbacks of true along a unique \(\chi \); monos compare to their image (iso given preimage choice); power objects are \(X\Rightarrow \Omega \). \(\mathrm {Sub}(X)\simeq \mathrm {Hom}(X,\Omega )/\!\leftrightarrow ;\quad c\wedge a\le b\iff c\le a\Rightarrow b\).

found/Topos.lean

/-
  T63. found/Topos — the subobject classifier and its Heyting algebra.

  * Heyting algebras (preorder form, equality = two-way ≤, no propext).
  * Ω = (Prop, ↔) is a setoid and a Heyting algebra; ∧, ∨, → are maps of setoids.
  * Sub(X) = respecting predicates on a setoid X: a Heyting algebra.
  * Ω classifies: the subsetoid {x | φ x} is the pullback of `true` along χ_φ
    (universal property, unique factorisation), χ is unique (two predicates
    with isomorphic subsetoids over X are equivalent), every mono m has a
    characteristic map χ_m whose pullback receives m by a map that is mono and
    surjective on classes; with a choice of preimages it is an isomorphism.
  * Power objects P X = X ⇒ Ω from the CCC of setoids.
  So setoids with Ω = (Prop, ↔) are a topos up to the unique-choice step for
  monos; for subobjects given by predicates no choice is needed.

  Lean 4 core only, hand-written proofs, no axioms.

  CIC dependence: Ω = Prop (impredicative Prop, proof irrelevance), subtypes {x // φ x}.
-/
import found.CCC

namespace Found

universe u

/-! ## Heyting algebras -/

structure HA where
  car : Type u
  le : car → car → Prop
  le_refl : ∀ a, le a a
  le_trans : ∀ {a b c}, le a b → le b c → le a c
  top : car
  bot : car
  meet : car → car → car
  join : car → car → car
  imp : car → car → car
  le_top : ∀ a, le a top
  bot_le : ∀ a, le bot a
  meet_l : ∀ a b, le (meet a b) a
  meet_r : ∀ a b, le (meet a b) b
  meet_univ : ∀ {a b c}, le c a → le c b → le c (meet a b)
  join_l : ∀ a b, le a (join a b)
  join_r : ∀ a b, le b (join a b)
  join_univ : ∀ {a b c}, le a c → le b c → le (join a b) c
  imp_adj : ∀ {a b c}, le (meet c a) b ↔ le c (imp a b)

namespace HA
variable (H : HA.{u})

def neg (a : H.car) : H.car := H.imp a H.bot

theorem mp (a b : H.car) : H.le (H.meet (H.imp a b) a) b :=
  H.imp_adj.mpr (H.le_refl _)

theorem meet_neg (a : H.car) : H.le (H.meet a (H.neg a)) H.bot :=
  H.le_trans (H.meet_univ (H.meet_r _ _) (H.meet_l _ _)) (H.mp a H.bot)

theorem le_negneg (a : H.car) : H.le a (H.neg (H.neg a)) :=
  H.imp_adj.mp (H.meet_neg a)

theorem neg_antitone {a b : H.car} (h : H.le a b) : H.le (H.neg b) (H.neg a) :=
  H.imp_adj.mp (H.le_trans (H.meet_univ (H.meet_l _ _) (H.le_trans (H.meet_r _ _) h))
    (H.mp b H.bot))

theorem negnegneg (a : H.car) : H.le (H.neg (H.neg (H.neg a))) (H.neg a) :=
  H.neg_antitone (H.le_negneg a)

/-- modus ponens for ≤ : `a ≤ b ⇒ c` and `a ≤ b` give `a ≤ c` -/
theorem imp_elim {a b c : H.car} (h1 : H.le a (H.imp b c)) (h2 : H.le a b) : H.le a c :=
  H.le_trans (H.meet_univ h1 h2) (H.mp b c)

end HA

/-! ## Ω = (Prop, ↔) -/

def OmegaS : Setd.{0} := ⟨Prop, Iff, Iff.refl, Iff.symm, Iff.trans⟩

def OmegaHA : HA.{0} where
  car := Prop
  le p q := p → q
  le_refl _ h := h
  le_trans h k x := k (h x)
  top := True
  bot := False
  meet := And
  join := Or
  imp p q := p → q
  le_top _ _ := trivial
  bot_le _ h := h.elim
  meet_l _ _ h := h.1
  meet_r _ _ h := h.2
  meet_univ h k x := ⟨h x, k x⟩
  join_l _ _ h := Or.inl h
  join_r _ _ h := Or.inr h
  join_univ h k x := x.elim h k
  imp_adj := ⟨fun h c a => h ⟨c, a⟩, fun h x => h x.1 x.2⟩

def trueS : SHom (unitS.{0}) OmegaS := ⟨fun _ => True, fun _ => Iff.rfl⟩

def andS : SHom (prodS OmegaS OmegaS) OmegaS :=
  ⟨fun p => p.1 ∧ p.2, fun h => ⟨fun x => ⟨h.1.mp x.1, h.2.mp x.2⟩, fun x => ⟨h.1.mpr x.1, h.2.mpr x.2⟩⟩⟩

def orS : SHom (prodS OmegaS OmegaS) OmegaS :=
  ⟨fun p => p.1 ∨ p.2, fun h =>
    ⟨fun x => x.elim (fun a => Or.inl (h.1.mp a)) (fun b => Or.inr (h.2.mp b)),
     fun x => x.elim (fun a => Or.inl (h.1.mpr a)) (fun b => Or.inr (h.2.mpr b))⟩⟩

def impS : SHom (prodS OmegaS OmegaS) OmegaS :=
  ⟨fun p => p.1 → p.2, fun h => ⟨fun f a => h.2.mp (f (h.1.mpr a)), fun f a => h.2.mpr (f (h.1.mp a))⟩⟩

/-! ## Sub(X): respecting predicates -/

def Resp (X : Setd.{0}) (φ : X.car → Prop) : Prop := ∀ {x y}, X.eqv x y → φ x → φ y

structure Pred (X : Setd.{0}) where
  p : X.car → Prop
  resp : Resp X p

def SubHA (X : Setd.{0}) : HA.{0} where
  car := Pred X
  le φ ψ := ∀ x, φ.p x → ψ.p x
  le_refl _ _ h := h
  le_trans h k x a := k x (h x a)
  top := ⟨fun _ => True, fun _ _ => trivial⟩
  bot := ⟨fun _ => False, fun _ h => h⟩
  meet φ ψ := ⟨fun x => φ.p x ∧ ψ.p x, fun e h => ⟨φ.resp e h.1, ψ.resp e h.2⟩⟩
  join φ ψ := ⟨fun x => φ.p x ∨ ψ.p x,
    fun e h => h.elim (fun a => Or.inl (φ.resp e a)) (fun b => Or.inr (ψ.resp e b))⟩
  imp φ ψ := ⟨fun x => φ.p x → ψ.p x,
    fun e f a => ψ.resp e (f (φ.resp (X.symm e) a))⟩
  le_top _ _ _ := trivial
  bot_le _ _ h := h.elim
  meet_l _ _ _ h := h.1
  meet_r _ _ _ h := h.2
  meet_univ h k x a := ⟨h x a, k x a⟩
  join_l _ _ _ h := Or.inl h
  join_r _ _ _ h := Or.inr h
  join_univ h k x a := a.elim (h x) (k x)
  imp_adj := ⟨fun h x c a => h x ⟨c, a⟩, fun h x a => h x a.1 a.2⟩

/-! ## Ω classifies subsetoids -/

section Classify
variable {X : Setd.{0}}

def subS (X : Setd.{0}) (φ : X.car → Prop) : Setd.{0} where
  car := {x // φ x}
  eqv a b := X.eqv a.val b.val
  refl a := X.refl a.val
  symm h := X.symm h
  trans h k := X.trans h k

def incl (φ : X.car → Prop) : SHom (subS X φ) X := ⟨Subtype.val, fun h => h⟩

/-- the characteristic map of a respecting predicate -/
def chi (φ : Pred X) : SHom X OmegaS := ⟨φ.p, fun e => ⟨φ.resp e, φ.resp (X.symm e)⟩⟩

/-- the square commutes: χ ∘ incl = true ∘ ! -/
theorem chi_square (φ : Pred X) :
    SetdCat.heq (SetdCat.comp (incl φ.p) (chi φ))
      (SetdCat.comp (setdTerminal.bang (subS X φ.p)) trueS) :=
  fun a => ⟨fun _ => trivial, fun _ => a.property⟩

/-- the pullback: every map landing in φ factors through the subsetoid -/
def factor (φ : Pred X) {Z : Setd.{0}} (f : SHom Z X) (hf : ∀ z, φ.p (f.fn z)) :
    SHom Z (subS X φ.p) := ⟨fun z => ⟨f.fn z, hf z⟩, fun h => f.resp h⟩

theorem factor_comm (φ : Pred X) {Z : Setd.{0}} (f : SHom Z X) (hf : ∀ z, φ.p (f.fn z)) :
    SetdCat.heq (SetdCat.comp (factor φ f hf) (incl φ.p)) f := fun z => X.refl (f.fn z)

theorem factor_uniq (φ : Pred X) {Z : Setd.{0}} (f : SHom Z X) (hf : ∀ z, φ.p (f.fn z))
    (g : SHom Z (subS X φ.p)) (hg : SetdCat.heq (SetdCat.comp g (incl φ.p)) f) :
    SetdCat.heq g (factor φ f hf) := hg

/-- a map whose χ-image is true lands in φ (the pullback condition in Ω) -/
theorem lands_of_chi (φ : Pred X) {Z : Setd.{0}} (f : SHom Z X)
    (h : SetdCat.heq (SetdCat.comp f (chi φ)) (SetdCat.comp (setdTerminal.bang Z) trueS)) :
    ∀ z, φ.p (f.fn z) := fun z => (h z).mpr trivial

/-- uniqueness of χ: predicates with isomorphic subsetoids over X agree -/
theorem chi_unique (φ ψ : Pred X)
    (u : SHom (subS X φ.p) (subS X ψ.p))
    (hu : SetdCat.heq (SetdCat.comp u (incl ψ.p)) (incl φ.p))
    (w : SHom (subS X ψ.p) (subS X φ.p))
    (hw : SetdCat.heq (SetdCat.comp w (incl φ.p)) (incl ψ.p)) :
    ∀ x, φ.p x ↔ ψ.p x :=
  fun x => ⟨fun a => ψ.resp (hu ⟨x, a⟩) (u.fn ⟨x, a⟩).property,
            fun b => φ.resp (hw ⟨x, b⟩) (w.fn ⟨x, b⟩).property⟩

/-! ### monos -/

def Mono {A : Setd.{0}} (m : SHom A X) : Prop := ∀ a a', X.eqv (m.fn a) (m.fn a') → A.eqv a a'

/-- the image predicate of any map -/
def imageP {A : Setd.{0}} (m : SHom A X) : Pred X :=
  ⟨fun x => ∃ a, X.eqv (m.fn a) x, fun e ⟨a, h⟩ => ⟨a, X.trans h e⟩⟩

def compare {A : Setd.{0}} (m : SHom A X) : SHom A (subS X (imageP m).p) :=
  factor (imageP m) m (fun a => ⟨a, X.refl _⟩)

theorem compare_mono {A : Setd.{0}} (m : SHom A X) (hm : Mono m) :
    ∀ a a', (subS X (imageP m).p).eqv ((compare m).fn a) ((compare m).fn a') → A.eqv a a' :=
  fun a a' h => hm a a' h

theorem compare_surj {A : Setd.{0}} (m : SHom A X) :
    ∀ y : (subS X (imageP m).p).car, ∃ a, (subS X (imageP m).p).eqv ((compare m).fn a) y :=
  fun ⟨_, a, h⟩ => ⟨a, h⟩

/-- with a choice of preimages, the comparison of a mono is an isomorphism -/
theorem compare_iso {A : Setd.{0}} (m : SHom A X) (hm : Mono m)
    (s : (x : X.car) → (∃ a, X.eqv (m.fn a) x) → A.car)
    (hs : ∀ x h, X.eqv (m.fn (s x h)) x) :
    ∃ inv : SHom (subS X (imageP m).p) A,
      SetdCat.heq (SetdCat.comp (compare m) inv) (SetdCat.id A) ∧
      SetdCat.heq (SetdCat.comp inv (compare m)) (SetdCat.id _) :=
  ⟨⟨fun y => s y.val y.property,
    fun {y y'} e => hm _ _ (X.trans (hs y.val y.property) (X.trans e (X.symm (hs y'.val y'.property))))⟩,
   fun a => hm _ _ (hs (m.fn a) _),
   fun y => hs y.val y.property⟩

end Classify

/-! ## Power objects from the CCC: P X = X ⇒ Ω -/

def powerS (X : Setd.{0}) : Setd.{0} := expS X OmegaS

def memS (X : Setd.{0}) : SHom (prodS (powerS X) X) OmegaS := setdCCC.ev X OmegaS

/-- every relation `R ⊆ Z × X` (as a map to Ω) is named by a unique `Z → P X` -/
theorem power_beta {Z X : Setd.{0}} (R : SHom (prodS Z X) OmegaS) :
    SetdCat.heq (SetdCat.comp (setdCCC.times X (setdCCC.curry R)) (memS X)) R :=
  setdCCC.beta R

theorem power_uniq {Z X : Setd.{0}} (R : SHom (prodS Z X) OmegaS) (k : SHom Z (powerS X))
    (h : SetdCat.heq (SetdCat.comp (setdCCC.times X k) (memS X)) R) :
    SetdCat.heq k (setdCCC.curry R) := setdCCC.curry_uniq k R h

end Found

#print axioms Found.HA.mp
#print axioms Found.HA.meet_neg
#print axioms Found.HA.le_negneg
#print axioms Found.HA.neg_antitone
#print axioms Found.HA.negnegneg
#print axioms Found.HA.imp_elim
#print axioms Found.OmegaHA
#print axioms Found.andS
#print axioms Found.orS
#print axioms Found.impS
#print axioms Found.SubHA
#print axioms Found.chi_square
#print axioms Found.factor_comm
#print axioms Found.factor_uniq
#print axioms Found.lands_of_chi
#print axioms Found.chi_unique
#print axioms Found.compare_mono
#print axioms Found.compare_surj
#print axioms Found.compare_iso
#print axioms Found.power_beta
#print axioms Found.power_uniq

#print axioms: 21 theorems, no axioms.

85.5 Internal language of the setoid topos

Formulas denote subobjects of the environment setoid; intuitionistic natural deduction with \(\forall ,\exists \) and Leibniz equality is sound, hence consistent. \(\Gamma \vdash \varphi \ \Rightarrow \ \forall \rho ,\ \llbracket \Gamma \rrbracket \rho \to \llbracket \varphi \rrbracket \rho \).

found/Internal.lean

/-
  T64. found/Internal — the internal language of the setoid topos.

  * Formulas of first-order logic over one sort (de Bruijn variables),
    atoms interpreted by respecting predicates `Pred X`, equality by the
    setoid relation.
  * Semantics in Ω = (Prop, ↔), environments `Nat → X`.
  * Every formula denotes a subobject of the environment setoid (it respects
    pointwise equivalence): the Mitchell–Bénabou reading "formula = map to Ω".
  * Intuitionistic natural deduction with ∀, ∃ and Leibniz equality is sound.

  Lean 4 core only, hand-written proofs, no axioms.

  CIC dependence: truth values = impredicative Prop.
-/
import found.Topos

namespace Found

namespace IL

inductive Form where
  | top : Form
  | bot : Form
  | atom : Nat → Nat → Form      -- predicate symbol, variable
  | eq : Nat → Nat → Form
  | and : Form → Form → Form
  | or : Form → Form → Form
  | imp : Form → Form → Form
  | all : Form → Form
  | ex : Form → Form

def lift (f : Nat → Nat) : Nat → Nat
  | 0 => 0
  | n + 1 => f n + 1

def rename (f : Nat → Nat) : Form → Form
  | .top => .top
  | .bot => .bot
  | .atom r i => .atom r (f i)
  | .eq i j => .eq (f i) (f j)
  | .and a b => .and (rename f a) (rename f b)
  | .or a b => .or (rename f a) (rename f b)
  | .imp a b => .imp (rename f a) (rename f b)
  | .all a => .all (rename (lift f) a)
  | .ex a => .ex (rename (lift f) a)

def shift : Form → Form := rename Nat.succ

def instF (i : Nat) : Nat → Nat
  | 0 => i
  | n + 1 => n

/-- `φ[i/0]` -/
def inst (i : Nat) : Form → Form := rename (instF i)

section Sem
variable {X : Setd.{0}} (R : Nat → Pred X)

def cons (x : X.car) (ρ : Nat → X.car) : Nat → X.car
  | 0 => x
  | n + 1 => ρ n

def sem : Form → (Nat → X.car) → Prop
  | .top, _ => True
  | .bot, _ => False
  | .atom r i, ρ => (R r).p (ρ i)
  | .eq i j, ρ => X.eqv (ρ i) (ρ j)
  | .and a b, ρ => sem a ρ ∧ sem b ρ
  | .or a b, ρ => sem a ρ ∨ sem b ρ
  | .imp a b, ρ => sem a ρ → sem b ρ
  | .all a, ρ => ∀ x, sem a (cons x ρ)
  | .ex a, ρ => ∃ x, sem a (cons x ρ)

def EnvEqv (ρ σ : Nat → X.car) : Prop := ∀ n, X.eqv (ρ n) (σ n)

theorem envEqv_symm {ρ σ : Nat → X.car} (h : EnvEqv ρ σ) : EnvEqv σ ρ := fun n => X.symm (h n)

theorem envEqv_cons (x : X.car) {ρ σ : Nat → X.car} (h : EnvEqv ρ σ) :
    EnvEqv (cons x ρ) (cons x σ)
  | 0 => X.refl x
  | n + 1 => h n

/-- every formula respects equivalence of environments: it is a subobject -/
theorem sem_resp : (φ : Form) → ∀ {ρ σ : Nat → X.car}, EnvEqv ρ σ → sem R φ ρ → sem R φ σ
  | .top, _, _, _, h => h
  | .bot, _, _, _, h => h
  | .atom r i, _, _, e, h => (R r).resp (e i) h
  | .eq i j, _, _, e, h => X.trans (X.symm (e i)) (X.trans h (e j))
  | .and a b, _, _, e, h => ⟨sem_resp a e h.1, sem_resp b e h.2⟩
  | .or a b, _, _, e, h => h.elim (fun x => Or.inl (sem_resp a e x)) (fun y => Or.inr (sem_resp b e y))
  | .imp a b, _, _, e, h => fun x => sem_resp b e (h (sem_resp a (envEqv_symm e) x))
  | .all a, _, _, e, h => fun x => sem_resp a (envEqv_cons x e) (h x)
  | .ex a, _, _, e, h => match h with | ⟨x, hx⟩ => ⟨x, sem_resp a (envEqv_cons x e) hx⟩

theorem sem_iff (φ : Form) {ρ σ : Nat → X.car} (e : EnvEqv ρ σ) : sem R φ ρ ↔ sem R φ σ :=
  ⟨sem_resp R φ e, sem_resp R φ (envEqv_symm e)⟩

/-- the environments as a setoid, and a formula as a subobject of it -/
def envS (X : Setd.{0}) : Setd.{0} where
  car := Nat → X.car
  eqv := @EnvEqv X
  refl ρ n := X.refl (ρ n)
  symm h := envEqv_symm h
  trans h k n := X.trans (h n) (k n)

def toPred (φ : Form) : Pred (envS X) := ⟨sem R φ, fun e h => sem_resp R φ e h⟩

theorem env_lift (f : Nat → Nat) (x : X.car) (ρ : Nat → X.car) :
    EnvEqv (fun n => cons x ρ (lift f n)) (cons x (fun n => ρ (f n)))
  | 0 => X.refl x
  | _ + 1 => X.refl _

theorem rename_sem : (φ : Form) → ∀ (f : Nat → Nat) (ρ : Nat → X.car),
    sem R (rename f φ) ρ ↔ sem R φ (fun n => ρ (f n))
  | .top, _, _ => Iff.rfl
  | .bot, _, _ => Iff.rfl
  | .atom _ _, _, _ => Iff.rfl
  | .eq _ _, _, _ => Iff.rfl
  | .and a b, f, ρ =>
    ⟨fun h => ⟨(rename_sem a f ρ).mp h.1, (rename_sem b f ρ).mp h.2⟩,
     fun h => ⟨(rename_sem a f ρ).mpr h.1, (rename_sem b f ρ).mpr h.2⟩⟩
  | .or a b, f, ρ =>
    ⟨fun h => h.elim (fun x => Or.inl ((rename_sem a f ρ).mp x)) (fun y => Or.inr ((rename_sem b f ρ).mp y)),
     fun h => h.elim (fun x => Or.inl ((rename_sem a f ρ).mpr x)) (fun y => Or.inr ((rename_sem b f ρ).mpr y))⟩
  | .imp a b, f, ρ =>
    ⟨fun h x => (rename_sem b f ρ).mp (h ((rename_sem a f ρ).mpr x)),
     fun h x => (rename_sem b f ρ).mpr (h ((rename_sem a f ρ).mp x))⟩
  | .all a, f, ρ =>
    ⟨fun h x => (sem_iff R a (env_lift f x ρ)).mp ((rename_sem a (lift f) (cons x ρ)).mp (h x)),
     fun h x => (rename_sem a (lift f) (cons x ρ)).mpr ((sem_iff R a (env_lift f x ρ)).mpr (h x))⟩
  | .ex a, f, ρ =>
    ⟨fun ⟨x, hx⟩ => ⟨x, (sem_iff R a (env_lift f x ρ)).mp ((rename_sem a (lift f) (cons x ρ)).mp hx)⟩,
     fun ⟨x, hx⟩ => ⟨x, (rename_sem a (lift f) (cons x ρ)).mpr ((sem_iff R a (env_lift f x ρ)).mpr hx)⟩⟩

theorem shift_sem (φ : Form) (x : X.car) (ρ : Nat → X.car) :
    sem R (shift φ) (cons x ρ) ↔ sem R φ ρ := rename_sem R φ Nat.succ (cons x ρ)

theorem env_inst (i : Nat) (ρ : Nat → X.car) :
    EnvEqv (fun n => ρ (instF i n)) (cons (ρ i) ρ)
  | 0 => X.refl _
  | _ + 1 => X.refl _

theorem inst_sem (φ : Form) (i : Nat) (ρ : Nat → X.car) :
    sem R (inst i φ) ρ ↔ sem R φ (cons (ρ i) ρ) :=
  (rename_sem R φ (instF i) ρ).trans (sem_iff R φ (env_inst i ρ))

end Sem

/-! ## Natural deduction -/

inductive In : Form → List Form → Prop where
  | here (a : Form) (l : List Form) : In a (a :: l)
  | there (a b : Form) (l : List Form) : In a l → In a (b :: l)

inductive Deriv : List Form → Form → Prop where
  | hyp {Γ a} : In a Γ → Deriv Γ a
  | topI {Γ} : Deriv Γ .top
  | botE {Γ a} : Deriv Γ .bot → Deriv Γ a
  | andI {Γ a b} : Deriv Γ a → Deriv Γ b → Deriv Γ (.and a b)
  | andE1 {Γ a b} : Deriv Γ (.and a b) → Deriv Γ a
  | andE2 {Γ a b} : Deriv Γ (.and a b) → Deriv Γ b
  | orI1 {Γ a b} : Deriv Γ a → Deriv Γ (.or a b)
  | orI2 {Γ a b} : Deriv Γ b → Deriv Γ (.or a b)
  | orE {Γ a b c} : Deriv Γ (.or a b) → Deriv (a :: Γ) c → Deriv (b :: Γ) c → Deriv Γ c
  | impI {Γ a b} : Deriv (a :: Γ) b → Deriv Γ (.imp a b)
  | impE {Γ a b} : Deriv Γ (.imp a b) → Deriv Γ a → Deriv Γ b
  | allI {Γ a} : Deriv (Γ.map shift) a → Deriv Γ (.all a)
  | allE {Γ a} (i : Nat) : Deriv Γ (.all a) → Deriv Γ (inst i a)
  | exI {Γ a} (i : Nat) : Deriv Γ (inst i a) → Deriv Γ (.ex a)
  | exE {Γ a c} : Deriv Γ (.ex a) → Deriv (a :: Γ.map shift) (shift c) → Deriv Γ c
  | eqRefl {Γ} (i : Nat) : Deriv Γ (.eq i i)
  | eqSubst {Γ a} (i j : Nat) : Deriv Γ (.eq i j) → Deriv Γ (inst i a) → Deriv Γ (inst j a)

section Sound
variable {X : Setd.{0}} (R : Nat → Pred X)

def AllTrue (ρ : Nat → X.car) : List Form → Prop
  | [] => True
  | a :: l => sem R a ρ ∧ AllTrue ρ l

theorem allTrue_in {ρ : Nat → X.car} {a : Form} {Γ : List Form} (m : In a Γ) :
    AllTrue R ρ Γ → sem R a ρ := by
  induction m with
  | here _ => exact fun h => h.1
  | there _ _ _ ih => exact fun h => ih h.2

theorem allTrue_shift (x : X.car) (ρ : Nat → X.car) :
    (Γ : List Form) → AllTrue R ρ Γ → AllTrue R (cons x ρ) (Γ.map shift)
  | [], _ => trivial
  | a :: l, h => ⟨(shift_sem R a x ρ).mpr h.1, allTrue_shift x ρ l h.2⟩

/-- soundness of intuitionistic natural deduction in the setoid topos -/
theorem soundness {Γ : List Form} {φ : Form} (d : Deriv Γ φ) :
    ∀ ρ : Nat → X.car, AllTrue R ρ Γ → sem R φ ρ := by
  induction d with
  | hyp m => exact fun ρ h => allTrue_in R m h
  | topI => exact fun _ _ => trivial
  | botE _ ih => exact fun ρ h => (ih ρ h).elim
  | andI _ _ iha ihb => exact fun ρ h => ⟨iha ρ h, ihb ρ h⟩
  | andE1 _ ih => exact fun ρ h => (ih ρ h).1
  | andE2 _ ih => exact fun ρ h => (ih ρ h).2
  | orI1 _ ih => exact fun ρ h => Or.inl (ih ρ h)
  | orI2 _ ih => exact fun ρ h => Or.inr (ih ρ h)
  | orE _ _ _ ih iha ihb =>
    exact fun ρ h => (ih ρ h).elim (fun x => iha ρ ⟨x, h⟩) (fun y => ihb ρ ⟨y, h⟩)
  | impI _ ih => exact fun ρ h x => ih ρ ⟨x, h⟩
  | impE _ _ ihf iha => exact fun ρ h => ihf ρ h (iha ρ h)
  | allI _ ih => exact fun ρ h x => ih (cons x ρ) (allTrue_shift R x ρ _ h)
  | allE i _ ih => exact fun ρ h => (inst_sem R _ i ρ).mpr (ih ρ h (ρ i))
  | exI i _ ih => exact fun ρ h => ⟨ρ i, (inst_sem R _ i ρ).mp (ih ρ h)⟩
  | exE _ _ ih ihc =>
    exact fun ρ h => match ih ρ h with
      | ⟨x, hx⟩ => (shift_sem R _ x ρ).mp (ihc (cons x ρ) ⟨hx, allTrue_shift R x ρ _ h⟩)
  | eqRefl i => exact fun ρ _ => X.refl (ρ i)
  | @eqSubst _ a i j _ _ ihe iha =>
    exact fun ρ h =>
      have e : EnvEqv (cons (ρ i) ρ) (cons (ρ j) ρ) := fun n =>
        match n with
        | 0 => ihe ρ h
        | _ + 1 => X.refl _
      (inst_sem R a j ρ).mpr (sem_resp R a e ((inst_sem R a i ρ).mp (iha ρ h)))

/-- consistency: ⊥ is not derivable from no hypotheses (any inhabited sort) -/
theorem consistent (R : Nat → Pred X) (x : X.car) : ¬ Deriv [] .bot :=
  fun d => soundness (X := X) R d (fun _ => x) trivial

end Sound

/-- an example derivation: ∀x (P x) → ∃x (P x), on an inhabited sort -/
theorem ex_all_ex : Deriv [] (.imp (.all (.atom 0 0)) (.ex (.atom 0 0))) :=
  .impI (.exI 0 (.allE 0 (.hyp (.here _ _))))

end IL

end Found

#print axioms Found.IL.sem_resp
#print axioms Found.IL.sem_iff
#print axioms Found.IL.toPred
#print axioms Found.IL.rename_sem
#print axioms Found.IL.shift_sem
#print axioms Found.IL.inst_sem
#print axioms Found.IL.allTrue_in
#print axioms Found.IL.allTrue_shift
#print axioms Found.IL.soundness
#print axioms Found.IL.consistent
#print axioms Found.IL.ex_all_ex

#print axioms: 11 theorems, no axioms.

85.6 Minimal and intuitionistic logic

One deduction system with optional ex falso is sound in every Heyting algebra; intuitionistic = minimal plus atomic ex falso; minimal \(\nvdash \bot \to p\), intuitionistic \(\nvdash p\vee \neg p\), \(\nvdash \neg \neg p\to p\). \(\Gamma \vdash _{\mathrm {int}}\varphi \iff \Gamma \cup \{\bot \to p\}\vdash _{\mathrm {min}}\varphi \).

found/Minimal.lean

/-
  T65. found/Minimal — minimal and intuitionistic propositional logic.

  * One natural deduction system `PD I`, with ex falso exactly when `I = true`:
    `PD false` = minimal logic, `PD true` = intuitionistic logic.
  * Condition in the frame: both are sound in every Heyting algebra (T63);
    minimal logic interprets ⊥ by an arbitrary element, intuitionistic logic
    by the least element.
  * Translation: Γ ⊢_int φ  ⟺  Γ ∪ {⊥ → p | p atom} ⊢_min φ.
  * Separations: minimal ⊬ ⊥ → p (⊥ read as True in Ω);
    intuitionistic ⊬ p ∨ ¬p and ⊬ ¬¬p → p (three-element Heyting algebra).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Topos


universe u

namespace Found

namespace Prp

inductive Form where
  | var : Nat → Form
  | bot : Form
  | and : Form → Form → Form
  | or : Form → Form → Form
  | imp : Form → Form → Form

def neg (a : Form) : Form := .imp a .bot

def ext (Γ : Form → Prop) (a : Form) : Form → Prop := fun x => x = a ∨ Γ x

inductive PD (I : Bool) : (Form → Prop) → Form → Prop where
  | hyp {Γ a} : Γ a → PD I Γ a
  | botE {Γ a} : I = true → PD I Γ .bot → PD I Γ a
  | andI {Γ a b} : PD I Γ a → PD I Γ b → PD I Γ (.and a b)
  | andE1 {Γ a b} : PD I Γ (.and a b) → PD I Γ a
  | andE2 {Γ a b} : PD I Γ (.and a b) → PD I Γ b
  | orI1 {Γ a b} : PD I Γ a → PD I Γ (.or a b)
  | orI2 {Γ a b} : PD I Γ b → PD I Γ (.or a b)
  | orE {Γ a b c} : PD I Γ (.or a b) → PD I (ext Γ a) c → PD I (ext Γ b) c → PD I Γ c
  | impI {Γ a b} : PD I (ext Γ a) b → PD I Γ (.imp a b)
  | impE {Γ a b} : PD I Γ (.imp a b) → PD I Γ a → PD I Γ b

/-! ## Structural facts -/

theorem ext_mono {Γ Δ : Form → Prop} (h : ∀ x, Γ x → Δ x) (a : Form) :
    ∀ x, ext Γ a x → ext Δ a x :=
  fun x e => e.elim Or.inl (fun g => Or.inr (h x g))

theorem mono {I : Bool} {Γ : Form → Prop} {φ : Form} (d : PD I Γ φ) :
    ∀ {Δ : Form → Prop}, (∀ x, Γ x → Δ x) → PD I Δ φ := by
  induction d with
  | hyp g => exact fun h => .hyp (h _ g)
  | botE e _ ih => exact fun h => .botE e (ih h)
  | andI _ _ iha ihb => exact fun h => .andI (iha h) (ihb h)
  | andE1 _ ih => exact fun h => .andE1 (ih h)
  | andE2 _ ih => exact fun h => .andE2 (ih h)
  | orI1 _ ih => exact fun h => .orI1 (ih h)
  | orI2 _ ih => exact fun h => .orI2 (ih h)
  | orE _ _ _ ih iha ihb => exact fun h => .orE (ih h) (iha (ext_mono h _)) (ihb (ext_mono h _))
  | impI _ ih => exact fun h => .impI (ih (ext_mono h _))
  | impE _ _ ihf iha => exact fun h => .impE (ihf h) (iha h)

/-- cut: derivable hypotheses can be discharged -/
theorem cut {I : Bool} {Δ : Form → Prop} {φ : Form} (d : PD I Δ φ) :
    ∀ {Γ : Form → Prop}, (∀ x, Δ x → PD I Γ x) → PD I Γ φ := by
  induction d with
  | hyp g => exact fun h => h _ g
  | botE e _ ih => exact fun h => .botE e (ih h)
  | andI _ _ iha ihb => exact fun h => .andI (iha h) (ihb h)
  | andE1 _ ih => exact fun h => .andE1 (ih h)
  | andE2 _ ih => exact fun h => .andE2 (ih h)
  | orI1 _ ih => exact fun h => .orI1 (ih h)
  | orI2 _ ih => exact fun h => .orI2 (ih h)
  | @orE _ a b _ _ _ _ ih iha ihb =>
    exact fun {Γ} h => .orE (ih h)
      (iha (Γ := ext Γ a) (fun x e => e.elim (fun q => q ▸ .hyp (Or.inl rfl))
        (fun g => mono (h x g) (fun _ k => Or.inr k))))
      (ihb (Γ := ext Γ b) (fun x e => e.elim (fun q => q ▸ .hyp (Or.inl rfl))
        (fun g => mono (h x g) (fun _ k => Or.inr k))))
  | @impI _ a _ _ ih =>
    exact fun {Γ} h => .impI (ih (Γ := ext Γ a) (fun x e => e.elim (fun q => q ▸ .hyp (Or.inl rfl))
        (fun g => mono (h x g) (fun _ k => Or.inr k))))
  | impE _ _ ihf iha => exact fun h => .impE (ihf h) (iha h)

/-- minimal derivations are intuitionistic derivations -/
theorem min_to_int {Γ : Form → Prop} {φ : Form} (d : PD false Γ φ) : PD true Γ φ := by
  induction d with
  | hyp g => exact .hyp g
  | botE e _ _ => exact Bool.noConfusion e
  | andI _ _ iha ihb => exact .andI iha ihb
  | andE1 _ ih => exact .andE1 ih
  | andE2 _ ih => exact .andE2 ih
  | orI1 _ ih => exact .orI1 ih
  | orI2 _ ih => exact .orI2 ih
  | orE _ _ _ ih iha ihb => exact .orE ih iha ihb
  | impI _ ih => exact .impI ih
  | impE _ _ ihf iha => exact .impE ihf iha

/-! ## Translation: intuitionistic = minimal + atomic ex falso -/

def EFQ (Γ : Form → Prop) : Form → Prop := fun x => Γ x ∨ ∃ n, x = .imp .bot (.var n)

def HasEFQ (Δ : Form → Prop) : Prop := ∀ n, Δ (.imp .bot (.var n))

theorem hasEFQ_ext {Δ : Form → Prop} (h : HasEFQ Δ) (a : Form) : HasEFQ (ext Δ a) :=
  fun n => Or.inr (h n)

theorem here {Δ : Form → Prop} {a : Form} : PD false (ext Δ a) a := .hyp (Or.inl rfl)

theorem efq_all : (ψ : Form) → ∀ {Δ : Form → Prop}, HasEFQ Δ → PD false Δ (.imp .bot ψ)
  | .var n, _, h => .hyp (h n)
  | .bot, _, _ => .impI here
  | .and a b, _, h =>
    .impI (.andI (.impE (efq_all a (hasEFQ_ext h _)) here) (.impE (efq_all b (hasEFQ_ext h _)) here))
  | .or a _, _, h => .impI (.orI1 (.impE (efq_all a (hasEFQ_ext h _)) here))
  | .imp _ b, _, h =>
    .impI (.impI (.impE (efq_all b (hasEFQ_ext (hasEFQ_ext h _) _)) (.hyp (Or.inr (Or.inl rfl)))))

theorem int_to_min {Γ : Form → Prop} {φ : Form} (d : PD true Γ φ) :
    ∀ {Δ : Form → Prop}, (∀ x, Γ x → Δ x) → HasEFQ Δ → PD false Δ φ := by
  induction d with
  | hyp g => exact fun h _ => .hyp (h _ g)
  | @botE _ a _ _ ih => exact fun h e => .impE (efq_all a e) (ih h e)
  | andI _ _ iha ihb => exact fun h e => .andI (iha h e) (ihb h e)
  | andE1 _ ih => exact fun h e => .andE1 (ih h e)
  | andE2 _ ih => exact fun h e => .andE2 (ih h e)
  | orI1 _ ih => exact fun h e => .orI1 (ih h e)
  | orI2 _ ih => exact fun h e => .orI2 (ih h e)
  | orE _ _ _ ih iha ihb =>
    exact fun h e => .orE (ih h e) (iha (ext_mono h _) (hasEFQ_ext e _)) (ihb (ext_mono h _) (hasEFQ_ext e _))
  | impI _ ih => exact fun h e => .impI (ih (ext_mono h _) (hasEFQ_ext e _))
  | impE _ _ ihf iha => exact fun h e => .impE (ihf h e) (iha h e)

/-- Γ ⊢_int φ ⟺ Γ ∪ EFQ ⊢_min φ -/
theorem int_iff_min_efq (Γ : Form → Prop) (φ : Form) :
    PD true Γ φ ↔ PD false (EFQ Γ) φ :=
  ⟨fun d => int_to_min d (fun _ g => Or.inl g) (fun n => Or.inr ⟨n, rfl⟩),
   fun d => cut (min_to_int d) (fun _ e => e.elim (fun g => .hyp g)
     (fun ⟨_, q⟩ => q ▸ .impI (.botE rfl here_i)))⟩
where
  here_i {Δ : Form → Prop} {a : Form} : PD true (ext Δ a) a := .hyp (Or.inl rfl)

/-! ## Heyting semantics -/

section Sem
variable (H : HA.{u})

theorem distrib (c a b : H.car) :
    H.le (H.meet c (H.join a b)) (H.join (H.meet c a) (H.meet c b)) := by
  have ha : H.le a (H.imp c (H.join (H.meet c a) (H.meet c b))) :=
    H.imp_adj.mp (H.le_trans (H.meet_univ (H.meet_r _ _) (H.meet_l _ _)) (H.join_l _ _))
  have hb : H.le b (H.imp c (H.join (H.meet c a) (H.meet c b))) :=
    H.imp_adj.mp (H.le_trans (H.meet_univ (H.meet_r _ _) (H.meet_l _ _)) (H.join_r _ _))
  exact H.le_trans (H.meet_univ (H.meet_r _ _) (H.meet_l _ _)) (H.imp_adj.mpr (H.join_univ ha hb))

def interp (v : Nat → H.car) (f : H.car) : Form → H.car
  | .var n => v n
  | .bot => f
  | .and a b => H.meet (interp v f a) (interp v f b)
  | .or a b => H.join (interp v f a) (interp v f b)
  | .imp a b => H.imp (interp v f a) (interp v f b)

/-- soundness in any Heyting algebra; ⊥ is read as `f`, which must be least
  when ex falso is allowed -/
theorem soundness {I : Bool} {Γ : Form → Prop} {φ : Form} (d : PD I Γ φ)
    (v : Nat → H.car) (f : H.car) (hf : I = true → ∀ x, H.le f x) :
    ∀ c, (∀ ψ, Γ ψ → H.le c (interp H v f ψ)) → H.le c (interp H v f φ) := by
  induction d with
  | hyp g => exact fun c h => h _ g
  | botE e _ ih => exact fun c h => H.le_trans (ih c h) (hf e _)
  | andI _ _ iha ihb => exact fun c h => H.meet_univ (iha c h) (ihb c h)
  | andE1 _ ih => exact fun c h => H.le_trans (ih c h) (H.meet_l _ _)
  | andE2 _ ih => exact fun c h => H.le_trans (ih c h) (H.meet_r _ _)
  | orI1 _ ih => exact fun c h => H.le_trans (ih c h) (H.join_l _ _)
  | orI2 _ ih => exact fun c h => H.le_trans (ih c h) (H.join_r _ _)
  | @orE _ a b _ _ _ _ ih iha ihb =>
    exact fun c h =>
      have ka := iha (H.meet c (interp H v f a)) (fun ψ e => by
        cases e with
        | inl q => cases q; exact H.meet_r _ _
        | inr g => exact H.le_trans (H.meet_l _ _) (h ψ g))
      have kb := ihb (H.meet c (interp H v f b)) (fun ψ e => by
        cases e with
        | inl q => cases q; exact H.meet_r _ _
        | inr g => exact H.le_trans (H.meet_l _ _) (h ψ g))
      H.le_trans (H.meet_univ (H.le_refl c) (ih c h))
        (H.le_trans (distrib H _ _ _) (H.join_univ ka kb))
  | @impI _ a _ _ ih =>
    exact fun c h => H.imp_adj.mp (ih (H.meet c (interp H v f a)) (fun ψ e => by
        cases e with
        | inl q => cases q; exact H.meet_r _ _
        | inr g => exact H.le_trans (H.meet_l _ _) (h ψ g)))
  | impE _ _ ihf iha => exact fun c h => H.imp_elim (ihf c h) (iha c h)

/-- a theorem (no hypotheses) is valued top -/
theorem valid {I : Bool} {φ : Form} (d : PD I (fun _ => False) φ)
    (v : Nat → H.car) (f : H.car) (hf : I = true → ∀ x, H.le f x) :
    H.le H.top (interp H v f φ) :=
  soundness H d v f hf H.top (fun _ g => g.elim)

end Sem

/-! ## Separations -/

/-- minimal logic does not prove ⊥ → p: read ⊥ as True, p as False in Ω -/
theorem min_not_efq : ¬ PD false (fun _ => False) (.imp .bot (.var 0)) :=
  fun d => valid OmegaHA d (fun _ => False) True (fun e => Bool.noConfusion e) trivial trivial

/-- the three-element Heyting algebra 0 < ½ < 1 -/
inductive Three where
  | z : Three
  | h : Three
  | o : Three

namespace Three

def le : Three → Three → Prop
  | z, z => True
  | z, h => True
  | z, o => True
  | h, z => False
  | h, h => True
  | h, o => True
  | o, z => False
  | o, h => False
  | o, o => True

def meet : Three → Three → Three
  | z, z => z
  | z, h => z
  | z, o => z
  | h, z => z
  | h, h => h
  | h, o => h
  | o, z => z
  | o, h => h
  | o, o => o

def join : Three → Three → Three
  | z, z => z
  | z, h => h
  | z, o => o
  | h, z => h
  | h, h => h
  | h, o => o
  | o, z => o
  | o, h => o
  | o, o => o

def imp : Three → Three → Three
  | z, z => o
  | z, h => o
  | z, o => o
  | h, z => z
  | h, h => o
  | h, o => o
  | o, z => z
  | o, h => h
  | o, o => o

def HA3 : HA.{0} where
  car := Three
  le := le
  le_refl a := by cases a <;> exact trivial
  le_trans {a b c} := by
    cases a <;> cases b <;> cases c <;> intro p q <;> first | exact trivial | exact p.elim | exact q.elim
  top := o
  bot := z
  meet := meet
  join := join
  imp := imp
  le_top a := by cases a <;> exact trivial
  bot_le a := by cases a <;> exact trivial
  meet_l a b := by cases a <;> cases b <;> exact trivial
  meet_r a b := by cases a <;> cases b <;> exact trivial
  meet_univ {a b c} := by
    cases a <;> cases b <;> cases c <;> intro p q <;> first | exact trivial | exact p.elim | exact q.elim
  join_l a b := by cases a <;> cases b <;> exact trivial
  join_r a b := by cases a <;> cases b <;> exact trivial
  join_univ {a b c} := by
    cases a <;> cases b <;> cases c <;> intro p q <;> first | exact trivial | exact p.elim | exact q.elim
  imp_adj {a b c} := by
    cases a <;> cases b <;> cases c <;>
      exact ⟨fun p => p, fun p => p⟩

end Three

/-- intuitionistic logic does not prove p ∨ ¬p -/
theorem int_not_lem : ¬ PD true (fun _ => False) (.or (.var 0) (neg (.var 0))) :=
  fun d => valid Three.HA3 d (fun _ => Three.h) Three.z (fun _ x => by cases x <;> exact trivial)

/-- intuitionistic logic does not prove ¬¬p → p -/
theorem int_not_dne : ¬ PD true (fun _ => False) (.imp (neg (neg (.var 0))) (.var 0)) :=
  fun d => valid Three.HA3 d (fun _ => Three.h) Three.z (fun _ x => by cases x <;> exact trivial)

end Prp

end Found

#print axioms Found.Prp.mono
#print axioms Found.Prp.cut
#print axioms Found.Prp.min_to_int
#print axioms Found.Prp.efq_all
#print axioms Found.Prp.int_to_min
#print axioms Found.Prp.int_iff_min_efq
#print axioms Found.Prp.distrib
#print axioms Found.Prp.soundness
#print axioms Found.Prp.valid
#print axioms Found.Prp.min_not_efq
#print axioms Found.Prp.Three.HA3
#print axioms Found.Prp.int_not_lem
#print axioms Found.Prp.int_not_dne

#print axioms: 13 theorems, no axioms.

85.7 Classical logic and the double-negation translation

Classical logic is intuitionistic logic plus \(\neg \neg a\to a\), sound in Boolean Heyting algebras; \(\Omega \) is Boolean iff \(\neg \neg p\to p\); the Gödel–Gentzen translation is sound and faithful. \(\Gamma \vdash _{c}\varphi \iff gg(\Gamma )\vdash _{i}gg(\varphi )\).

found/Classical.lean

/-
  T66. found/Classical — classical logic as a condition, and the
  Gödel–Gentzen double-negation translation (propositional).

  * Classical derivability: intuitionistic derivability from Γ plus all
    instances of ¬¬a → a.
  * Condition in the frame: classical logic is sound in every Boolean
    Heyting algebra (¬¬a ≤ a); Ω = (Prop, ↔) is Boolean exactly when
    ¬¬p → p holds for all p; the three-element algebra is not Boolean.
  * Gödel–Gentzen: Γ ⊢_c φ ⟺ gg Γ ⊢_i gg φ (sound and faithful).
  * Classical logic proves p ∨ ¬p (which intuitionistic logic does not, T65).

  No classical axiom is assumed: excluded middle only appears through the
  translation, as a hypothesis set or as a Boolean condition.
  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Minimal


universe u

namespace Found

namespace Prp

def DNE (Γ : Form → Prop) : Form → Prop :=
  fun x => Γ x ∨ ∃ a, x = .imp (neg (neg a)) a

/-- classical derivability -/
def CD (Γ : Form → Prop) (φ : Form) : Prop := PD true (DNE Γ) φ

def HasDNE (Δ : Form → Prop) : Prop := ∀ a, Δ (.imp (neg (neg a)) a)

theorem hasDNE_ext {Δ : Form → Prop} (h : HasDNE Δ) (b : Form) : HasDNE (ext Δ b) :=
  fun a => Or.inr (h a)

section Hyps
variable {I : Bool} {Δ : Form → Prop} {a b c d : Form}
theorem h0 : PD I (ext Δ a) a := .hyp (Or.inl rfl)
theorem h1 : PD I (ext (ext Δ a) b) a := .hyp (Or.inr (Or.inl rfl))
theorem h2 : PD I (ext (ext (ext Δ a) b) c) a := .hyp (Or.inr (Or.inr (Or.inl rfl)))
theorem wk {φ : Form} (d : PD I Δ φ) : PD I (ext Δ a) φ := mono d (fun _ k => Or.inr k)
end Hyps

/-! ## Gödel–Gentzen -/

def gg : Form → Form
  | .var n => neg (neg (.var n))
  | .bot => .bot
  | .and a b => .and (gg a) (gg b)
  | .or a b => neg (.and (neg (gg a)) (neg (gg b)))
  | .imp a b => .imp (gg a) (gg b)

/-- ¬¬¬A → ¬A -/
theorem tn (Θ : Form → Prop) (A : Form) : PD true Θ (.imp (neg (neg (neg A))) (neg A)) :=
  .impI (.impI (.impE h1 (.impI (.impE h0 h1))))

/-- every translated formula is ¬¬-stable, intuitionistically -/
theorem stable : (φ : Form) → ∀ (Θ : Form → Prop), PD true Θ (.imp (neg (neg (gg φ))) (gg φ))
  | .var _, Θ => tn Θ _
  | .bot, _ => .impI (.impE h0 (.impI h0))
  | .and a b, _ =>
    .impI (.andI
      (.impE (stable a _) (.impI (.impE h1 (.impI (.impE h1 (.andE1 h0))))))
      (.impE (stable b _) (.impI (.impE h1 (.impI (.impE h1 (.andE2 h0)))))))
  | .or _ _, Θ => tn Θ _
  | .imp _ b, _ =>
    .impI (.impI (.impE (stable b _)
      (.impI (.impE h2 (.impI (.impE h1 (.impE h0 h2)))))))

/-- soundness of the translation, in cut form -/
theorem gg_sound {Δ : Form → Prop} {φ : Form} (d : PD true Δ φ) :
    ∀ {Θ : Form → Prop}, (∀ x, Δ x → PD true Θ (gg x)) → PD true Θ (gg φ) := by
  induction d with
  | hyp g => exact fun h => h _ g
  | botE _ _ ih => exact fun h => .botE rfl (ih h)
  | andI _ _ iha ihb => exact fun h => .andI (iha h) (ihb h)
  | andE1 _ ih => exact fun h => .andE1 (ih h)
  | andE2 _ ih => exact fun h => .andE2 (ih h)
  | orI1 _ ih => exact fun h => .impI (.impE (.andE1 h0) (wk (ih h)))
  | orI2 _ ih => exact fun h => .impI (.impE (.andE2 h0) (wk (ih h)))
  | @orE _ a b c _ _ _ ih iha ihb =>
    exact fun {Θ} h =>
      have ext_h : ∀ (e : Form), ∀ x, ext _ e x → PD true (ext Θ (gg e)) (gg x) :=
        fun _ x k => k.elim (fun q => q ▸ h0) (fun g => wk (h x g))
      have ca := iha (Θ := ext Θ (gg a)) (ext_h a)
      have cb := ihb (Θ := ext Θ (gg b)) (ext_h b)
      have inc : ∀ (e : Form), ∀ x, ext Θ (gg e) x → ext (ext Θ (neg (gg c))) (gg e) x :=
        fun _ x k => k.elim Or.inl (fun g => Or.inr (Or.inr g))
      .impE (stable c Θ) (.impI (.impE (wk (ih h))
        (.andI (.impI (.impE h1 (mono ca (inc a)))) (.impI (.impE h1 (mono cb (inc b)))))))
  | @impI _ a _ _ ih =>
    exact fun {Θ} h => .impI (ih (Θ := ext Θ (gg a))
      (fun x k => k.elim (fun q => q ▸ h0) (fun g => wk (h x g))))
  | impE _ _ ihf iha => exact fun h => .impE (ihf h) (iha h)

/-- classically, every formula is equivalent to its translation -/
theorem gg_eqv : (φ : Form) → ∀ {Δ : Form → Prop}, HasDNE Δ →
    PD true Δ (.imp φ (gg φ)) ∧ PD true Δ (.imp (gg φ) φ)
  | .var _, _, hD => ⟨.impI (.impI (.impE h0 h1)), .hyp (hD _)⟩
  | .bot, _, _ => ⟨.impI h0, .impI h0⟩
  | .and a b, _, hD =>
    ⟨.impI (.andI (.impE (gg_eqv a (hasDNE_ext hD _)).1 (.andE1 h0))
                  (.impE (gg_eqv b (hasDNE_ext hD _)).1 (.andE2 h0))),
     .impI (.andI (.impE (gg_eqv a (hasDNE_ext hD _)).2 (.andE1 h0))
                  (.impE (gg_eqv b (hasDNE_ext hD _)).2 (.andE2 h0)))⟩
  | .or a b, _, hD =>
    ⟨.impI (.impI (.orE h1
        (.impE (.andE1 h1) (.impE (gg_eqv a (hasDNE_ext (hasDNE_ext (hasDNE_ext hD _) _) _)).1 h0))
        (.impE (.andE2 h1) (.impE (gg_eqv b (hasDNE_ext (hasDNE_ext (hasDNE_ext hD _) _) _)).1 h0)))),
     .impI (.impE (.hyp (hasDNE_ext hD _ (.or a b)))
       (.impI (.impE h1 (.andI
         (.impI (.impE h1 (.orI1 (.impE (gg_eqv a (hasDNE_ext (hasDNE_ext (hasDNE_ext hD _) _) _)).2 h0))))
         (.impI (.impE h1 (.orI2 (.impE (gg_eqv b (hasDNE_ext (hasDNE_ext (hasDNE_ext hD _) _) _)).2 h0))))))))⟩
  | .imp a b, _, hD =>
    ⟨.impI (.impI (.impE (gg_eqv b (hasDNE_ext (hasDNE_ext hD _) _)).1
        (.impE h1 (.impE (gg_eqv a (hasDNE_ext (hasDNE_ext hD _) _)).2 h0)))),
     .impI (.impI (.impE (gg_eqv b (hasDNE_ext (hasDNE_ext hD _) _)).2
        (.impE h1 (.impE (gg_eqv a (hasDNE_ext (hasDNE_ext hD _) _)).1 h0))))⟩

def GG (Γ : Form → Prop) : Form → Prop := fun x => ∃ y, Γ y ∧ x = gg y

theorem dne_has (Γ : Form → Prop) : HasDNE (DNE Γ) := fun a => Or.inr ⟨a, rfl⟩

/-- Gödel–Gentzen: classical ⊢ φ from Γ iff intuitionistic ⊢ gg φ from gg Γ -/
theorem gg_iff (Γ : Form → Prop) (φ : Form) : CD Γ φ ↔ PD true (GG Γ) (gg φ) :=
  ⟨fun d => gg_sound d (fun x k => k.elim (fun g => .hyp ⟨x, g, rfl⟩)
      (fun ⟨a, q⟩ => q ▸ stable a (GG Γ))),
   fun d => .impE (gg_eqv φ (dne_has Γ)).2
      (cut d (fun _ ⟨y, g, q⟩ => q ▸ .impE (gg_eqv y (dne_has Γ)).1 (.hyp (Or.inl g))))⟩

/-- classical logic proves excluded middle -/
theorem cd_lem (Γ : Form → Prop) (p : Form) : CD Γ (.or p (neg p)) :=
  .impE (.hyp (dne_has Γ _)) (.impI (.impE h0 (.orI2 (.impI (.impE h1 (.orI1 h0))))))

/-! ## The Boolean condition -/

def Boolean (H : HA.{u}) : Prop := ∀ a, H.le (H.neg (H.neg a)) a

/-- classical logic is sound in every Boolean Heyting algebra -/
theorem cd_sound (H : HA.{u}) (hB : Boolean H) {φ : Form} (d : CD (fun _ => False) φ)
    (v : Nat → H.car) : H.le H.top (interp H v H.bot φ) :=
  soundness H d v H.bot (fun _ => H.bot_le) H.top (fun _ k => k.elim (fun g => g.elim)
    (fun ⟨_, q⟩ => q ▸ H.imp_adj.mp (H.le_trans (H.meet_r _ _) (hB _))))

/-- Ω is Boolean exactly when double negation elimination holds for all propositions -/
theorem omega_boolean_iff : Boolean OmegaHA ↔ ∀ p : Prop, ¬¬p → p := Iff.rfl

theorem three_not_boolean : ¬ Boolean Three.HA3 := fun h => h Three.h

end Prp

end Found

#print axioms Found.Prp.tn
#print axioms Found.Prp.stable
#print axioms Found.Prp.gg_sound
#print axioms Found.Prp.gg_eqv
#print axioms Found.Prp.gg_iff
#print axioms Found.Prp.cd_lem
#print axioms Found.Prp.cd_sound
#print axioms Found.Prp.omega_boolean_iff
#print axioms Found.Prp.three_not_boolean

#print axioms: 9 theorems, no axioms.

85.8 Modal logics K, T, S4, S5

Modal axioms T, 4, B, 5 hold on a frame iff it is reflexive, transitive, symmetric, euclidean; Kripke models of intuitionistic logic are upset Heyting algebras and the Gödel–McKinsey–Tarski translation is valid on S4 frames. \(\Box p\to p\iff \mathrm {Refl},\ \Box p\to \Box \Box p\iff \mathrm {Trans};\ \vdash _i\varphi \Rightarrow \ \models _{S4}\mathrm {gmt}(\varphi )\).

found/Modal.lean

/-
  T67. found/Modal — modal logics K, T, S4, S5 as conditions on □.

  * Modal formulas, Kripke semantics in Ω over a frame (W, R).
  * A Hilbert system with optional axioms T, 4, B, 5; soundness on frames
    with the matching conditions.
  * Correspondence (both directions, constructive):
      T ⇔ reflexive, 4 ⇔ transitive, B ⇔ symmetric, 5 ⇔ euclidean.
    So K, T, S4, S5 are the same □ with conditions on R.
  * Upward-closed predicates on a preorder form a Heyting algebra; hence
    intuitionistic logic (T65) is sound in Kripke models.
  * Gödel–McKinsey–Tarski: on every S4 frame the intuitionistic value of φ
    (with boxed valuation) is the modal value of its box translation.

  Lean 4 core only, hand-written proofs, no axioms.

  CIC dependence: Kripke semantics is Prop-valued.
-/
import found.Classical


universe u

namespace Found

namespace Modal

inductive MForm where
  | var : Nat → MForm
  | bot : MForm
  | and : MForm → MForm → MForm
  | or : MForm → MForm → MForm
  | imp : MForm → MForm → MForm
  | box : MForm → MForm
  | dia : MForm → MForm

section Sem
variable {W : Type u} (R : W → W → Prop) (V : W → Nat → Prop)

def sat : W → MForm → Prop
  | w, .var n => V w n
  | _, .bot => False
  | w, .and a b => sat w a ∧ sat w b
  | w, .or a b => sat w a ∨ sat w b
  | w, .imp a b => sat w a → sat w b
  | w, .box a => ∀ v, R w v → sat v a
  | w, .dia a => ∃ v, R w v ∧ sat v a

end Sem

structure MLogic where
  t : Bool
  four : Bool
  b : Bool
  five : Bool

def K : MLogic := ⟨false, false, false, false⟩
def LT : MLogic := ⟨true, false, false, false⟩
def S4 : MLogic := ⟨true, true, false, false⟩
def S5 : MLogic := ⟨true, true, true, false⟩

inductive HD (L : MLogic) : MForm → Prop where
  | k1 (a b : MForm) : HD L (.imp a (.imp b a))
  | s (a b c : MForm) : HD L (.imp (.imp a (.imp b c)) (.imp (.imp a b) (.imp a c)))
  | andI (a b : MForm) : HD L (.imp a (.imp b (.and a b)))
  | andE1 (a b : MForm) : HD L (.imp (.and a b) a)
  | andE2 (a b : MForm) : HD L (.imp (.and a b) b)
  | orI1 (a b : MForm) : HD L (.imp a (.or a b))
  | orI2 (a b : MForm) : HD L (.imp b (.or a b))
  | orE (a b c : MForm) : HD L (.imp (.imp a c) (.imp (.imp b c) (.imp (.or a b) c)))
  | efq (a : MForm) : HD L (.imp .bot a)
  | kax (a b : MForm) : HD L (.imp (.box (.imp a b)) (.imp (.box a) (.box b)))
  | tax (a : MForm) : L.t = true → HD L (.imp (.box a) a)
  | fourax (a : MForm) : L.four = true → HD L (.imp (.box a) (.box (.box a)))
  | bax (a : MForm) : L.b = true → HD L (.imp a (.box (.dia a)))
  | fiveax (a : MForm) : L.five = true → HD L (.imp (.dia a) (.box (.dia a)))
  | mp {a b : MForm} : HD L (.imp a b) → HD L a → HD L b
  | nec {a : MForm} : HD L a → HD L (.box a)

section Frames
variable {W : Type u} (R : W → W → Prop)

def Refl : Prop := ∀ w, R w w
def Trans : Prop := ∀ u v w, R u v → R v w → R u w
def Symm : Prop := ∀ u v, R u v → R v u
def Eucl : Prop := ∀ u v w, R u v → R u w → R v w

structure FrameOK (L : MLogic) : Prop where
  refl : L.t = true → Refl R
  trans : L.four = true → Trans R
  symm : L.b = true → Symm R
  eucl : L.five = true → Eucl R

/-- soundness of the Hilbert system on frames satisfying the conditions -/
theorem soundness {L : MLogic} (hF : FrameOK R L) {φ : MForm} (d : HD L φ) :
    ∀ (V : W → Nat → Prop) w, sat R V w φ := by
  induction d with
  | k1 => exact fun _ _ x _ => x
  | s => exact fun _ _ f g x => f x (g x)
  | andI => exact fun _ _ x y => ⟨x, y⟩
  | andE1 => exact fun _ _ x => x.1
  | andE2 => exact fun _ _ x => x.2
  | orI1 => exact fun _ _ x => Or.inl x
  | orI2 => exact fun _ _ x => Or.inr x
  | orE => exact fun _ _ f g x => x.elim f g
  | efq => exact fun _ _ x => x.elim
  | kax => exact fun _ _ f g v r => f v r (g v r)
  | tax _ e => exact fun _ w x => x w (hF.refl e w)
  | fourax _ e => exact fun _ w x v r u r' => x u (hF.trans e w v u r r')
  | bax _ e => exact fun _ w x v r => ⟨w, hF.symm e w v r, x⟩
  | fiveax _ e => exact fun _ w x v r => match x with
      | ⟨u, r', y⟩ => ⟨u, hF.eucl e w v u r r', y⟩
  | mp _ _ ihf iha => exact fun V w => ihf V w (iha V w)
  | nec _ ih => exact fun V _ v _ => ih V v

/-! ## Correspondence -/

theorem t_iff_refl :
    (∀ (V : W → Nat → Prop) w, sat R V w (.imp (.box (.var 0)) (.var 0))) ↔ Refl R :=
  ⟨fun h w => h (fun v _ => R w v) w (fun _ r => r),
   fun hr _ w x => x w (hr w)⟩

theorem four_iff_trans :
    (∀ (V : W → Nat → Prop) w, sat R V w (.imp (.box (.var 0)) (.box (.box (.var 0))))) ↔ Trans R :=
  ⟨fun h u v w r r' => h (fun x _ => R u x) u (fun _ k => k) v r w r',
   fun ht _ w x v r u r' => x u (ht w v u r r')⟩

theorem b_iff_symm :
    (∀ (V : W → Nat → Prop) w, sat R V w (.imp (.var 0) (.box (.dia (.var 0))))) ↔ Symm R :=
  ⟨fun h u v r => match h (fun x _ => x = u) u rfl v r with
     | ⟨_, r', e⟩ => e ▸ r',
   fun hs _ w x v r => ⟨w, hs w v r, x⟩⟩

theorem five_iff_eucl :
    (∀ (V : W → Nat → Prop) w, sat R V w (.imp (.dia (.var 0)) (.box (.dia (.var 0))))) ↔ Eucl R :=
  ⟨fun h u v w r r' => match h (fun x _ => x = w) u ⟨w, r', rfl⟩ v r with
     | ⟨_, r'', e⟩ => e ▸ r'',
   fun he _ w x v r => match x with
     | ⟨u, r', y⟩ => ⟨u, he w v u r r', y⟩⟩

/-- S5 frames are exactly equivalence relations; with T, 5 gives B and 4 -/
theorem eucl_refl_symm (hr : Refl R) (he : Eucl R) : Symm R :=
  fun u v r => he u v u r (hr u)

theorem eucl_refl_trans (hr : Refl R) (he : Eucl R) : Trans R :=
  fun u v w r r' => he v u w (eucl_refl_symm R hr he u v r) r'

end Frames

/-! ## Kripke models of intuitionistic logic = upsets of a preorder -/

section Up
variable {W : Type u} (R : W → W → Prop) (hr : Refl R) (ht : Trans R)

structure Up where
  p : W → Prop
  up : ∀ w v, R w v → p w → p v

def UpHA : HA.{u} where
  car := Up R
  le P Q := ∀ w, P.p w → Q.p w
  le_refl _ _ h := h
  le_trans h k w x := k w (h w x)
  top := ⟨fun _ => True, fun _ _ _ _ => trivial⟩
  bot := ⟨fun _ => False, fun _ _ _ h => h⟩
  meet P Q := ⟨fun w => P.p w ∧ Q.p w, fun w v r h => ⟨P.up w v r h.1, Q.up w v r h.2⟩⟩
  join P Q := ⟨fun w => P.p w ∨ Q.p w,
    fun w v r h => h.elim (fun a => Or.inl (P.up w v r a)) (fun b => Or.inr (Q.up w v r b))⟩
  imp P Q := ⟨fun w => ∀ v, R w v → P.p v → Q.p v, fun _ _ r h u r' x => h u (ht _ _ _ r r') x⟩
  le_top _ _ _ := trivial
  bot_le _ _ h := h.elim
  meet_l _ _ _ h := h.1
  meet_r _ _ _ h := h.2
  meet_univ h k w x := ⟨h w x, k w x⟩
  join_l _ _ _ h := Or.inl h
  join_r _ _ _ h := Or.inr h
  join_univ h k w x := x.elim (h w) (k w)
  imp_adj {_ _ C} := ⟨fun h w c v r x => h v ⟨C.up w v r c, x⟩,
                      fun h w x => h w x.1 w (hr w) x.2⟩

/-- the boxed valuation: an upset for any valuation -/
def boxV (V : W → Nat → Prop) (n : Nat) : Up R :=
  ⟨fun w => ∀ v, R w v → V v n, fun _ _ r h u r' => h u (ht _ _ _ r r')⟩

/-- the Gödel–McKinsey–Tarski translation -/
def gmt : Prp.Form → MForm
  | .var n => .box (.var n)
  | .bot => .bot
  | .and a b => .and (gmt a) (gmt b)
  | .or a b => .or (gmt a) (gmt b)
  | .imp a b => .box (.imp (gmt a) (gmt b))

theorem gmt_sem (V : W → Nat → Prop) : (φ : Prp.Form) → ∀ w,
    (Prp.interp (UpHA R hr ht) (boxV R ht V) (UpHA R hr ht).bot φ).p w ↔ sat R V w (gmt φ)
  | .var _, _ => Iff.rfl
  | .bot, _ => Iff.rfl
  | .and a b, w =>
    ⟨fun h => ⟨(gmt_sem V a w).mp h.1, (gmt_sem V b w).mp h.2⟩,
     fun h => ⟨(gmt_sem V a w).mpr h.1, (gmt_sem V b w).mpr h.2⟩⟩
  | .or a b, w =>
    ⟨fun h => h.elim (fun x => Or.inl ((gmt_sem V a w).mp x)) (fun y => Or.inr ((gmt_sem V b w).mp y)),
     fun h => h.elim (fun x => Or.inl ((gmt_sem V a w).mpr x)) (fun y => Or.inr ((gmt_sem V b w).mpr y))⟩
  | .imp a b, _ =>
    ⟨fun h v r x => (gmt_sem V b v).mp (h v r ((gmt_sem V a v).mpr x)),
     fun h v r x => (gmt_sem V b v).mpr (h v r ((gmt_sem V a v).mp x))⟩

include hr ht in
/-- every intuitionistic theorem becomes, by GMT, valid on every S4 frame -/
theorem gmt_valid {φ : Prp.Form} (d : Prp.PD true (fun _ => False) φ)
    (V : W → Nat → Prop) (w : W) : sat R V w (gmt φ) :=
  (gmt_sem R hr ht V φ w).mp
    (Prp.valid (UpHA R hr ht) d (boxV R ht V) (UpHA R hr ht).bot (fun _ _ _ h => h.elim) w trivial)

end Up

/-- the two-world S4 frame 0 ≤ 1 refutes the GMT image of p ∨ ¬p -/
theorem gmt_lem_fails :
    ¬ sat (fun (a b : Bool) => a = false ∨ b = true) (fun w _ => w = true) false
      (gmt (.or (.var 0) (Prp.neg (.var 0)))) :=
  fun h => h.elim
    (fun x => Bool.noConfusion (x false (Or.inl rfl)))
    (fun x => x true (Or.inl rfl) (fun _ r => r.elim (fun e => Bool.noConfusion e) (fun e => e)))

end Modal

end Found

#print axioms Found.Modal.soundness
#print axioms Found.Modal.t_iff_refl
#print axioms Found.Modal.four_iff_trans
#print axioms Found.Modal.b_iff_symm
#print axioms Found.Modal.five_iff_eucl
#print axioms Found.Modal.eucl_refl_symm
#print axioms Found.Modal.eucl_refl_trans
#print axioms Found.Modal.UpHA
#print axioms Found.Modal.gmt_sem
#print axioms Found.Modal.gmt_valid
#print axioms Found.Modal.gmt_lem_fails

#print axioms: 11 theorems, no axioms.

85.9 Linear logic

Linear sequents are sound in commutative residuated lattices with an exponential; weakening and contraction make such a model a Heyting algebra; the co-Kleisli order of \(!\) is Heyting, so intuitionistic theorems are valid under the Girard translation; contraction fails in \(\L _3\). \(a\otimes b\le a,\ a\le a\otimes a\Rightarrow (\otimes =\wedge );\quad \vdash _i\varphi \Rightarrow \ !1\le \llbracket \varphi ^{*}\rrbracket \).

found/Linear.lean

/-
  T68. found/Linear — intuitionistic linear logic as a condition.

  * Sequent calculus for intuitionistic linear logic (⊗, 1, ⊸, &, ⊕, 0, !)
    with list contexts and an explicit permutation rule.
  * Models: commutative residuated lattices with an exponential `!`
    (the poset shadow of a symmetric monoidal closed category with a
    comonad).  Soundness of the calculus.
  * Condition: a residuated lattice with weakening and contraction is a
    Heyting algebra (⊗ = ∧, ⊸ = →); conversely every Heyting algebra is a
    model with ! = id, so linear derivations erase to intuitionistic truths.
  * Girard: the co-Kleisli order a ≤! b :⟺ !a ≤ b of any model is a Heyting
    algebra with a → b := !a ⊸ b, a ∨ b := !a ⊕ !b (Seely); so every
    intuitionistic theorem is valid under the Girard translation.
  * Separation: Łukasiewicz three-valued algebra refutes contraction p ⊸ p ⊗ p.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Minimal


universe u

namespace Found

namespace Lin

inductive LForm where
  | var : Nat → LForm
  | one : LForm
  | zero : LForm
  | tens : LForm → LForm → LForm
  | lolli : LForm → LForm → LForm
  | wth : LForm → LForm → LForm
  | pls : LForm → LForm → LForm
  | bang : LForm → LForm

inductive Perm : List LForm → List LForm → Prop where
  | nil : Perm [] []
  | cons (x : LForm) {l₁ l₂ : List LForm} : Perm l₁ l₂ → Perm (x :: l₁) (x :: l₂)
  | swap (x y : LForm) (l : List LForm) : Perm (x :: y :: l) (y :: x :: l)
  | trans {l₁ l₂ l₃ : List LForm} : Perm l₁ l₂ → Perm l₂ l₃ → Perm l₁ l₃

inductive LD : List LForm → LForm → Prop where
  | ax (a : LForm) : LD [a] a
  | perm {Γ Δ c} : Perm Γ Δ → LD Γ c → LD Δ c
  | cut {Γ Δ a c} : LD Γ a → LD (a :: Δ) c → LD (Γ ++ Δ) c
  | tensR {Γ Δ a b} : LD Γ a → LD Δ b → LD (Γ ++ Δ) (.tens a b)
  | tensL {Γ a b c} : LD (a :: b :: Γ) c → LD (.tens a b :: Γ) c
  | oneR : LD [] .one
  | oneL {Γ c} : LD Γ c → LD (.one :: Γ) c
  | lolliR {Γ a b} : LD (a :: Γ) b → LD Γ (.lolli a b)
  | lolliL {Γ Δ a b c} : LD Γ a → LD (b :: Δ) c → LD (.lolli a b :: (Γ ++ Δ)) c
  | wthR {Γ a b} : LD Γ a → LD Γ b → LD Γ (.wth a b)
  | wthL1 {Γ a b c} : LD (a :: Γ) c → LD (.wth a b :: Γ) c
  | wthL2 {Γ a b c} : LD (b :: Γ) c → LD (.wth a b :: Γ) c
  | plsR1 {Γ a b} : LD Γ a → LD Γ (.pls a b)
  | plsR2 {Γ a b} : LD Γ b → LD Γ (.pls a b)
  | plsL {Γ a b c} : LD (a :: Γ) c → LD (b :: Γ) c → LD (.pls a b :: Γ) c
  | zeroL {Γ c} : LD (.zero :: Γ) c
  | derel {Γ a c} : LD (a :: Γ) c → LD (.bang a :: Γ) c
  | weak {Γ a c} : LD Γ c → LD (.bang a :: Γ) c
  | contr {Γ a c} : LD (.bang a :: .bang a :: Γ) c → LD (.bang a :: Γ) c
  | prom {Γ : List LForm} {a : LForm} : LD (Γ.map .bang) a → LD (Γ.map .bang) (.bang a)

/-! ## Models: commutative residuated lattices with an exponential -/

structure CRL where
  car : Type u
  le : car → car → Prop
  le_refl : ∀ a, le a a
  le_trans : ∀ {a b c}, le a b → le b c → le a c
  one : car
  tens : car → car → car
  lolli : car → car → car
  wth : car → car → car
  pls : car → car → car
  zero : car
  bang : car → car
  tens_mono : ∀ {a a' b b'}, le a a' → le b b' → le (tens a b) (tens a' b')
  tens_comm : ∀ a b, le (tens a b) (tens b a)
  assoc1 : ∀ a b c, le (tens (tens a b) c) (tens a (tens b c))
  assoc2 : ∀ a b c, le (tens a (tens b c)) (tens (tens a b) c)
  unit1 : ∀ a, le (tens one a) a
  unit2 : ∀ a, le a (tens one a)
  adj : ∀ {a b c}, le (tens a b) c ↔ le b (lolli a c)
  wth_l : ∀ a b, le (wth a b) a
  wth_r : ∀ a b, le (wth a b) b
  wth_univ : ∀ {a b c}, le c a → le c b → le c (wth a b)
  pls_l : ∀ a b, le a (pls a b)
  pls_r : ∀ a b, le b (pls a b)
  pls_univ : ∀ {a b c}, le a c → le b c → le (pls a b) c
  zero_le : ∀ a, le zero a
  bang_le : ∀ a, le (bang a) a
  bang_unit : ∀ a, le (bang a) one
  bang_dup : ∀ a, le (bang a) (tens (bang a) (bang a))

namespace CRL
variable (M : CRL)

def ctx : List M.car → M.car
  | [] => M.one
  | a :: l => M.tens a (ctx l)

/-- promotion: a product of banged elements below `a` is below `!a` -/
def PromOK : Prop := ∀ (l : List M.car) (a : M.car), M.le (M.ctx (l.map M.bang)) a →
  M.le (M.ctx (l.map M.bang)) (M.bang a)

theorem ev (a b : M.car) : M.le (M.tens (M.lolli a b) a) b :=
  M.le_trans (M.tens_comm _ _) (M.adj.mpr (M.le_refl _))

theorem swap (x y g : M.car) : M.le (M.tens x (M.tens y g)) (M.tens y (M.tens x g)) :=
  M.le_trans (M.assoc2 _ _ _) (M.le_trans (M.tens_mono (M.tens_comm x y) (M.le_refl g)) (M.assoc1 _ _ _))

theorem ctx_append : (l₁ l₂ : List M.car) →
    M.le (M.ctx (l₁ ++ l₂)) (M.tens (M.ctx l₁) (M.ctx l₂))
  | [], _ => M.unit2 _
  | a :: l, l₂ => M.le_trans (M.tens_mono (M.le_refl a) (ctx_append l l₂)) (M.assoc2 _ _ _)

end CRL

section Sound
variable (M : CRL) (v : Nat → M.car)

def interp : LForm → M.car
  | .var n => v n
  | .one => M.one
  | .zero => M.zero
  | .tens a b => M.tens (interp a) (interp b)
  | .lolli a b => M.lolli (interp a) (interp b)
  | .wth a b => M.wth (interp a) (interp b)
  | .pls a b => M.pls (interp a) (interp b)
  | .bang a => M.bang (interp a)

def cI (Γ : List LForm) : M.car := M.ctx (Γ.map (interp M v))

theorem perm_le {Γ Δ : List LForm} (p : Perm Γ Δ) : M.le (cI M v Γ) (cI M v Δ) := by
  induction p with
  | nil => exact M.le_refl _
  | cons x _ ih => exact M.tens_mono (M.le_refl _) ih
  | swap x y l => exact M.swap _ _ _
  | trans _ _ ih₁ ih₂ => exact M.le_trans ih₁ ih₂

theorem perm_ge {Γ Δ : List LForm} (p : Perm Γ Δ) : M.le (cI M v Δ) (cI M v Γ) := by
  induction p with
  | nil => exact M.le_refl _
  | cons x _ ih => exact M.tens_mono (M.le_refl _) ih
  | swap x y l => exact M.swap _ _ _
  | trans _ _ ih₁ ih₂ => exact M.le_trans ih₂ ih₁

theorem cI_append (Γ Δ : List LForm) :
    M.le (cI M v (Γ ++ Δ)) (M.tens (cI M v Γ) (cI M v Δ)) := by
  have e : (Γ ++ Δ).map (interp M v) = Γ.map (interp M v) ++ Δ.map (interp M v) :=
    map_append_eq Γ Δ
  unfold cI
  rw [e]
  exact M.ctx_append _ _
where
  map_append_eq : (Γ Δ : List LForm) →
      (Γ ++ Δ).map (interp M v) = Γ.map (interp M v) ++ Δ.map (interp M v)
    | [], _ => rfl
    | a :: l, Δ => congrArg (List.cons (interp M v a)) (map_append_eq l Δ)

theorem cI_map_bang (Γ : List LForm) :
    cI M v (Γ.map .bang) = M.ctx ((Γ.map (interp M v)).map M.bang) := by
  induction Γ with
  | nil => rfl
  | cons a l ih => exact congrArg (M.tens (M.bang (interp M v a))) ih

/-- soundness of linear sequents: ⊗Γ ≤ c -/
theorem soundness (hP : M.PromOK) {Γ : List LForm} {c : LForm} (d : LD Γ c) :
    M.le (cI M v Γ) (interp M v c) := by
  induction d with
  | ax a => exact M.le_trans (M.tens_comm _ _) (M.unit1 _)
  | perm p _ ih => exact M.le_trans (perm_ge M v p) ih
  | cut _ _ ih₁ ih₂ => exact M.le_trans (cI_append M v _ _) (M.le_trans (M.tens_mono ih₁ (M.le_refl _)) ih₂)
  | tensR _ _ ih₁ ih₂ => exact M.le_trans (cI_append M v _ _) (M.tens_mono ih₁ ih₂)
  | tensL _ ih => exact M.le_trans (M.assoc1 _ _ _) ih
  | oneR => exact M.le_refl _
  | oneL _ ih => exact M.le_trans (M.unit1 _) ih
  | lolliR _ ih => exact M.adj.mp ih
  | lolliL _ _ ih₁ ih₂ =>
    exact M.le_trans (M.tens_mono (M.le_refl _) (cI_append M v _ _))
      (M.le_trans (M.assoc2 _ _ _)
      (M.le_trans (M.tens_mono (M.le_trans (M.tens_mono (M.le_refl _) ih₁) (M.ev _ _)) (M.le_refl _)) ih₂))
  | wthR _ _ ih₁ ih₂ => exact M.wth_univ ih₁ ih₂
  | wthL1 _ ih => exact M.le_trans (M.tens_mono (M.wth_l _ _) (M.le_refl _)) ih
  | wthL2 _ ih => exact M.le_trans (M.tens_mono (M.wth_r _ _) (M.le_refl _)) ih
  | plsR1 _ ih => exact M.le_trans ih (M.pls_l _ _)
  | plsR2 _ ih => exact M.le_trans ih (M.pls_r _ _)
  | plsL _ _ ih₁ ih₂ =>
    exact M.le_trans (M.tens_comm _ _) (M.adj.mpr (M.pls_univ
      (M.adj.mp (M.le_trans (M.tens_comm _ _) ih₁)) (M.adj.mp (M.le_trans (M.tens_comm _ _) ih₂))))
  | zeroL => exact M.le_trans (M.tens_comm _ _) (M.adj.mpr (M.zero_le _))
  | derel _ ih => exact M.le_trans (M.tens_mono (M.bang_le _) (M.le_refl _)) ih
  | weak _ ih => exact M.le_trans (M.tens_mono (M.bang_unit _) (M.le_refl _)) (M.le_trans (M.unit1 _) ih)
  | contr _ ih =>
    exact M.le_trans (M.tens_mono (M.bang_dup _) (M.le_refl _)) (M.le_trans (M.assoc1 _ _ _) ih)
  | @prom Γ _ _ ih =>
    exact (cI_map_bang M v Γ) ▸ hP _ _ ((cI_map_bang M v Γ) ▸ ih)

end Sound

/-! ## Condition: weakening + contraction turn a model into a Heyting algebra -/

section ToHA
variable (M : CRL) (wk : ∀ a b, M.le (M.tens a b) a) (ct : ∀ a, M.le a (M.tens a a))

include wk in
theorem tens_le_wth (a b : M.car) : M.le (M.tens a b) (M.wth a b) :=
  M.wth_univ (wk a b) (M.le_trans (M.tens_comm a b) (wk b a))

include ct in
theorem wth_le_tens (a b : M.car) : M.le (M.wth a b) (M.tens a b) :=
  M.le_trans (ct _) (M.tens_mono (M.wth_l a b) (M.wth_r a b))

include wk ct in
/-- with weakening and contraction, a residuated lattice is a Heyting algebra -/
def toHA : HA.{u} where
  car := M.car
  le := M.le
  le_refl := M.le_refl
  le_trans := M.le_trans
  top := M.one
  bot := M.zero
  meet := M.wth
  join := M.pls
  imp := M.lolli
  le_top a := M.le_trans (M.unit2 a) (wk _ _)
  bot_le := M.zero_le
  meet_l := M.wth_l
  meet_r := M.wth_r
  meet_univ := M.wth_univ
  join_l := M.pls_l
  join_r := M.pls_r
  join_univ := M.pls_univ
  imp_adj := ⟨fun h => M.adj.mp (M.le_trans (M.tens_comm _ _) (M.le_trans (tens_le_wth M wk _ _) h)),
              fun h => M.le_trans (wth_le_tens M ct _ _) (M.le_trans (M.tens_comm _ _) (M.adj.mpr h))⟩

end ToHA

/-- every Heyting algebra is a linear model with ⊗ = ∧ and ! = id -/
def ofHA (H : HA.{u}) : CRL.{u} where
  car := H.car
  le := H.le
  le_refl := H.le_refl
  le_trans := H.le_trans
  one := H.top
  tens := H.meet
  lolli := H.imp
  wth := H.meet
  pls := H.join
  zero := H.bot
  bang a := a
  tens_mono h k := H.meet_univ (H.le_trans (H.meet_l _ _) h) (H.le_trans (H.meet_r _ _) k)
  tens_comm _ _ := H.meet_univ (H.meet_r _ _) (H.meet_l _ _)
  assoc1 _ _ _ := H.meet_univ (H.le_trans (H.meet_l _ _) (H.meet_l _ _))
    (H.meet_univ (H.le_trans (H.meet_l _ _) (H.meet_r _ _)) (H.meet_r _ _))
  assoc2 _ _ _ := H.meet_univ (H.meet_univ (H.meet_l _ _) (H.le_trans (H.meet_r _ _) (H.meet_l _ _)))
    (H.le_trans (H.meet_r _ _) (H.meet_r _ _))
  unit1 _ := H.meet_r _ _
  unit2 a := H.meet_univ (H.le_top a) (H.le_refl a)
  adj := ⟨fun h => H.imp_adj.mp (H.le_trans (H.meet_univ (H.meet_r _ _) (H.meet_l _ _)) h),
          fun h => H.le_trans (H.meet_univ (H.meet_r _ _) (H.meet_l _ _)) (H.imp_adj.mpr h)⟩
  wth_l := H.meet_l
  wth_r := H.meet_r
  wth_univ := H.meet_univ
  pls_l := H.join_l
  pls_r := H.join_r
  pls_univ := H.join_univ
  zero_le := H.bot_le
  bang_le a := H.le_refl a
  bang_unit a := H.le_top a
  bang_dup a := H.meet_univ (H.le_refl a) (H.le_refl a)

theorem ofHA_prom (H : HA.{u}) : (ofHA H).PromOK := fun _ _ h => h

/-! ## Girard: the co-Kleisli order of `!` is a Heyting algebra -/

section Girard
variable (M : CRL) (hP : M.PromOK)

include hP in
theorem bang_mono {a b : M.car} (h : M.le (M.bang a) b) : M.le (M.bang a) (M.bang b) :=
  M.le_trans (M.le_trans (M.unit2 _) (M.tens_comm _ _))
    (hP [a] b (M.le_trans (M.le_trans (M.tens_comm _ _) (M.unit1 _)) h))

include hP in
theorem seely1 (c a : M.car) : M.le (M.tens (M.bang c) (M.bang a)) (M.bang (M.wth c a)) := by
  have k : M.le (M.ctx ([c, a].map M.bang)) (M.wth c a) :=
    M.wth_univ
      (M.le_trans (M.tens_mono (M.bang_le c) (M.le_trans (M.tens_mono (M.bang_unit a) (M.le_refl _)) (M.unit1 _)))
        (M.le_trans (M.tens_comm _ _) (M.unit1 _)))
      (M.le_trans (M.tens_mono (M.bang_unit c) (M.le_trans (M.tens_mono (M.bang_le a) (M.le_refl _))
          (M.le_trans (M.tens_comm _ _) (M.unit1 _)))) (M.unit1 _))
  exact M.le_trans (M.tens_mono (M.le_refl _) (M.le_trans (M.unit2 _) (M.tens_comm _ _)))
    (hP [c, a] _ k)

include hP in
theorem seely2 (c a : M.car) : M.le (M.bang (M.wth c a)) (M.tens (M.bang c) (M.bang a)) :=
  M.le_trans (M.bang_dup _)
    (M.tens_mono (bang_mono M hP (M.le_trans (M.bang_le _) (M.wth_l _ _)))
                 (bang_mono M hP (M.le_trans (M.bang_le _) (M.wth_r _ _))))

include hP in
/-- the co-Kleisli Heyting algebra: a ≤! b ⟺ !a ≤ b -/
def coKleisli : HA.{u} where
  car := M.car
  le a b := M.le (M.bang a) b
  le_refl a := M.bang_le a
  le_trans h k := M.le_trans (bang_mono M hP h) k
  top := M.one
  bot := M.zero
  meet := M.wth
  join a b := M.pls (M.bang a) (M.bang b)
  imp a b := M.lolli (M.bang a) b
  le_top a := M.bang_unit a
  bot_le a := M.le_trans (M.bang_le _) (M.zero_le a)
  meet_l a b := M.le_trans (M.bang_le _) (M.wth_l a b)
  meet_r a b := M.le_trans (M.bang_le _) (M.wth_r a b)
  meet_univ h k := M.wth_univ h k
  join_l _ _ := M.pls_l _ _
  join_r _ _ := M.pls_r _ _
  join_univ h k := M.le_trans (M.bang_le _) (M.pls_univ h k)
  imp_adj := ⟨fun h => M.adj.mp (M.le_trans (M.tens_comm _ _) (M.le_trans (seely1 M hP _ _) h)),
              fun h => M.le_trans (seely2 M hP _ _) (M.le_trans (M.tens_comm _ _) (M.adj.mpr h))⟩

theorem cong2 {α β γ : Sort _} (f : α → β → γ) {a a' : α} {b b' : β} (h1 : a = a') (h2 : b = b') :
    f a b = f a' b' := by
  cases h1
  cases h2
  rfl

/-- the Girard translation into linear formulas -/
def girard : Prp.Form → LForm
  | .var n => .var n
  | .bot => .zero
  | .and a b => .wth (girard a) (girard b)
  | .or a b => .pls (.bang (girard a)) (.bang (girard b))
  | .imp a b => .lolli (.bang (girard a)) (girard b)

theorem girard_interp (v : Nat → M.car) : (φ : Prp.Form) →
    Prp.interp (coKleisli M hP) v M.zero φ = interp M v (girard φ)
  | .var _ => rfl
  | .bot => rfl
  | .and a b => cong2 M.wth (girard_interp v a) (girard_interp v b)
  | .or a b => cong2 (fun x y => M.pls (M.bang x) (M.bang y)) (girard_interp v a) (girard_interp v b)
  | .imp a b => cong2 (fun x y => M.lolli (M.bang x) y) (girard_interp v a) (girard_interp v b)

include hP in
/-- every intuitionistic theorem is valid under the Girard translation: !1 ≤ ⟦φ*⟧ -/
theorem girard_valid {φ : Prp.Form} (d : Prp.PD true (fun _ => False) φ) (v : Nat → M.car) :
    M.le (M.bang M.one) (interp M v (girard φ)) :=
  girard_interp M hP v φ ▸
    Prp.valid (coKleisli M hP) d v M.zero (fun _ x => M.le_trans (M.bang_le _) (M.zero_le x))

end Girard

/-! ## Łukasiewicz three-valued model: contraction fails -/

inductive L3 where
  | z : L3
  | h : L3
  | o : L3

namespace L3

def rk : L3 → Nat
  | z => 0
  | h => 1
  | o => 2

def le (a b : L3) : Prop := Nat.ble (rk a) (rk b) = true

def tens : L3 → L3 → L3
  | z, z => z
  | z, h => z
  | z, o => z
  | h, z => z
  | h, h => z
  | h, o => h
  | o, z => z
  | o, h => h
  | o, o => o

def lolli : L3 → L3 → L3
  | z, z => o
  | z, h => o
  | z, o => o
  | h, z => h
  | h, h => o
  | h, o => o
  | o, z => z
  | o, h => h
  | o, o => o

def wth : L3 → L3 → L3
  | z, z => z
  | z, h => z
  | z, o => z
  | h, z => z
  | h, h => h
  | h, o => h
  | o, z => z
  | o, h => h
  | o, o => o

def pls : L3 → L3 → L3
  | z, z => z
  | z, h => h
  | z, o => o
  | h, z => h
  | h, h => h
  | h, o => o
  | o, z => o
  | o, h => o
  | o, o => o

def bang : L3 → L3
  | z => z
  | h => z
  | o => o

def M3 : CRL where
  car := L3
  le := le
  le_refl a := by cases a <;> rfl
  le_trans {a b c} := by cases a <;> cases b <;> cases c <;> intro p q <;> first | rfl | exact p | exact q
  one := o
  tens := tens
  lolli := lolli
  wth := wth
  pls := pls
  zero := z
  bang := bang
  tens_mono {a a' b b'} := by
    cases a <;> cases a' <;> cases b <;> cases b' <;> intro p q <;> first | rfl | exact p | exact q
  tens_comm a b := by cases a <;> cases b <;> rfl
  assoc1 a b c := by cases a <;> cases b <;> cases c <;> rfl
  assoc2 a b c := by cases a <;> cases b <;> cases c <;> rfl
  unit1 a := by cases a <;> rfl
  unit2 a := by cases a <;> rfl
  adj {a b c} := by
    cases a <;> cases b <;> cases c <;> exact ⟨fun p => p, fun p => p⟩
  wth_l a b := by cases a <;> cases b <;> rfl
  wth_r a b := by cases a <;> cases b <;> rfl
  wth_univ {a b c} := by cases a <;> cases b <;> cases c <;> intro p q <;> first | rfl | exact p | exact q
  pls_l a b := by cases a <;> cases b <;> rfl
  pls_r a b := by cases a <;> cases b <;> rfl
  pls_univ {a b c} := by cases a <;> cases b <;> cases c <;> intro p q <;> first | rfl | exact p | exact q
  zero_le a := by cases a <;> rfl
  bang_le a := by cases a <;> rfl
  bang_unit a := by cases a <;> rfl
  bang_dup a := by cases a <;> rfl

theorem tens_z (c : L3) : tens z c = z := by cases c <;> rfl

theorem tens_o (c : L3) : tens o c = c := by cases c <;> rfl

/-- a product of banged elements is `o` or `z` -/
theorem ctx_bang : (l : List L3) → M3.ctx (l.map bang) = o ∨ M3.ctx (l.map bang) = z
  | [] => Or.inl rfl
  | z :: _ => Or.inr (tens_z _)
  | h :: _ => Or.inr (tens_z _)
  | o :: l => match ctx_bang l with
    | Or.inl e => Or.inl ((tens_o _).trans e)
    | Or.inr e => Or.inr ((tens_o _).trans e)

theorem key : (c a : L3) → (c = o ∨ c = z) → le c a → le c (bang a)
  | o, o, _, _ => rfl
  | o, h, _, k => k
  | o, z, _, k => k
  | z, _, _, _ => rfl
  | h, _, e, _ => (e.elim (fun q => L3.noConfusion q) (fun q => L3.noConfusion q))

theorem prom : M3.PromOK := fun l a k => key _ a (ctx_bang l) k

end L3

/-- contraction p ⊸ p ⊗ p is not derivable -/
theorem no_contraction : ¬ LD [] (.lolli (.var 0) (.tens (.var 0) (.var 0))) :=
  fun d => Bool.noConfusion (soundness L3.M3 (fun _ => L3.h) L3.prom d)

end Lin

end Found

#print axioms Found.Lin.CRL.ev
#print axioms Found.Lin.CRL.swap
#print axioms Found.Lin.CRL.ctx_append
#print axioms Found.Lin.perm_le
#print axioms Found.Lin.cI_append
#print axioms Found.Lin.soundness
#print axioms Found.Lin.tens_le_wth
#print axioms Found.Lin.wth_le_tens
#print axioms Found.Lin.toHA
#print axioms Found.Lin.ofHA
#print axioms Found.Lin.ofHA_prom
#print axioms Found.Lin.bang_mono
#print axioms Found.Lin.seely1
#print axioms Found.Lin.seely2
#print axioms Found.Lin.coKleisli
#print axioms Found.Lin.girard_interp
#print axioms Found.Lin.girard_valid
#print axioms Found.Lin.L3.M3
#print axioms Found.Lin.L3.prom
#print axioms Found.Lin.no_contraction

#print axioms: 20 theorems, no axioms.

85.10 Relevant and affine logic

Weakening and contraction are two conditions on the same residuated models: Sugihara RM3 has contraction without weakening, \(\L _3\) weakening without contraction, both together give Heyting algebras; linear logic proves neither. \(\mathrm {RM}_3\models a\le a\otimes a,\ \mathrm {RM}_3\not \models a\otimes b\le a;\quad \nvdash _{LL} p\multimap (q\multimap p)\).

found/Relevant.lean

/-
  T69. found/Relevant — substructural logics as two conditions on the same
  models (commutative residuated lattices with !, T68).

  * Weakening  W : a ⊗ b ≤ a        (affine)
  * Contraction C : a ≤ a ⊗ a        (relevant)
  linear = neither, affine = W, relevant = C, intuitionistic = W + C (T68 toHA).
  * Sugihara RM3 (−1 < 0 < 1) satisfies C but not W; Łukasiewicz Ł3 satisfies
    W but not C.  Hence linear logic proves neither p ⊸ (q ⊸ p) nor p ⊸ p ⊗ p,
    the relevant models validate contraction, the affine ones weakening.
  * Relevant and affine models with both conditions are Heyting algebras, so
    each corner of the square erases into intuitionistic logic.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Linear


universe u

namespace Found

namespace Lin

def Weakening (M : CRL) : Prop := ∀ a b, M.le (M.tens a b) a
def Contraction (M : CRL) : Prop := ∀ a, M.le a (M.tens a a)

/-! ## Sugihara RM3 -/

inductive RM where
  | n : RM
  | e : RM
  | p : RM

namespace RM

def rk : RM → Nat
  | n => 0
  | e => 1
  | p => 2

def le (a b : RM) : Prop := Nat.ble (rk a) (rk b) = true

def tens : RM → RM → RM
  | n, n => n
  | n, e => n
  | n, p => n
  | e, n => n
  | e, e => e
  | e, p => p
  | p, n => n
  | p, e => p
  | p, p => p

def lolli : RM → RM → RM
  | n, n => p
  | n, e => p
  | n, p => p
  | e, n => n
  | e, e => e
  | e, p => p
  | p, n => n
  | p, e => n
  | p, p => p

def wth : RM → RM → RM
  | n, n => n
  | n, e => n
  | n, p => n
  | e, n => n
  | e, e => e
  | e, p => e
  | p, n => n
  | p, e => e
  | p, p => p

def pls : RM → RM → RM
  | n, n => n
  | n, e => e
  | n, p => p
  | e, n => e
  | e, e => e
  | e, p => p
  | p, n => p
  | p, e => p
  | p, p => p

def bang : RM → RM
  | n => n
  | e => e
  | p => e

def M : CRL where
  car := RM
  le := le
  le_refl a := by cases a <;> rfl
  le_trans {a b c} := by cases a <;> cases b <;> cases c <;> intro x y <;> first | rfl | exact x | exact y
  one := e
  tens := tens
  lolli := lolli
  wth := wth
  pls := pls
  zero := n
  bang := bang
  tens_mono {a a' b b'} := by
    cases a <;> cases a' <;> cases b <;> cases b' <;> intro x y <;> first | rfl | exact x | exact y
  tens_comm a b := by cases a <;> cases b <;> rfl
  assoc1 a b c := by cases a <;> cases b <;> cases c <;> rfl
  assoc2 a b c := by cases a <;> cases b <;> cases c <;> rfl
  unit1 a := by cases a <;> rfl
  unit2 a := by cases a <;> rfl
  adj {a b c} := by cases a <;> cases b <;> cases c <;> exact ⟨fun x => x, fun x => x⟩
  wth_l a b := by cases a <;> cases b <;> rfl
  wth_r a b := by cases a <;> cases b <;> rfl
  wth_univ {a b c} := by cases a <;> cases b <;> cases c <;> intro x y <;> first | rfl | exact x | exact y
  pls_l a b := by cases a <;> cases b <;> rfl
  pls_r a b := by cases a <;> cases b <;> rfl
  pls_univ {a b c} := by cases a <;> cases b <;> cases c <;> intro x y <;> first | rfl | exact x | exact y
  zero_le a := by cases a <;> rfl
  bang_le a := by cases a <;> rfl
  bang_unit a := by cases a <;> rfl
  bang_dup a := by cases a <;> rfl

theorem tens_n (c : RM) : tens n c = n := by cases c <;> rfl
theorem tens_e (c : RM) : tens e c = c := by cases c <;> rfl

theorem ctx_bang : (l : List RM) → M.ctx (l.map bang) = e ∨ M.ctx (l.map bang) = n
  | [] => Or.inl rfl
  | n :: _ => Or.inr (tens_n _)
  | e :: l => match ctx_bang l with
    | Or.inl q => Or.inl ((tens_e _).trans q)
    | Or.inr q => Or.inr ((tens_e _).trans q)
  | p :: l => match ctx_bang l with
    | Or.inl q => Or.inl ((tens_e _).trans q)
    | Or.inr q => Or.inr ((tens_e _).trans q)

theorem key : (c a : RM) → (c = e ∨ c = n) → le c a → le c (bang a)
  | e, n, _, k => k
  | e, e, _, _ => rfl
  | e, p, _, _ => rfl
  | n, _, _, _ => rfl
  | p, _, q, _ => q.elim (fun r => RM.noConfusion r) (fun r => RM.noConfusion r)

theorem prom : M.PromOK := fun l a k => key _ a (ctx_bang l) k

theorem contraction : Contraction M := fun a => by cases a <;> rfl

theorem not_weakening : ¬ Weakening M := fun h => Bool.noConfusion (h e p)

end RM

/-! ## The square -/

theorem L3_weakening : Weakening L3.M3 := fun a b => by cases a <;> cases b <;> rfl

theorem L3_not_contraction : ¬ Contraction L3.M3 := fun h => Bool.noConfusion (h L3.h)

/-- linear logic does not prove weakening p ⊸ (q ⊸ p) -/
theorem no_weakening : ¬ LD [] (.lolli (.var 0) (.lolli (.var 1) (.var 0))) :=
  fun d => Bool.noConfusion
    (soundness RM.M (fun k => match k with | 0 => RM.e | _ => RM.p) RM.prom d)

/-- every Heyting algebra (as a model) has both weakening and contraction -/
theorem ofHA_weakening (H : HA.{u}) : Weakening (ofHA H) := fun a b => H.meet_l a b
theorem ofHA_contraction (H : HA.{u}) : Contraction (ofHA H) :=
  fun a => H.meet_univ (H.le_refl a) (H.le_refl a)

/-- relevant + affine = intuitionistic: both conditions give a Heyting algebra -/
def relAffToHA (M : CRL.{u}) (w : Weakening M) (c : Contraction M) : HA.{u} := toHA M w c

end Lin

end Found

#print axioms Found.Lin.RM.M
#print axioms Found.Lin.RM.prom
#print axioms Found.Lin.RM.contraction
#print axioms Found.Lin.RM.not_weakening
#print axioms Found.Lin.L3_weakening
#print axioms Found.Lin.L3_not_contraction
#print axioms Found.Lin.no_weakening
#print axioms Found.Lin.ofHA_weakening
#print axioms Found.Lin.ofHA_contraction
#print axioms Found.Lin.relAffToHA

#print axioms: 10 theorems, no axioms.

85.11 Paraconsistent logic

The order dual of any Heyting algebra (in particular of \(\Omega \)) is co-Heyting; there excluded middle holds and explosion fails, while every Heyting algebra is explosive; Priest’s LP refutes \(p,\neg p\models q\) and is classical on two values. \(a\setminus b\le c\iff a\le b\vee c;\quad \top \le a\vee {\sim }a,\ a\wedge {\sim }a\not \le b\).

found/Paracons.lean

/-
  T70. found/Paracons — paraconsistent logic as a condition.

  * Co-Heyting algebras: subtraction a ∖ b with  a ∖ b ≤ c ⟺ a ≤ b ∨ c,
    negation ∼a := ⊤ ∖ a.
  * Condition in the frame: the order dual of any Heyting algebra (in
    particular of Ω) is co-Heyting (dual-intuitionistic = paraconsistent
    reading of the closed-set side of a topos).
  * In every co-Heyting algebra excluded middle holds (⊤ ≤ a ∨ ∼a), while
    explosion a ∧ ∼a ≤ b fails in the three-element chain; in every
    Heyting algebra explosion holds.  So intuitionistic ↔ paraconsistent is
    exactly order duality.
  * Priest's LP: three values, designated {½, 1}: p, ¬p ⊭ q, ⊨ p ∨ ¬p, and on
    two-valued valuations explosion holds (LP = classical + glut value).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Topos


universe u

namespace Found

namespace Para

structure CoHA where
  car : Type u
  le : car → car → Prop
  le_refl : ∀ a, le a a
  le_trans : ∀ {a b c}, le a b → le b c → le a c
  top : car
  bot : car
  meet : car → car → car
  join : car → car → car
  sub : car → car → car
  le_top : ∀ a, le a top
  bot_le : ∀ a, le bot a
  meet_l : ∀ a b, le (meet a b) a
  meet_r : ∀ a b, le (meet a b) b
  meet_univ : ∀ {a b c}, le c a → le c b → le c (meet a b)
  join_l : ∀ a b, le a (join a b)
  join_r : ∀ a b, le b (join a b)
  join_univ : ∀ {a b c}, le a c → le b c → le (join a b) c
  sub_adj : ∀ {a b c}, le (sub a b) c ↔ le a (join b c)

namespace CoHA
variable (K : CoHA)

def neg (a : K.car) : K.car := K.sub K.top a

/-- excluded middle holds in every co-Heyting algebra -/
theorem lem (a : K.car) : K.le K.top (K.join a (K.neg a)) := K.sub_adj.mp (K.le_refl _)

/-- dual non-contradiction fails in general; what holds is ∼∼a ≤ a -/
theorem negneg_le (a : K.car) : K.le (K.neg (K.neg a)) a :=
  K.sub_adj.mpr (K.le_trans (K.lem a) (K.join_univ (K.join_r _ _) (K.join_l _ _)))

end CoHA

/-- the order dual of a Heyting algebra is co-Heyting -/
def opHA (H : HA.{u}) : CoHA.{u} where
  car := H.car
  le a b := H.le b a
  le_refl := H.le_refl
  le_trans h k := H.le_trans k h
  top := H.bot
  bot := H.top
  meet := H.join
  join := H.meet
  sub a b := H.imp b a
  le_top := H.bot_le
  bot_le := H.le_top
  meet_l := H.join_l
  meet_r := H.join_r
  meet_univ h k := H.join_univ h k
  join_l := H.meet_l
  join_r := H.meet_r
  join_univ h k := H.meet_univ h k
  sub_adj := ⟨fun h => H.le_trans (H.meet_univ (H.meet_r _ _) (H.meet_l _ _)) (H.imp_adj.mpr h),
              fun h => H.imp_adj.mp (H.le_trans (H.meet_univ (H.meet_r _ _) (H.meet_l _ _)) h)⟩

/-- the dual of Ω = (Prop, ↔) is co-Heyting: the paraconsistent side of the frame -/
def omegaOp : CoHA := opHA OmegaHA

/-! ## The three-element chain as a co-Heyting algebra -/

inductive T3 where
  | z : T3
  | h : T3
  | o : T3

namespace T3

def rk : T3 → Nat
  | z => 0
  | h => 1
  | o => 2

def le (a b : T3) : Prop := Nat.ble (rk a) (rk b) = true

def meet : T3 → T3 → T3
  | z, z => z
  | z, h => z
  | z, o => z
  | h, z => z
  | h, h => h
  | h, o => h
  | o, z => z
  | o, h => h
  | o, o => o

def join : T3 → T3 → T3
  | z, z => z
  | z, h => h
  | z, o => o
  | h, z => h
  | h, h => h
  | h, o => o
  | o, z => o
  | o, h => o
  | o, o => o

def sub : T3 → T3 → T3
  | z, z => z
  | z, h => z
  | z, o => z
  | h, z => h
  | h, h => z
  | h, o => z
  | o, z => o
  | o, h => o
  | o, o => z

def C3 : CoHA where
  car := T3
  le := le
  le_refl a := by cases a <;> rfl
  le_trans {a b c} := by cases a <;> cases b <;> cases c <;> intro x y <;> first | rfl | exact x | exact y
  top := o
  bot := z
  meet := meet
  join := join
  sub := sub
  le_top a := by cases a <;> rfl
  bot_le a := by cases a <;> rfl
  meet_l a b := by cases a <;> cases b <;> rfl
  meet_r a b := by cases a <;> cases b <;> rfl
  meet_univ {a b c} := by cases a <;> cases b <;> cases c <;> intro x y <;> first | rfl | exact x | exact y
  join_l a b := by cases a <;> cases b <;> rfl
  join_r a b := by cases a <;> cases b <;> rfl
  join_univ {a b c} := by cases a <;> cases b <;> cases c <;> intro x y <;> first | rfl | exact x | exact y
  sub_adj {a b c} := by cases a <;> cases b <;> cases c <;> exact ⟨fun x => x, fun x => x⟩

end T3

/-- explosion fails in a co-Heyting algebra -/
theorem no_explosion : ¬ ∀ a b : T3.C3.car, T3.C3.le (T3.C3.meet a (T3.C3.neg a)) b :=
  fun h => Bool.noConfusion (h T3.h T3.z)

/-- explosion holds in every Heyting algebra -/
theorem explosion_HA (H : HA.{u}) (a b : H.car) : H.le (H.meet a (H.neg a)) b :=
  H.le_trans (H.meet_neg a) (H.bot_le b)

/-! ## Priest's LP -/

inductive LF where
  | var : Nat → LF
  | neg : LF → LF
  | and : LF → LF → LF
  | or : LF → LF → LF

def lneg : T3 → T3
  | .z => .o
  | .h => .h
  | .o => .z

def lval (v : Nat → T3) : LF → T3
  | .var n => v n
  | .neg a => lneg (lval v a)
  | .and a b => T3.meet (lval v a) (lval v b)
  | .or a b => T3.join (lval v a) (lval v b)

def Des (x : T3) : Prop := x ≠ .z

/-- LP entailment: every valuation designating all premises designates the conclusion -/
def Ent (Γ : List LF) (φ : LF) (two : Bool) : Prop :=
  ∀ v : Nat → T3, (two = true → ∀ n, v n ≠ .h) → (∀ ψ, ψ ∈ Γ → Des (lval v ψ)) → Des (lval v φ)

theorem des_or_neg (x : T3) : Des (T3.join x (lneg x)) := by
  cases x <;> exact fun e => T3.noConfusion e

/-- LP validates excluded middle -/
theorem lp_lem (p : LF) : Ent [] (.or p (.neg p)) false := fun v _ _ => des_or_neg (lval v p)

/-- LP is not explosive: p, ¬p ⊭ q -/
theorem lp_no_explosion : ¬ Ent [.var 0, .neg (.var 0)] (.var 1) false :=
  fun h => h (fun n => match n with | 0 => .h | _ => .z) (fun e => Bool.noConfusion e)
    (fun ψ m => by
      cases m with
      | head => exact fun e => T3.noConfusion e
      | tail _ m' => cases m' with
        | head => exact fun e => T3.noConfusion e
        | tail _ m'' => cases m'') rfl

/-- on two-valued valuations, explosion holds: LP = classical + a glut value -/
theorem two_valued_explosion (q : LF) : Ent [.var 0, .neg (.var 0)] q true := by
  intro v two hyp
  have h0 := hyp (.var 0) (List.Mem.head _)
  have h1 := hyp (.neg (.var 0)) (List.Mem.tail _ (List.Mem.head _))
  have hv := two rfl 0
  revert h0 h1 hv
  show Des (v 0) → Des (lneg (v 0)) → v 0 ≠ .h → _
  cases v 0 with
  | z => exact fun a _ _ => (a rfl).elim
  | h => exact fun _ _ c => (c rfl).elim
  | o => exact fun _ b _ => (b rfl).elim

end Para

end Found

#print axioms Found.Para.CoHA.lem
#print axioms Found.Para.CoHA.negneg_le
#print axioms Found.Para.opHA
#print axioms Found.Para.omegaOp
#print axioms Found.Para.T3.C3
#print axioms Found.Para.no_explosion
#print axioms Found.Para.explosion_HA
#print axioms Found.Para.des_or_neg
#print axioms Found.Para.lp_lem
#print axioms Found.Para.lp_no_explosion
#print axioms Found.Para.two_valued_explosion

#print axioms: 11 theorems, no axioms.

85.12 Many-valued and fuzzy logic

Gödel–Dummett logic is intuitionistic logic plus prelinearity, sound in prelinear Heyting algebras and not intuitionistically derivable; integral idempotent residuated models are Heyting, and with involution Boolean; \(\L _3\) is MV and prelinear but not idempotent. \((a\to b)\vee (b\to a)=\top ;\quad \mathrm {MV}+a\le a\otimes a\Rightarrow \text {Boolean}\).

found/ManyValued.lean

/-
  T71. found/ManyValued — many-valued and fuzzy logics as conditions.

  * Prelinearity (a → b) ∨ (b → a) = ⊤ on a Heyting algebra: Gödel–Dummett
    logic = intuitionistic logic + prelinearity, sound in prelinear Heyting
    algebras (e.g. every chain, the three-element one).
  * Intuitionistic logic does not prove prelinearity (five-element algebra
    0 < a, b < a ∨ b < 1).
  * Residuated models (T68): integral + idempotent ⊗ is a Heyting algebra;
    adding involution ¬¬a = a (MV) gives a Boolean algebra: MV + idempotent
    = classical.  Łukasiewicz Ł3 is MV, integral, prelinear, not idempotent.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Relevant
import found.Classical


universe u

namespace Found

namespace MV

open Prp

/-! ## Gödel–Dummett: prelinearity -/

def Prelinear (H : HA.{u}) : Prop := ∀ a b, H.le H.top (H.join (H.imp a b) (H.imp b a))

def prelin (p q : Form) : Form := .or (.imp p q) (.imp q p)

def PL (Γ : Form → Prop) : Form → Prop := fun x => Γ x ∨ ∃ p q, x = prelin p q

/-- Gödel–Dummett derivability -/
def GD (Γ : Form → Prop) (φ : Form) : Prop := PD true (PL Γ) φ

theorem gd_sound (H : HA.{u}) (hP : Prelinear H) {φ : Form} (d : GD (fun _ => False) φ)
    (v : Nat → H.car) : H.le H.top (interp H v H.bot φ) :=
  soundness H d v H.bot (fun _ => H.bot_le) H.top (fun _ k => k.elim (fun g => g.elim)
    (fun ⟨_, _, q⟩ => q ▸ hP _ _))

theorem three_prelinear : Prelinear Three.HA3 := fun a b => by cases a <;> cases b <;> exact trivial

/-- the five-element Heyting algebra 0 < a, b < c < 1 -/
inductive F5 where
  | zz : F5
  | a : F5
  | b : F5
  | c : F5
  | one : F5

namespace F5

def le : F5 → F5 → Prop
  | zz, zz => True
  | zz, a => True
  | zz, b => True
  | zz, c => True
  | zz, one => True
  | a, zz => False
  | a, a => True
  | a, b => False
  | a, c => True
  | a, one => True
  | b, zz => False
  | b, a => False
  | b, b => True
  | b, c => True
  | b, one => True
  | c, zz => False
  | c, a => False
  | c, b => False
  | c, c => True
  | c, one => True
  | one, zz => False
  | one, a => False
  | one, b => False
  | one, c => False
  | one, one => True

def meet : F5 → F5 → F5
  | zz, zz => zz
  | zz, a => zz
  | zz, b => zz
  | zz, c => zz
  | zz, one => zz
  | a, zz => zz
  | a, a => a
  | a, b => zz
  | a, c => a
  | a, one => a
  | b, zz => zz
  | b, a => zz
  | b, b => b
  | b, c => b
  | b, one => b
  | c, zz => zz
  | c, a => a
  | c, b => b
  | c, c => c
  | c, one => c
  | one, zz => zz
  | one, a => a
  | one, b => b
  | one, c => c
  | one, one => one

def join : F5 → F5 → F5
  | zz, zz => zz
  | zz, a => a
  | zz, b => b
  | zz, c => c
  | zz, one => one
  | a, zz => a
  | a, a => a
  | a, b => c
  | a, c => c
  | a, one => one
  | b, zz => b
  | b, a => c
  | b, b => b
  | b, c => c
  | b, one => one
  | c, zz => c
  | c, a => c
  | c, b => c
  | c, c => c
  | c, one => one
  | one, zz => one
  | one, a => one
  | one, b => one
  | one, c => one
  | one, one => one

def imp : F5 → F5 → F5
  | zz, zz => one
  | zz, a => one
  | zz, b => one
  | zz, c => one
  | zz, one => one
  | a, zz => b
  | a, a => one
  | a, b => b
  | a, c => one
  | a, one => one
  | b, zz => a
  | b, a => a
  | b, b => one
  | b, c => one
  | b, one => one
  | c, zz => zz
  | c, a => a
  | c, b => b
  | c, c => one
  | c, one => one
  | one, zz => zz
  | one, a => a
  | one, b => b
  | one, c => c
  | one, one => one

def HA5 : HA.{0} where
  car := F5
  le := le
  le_refl x := by cases x <;> exact trivial
  le_trans {x y z} := by
    cases x <;> cases y <;> cases z <;> intro p q <;> first | exact trivial | exact p.elim | exact q.elim
  top := one
  bot := zz
  meet := meet
  join := join
  imp := imp
  le_top x := by cases x <;> exact trivial
  bot_le x := by cases x <;> exact trivial
  meet_l x y := by cases x <;> cases y <;> exact trivial
  meet_r x y := by cases x <;> cases y <;> exact trivial
  meet_univ {x y z} := by
    cases x <;> cases y <;> cases z <;> intro p q <;> first | exact trivial | exact p.elim | exact q.elim
  join_l x y := by cases x <;> cases y <;> exact trivial
  join_r x y := by cases x <;> cases y <;> exact trivial
  join_univ {x y z} := by
    cases x <;> cases y <;> cases z <;> intro p q <;> first | exact trivial | exact p.elim | exact q.elim
  imp_adj {x y z} := by cases x <;> cases y <;> cases z <;> exact ⟨fun p => p, fun p => p⟩

end F5

theorem f5_not_prelinear : ¬ Prelinear F5.HA5 := fun h => h F5.a F5.b

/-- intuitionistic logic does not prove prelinearity -/
theorem int_not_prelin : ¬ PD true (fun _ => False) (prelin (.var 0) (.var 1)) :=
  fun d => valid F5.HA5 d (fun n => match n with | 0 => F5.a | _ => F5.b) F5.zz
    (fun _ x => by cases x <;> exact trivial)

/-- Gödel–Dummett proves prelinearity -/
theorem gd_prelin (p q : Form) : GD (fun _ => False) (prelin p q) := .hyp (Or.inr ⟨p, q, rfl⟩)

/-! ## Residuated side: MV, idempotence, Boolean -/

open Lin

def Integral (M : CRL) : Prop := ∀ a, M.le a M.one
def Idempotent (M : CRL) : Prop := ∀ a, M.le a (M.tens a a)
def Involutive (M : CRL) : Prop := ∀ a, M.le (M.lolli (M.lolli a M.zero) M.zero) a

theorem integral_weakening (M : CRL) (hI : Integral M) : Weakening M :=
  fun a b => M.le_trans (M.tens_mono (M.le_refl a) (hI b))
    (M.le_trans (M.tens_comm _ _) (M.unit1 a))

/-- integral + idempotent: a Heyting algebra (Gödel side) -/
def toHA' (M : CRL.{u}) (hI : Integral M) (hE : Idempotent M) : HA.{u} :=
  toHA M (integral_weakening M hI) hE

/-- MV + idempotent = Boolean: the classical corner -/
theorem mv_idem_boolean (M : CRL) (hI : Integral M) (hE : Idempotent M) (hV : Involutive M) :
    Boolean (toHA' M hI hE) := hV

theorem L3_integral : Integral L3.M3 := fun a => by cases a <;> rfl
theorem L3_involutive : Involutive L3.M3 := fun a => by cases a <;> rfl
theorem L3_not_idempotent : ¬ Idempotent L3.M3 := L3_not_contraction

/-- prelinearity in a residuated model: 1 ≤ (a ⊸ b) ∨ (b ⊸ a) -/
def RPrelinear (M : CRL) : Prop := ∀ a b, M.le M.one (M.pls (M.lolli a b) (M.lolli b a))

theorem L3_prelinear : RPrelinear L3.M3 := fun a b => by cases a <;> cases b <;> rfl

end MV

end Found

#print axioms Found.MV.gd_sound
#print axioms Found.MV.three_prelinear
#print axioms Found.MV.F5.HA5
#print axioms Found.MV.f5_not_prelinear
#print axioms Found.MV.int_not_prelin
#print axioms Found.MV.gd_prelin
#print axioms Found.MV.integral_weakening
#print axioms Found.MV.toHA'
#print axioms Found.MV.mv_idem_boolean
#print axioms Found.MV.L3_integral
#print axioms Found.MV.L3_involutive
#print axioms Found.MV.L3_not_idempotent
#print axioms Found.MV.L3_prelinear

#print axioms: 13 theorems, no axioms.

85.13 Tense and epistemic logic

Tense operators form Galois adjunctions \(P\dashv G\), \(F\dashv H\) on the predicate lattice, giving the tense axioms; knowledge on equivalence frames is S5, and common knowledge is the greatest fixed point of \(\psi \mapsto E(\varphi \wedge \psi )\). \(P\varphi \le \psi \iff \varphi \le G\psi ;\quad C\varphi =\nu \psi .\,E(\varphi \wedge \psi )\).

found/TemporalEpistemic.lean

/-
  T72. found/TemporalEpistemic — tense and epistemic logic as operators on
  the predicate lattice Ω^W of a frame.

  * Tense: G ψ (always in the future), H ψ (always in the past), F, P their
    duals.  Condition: they come in Galois adjunctions  P ⊣ G  and  F ⊣ H
    (the same adjunction ∃_f ⊣ f* ⊣ ∀_f pattern as quantifiers, for the
    relation R); hence φ → G P φ, φ → H F φ, and monotonicity.
  * Epistemic S5_n: knowledge K_i on equivalence frames satisfies T, 4, 5;
    everybody-knows E, and common knowledge C φ is the greatest fixed point
    of ψ ↦ E (φ ∧ ψ) (post-fixed, and above every post-fixed point).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Modal

namespace Found

namespace Tense

variable {W : Type} (R : W → W → Prop)

def G (ψ : W → Prop) : W → Prop := fun w => ∀ v, R w v → ψ v
def H (ψ : W → Prop) : W → Prop := fun w => ∀ v, R v w → ψ v
def F (φ : W → Prop) : W → Prop := fun w => ∃ v, R w v ∧ φ v
def P (φ : W → Prop) : W → Prop := fun w => ∃ v, R v w ∧ φ v

def Le (φ ψ : W → Prop) : Prop := ∀ w, φ w → ψ w

/-- P ⊣ G -/
theorem P_adj_G (φ ψ : W → Prop) : Le (P R φ) ψ ↔ Le φ (G R ψ) :=
  ⟨fun h w x v r => h v ⟨w, r, x⟩, fun h w ⟨v, r, x⟩ => h v x w r⟩

/-- F ⊣ H -/
theorem F_adj_H (φ ψ : W → Prop) : Le (F R φ) ψ ↔ Le φ (H R ψ) :=
  ⟨fun h w x v r => h v ⟨w, r, x⟩, fun h w ⟨v, r, x⟩ => h v x w r⟩

/-- tense axiom φ → G P φ (unit of P ⊣ G) -/
theorem unit_GP (φ : W → Prop) : Le φ (G R (P R φ)) := (P_adj_G R φ (P R φ)).mp (fun _ x => x)

/-- tense axiom φ → H F φ (unit of F ⊣ H) -/
theorem unit_HF (φ : W → Prop) : Le φ (H R (F R φ)) := (F_adj_H R φ (F R φ)).mp (fun _ x => x)

/-- counits: P G ψ → ψ and F H ψ → ψ -/
theorem counit_PG (ψ : W → Prop) : Le (P R (G R ψ)) ψ := (P_adj_G R (G R ψ) ψ).mpr (fun _ x => x)
theorem counit_FH (ψ : W → Prop) : Le (F R (H R ψ)) ψ := (F_adj_H R (H R ψ) ψ).mpr (fun _ x => x)

theorem G_mono {φ ψ : W → Prop} (h : Le φ ψ) : Le (G R φ) (G R ψ) := fun _ x v r => h v (x v r)

/-- G preserves meets (axiom K) -/
theorem G_and (φ ψ : W → Prop) : Le (fun w => G R φ w ∧ G R ψ w) (G R (fun w => φ w ∧ ψ w)) :=
  fun _ x v r => ⟨x.1 v r, x.2 v r⟩

end Tense

namespace Epist

variable {W A : Type} (R : A → W → W → Prop)

def K (i : A) (φ : W → Prop) : W → Prop := fun w => ∀ v, R i w v → φ v

def E (φ : W → Prop) : W → Prop := fun w => ∀ i v, R i w v → φ v

inductive Reach : W → W → Prop where
  | one {i w v} : R i w v → Reach w v
  | step {i w u v} : R i w u → Reach u v → Reach w v

def C (φ : W → Prop) : W → Prop := fun w => ∀ v, Reach R w v → φ v

/-- knowledge on equivalence frames: T, 4, 5 -/
theorem K_T (i : A) (hr : Modal.Refl (R i)) (φ : W → Prop) (w : W) : K R i φ w → φ w :=
  fun h => h w (hr w)

theorem K_4 (i : A) (ht : Modal.Trans (R i)) (φ : W → Prop) (w : W) : K R i φ w → K R i (K R i φ) w :=
  fun h v r u r' => h u (ht w v u r r')

theorem K_5 (i : A) (he : Modal.Eucl (R i)) (φ : W → Prop) (w : W) :
    (∃ v, R i w v ∧ φ v) → K R i (fun u => ∃ v, R i u v ∧ φ v) w :=
  fun ⟨v, r, x⟩ u r' => ⟨v, he w u v r' r, x⟩

/-- common knowledge is a post-fixed point of ψ ↦ E (φ ∧ ψ) -/
theorem C_fix (φ : W → Prop) (w : W) : C R φ w → E R (fun v => φ v ∧ C R φ v) w :=
  fun h _ v r => ⟨h v (.one r), fun u k => h u (.step r k)⟩

/-- and it is the greatest one (induction rule) -/
theorem C_greatest (φ ψ : W → Prop) (hψ : ∀ w, ψ w → E R (fun v => φ v ∧ ψ v) w) :
    ∀ w, ψ w → C R φ w := by
  intro w x v k
  induction k with
  | one r => exact (hψ _ x _ _ r).1
  | step r _ ih => exact ih (hψ _ x _ _ r).2

/-- C φ implies everybody knows φ -/
theorem C_E (φ : W → Prop) (w : W) : C R φ w → E R φ w := fun h _ v r => h v (.one r)

end Epist

end Found

#print axioms Found.Tense.P_adj_G
#print axioms Found.Tense.F_adj_H
#print axioms Found.Tense.unit_GP
#print axioms Found.Tense.unit_HF
#print axioms Found.Tense.counit_PG
#print axioms Found.Tense.counit_FH
#print axioms Found.Tense.G_mono
#print axioms Found.Tense.G_and
#print axioms Found.Epist.K_T
#print axioms Found.Epist.K_4
#print axioms Found.Epist.K_5
#print axioms Found.Epist.C_fix
#print axioms Found.Epist.C_greatest
#print axioms Found.Epist.C_E

#print axioms: 14 theorems, no axioms.

85.14 Quantifiers as adjoints and higher-order logic

On respecting predicates of setoids reindexing has both adjoints, satisfying Frobenius reciprocity and Beck–Chevalley for projections; equality is \(\exists \) along the diagonal; higher-order quantification is \(\forall \) along the projection from the power object. \(\exists _f\varphi \le \psi \iff \varphi \le f^*\psi \quad f^*\psi \le \varphi \iff \psi \le \forall _f\varphi \).

found/HigherOrder.lean

/-
  T73. found/HigherOrder — quantifiers as adjoints (Lawvere), in the setoid
  topos.

  * For a map f : X → Y of setoids: reindexing f* on Sub(Y) = Pred Y has a
    left adjoint ∃_f and a right adjoint ∀_f:  ∃_f ⊣ f* ⊣ ∀_f.
  * Frobenius reciprocity ∃_f (φ ∧ f* ψ) = ∃_f φ ∧ ψ, and Beck–Chevalley
    for product projections.
  * Equality is ∃ along the diagonal: ∃_Δ ⊤ = the setoid relation.
  * Higher order: predicates on X are the points of the power object
    P X = X ⇒ Ω (T63), and quantifying over P X is ∀/∃ along the
    projection P X × Z → Z; first order = the same with X a base sort.

  Lean 4 core only, hand-written proofs, no axioms.

  CIC dependence: higher-order quantification = impredicative Prop (P X = X ⇒ Prop).
-/
import found.Topos

namespace Found

namespace HO

variable {X Y : Setd.{0}}

def LeP (φ ψ : Pred X) : Prop := ∀ x, φ.p x → ψ.p x

def pull (f : SHom X Y) (ψ : Pred Y) : Pred X :=
  ⟨fun x => ψ.p (f.fn x), fun e h => ψ.resp (f.resp e) h⟩

def exF (f : SHom X Y) (φ : Pred X) : Pred Y :=
  ⟨fun y => ∃ x, φ.p x ∧ Y.eqv (f.fn x) y, fun e ⟨x, h, k⟩ => ⟨x, h, Y.trans k e⟩⟩

def allF (f : SHom X Y) (φ : Pred X) : Pred Y :=
  ⟨fun y => ∀ x, Y.eqv (f.fn x) y → φ.p x, fun e h x k => h x (Y.trans k (Y.symm e))⟩

/-- ∃_f ⊣ f* -/
theorem ex_adj (f : SHom X Y) (φ : Pred X) (ψ : Pred Y) :
    LeP (exF f φ) ψ ↔ LeP φ (pull f ψ) :=
  ⟨fun h x a => h (f.fn x) ⟨x, a, Y.refl _⟩,
   fun h _ ⟨x, a, k⟩ => ψ.resp k (h x a)⟩

/-- f* ⊣ ∀_f -/
theorem all_adj (f : SHom X Y) (ψ : Pred Y) (φ : Pred X) :
    LeP (pull f ψ) φ ↔ LeP ψ (allF f φ) :=
  ⟨fun h _ b x k => h x (ψ.resp (Y.symm k) b),
   fun h x b => h (f.fn x) b x (Y.refl _)⟩

/-- Frobenius reciprocity -/
theorem frobenius (f : SHom X Y) (φ : Pred X) (ψ : Pred Y) (y : Y.car) :
    (∃ x, (φ.p x ∧ ψ.p (f.fn x)) ∧ Y.eqv (f.fn x) y) ↔ ((exF f φ).p y ∧ ψ.p y) :=
  ⟨fun ⟨x, ⟨a, b⟩, k⟩ => ⟨⟨x, a, k⟩, ψ.resp k b⟩,
   fun ⟨⟨x, a, k⟩, b⟩ => ⟨x, ⟨a, ψ.resp (Y.symm k) b⟩, k⟩⟩

/-! ## Beck–Chevalley for projections -/

section BC
variable {Z Z' : Setd.{0}}

def proj (Z X : Setd.{0}) : SHom (prodS Z X) Z := ⟨Prod.fst, fun h => h.1⟩

def gx (g : SHom Z' Z) (X : Setd.{0}) : SHom (prodS Z' X) (prodS Z X) :=
  ⟨fun p => (g.fn p.1, p.2), fun h => ⟨g.resp h.1, h.2⟩⟩

/-- g* ∃_π φ = ∃_π' (g × 1)* φ -/
theorem beck_chevalley (g : SHom Z' Z) (φ : Pred (prodS Z X)) (z' : Z'.car) :
    (pull g (exF (proj Z X) φ)).p z' ↔ (exF (proj Z' X) (pull (gx g X) φ)).p z' :=
  ⟨fun ⟨p, a, k⟩ => ⟨(z', p.2), φ.resp (x := p) (y := (g.fn z', p.2)) ⟨k, X.refl _⟩ a, Z'.refl z'⟩,
   fun ⟨q, a, k⟩ => ⟨(g.fn q.1, q.2), a, g.resp k⟩⟩

end BC

/-! ## Equality as ∃ along the diagonal -/

def diag (X : Setd.{0}) : SHom X (prodS X X) := ⟨fun x => (x, x), fun h => ⟨h, h⟩⟩

def topP (X : Setd.{0}) : Pred X := ⟨fun _ => True, fun _ _ => trivial⟩

theorem eq_is_ex_diag (x y : X.car) : (exF (diag X) (topP X)).p (x, y) ↔ X.eqv x y :=
  ⟨fun ⟨_, _, k⟩ => X.trans (X.symm k.1) k.2, fun e => ⟨x, trivial, X.refl x, e⟩⟩

/-! ## Higher order: predicates are points of P X -/

/-- every respecting predicate is named by a point of the power object -/
def name (φ : Pred X) : (powerS X).car := chi φ

theorem name_mem (φ : Pred X) (x : X.car) : (name φ).fn x ↔ φ.p x := Iff.rfl

/-- second-order comprehension: for every formula on Z × X there is a
  `Z`-indexed family of points of P X naming it -/
theorem comprehension {Z : Setd.{0}} (R : SHom (prodS Z X) OmegaS) (z : Z.car) (x : X.car) :
    ((setdCCC.curry R).fn z).fn x ↔ R.fn (z, x) := Iff.rfl

/-- quantifying over predicates = ∀ along the projection P X × Z → Z -/
theorem all_over_power {Z : Setd.{0}} (φ : Pred (prodS Z (powerS X))) (z : Z.car) :
    (allF (proj Z (powerS X)) φ).p z ↔ ∀ P : (powerS X).car, φ.p (z, P) :=
  ⟨fun h P => h (z, P) (Z.refl z), fun h q k => φ.resp (x := (z, q.2)) (y := q) ⟨Z.symm k, (powerS X).refl q.2⟩ (h q.2)⟩

end HO

end Found

#print axioms Found.HO.ex_adj
#print axioms Found.HO.all_adj
#print axioms Found.HO.frobenius
#print axioms Found.HO.beck_chevalley
#print axioms Found.HO.eq_is_ex_diag
#print axioms Found.HO.name_mem
#print axioms Found.HO.comprehension
#print axioms Found.HO.all_over_power

#print axioms: 8 theorems, no axioms.

85.15 Natural deduction and normalization

Every natural deduction derivation in the \(\to ,\wedge \) fragment has a normal derivation of the same formula, by evaluation in the Kripke model over contexts; there is no closed derivation of an atom. \(\mathrm {nf}:\mathrm {Tm}\,\Gamma \,A\to \mathrm {Nf}\,\Gamma \,A,\quad \mathrm {Tm}\,[\,]\,p=\varnothing \).

found/ND.lean

/-
  T74. found/ND — natural deduction for →, ∧ and its normalization.

  * Derivations are intrinsically typed terms (de Bruijn): `Tm Γ A`.
  * Normal derivations: `Nf` (introductions) over `Ne` (eliminations on a
    hypothesis); only atoms are switched from Ne to Nf (η-long).
  * Normalization by evaluation into the Kripke model of contexts and
    order-preserving embeddings (the presheaf topos over contexts):
    every derivation has a normal derivation of the same formula.
    Everything is structural recursion: no termination_by, no axioms.
  * Consequences: no normal (hence no) closed derivation of an atom
    (consistency), and normal closed derivations end in an introduction.

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace ND

inductive Ty where
  | base : Nat → Ty
  | arr : Ty → Ty → Ty
  | prod : Ty → Ty → Ty

inductive Var : List Ty → Ty → Type where
  | z {Γ A} : Var (A :: Γ) A
  | s {Γ A B} : Var Γ A → Var (B :: Γ) A

inductive Tm : List Ty → Ty → Type where
  | var {Γ A} : Var Γ A → Tm Γ A
  | lam {Γ A B} : Tm (A :: Γ) B → Tm Γ (.arr A B)
  | app {Γ A B} : Tm Γ (.arr A B) → Tm Γ A → Tm Γ B
  | pair {Γ A B} : Tm Γ A → Tm Γ B → Tm Γ (.prod A B)
  | fst {Γ A B} : Tm Γ (.prod A B) → Tm Γ A
  | snd {Γ A B} : Tm Γ (.prod A B) → Tm Γ B

mutual
inductive Ne : List Ty → Ty → Type where
  | var {Γ A} : Var Γ A → Ne Γ A
  | app {Γ A B} : Ne Γ (.arr A B) → Nf Γ A → Ne Γ B
  | fst {Γ A B} : Ne Γ (.prod A B) → Ne Γ A
  | snd {Γ A B} : Ne Γ (.prod A B) → Ne Γ B
inductive Nf : List Ty → Ty → Type where
  | ne {Γ n} : Ne Γ (.base n) → Nf Γ (.base n)
  | lam {Γ A B} : Nf (A :: Γ) B → Nf Γ (.arr A B)
  | pair {Γ A B} : Nf Γ A → Nf Γ B → Nf Γ (.prod A B)
end

/-! ## Order-preserving embeddings (weakenings) -/

inductive Wk : List Ty → List Ty → Type where
  | nil : Wk [] []
  | skip {Γ Δ A} : Wk Γ Δ → Wk (A :: Γ) Δ
  | keep {Γ Δ A} : Wk Γ Δ → Wk (A :: Γ) (A :: Δ)

def Wk.id : (Γ : List Ty) → Wk Γ Γ
  | [] => .nil
  | _ :: Γ => .keep (Wk.id Γ)

def Wk.comp {Γ Δ Θ : List Ty} : Wk Θ Δ → Wk Δ Γ → Wk Θ Γ
  | .nil, w => w
  | .skip w', w => .skip (Wk.comp w' w)
  | .keep w', .skip w => .skip (Wk.comp w' w)
  | .keep w', .keep w => .keep (Wk.comp w' w)

def renV {Γ Δ : List Ty} {A : Ty} : Wk Δ Γ → Var Γ A → Var Δ A
  | .skip w, v => .s (renV w v)
  | .keep _, .z => .z
  | .keep w, .s v => .s (renV w v)

mutual
def renNe {Γ Δ : List Ty} {A : Ty} (w : Wk Δ Γ) : Ne Γ A → Ne Δ A
  | .var v => .var (renV w v)
  | .app n m => .app (renNe w n) (renNf w m)
  | .fst n => .fst (renNe w n)
  | .snd n => .snd (renNe w n)
def renNf {Γ Δ : List Ty} {A : Ty} (w : Wk Δ Γ) : Nf Γ A → Nf Δ A
  | .ne n => .ne (renNe w n)
  | .lam m => .lam (renNf (.keep w) m)
  | .pair a b => .pair (renNf w a) (renNf w b)
end

/-! ## The Kripke model -/

def Sem : Ty → List Ty → Type
  | .base n, Γ => Nf Γ (.base n)
  | .arr A B, Γ => (Δ : List Ty) → Wk Δ Γ → Sem A Δ → Sem B Δ
  | .prod A B, Γ => Sem A Γ × Sem B Γ

def wkSem : (A : Ty) → {Γ Δ : List Ty} → Wk Δ Γ → Sem A Γ → Sem A Δ
  | .base _, _, _, w, x => renNf w x
  | .arr _ _, _, _, w, f => fun Θ w' a => f Θ (Wk.comp w' w) a
  | .prod A B, _, _, w, p => (wkSem A w p.1, wkSem B w p.2)

/-- reflection and reification, together by recursion on the formula -/
def rr : (A : Ty) → ((Γ : List Ty) → Ne Γ A → Sem A Γ) × ((Γ : List Ty) → Sem A Γ → Nf Γ A)
  | .base _ => (fun _ n => .ne n, fun _ x => x)
  | .arr A B =>
    (fun _ n Δ w a => (rr B).1 Δ (.app (renNe w n) ((rr A).2 Δ a)),
     fun Γ f => .lam ((rr B).2 (A :: Γ) (f (A :: Γ) (.skip (Wk.id Γ)) ((rr A).1 (A :: Γ) (.var .z)))))
  | .prod A B =>
    (fun Γ n => ((rr A).1 Γ (.fst n), (rr B).1 Γ (.snd n)),
     fun Γ p => .pair ((rr A).2 Γ p.1) ((rr B).2 Γ p.2))

def reflect (A : Ty) {Γ : List Ty} (n : Ne Γ A) : Sem A Γ := (rr A).1 Γ n
def reify (A : Ty) {Γ : List Ty} (x : Sem A Γ) : Nf Γ A := (rr A).2 Γ x

def Env (Δ Γ : List Ty) : Type := (A : Ty) → Var Γ A → Sem A Δ

def Env.ext {Δ Γ : List Ty} {A : Ty} (ρ : Env Δ Γ) (a : Sem A Δ) : Env Δ (A :: Γ) :=
  fun _ v => match v with
    | .z => a
    | .s v => ρ _ v

def Env.wk {Δ Θ Γ : List Ty} (w : Wk Θ Δ) (ρ : Env Δ Γ) : Env Θ Γ := fun B v => wkSem B w (ρ B v)

def eval {Γ : List Ty} {A : Ty} : Tm Γ A → {Δ : List Ty} → Env Δ Γ → Sem A Δ
  | .var v, _, ρ => ρ _ v
  | .lam t, _, ρ => fun _ w a => eval t ((ρ.wk w).ext a)
  | .app t u, Δ, ρ => (eval t ρ) Δ (Wk.id Δ) (eval u ρ)
  | .pair t u, _, ρ => (eval t ρ, eval u ρ)
  | .fst t, _, ρ => (eval t ρ).1
  | .snd t, _, ρ => (eval t ρ).2

/-- normalization: every derivation has a normal derivation of the same formula -/
def nf {Γ : List Ty} {A : Ty} (t : Tm Γ A) : Nf Γ A :=
  reify A (eval t (fun B v => reflect B (.var v)))

/-! ## Consequences -/

theorem ne_empty : {Γ : List Ty} → {A : Ty} → Ne Γ A → Γ = [] → False
  | _, _, .var v, e => by cases e; cases v
  | _, _, .app n _, e => ne_empty n e
  | _, _, .fst n, e => ne_empty n e
  | _, _, .snd n, e => ne_empty n e

theorem no_closed_ne {A : Ty} (n : Ne [] A) : False := ne_empty n rfl

/-- consistency: no closed derivation of an atom -/
theorem no_closed_atom (n : Nat) (t : Tm [] (.base n)) : False :=
  match nf t with
  | .ne m => no_closed_ne m

/-- closed normal derivations of an implication end with →I -/
theorem arr_nf {Γ : List Ty} {A B : Ty} (x : Nf Γ (.arr A B)) : ∃ m : Nf (A :: Γ) B, x = .lam m :=
  match x with
  | .lam m => ⟨m, rfl⟩

theorem closed_arr_intro {A B : Ty} (t : Tm [] (.arr A B)) : ∃ m : Nf [A] B, nf t = .lam m :=
  arr_nf (nf t)

end ND

end Found

#print axioms Found.ND.Wk.comp
#print axioms Found.ND.renNe
#print axioms Found.ND.wkSem
#print axioms Found.ND.rr
#print axioms Found.ND.eval
#print axioms Found.ND.nf
#print axioms Found.ND.ne_empty
#print axioms Found.ND.no_closed_ne
#print axioms Found.ND.no_closed_atom
#print axioms Found.ND.closed_arr_intro

#print axioms: 10 theorems, no axioms.

85.16 Sequent calculus and cut elimination

Sequent derivations with cut translate into natural deduction, normal natural deductions translate into cut-free sequent derivations; hence cut elimination for LJ in the \(\to ,\wedge \) fragment, by structural recursion only. \(\mathrm {LJ}^{+\mathrm {cut}}\to \mathrm {ND}\xrightarrow {\mathrm {nf}}\mathrm {Nf}\to \mathrm {LJ}^{-\mathrm {cut}}\).

found/Sequent.lean

/-
  T75. found/Sequent — the sequent calculus LJ (→, ∧) and cut elimination.

  * `LJ c Γ A`: sequents with left rules acting on a hypothesis; the cut
    rule is available only when `c = true`.
  * LJ → ND: every sequent derivation (with cuts) is a natural deduction
    term (cut and left rules become β-redexes).
  * ND normal forms → cut-free LJ: Nf/Ne translate into cut-free sequent
    derivations (eliminations on a hypothesis become left rules).
  * Cut elimination: LJ with cut → ND → normalize (T74) → cut-free LJ.
    Hence ND, LJ and cut-free LJ prove the same sequents; no cut-free (so no)
    derivation of an atom from no hypotheses.

  Lean 4 core only, hand-written, structural recursion, no axioms.
-/
import found.ND

namespace Found

namespace ND

inductive LJ (c : Bool) : List Ty → Ty → Type where
  | ax {Γ A} : Var Γ A → LJ c Γ A
  | impR {Γ A B} : LJ c (A :: Γ) B → LJ c Γ (.arr A B)
  | impL {Γ A B C} : Var Γ (.arr A B) → LJ c Γ A → LJ c (B :: Γ) C → LJ c Γ C
  | andR {Γ A B} : LJ c Γ A → LJ c Γ B → LJ c Γ (.prod A B)
  | andL {Γ A B C} : Var Γ (.prod A B) → LJ c (A :: B :: Γ) C → LJ c Γ C
  | cut {Γ A C} : c = true → LJ c Γ A → LJ c (A :: Γ) C → LJ c Γ C

/-! ## LJ → ND -/

def toTm {c : Bool} {Γ : List Ty} {A : Ty} : LJ c Γ A → Tm Γ A
  | .ax v => .var v
  | .impR d => .lam (toTm d)
  | .impL v d e => .app (.lam (toTm e)) (.app (.var v) (toTm d))
  | .andR d e => .pair (toTm d) (toTm e)
  | .andL v e => .app (.app (.lam (.lam (toTm e))) (.snd (.var v))) (.fst (.var v))
  | .cut _ d e => .app (.lam (toTm e)) (toTm d)

/-! ## renaming of sequent derivations -/

def Ren (Γ Δ : List Ty) : Type := (X : Ty) → Var Γ X → Var Δ X

def Ren.lift {Γ Δ : List Ty} {A : Ty} (r : Ren Γ Δ) : Ren (A :: Γ) (A :: Δ) :=
  fun _ v => match v with
    | .z => .z
    | .s v => .s (r _ v)

def renLJ {c : Bool} {Γ Δ : List Ty} {C : Ty} (r : Ren Γ Δ) : LJ c Γ C → LJ c Δ C
  | .ax v => .ax (r _ v)
  | .impR d => .impR (renLJ r.lift d)
  | .impL v d e => .impL (r _ v) (renLJ r d) (renLJ r.lift e)
  | .andR d e => .andR (renLJ r d) (renLJ r e)
  | .andL v e => .andL (r _ v) (renLJ r.lift.lift e)
  | .cut h d e => .cut h (renLJ r d) (renLJ r.lift e)

def wk1 {Γ : List Ty} {B : Ty} : Ren Γ (B :: Γ) := fun _ v => .s v

/-- use an existing hypothesis for the first one -/
def contractTo {Γ : List Ty} {A : Ty} (v : Var Γ A) : Ren (A :: Γ) Γ :=
  fun _ u => match u with
    | .z => v
    | .s u => u

def renFst {Γ : List Ty} {A B : Ty} : Ren (A :: Γ) (A :: B :: Ty.prod A B :: Γ) :=
  fun _ u => match u with
    | .z => .z
    | .s u => .s (.s (.s u))

def renSnd {Γ : List Ty} {A B : Ty} : Ren (B :: Γ) (A :: B :: Ty.prod A B :: Γ) :=
  fun _ u => match u with
    | .z => .s .z
    | .s u => .s (.s (.s u))

/-! ## normal forms → cut-free LJ -/

mutual
def nfLJ {Γ : List Ty} {A : Ty} : Nf Γ A → LJ false Γ A
  | .ne n => neLJ n _ (.ax .z)
  | .lam m => .impR (nfLJ m)
  | .pair a b => .andR (nfLJ a) (nfLJ b)
def neLJ {Γ : List Ty} {A : Ty} : Ne Γ A → (C : Ty) → LJ false (A :: Γ) C → LJ false Γ C
  | .var v, _, k => renLJ (contractTo v) k
  | .app n m, _, k => neLJ n _ (.impL .z (renLJ wk1 (nfLJ m)) (renLJ wk1.lift k))
  | .fst n, _, k => neLJ n _ (.andL .z (renLJ renFst k))
  | .snd n, _, k => neLJ n _ (.andL .z (renLJ renSnd k))
end

/-- cut elimination -/
def cutElim {Γ : List Ty} {A : Ty} (d : LJ true Γ A) : LJ false Γ A := nfLJ (nf (toTm d))

/-- cut-free derivations are derivations -/
def withCut {Γ : List Ty} {A : Ty} : LJ false Γ A → LJ true Γ A
  | .ax v => .ax v
  | .impR d => .impR (withCut d)
  | .impL v d e => .impL v (withCut d) (withCut e)
  | .andR d e => .andR (withCut d) (withCut e)
  | .andL v e => .andL v (withCut e)
  | .cut h _ _ => Bool.noConfusion h

/-- ND → cut-free LJ (so ND, LJ, cut-free LJ prove the same sequents) -/
def ndToLJ {Γ : List Ty} {A : Ty} (t : Tm Γ A) : LJ false Γ A := nfLJ (nf t)

/-- no cut-free derivation of an atom from no hypotheses (subformula argument) -/
theorem cutfree_no_atom (n : Nat) (d : LJ false [] (.base n)) : False :=
  match d with
  | .ax v => nomatch v
  | .impL v _ _ => nomatch v
  | .andL v _ => nomatch v
  | .cut h _ _ => Bool.noConfusion h

/-- hence none with cuts either -/
theorem lj_no_atom (n : Nat) (d : LJ true [] (.base n)) : False := cutfree_no_atom n (cutElim d)

end ND

end Found

#print axioms Found.ND.toTm
#print axioms Found.ND.renLJ
#print axioms Found.ND.nfLJ
#print axioms Found.ND.neLJ
#print axioms Found.ND.cutElim
#print axioms Found.ND.withCut
#print axioms Found.ND.ndToLJ
#print axioms Found.ND.cutfree_no_atom
#print axioms Found.ND.lj_no_atom

#print axioms: 9 theorems, no axioms.

85.17 Curry–Howard–Lambek

Simply typed terms erase to intuitionistic derivations of their types; every cartesian closed E-category models the simply typed \(\lambda \)-calculus, with renaming and substitution as composition, so \(\beta \eta \)-convertible terms denote equivalent morphisms. \(t=_{\beta \eta }t'\ \Rightarrow \ \llbracket t\rrbracket \simeq \llbracket t'\rrbracket :\llbracket \Gamma \rrbracket \to \llbracket A\rrbracket \) in every CCC.

found/CHL.lean

/-
  T76. found/CHL — Curry–Howard–Lambek.

  * Curry–Howard: a simply typed term is a natural deduction derivation;
    erasing it gives an intuitionistic derivation (T65) of its type read as
    a formula.
  * Lambek: every cartesian closed E-category (T62) is a model of the simply
    typed λ-calculus with βη: terms denote morphisms ⟦Γ⟧ → ⟦A⟧, renaming
    and substitution are composition, and βη-convertible terms denote
    equivalent morphisms.  With the setoid CCC this needs no funext.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Sequent
import found.CCC
import found.Minimal

namespace Found

namespace ND

/-! ## Curry–Howard: terms are derivations -/

def toForm : Ty → Prp.Form
  | .base n => .var n
  | .arr A B => .imp (toForm A) (toForm B)
  | .prod A B => .and (toForm A) (toForm B)

def ctxP (Γ : List Ty) : Prp.Form → Prop := fun x => ∃ B, Nonempty (Var Γ B) ∧ x = toForm B

theorem ctxP_cons (Γ : List Ty) (A : Ty) : ∀ x, ctxP (A :: Γ) x → Prp.ext (ctxP Γ) (toForm A) x :=
  fun _ ⟨B, ⟨v⟩, e⟩ => by
    cases v with
    | z => exact Or.inl e
    | s v => exact Or.inr ⟨B, ⟨v⟩, e⟩

theorem erase {Γ : List Ty} {A : Ty} : Tm Γ A → Prp.PD true (ctxP Γ) (toForm A)
  | .var v => .hyp ⟨_, ⟨v⟩, rfl⟩
  | @Tm.lam _ A' _ t => .impI (Prp.mono (erase t) (ctxP_cons _ A'))
  | .app t u => .impE (erase t) (erase u)
  | .pair t u => .andI (erase t) (erase u)
  | .fst t => .andE1 (erase t)
  | .snd t => .andE2 (erase t)

/-! ## Renaming and substitution of terms -/

def renTm {Γ Δ : List Ty} {A : Ty} (r : Ren Γ Δ) : Tm Γ A → Tm Δ A
  | .var v => .var (r _ v)
  | .lam t => .lam (renTm r.lift t)
  | .app t u => .app (renTm r t) (renTm r u)
  | .pair t u => .pair (renTm r t) (renTm r u)
  | .fst t => .fst (renTm r t)
  | .snd t => .snd (renTm r t)

def Sub (Γ Δ : List Ty) : Type := (X : Ty) → Var Δ X → Tm Γ X

def Sub.lift {Γ Δ : List Ty} {A : Ty} (σ : Sub Γ Δ) : Sub (A :: Γ) (A :: Δ) :=
  fun _ v => match v with
    | .z => .var .z
    | .s v => renTm wk1 (σ _ v)

def subTm {Γ Δ : List Ty} {A : Ty} (σ : Sub Γ Δ) : Tm Δ A → Tm Γ A
  | .var v => σ _ v
  | .lam t => .lam (subTm σ.lift t)
  | .app t u => .app (subTm σ t) (subTm σ u)
  | .pair t u => .pair (subTm σ t) (subTm σ u)
  | .fst t => .fst (subTm σ t)
  | .snd t => .snd (subTm σ t)

def single {Γ : List Ty} {A : Ty} (u : Tm Γ A) : Sub Γ (A :: Γ) :=
  fun _ v => match v with
    | .z => u
    | .s v => .var v

/-- βη-conversion -/
inductive Conv : {Γ : List Ty} → {A : Ty} → Tm Γ A → Tm Γ A → Prop where
  | refl {Γ A} (t : Tm Γ A) : Conv t t
  | symm {Γ A} {t u : Tm Γ A} : Conv t u → Conv u t
  | trans {Γ A} {t u w : Tm Γ A} : Conv t u → Conv u w → Conv t w
  | lam {Γ A B} {t t' : Tm (A :: Γ) B} : Conv t t' → Conv (.lam t) (.lam t')
  | app {Γ A B} {t t' : Tm Γ (.arr A B)} {u u' : Tm Γ A} : Conv t t' → Conv u u' → Conv (.app t u) (.app t' u')
  | pair {Γ A B} {t t' : Tm Γ A} {u u' : Tm Γ B} : Conv t t' → Conv u u' → Conv (.pair t u) (.pair t' u')
  | fst {Γ A B} {t t' : Tm Γ (.prod A B)} : Conv t t' → Conv (.fst t) (.fst t')
  | snd {Γ A B} {t t' : Tm Γ (.prod A B)} : Conv t t' → Conv (.snd t) (.snd t')
  | beta {Γ A B} (t : Tm (A :: Γ) B) (u : Tm Γ A) : Conv (.app (.lam t) u) (subTm (single u) t)
  | eta {Γ A B} (t : Tm Γ (.arr A B)) : Conv (.lam (.app (renTm wk1 t) (.var .z))) t
  | fstβ {Γ A B} (t : Tm Γ A) (u : Tm Γ B) : Conv (.fst (.pair t u)) t
  | sndβ {Γ A B} (t : Tm Γ A) (u : Tm Γ B) : Conv (.snd (.pair t u)) u
  | pairη {Γ A B} (t : Tm Γ (.prod A B)) : Conv (.pair (.fst t) (.snd t)) t

end ND

/-! ## Lambek: interpretation in a CCC -/

namespace CHL

open ND

universe u v

variable {C : ECat.{u, v}} (K : CCC C) (ι : Nat → C.Ob)

theorem pair_comp {x y a b : C.Ob} (P : Product C a b) (f : C.Hom x y) (g : C.Hom y a) (h : C.Hom y b) :
    C.heq (C.comp f (P.pair g h)) (P.pair (C.comp f g) (C.comp f h)) :=
  C.htrans (P.eta _) (P.pair_resp
    (C.htrans (C.assoc _ _ _) (C.rcong f (P.beta1 g h)))
    (C.htrans (C.assoc _ _ _) (C.rcong f (P.beta2 g h))))

def obj : Ty → C.Ob
  | .base n => ι n
  | .arr A B => K.exp (obj A) (obj B)
  | .prod A B => (K.prod (obj A) (obj B)).P

def ctxO : List Ty → C.Ob
  | [] => K.term.one
  | A :: Γ => (K.prod (ctxO Γ) (obj K ι A)).P

def denV : {Γ : List Ty} → {A : Ty} → Var Γ A → C.Hom (ctxO K ι Γ) (obj K ι A)
  | A :: Γ, _, .z => (K.prod (ctxO K ι Γ) (obj K ι A)).p2
  | B :: Γ, _, .s v => C.comp (K.prod (ctxO K ι Γ) (obj K ι B)).p1 (denV v)

def den : {Γ : List Ty} → {A : Ty} → Tm Γ A → C.Hom (ctxO K ι Γ) (obj K ι A)
  | _, _, .var v => denV K ι v
  | _, _, .lam t => K.curry (den t)
  | _, _, @Tm.app _ A B t u =>
    C.comp ((K.prod (K.exp (obj K ι A) (obj K ι B)) (obj K ι A)).pair (den t) (den u)) (K.ev _ _)
  | _, _, .pair t u => (K.prod _ _).pair (den t) (den u)
  | _, _, .fst t => C.comp (den t) (K.prod _ _).p1
  | _, _, .snd t => C.comp (den t) (K.prod _ _).p2

def denR : {Γ Δ : List Ty} → Ren Γ Δ → C.Hom (ctxO K ι Δ) (ctxO K ι Γ)
  | [], _, _ => K.term.bang _
  | A :: Γ, _, r => (K.prod (ctxO K ι Γ) (obj K ι A)).pair (denR (fun X v => r X (.s v))) (denV K ι (r A .z))

def denS : {Γ Δ : List Ty} → Sub Γ Δ → C.Hom (ctxO K ι Γ) (ctxO K ι Δ)
  | _, [], _ => K.term.bang _
  | _, A :: Δ, σ => (K.prod (ctxO K ι Δ) (obj K ι A)).pair (denS (fun X v => σ X (.s v))) (den K ι (σ A .z))

theorem var_ren : {Γ Δ : List Ty} → {X : Ty} → (r : Ren Γ Δ) → (v : Var Γ X) →
    C.heq (denV K ι (r X v)) (C.comp (denR K ι r) (denV K ι v))
  | _ :: _, _, _, _, .z => C.hsymm ((K.prod _ _).beta2 _ _)
  | _ :: _, _, _, r, .s v =>
    C.htrans (var_ren (fun X w => r X (.s w)) v)
      (C.hsymm (C.htrans (C.hsymm (C.assoc _ _ _)) (C.lcong ((K.prod _ _).beta1 _ _) _)))

theorem wk_ren {B : Ty} : {Γ Δ : List Ty} → (r : Ren Γ Δ) →
    C.heq (denR K ι (Γ := Γ) (Δ := B :: Δ) (fun X v => .s (r X v)))
      (C.comp (K.prod (ctxO K ι Δ) (obj K ι B)).p1 (denR K ι r))
  | [], _, _ => C.htrans (K.term.uniq _) (C.hsymm (K.term.uniq _))
  | _ :: _, _, r =>
    C.htrans ((K.prod _ _).pair_resp (wk_ren (fun X v => r X (.s v))) (C.hrefl _))
      (C.hsymm (pair_comp _ _ _ _))

theorem lift_ren {A : Ty} {Γ Δ : List Ty} (r : Ren Γ Δ) :
    C.heq (denR K ι (Ren.lift (A := A) r)) (K.times (obj K ι A) (denR K ι r)) :=
  (K.prod _ _).pair_resp (wk_ren K ι r) (C.hrefl _)

theorem id_ren : (Γ : List Ty) → C.heq (denR K ι (Γ := Γ) (fun _ v => v)) (C.id _)
  | [] => C.htrans (K.term.uniq _) (C.hsymm (K.term.uniq _))
  | _ :: Γ =>
    C.htrans ((K.prod _ _).pair_resp
        (C.htrans (wk_ren K ι (Γ := Γ) (fun _ v => v))
          (C.htrans (C.rcong _ (id_ren Γ)) (C.htrans (C.comp_id _) (C.hsymm (C.id_comp _)))))
        (C.hsymm (C.id_comp _)))
      (C.hsymm ((K.prod _ _).eta _))

theorem ren_den : {Γ Δ : List Ty} → {A : Ty} → (r : Ren Γ Δ) → (t : Tm Γ A) →
    C.heq (den K ι (renTm r t)) (C.comp (denR K ι r) (den K ι t))
  | _, _, _, r, .var v => var_ren K ι r v
  | _, _, _, r, @Tm.lam _ A _ t =>
    C.htrans (K.curry_resp (C.htrans (ren_den r.lift t) (C.lcong (lift_ren K ι (A := A) r) _)))
      ((K.adj (obj K ι A)).nat_l (denR K ι r) (den K ι t))
  | _, _, _, r, .app t u =>
    C.htrans (C.lcong ((K.prod _ _).pair_resp (ren_den r t) (ren_den r u)) _)
      (C.htrans (C.lcong (C.hsymm (pair_comp _ _ _ _)) _) (C.assoc _ _ _))
  | _, _, _, r, .pair t u =>
    C.htrans ((K.prod _ _).pair_resp (ren_den r t) (ren_den r u)) (C.hsymm (pair_comp _ _ _ _))
  | _, _, _, r, .fst t => C.htrans (C.lcong (ren_den r t) _) (C.assoc _ _ _)
  | _, _, _, r, .snd t => C.htrans (C.lcong (ren_den r t) _) (C.assoc _ _ _)

theorem wk1_den {B : Ty} {Γ : List Ty} :
    C.heq (denR K ι (wk1 (Γ := Γ) (B := B))) (K.prod (ctxO K ι Γ) (obj K ι B)).p1 :=
  C.htrans (wk_ren K ι (B := B) (fun _ v => v)) (C.htrans (C.rcong _ (id_ren K ι Γ)) (C.comp_id _))

theorem var_sub : {Γ Δ : List Ty} → {X : Ty} → (σ : Sub Γ Δ) → (v : Var Δ X) →
    C.heq (den K ι (σ X v)) (C.comp (denS K ι σ) (denV K ι v))
  | _, _ :: _, _, _, .z => C.hsymm ((K.prod _ _).beta2 _ _)
  | _, _ :: _, _, σ, .s v =>
    C.htrans (var_sub (fun X w => σ X (.s w)) v)
      (C.hsymm (C.htrans (C.hsymm (C.assoc _ _ _)) (C.lcong ((K.prod _ _).beta1 _ _) _)))

theorem wk_sub {B : Ty} : {Γ Δ : List Ty} → (σ : Sub Γ Δ) →
    C.heq (denS K ι (Γ := B :: Γ) (Δ := Δ) (fun X v => renTm wk1 (σ X v)))
      (C.comp (K.prod (ctxO K ι Γ) (obj K ι B)).p1 (denS K ι σ))
  | _, [], _ => C.htrans (K.term.uniq _) (C.hsymm (K.term.uniq _))
  | _, _ :: _, σ =>
    C.htrans ((K.prod _ _).pair_resp (wk_sub (fun X v => σ X (.s v)))
        (C.htrans (ren_den K ι wk1 _) (C.lcong (wk1_den K ι) _)))
      (C.hsymm (pair_comp _ _ _ _))

theorem lift_sub {A : Ty} {Γ Δ : List Ty} (σ : Sub Γ Δ) :
    C.heq (denS K ι (Sub.lift (A := A) σ)) (K.times (obj K ι A) (denS K ι σ)) :=
  (K.prod _ _).pair_resp (wk_sub K ι σ) (C.hrefl _)

theorem sub_den : {Γ Δ : List Ty} → {A : Ty} → (σ : Sub Γ Δ) → (t : Tm Δ A) →
    C.heq (den K ι (subTm σ t)) (C.comp (denS K ι σ) (den K ι t))
  | _, _, _, σ, .var v => var_sub K ι σ v
  | _, _, _, σ, @Tm.lam _ A _ t =>
    C.htrans (K.curry_resp (C.htrans (sub_den σ.lift t) (C.lcong (lift_sub K ι (A := A) σ) _)))
      ((K.adj (obj K ι A)).nat_l (denS K ι σ) (den K ι t))
  | _, _, _, σ, .app t u =>
    C.htrans (C.lcong ((K.prod _ _).pair_resp (sub_den σ t) (sub_den σ u)) _)
      (C.htrans (C.lcong (C.hsymm (pair_comp _ _ _ _)) _) (C.assoc _ _ _))
  | _, _, _, σ, .pair t u =>
    C.htrans ((K.prod _ _).pair_resp (sub_den σ t) (sub_den σ u)) (C.hsymm (pair_comp _ _ _ _))
  | _, _, _, σ, .fst t => C.htrans (C.lcong (sub_den σ t) _) (C.assoc _ _ _)
  | _, _, _, σ, .snd t => C.htrans (C.lcong (sub_den σ t) _) (C.assoc _ _ _)

theorem varsub_ren : {Γ Δ : List Ty} → (r : Ren Δ Γ) →
    C.heq (denS K ι (Γ := Γ) (Δ := Δ) (fun X v => .var (r X v))) (denR K ι r)
  | _, [], _ => C.hrefl _
  | _, _ :: _, r => (K.prod _ _).pair_resp (varsub_ren (fun X v => r X (.s v))) (C.hrefl _)

theorem single_den {Γ : List Ty} {A : Ty} (u : Tm Γ A) :
    C.heq (denS K ι (single u)) ((K.prod (ctxO K ι Γ) (obj K ι A)).pair (C.id _) (den K ι u)) :=
  (K.prod _ _).pair_resp (C.htrans (varsub_ren K ι (fun _ v => v)) (id_ren K ι Γ)) (C.hrefl _)

/-- Lambek soundness: βη-convertible terms denote equivalent morphisms in every CCC -/
theorem conv_sound {Γ : List Ty} {A : Ty} {t t' : Tm Γ A} (h : Conv t t') :
    C.heq (den K ι t) (den K ι t') := by
  induction h with
  | refl t => exact C.hrefl _
  | symm _ ih => exact C.hsymm ih
  | trans _ _ ih₁ ih₂ => exact C.htrans ih₁ ih₂
  | lam _ ih => exact K.curry_resp ih
  | app _ _ ih₁ ih₂ => exact C.lcong ((K.prod _ _).pair_resp ih₁ ih₂) _
  | pair _ _ ih₁ ih₂ => exact (K.prod _ _).pair_resp ih₁ ih₂
  | fst _ ih => exact C.lcong ih _
  | snd _ ih => exact C.lcong ih _
  | @beta Γ A B t u =>
    have e1 : C.heq ((K.prod (K.exp (obj K ι A) (obj K ι B)) (obj K ι A)).pair (K.curry (den K ι t)) (den K ι u))
        (C.comp ((K.prod (ctxO K ι Γ) (obj K ι A)).pair (C.id _) (den K ι u)) (K.times (obj K ι A) (K.curry (den K ι t)))) :=
      C.hsymm (C.htrans (pair_comp _ _ _ _) ((K.prod _ _).pair_resp
        (C.htrans (C.hsymm (C.assoc _ _ _)) (C.htrans (C.lcong ((K.prod _ _).beta1 _ _) _) (C.id_comp _)))
        ((K.prod _ _).beta2 _ _)))
    exact C.htrans (C.lcong e1 _) (C.htrans (C.assoc _ _ _)
      (C.htrans (C.rcong _ (K.beta (den K ι t)))
        (C.hsymm (C.htrans (sub_den K ι (single u) t) (C.lcong (single_den K ι u) _)))))
  | @eta Γ A B t =>
    exact C.htrans (K.curry_resp (C.lcong ((K.prod _ _).pair_resp
        (C.htrans (ren_den K ι wk1 t) (C.lcong (wk1_den K ι) _)) (C.hrefl _)) _)) (K.eta (den K ι t))
  | fstβ t u => exact (K.prod _ _).beta1 _ _
  | sndβ t u => exact (K.prod _ _).beta2 _ _
  | pairη t => exact C.hsymm ((K.prod _ _).eta _)

end CHL

end Found

#print axioms Found.ND.erase
#print axioms Found.ND.renTm
#print axioms Found.ND.subTm
#print axioms Found.CHL.pair_comp
#print axioms Found.CHL.var_ren
#print axioms Found.CHL.wk_ren
#print axioms Found.CHL.lift_ren
#print axioms Found.CHL.id_ren
#print axioms Found.CHL.ren_den
#print axioms Found.CHL.wk1_den
#print axioms Found.CHL.var_sub
#print axioms Found.CHL.wk_sub
#print axioms Found.CHL.lift_sub
#print axioms Found.CHL.sub_den
#print axioms Found.CHL.varsub_ren
#print axioms Found.CHL.single_den
#print axioms Found.CHL.conv_sound

#print axioms: 17 theorems, no axioms.

85.18 Double-negation translations

Intuitionistically \(gg\,\varphi \leftrightarrow \neg \neg \varphi \), so the Gödel–Gentzen and (propositional) Kuroda translations agree and Glivenko’s theorem holds; Friedman’s A-translation preserves intuitionistic derivability. \(\vdash _c\varphi \iff \vdash _i\neg \neg \varphi ;\quad \Gamma \vdash _i\varphi \Rightarrow \Gamma ^A\vdash _i\varphi ^A\).

found/DNTrans.lean

/-
  T77. found/DNTrans — double-negation translations compared (propositional).

  * Intuitionistically gg φ ↔ ¬¬φ for every formula; propositional Kuroda
    is φ ↦ ¬¬φ, so Gödel–Gentzen and Kuroda agree up to provable equivalence.
  * Glivenko: Γ ⊢_c φ ⟺ gg Γ ⊢_i ¬¬φ; in particular ⊢_c φ ⟺ ⊢_i ¬¬φ.
  * Friedman's A-translation (⊥ ↦ A, p ↦ p ∨ A) preserves intuitionistic
    derivability; first-order Π⁰₂-conservativity uses it in T83.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Classical

namespace Found

namespace Prp

def N (x : Form) : Form := neg (neg x)

/-- intuitionistically, gg φ ↔ ¬¬φ (both directions, in any context) -/
theorem gg_nn : (φ : Form) → ∀ (Θ : Form → Prop),
    PD true Θ (.imp (gg φ) (N φ)) ∧ PD true Θ (.imp (N φ) (gg φ))
  | .var _, _ => ⟨.impI h0, .impI h0⟩
  | .bot, _ => ⟨.impI (.impI (.impE h0 h1)), .impI (.impE h0 (.impI h0))⟩
  | .and a b, _ =>
    ⟨.impI (.impI (.impE (.impE (gg_nn a _).1 (.andE1 h1))
        (.impI (.impE (.impE (gg_nn b _).1 (.andE2 h2)) (.impI (.impE h2 (.andI h1 h0))))))),
     .impI (.andI
        (.impE (gg_nn a _).2 (.impI (.impE h1 (.impI (.impE h1 (.andE1 h0))))))
        (.impE (gg_nn b _).2 (.impI (.impE h1 (.impI (.impE h1 (.andE2 h0)))))))⟩
  | .or a b, _ =>
    ⟨.impI (.impI (.impE h1 (.andI
        (.impI (.impE (.impE (gg_nn a _).1 h0) (.impI (.impE h2 (.orI1 h0)))))
        (.impI (.impE (.impE (gg_nn b _).1 h0) (.impI (.impE h2 (.orI2 h0)))))))),
     .impI (.impI (.impE h1 (.impI (.orE h0
        (.impE (.andE1 h2) (.impE (gg_nn a _).2 (.impI (.impE h0 h1))))
        (.impE (.andE2 h2) (.impE (gg_nn b _).2 (.impI (.impE h0 h1))))))))⟩
  | .imp a b, _ =>
    ⟨.impI (.impI (.impE
        (.impE (gg_nn b _).1 (.impE h1 (.impE (gg_nn a _).2
          (.impI (.impE h1 (.impI (.botE rfl (.impE h1 h0))))))))
        (.impI (.impE h1 (.impI h1))))),
     .impI (.impI (.impE (gg_nn b _).2 (.impI (.impE h2 (.impI
        (.impE (.impE (gg_nn a _).1 h2) (.impI (.impE h2 (.impE h1 h0)))))))))⟩

/-- Glivenko: Γ ⊢_c φ ⟺ gg Γ ⊢_i ¬¬φ -/
theorem glivenko (Γ : Form → Prop) (φ : Form) : CD Γ φ ↔ PD true (GG Γ) (N φ) :=
  ⟨fun d => .impE (gg_nn φ _).1 ((gg_iff Γ φ).mp d),
   fun d => (gg_iff Γ φ).mpr (.impE (gg_nn φ _).2 d)⟩

/-- Glivenko for theorems: ⊢_c φ ⟺ ⊢_i ¬¬φ -/
theorem glivenko0 (φ : Form) : CD (fun _ => False) φ ↔ PD true (fun _ => False) (N φ) :=
  ⟨fun d => mono ((glivenko _ φ).mp d) (fun _ ⟨_, g, _⟩ => g.elim),
   fun d => (glivenko _ φ).mpr (mono d (fun _ g => g.elim))⟩

/-- propositional Kuroda: φ ↦ ¬¬φ; it agrees with Gödel–Gentzen -/
def kuroda (φ : Form) : Form := N φ

theorem kuroda_gg (φ : Form) (Θ : Form → Prop) :
    PD true Θ (.imp (kuroda φ) (gg φ)) ∧ PD true Θ (.imp (gg φ) (kuroda φ)) :=
  ⟨(gg_nn φ Θ).2, (gg_nn φ Θ).1⟩

/-! ## Friedman's A-translation -/

def atr (A : Form) : Form → Form
  | .var n => .or (.var n) A
  | .bot => A
  | .and a b => .and (atr A a) (atr A b)
  | .or a b => .or (atr A a) (atr A b)
  | .imp a b => .imp (atr A a) (atr A b)

theorem efqA (A : Form) : (φ : Form) → ∀ (Θ : Form → Prop), PD true Θ (.imp A (atr A φ))
  | .var _, _ => .impI (.orI2 h0)
  | .bot, _ => .impI h0
  | .and a b, _ => .impI (.andI (.impE (efqA A a _) h0) (.impE (efqA A b _) h0))
  | .or a _, _ => .impI (.orI1 (.impE (efqA A a _) h0))
  | .imp _ b, _ => .impI (.impI (.impE (efqA A b _) h1))

/-- the A-translation preserves intuitionistic derivability -/
theorem atr_sound (A : Form) {Δ : Form → Prop} {φ : Form} (d : PD true Δ φ) :
    ∀ {Θ : Form → Prop}, (∀ x, Δ x → PD true Θ (atr A x)) → PD true Θ (atr A φ) := by
  induction d with
  | hyp g => exact fun h => h _ g
  | @botE _ a _ _ ih => exact fun h => .impE (efqA A a _) (ih h)
  | andI _ _ iha ihb => exact fun h => .andI (iha h) (ihb h)
  | andE1 _ ih => exact fun h => .andE1 (ih h)
  | andE2 _ ih => exact fun h => .andE2 (ih h)
  | orI1 _ ih => exact fun h => .orI1 (ih h)
  | orI2 _ ih => exact fun h => .orI2 (ih h)
  | @orE _ a b _ _ _ _ ih iha ihb =>
    exact fun {Θ} h => .orE (ih h)
      (iha (Θ := ext Θ (atr A a)) (fun x k => k.elim (fun q => q ▸ h0) (fun g => wk (h x g))))
      (ihb (Θ := ext Θ (atr A b)) (fun x k => k.elim (fun q => q ▸ h0) (fun g => wk (h x g))))
  | @impI _ a _ _ ih =>
    exact fun {Θ} h => .impI (ih (Θ := ext Θ (atr A a))
      (fun x k => k.elim (fun q => q ▸ h0) (fun g => wk (h x g))))
  | impE _ _ ihf iha => exact fun h => .impE (ihf h) (iha h)

/-- Friedman's trick, propositional form: from ⊢_i ¬¬p get ⊢_i p via A := p -/
theorem friedman_atom (n : Nat) (d : PD true (fun _ => False) (N (.var n))) :
    PD true (fun _ => False) (.var n) :=
  .impE (atr_sound (.var n) d (fun _ g => g.elim))
    (.impI (.orE h0 h0 h0))

end Prp

end Found

#print axioms Found.Prp.gg_nn
#print axioms Found.Prp.glivenko
#print axioms Found.Prp.glivenko0
#print axioms Found.Prp.kuroda_gg
#print axioms Found.Prp.efqA
#print axioms Found.Prp.atr_sound
#print axioms Found.Prp.friedman_atom

#print axioms: 7 theorems, no axioms.

85.19 Untyped lambda calculus

Well-scoped untyped \(\lambda \)-terms with pointwise \(\sigma \)-calculus laws; parallel reduction has the triangle property with complete development, hence Church–Rosser for \(\beta \) and uniqueness of normal forms. \(t\to _\beta ^* u_1,\ t\to _\beta ^* u_2\Rightarrow \exists w,\ u_1\to _\beta ^* w\ \wedge \ u_2\to _\beta ^* w\).

found/Lambda.lean

/-
  T78. found/Lambda — the untyped λ-calculus and Church–Rosser (scopes indexed by List Unit: Nat-indexed matching pulls in propext).

  * Well-scoped de Bruijn terms `T n`, renaming and simultaneous
    substitution; the σ-calculus laws are proved pointwise (no funext).
  * β-reduction, parallel reduction, complete development (Takahashi);
    triangle lemma, diamond for parallel reduction, Church–Rosser for β*.
  * Consequence: a term has at most one β-normal form.

  Lean 4 core only, hand-written proofs, no arithmetic, no axioms.
-/

namespace Found

namespace UL

inductive V : List Unit → Type where
  | z {n} : V (() :: n)
  | s {n} : V n → V (() :: n)

inductive T : List Unit → Type where
  | var {n} : V n → T n
  | app {n} : T n → T n → T n
  | lam {n} : T (() :: n) → T n

def lift {m n : List Unit} (r : V m → V n) : V (() :: m) → V (() :: n)
  | .z => .z
  | .s v => .s (r v)

def ren {m n : List Unit} (r : V m → V n) : T m → T n
  | .var v => .var (r v)
  | .app a b => .app (ren r a) (ren r b)
  | .lam t => .lam (ren (lift r) t)

def liftS {m n : List Unit} (σ : V m → T n) : V (() :: m) → T (() :: n)
  | .z => .var .z
  | .s v => ren V.s (σ v)

def sub {m n : List Unit} (σ : V m → T n) : T m → T n
  | .var v => σ v
  | .app a b => .app (sub σ a) (sub σ b)
  | .lam t => .lam (sub (liftS σ) t)

def single {n : List Unit} (u : T n) : V (() :: n) → T n
  | .z => u
  | .s v => .var v

def inst {n : List Unit} (t : T (() :: n)) (u : T n) : T n := sub (single u) t

/-! ## σ-calculus, pointwise -/

theorem lift_ext {m n : List Unit} {r r' : V m → V n} (h : ∀ v, r v = r' v) : ∀ v, lift r v = lift r' v
  | .z => rfl
  | .s v => congrArg V.s (h v)

theorem cong2 {α β γ : Type} (f : α → β → γ) {a a' : α} {b b' : β} (h1 : a = a') (h2 : b = b') :
    f a b = f a' b' := by
  cases h1
  cases h2
  rfl

theorem ren_ext : {m : List Unit} → (t : T m) → ∀ {n : List Unit} {r r' : V m → V n},
    (∀ v, r v = r' v) → ren r t = ren r' t
  | _, .var v, _, _, _, h => congrArg T.var (h v)
  | _, .app a b, _, _, _, h => cong2 T.app (ren_ext a h) (ren_ext b h)
  | _, .lam t, _, _, _, h => congrArg T.lam (ren_ext t (lift_ext h))

theorem ren_ren : {m : List Unit} → (t : T m) → ∀ {n k : List Unit} (r : V n → V k) (r' : V m → V n),
    ren r (ren r' t) = ren (fun x => r (r' x)) t
  | _, .var _, _, _, _, _ => rfl
  | _, .app a b, _, _, r, r' => cong2 T.app (ren_ren a r r') (ren_ren b r r')
  | _, .lam t, _, _, r, r' => congrArg T.lam ((ren_ren t (lift r) (lift r')).trans
      (ren_ext t (fun v => match v with | .z => rfl | .s _ => rfl)))

theorem liftS_ext {m n : List Unit} {σ τ : V m → T n} (h : ∀ v, σ v = τ v) : ∀ v, liftS σ v = liftS τ v
  | .z => rfl
  | .s v => congrArg (ren V.s) (h v)

theorem sub_ext : {m : List Unit} → (t : T m) → ∀ {n : List Unit} {σ τ : V m → T n},
    (∀ v, σ v = τ v) → sub σ t = sub τ t
  | _, .var v, _, _, _, h => h v
  | _, .app a b, _, _, _, h => cong2 T.app (sub_ext a h) (sub_ext b h)
  | _, .lam t, _, _, _, h => congrArg T.lam (sub_ext t (liftS_ext h))

theorem sub_ren : {m : List Unit} → (t : T m) → ∀ {n k : List Unit} (σ : V n → T k) (r : V m → V n),
    sub σ (ren r t) = sub (fun x => σ (r x)) t
  | _, .var _, _, _, _, _ => rfl
  | _, .app a b, _, _, σ, r => cong2 T.app (sub_ren a σ r) (sub_ren b σ r)
  | _, .lam t, _, _, σ, r => congrArg T.lam ((sub_ren t (liftS σ) (lift r)).trans
      (sub_ext t (fun v => match v with | .z => rfl | .s _ => rfl)))

theorem ren_sub : {m : List Unit} → (t : T m) → ∀ {n k : List Unit} (r : V n → V k) (σ : V m → T n),
    ren r (sub σ t) = sub (fun x => ren r (σ x)) t
  | _, .var _, _, _, _, _ => rfl
  | _, .app a b, _, _, r, σ => cong2 T.app (ren_sub a r σ) (ren_sub b r σ)
  | _, .lam t, _, _, r, σ => congrArg T.lam ((ren_sub t (lift r) (liftS σ)).trans
      (sub_ext t (fun v => match v with
        | .z => rfl
        | .s w => (ren_ren (σ w) (lift r) V.s).trans (ren_ren (σ w) V.s r).symm)))

theorem sub_sub : {m : List Unit} → (t : T m) → ∀ {n k : List Unit} (σ : V n → T k) (τ : V m → T n),
    sub σ (sub τ t) = sub (fun x => sub σ (τ x)) t
  | _, .var _, _, _, _, _ => rfl
  | _, .app a b, _, _, σ, τ => cong2 T.app (sub_sub a σ τ) (sub_sub b σ τ)
  | _, .lam t, _, _, σ, τ => congrArg T.lam ((sub_sub t (liftS σ) (liftS τ)).trans
      (sub_ext t (fun v => match v with
        | .z => rfl
        | .s w => (sub_ren (τ w) (liftS σ) V.s).trans (ren_sub (τ w) V.s σ).symm)))

theorem sub_var : {m : List Unit} → (t : T m) → sub T.var t = t
  | _, .var _ => rfl
  | _, .app a b => cong2 T.app (sub_var a) (sub_var b)
  | _, .lam t => congrArg T.lam
      ((sub_ext t (σ := liftS T.var) (τ := T.var) (fun v => match v with | .z => rfl | .s _ => rfl)).trans (sub_var t))

/-- substitution commutes with instantiation -/
theorem sub_inst {m n : List Unit} (σ : V m → T n) (t : T (() :: m)) (u : T m) :
    inst (sub (liftS σ) t) (sub σ u) = sub σ (inst t u) :=
  (sub_sub t (single (sub σ u)) (liftS σ)).trans ((sub_ext t
    (σ := fun x => sub (single (sub σ u)) (liftS σ x)) (τ := fun x => sub σ (single u x))
    (fun v => match v with
    | .z => rfl
    | .s w => (sub_ren (σ w) (single (sub σ u)) V.s).trans (sub_var (σ w)))).trans (sub_sub t σ (single u)).symm)

theorem ren_inst {m n : List Unit} (r : V m → V n) (t : T (() :: m)) (u : T m) :
    ren r (inst t u) = inst (ren (lift r) t) (ren r u) :=
  (ren_sub t r (single u)).trans ((sub_ext t
    (σ := fun x => ren r (single u x)) (τ := fun x => single (ren r u) (lift r x))
    (fun v => match v with
    | .z => rfl
    | .s _ => rfl)).trans (sub_ren t (single (ren r u)) (lift r)).symm)

/-! ## Reductions -/

inductive Beta : {n : List Unit} → T n → T n → Prop where
  | beta {n} (t : T (() :: n)) (u : T n) : Beta (.app (.lam t) u) (inst t u)
  | appL {n} {a a' : T n} (b : T n) : Beta a a' → Beta (.app a b) (.app a' b)
  | appR {n} (a : T n) {b b' : T n} : Beta b b' → Beta (.app a b) (.app a b')
  | lam {n} {t t' : T (() :: n)} : Beta t t' → Beta (.lam t) (.lam t')

inductive Star {α : Type} (R : α → α → Prop) : α → α → Prop where
  | refl (a : α) : Star R a a
  | step {a b c : α} : R a b → Star R b c → Star R a c

theorem Star.trans' {α : Type} {R : α → α → Prop} {a b c : α} (h : Star R a b) (k : Star R b c) :
    Star R a c := by
  induction h with
  | refl => exact k
  | step r _ ih => exact .step r (ih k)

theorem Star.one {α : Type} {R : α → α → Prop} {a b : α} (r : R a b) : Star R a b := .step r (.refl b)

theorem Star.map {α β : Type} {R : α → α → Prop} {S : β → β → Prop} (f : α → β)
    (hf : ∀ {a b}, R a b → S (f a) (f b)) {a b : α} (h : Star R a b) : Star S (f a) (f b) := by
  induction h with
  | refl => exact .refl _
  | step r _ ih => exact .step (hf r) ih

inductive Par : {n : List Unit} → T n → T n → Prop where
  | var {n} (v : V n) : Par (.var v) (.var v)
  | app {n} {a a' b b' : T n} : Par a a' → Par b b' → Par (.app a b) (.app a' b')
  | lam {n} {t t' : T (() :: n)} : Par t t' → Par (.lam t) (.lam t')
  | beta {n} {t t' : T (() :: n)} {u u' : T n} : Par t t' → Par u u' → Par (.app (.lam t) u) (inst t' u')

theorem par_refl {n : List Unit} (t : T n) : Par t t := by
  induction t with
  | var v => exact .var v
  | app a b iha ihb => exact .app iha ihb
  | lam t ih => exact .lam ih

theorem par_ren {m : List Unit} {t t' : T m} (h : Par t t') : ∀ {n : List Unit} (r : V m → V n), Par (ren r t) (ren r t') := by
  induction h with
  | var v => exact fun r => .var (r v)
  | app _ _ iha ihb => exact fun r => .app (iha r) (ihb r)
  | lam _ ih => exact fun r => .lam (ih (lift r))
  | @beta _ t t' u u' _ _ iht ihu =>
    exact fun r => (ren_inst r t' u') ▸ Par.beta (iht (lift r)) (ihu r)

theorem par_sub {m : List Unit} {t t' : T m} (h : Par t t') :
    ∀ {n : List Unit} {σ τ : V m → T n}, (∀ v, Par (σ v) (τ v)) → Par (sub σ t) (sub τ t') := by
  induction h with
  | var v => exact fun hs => hs v
  | app _ _ iha ihb => exact fun hs => .app (iha hs) (ihb hs)
  | lam _ ih => exact fun hs => .lam (ih (fun v => match v with
      | .z => .var .z
      | .s w => par_ren (hs w) V.s))
  | @beta _ t t' u u' _ _ iht ihu =>
    exact fun {_ σ τ} hs => (sub_inst τ t' u') ▸ Par.beta (iht (fun v => match v with
      | .z => .var .z
      | .s w => par_ren (hs w) V.s)) (ihu hs)

theorem par_inst {n : List Unit} {t t' : T (() :: n)} {u u' : T n} (ht : Par t t') (hu : Par u u') :
    Par (inst t u) (inst t' u') :=
  par_sub ht (fun v => match v with
    | .z => hu
    | .s w => .var w)

/-! ## Complete development and the triangle -/

def cd {n : List Unit} : T n → T n
  | .var v => .var v
  | .lam t => .lam (cd t)
  | .app (.lam t) u => inst (cd t) (cd u)
  | .app (.var v) u => .app (.var v) (cd u)
  | .app (.app a b) u => .app (cd (.app a b)) (cd u)

theorem par_lam_inv {n : List Unit} {t : T (() :: n)} {s : T n} (h : Par (.lam t) s) :
    ∃ t', s = .lam t' ∧ Par t t' := by
  cases h with
  | lam k => exact ⟨_, rfl, k⟩

theorem triangle {n : List Unit} {t u : T n} (h : Par t u) : Par u (cd t) := by
  induction h with
  | var v => exact .var v
  | lam _ ih => exact .lam ih
  | @app _ a a' b b' ha _ iha ihb =>
    cases a with
    | var v => cases ha; exact .app (.var v) ihb
    | app a₁ a₂ => exact .app iha ihb
    | lam t =>
      match par_lam_inv ha with
      | ⟨t', e, k⟩ =>
        cases e
        match par_lam_inv iha with
        | ⟨_, e', k'⟩ =>
          cases e'
          exact .beta k' ihb
  | beta _ _ iht ihu => exact par_inst iht ihu

theorem par_diamond {n : List Unit} {t u₁ u₂ : T n} (h₁ : Par t u₁) (h₂ : Par t u₂) :
    ∃ w, Par u₁ w ∧ Par u₂ w := ⟨cd t, triangle h₁, triangle h₂⟩

/-! ## Church–Rosser -/

theorem strip {n : List Unit} {t u₁ u₂ : T n} (h₁ : Par t u₁) (h₂ : Star Par t u₂) :
    ∃ w, Star Par u₁ w ∧ Par u₂ w := by
  induction h₂ generalizing u₁ with
  | refl => exact ⟨u₁, .refl _, h₁⟩
  | step r _ ih =>
    match par_diamond h₁ r with
    | ⟨w, k₁, k₂⟩ =>
      match ih k₂ with
      | ⟨w', s, k⟩ => exact ⟨w', .step k₁ s, k⟩

theorem par_cr {n : List Unit} {t u₁ u₂ : T n} (h₁ : Star Par t u₁) (h₂ : Star Par t u₂) :
    ∃ w, Star Par u₁ w ∧ Star Par u₂ w := by
  induction h₁ generalizing u₂ with
  | refl => exact ⟨u₂, h₂, .refl _⟩
  | step r _ ih =>
    match strip r h₂ with
    | ⟨w, s, k⟩ =>
      match ih s with
      | ⟨w', s₁, s₂⟩ => exact ⟨w', s₁, .step k s₂⟩

theorem beta_par {n : List Unit} {t u : T n} (h : Beta t u) : Par t u := by
  induction h with
  | beta t u => exact .beta (par_refl t) (par_refl u)
  | appL b _ ih => exact .app ih (par_refl b)
  | appR a _ ih => exact .app (par_refl a) ih
  | lam _ ih => exact .lam ih

theorem par_betas {n : List Unit} {t u : T n} (h : Par t u) : Star Beta t u := by
  induction h with
  | var v => exact .refl _
  | @app _ a a' b b' _ _ iha ihb =>
    exact (Star.map (fun x => T.app x b) (fun r => .appL b r) iha).trans'
      (Star.map (fun y => T.app a' y) (fun r => .appR a' r) ihb)
  | lam _ ih => exact Star.map T.lam (fun r => .lam r) ih
  | @beta _ t t' u u' _ _ iht ihu =>
    exact ((Star.map (fun x => T.app (T.lam x) u) (fun r => .appL u (.lam r)) iht).trans'
      (Star.map (fun y => T.app (T.lam t') y) (fun r => .appR _ r) ihu)).trans' (.one (.beta t' u'))

theorem betas_pars {n : List Unit} {t u : T n} (h : Star Beta t u) : Star Par t u :=
  Star.map (fun x => x) (fun r => beta_par r) h

theorem pars_betas {n : List Unit} {t u : T n} (h : Star Par t u) : Star Beta t u := by
  induction h with
  | refl => exact .refl _
  | step r _ ih => exact (par_betas r).trans' ih

/-- Church–Rosser for β -/
theorem church_rosser {n : List Unit} {t u₁ u₂ : T n} (h₁ : Star Beta t u₁) (h₂ : Star Beta t u₂) :
    ∃ w, Star Beta u₁ w ∧ Star Beta u₂ w :=
  match par_cr (betas_pars h₁) (betas_pars h₂) with
  | ⟨w, s₁, s₂⟩ => ⟨w, pars_betas s₁, pars_betas s₂⟩

def Normal {n : List Unit} (t : T n) : Prop := ∀ u, ¬ Beta t u

theorem normal_star {n : List Unit} {t u : T n} (hn : Normal t) (h : Star Beta t u) : t = u := by
  cases h with
  | refl => rfl
  | step r _ => exact (hn _ r).elim

/-- uniqueness of normal forms -/
theorem nf_unique {n : List Unit} {t u₁ u₂ : T n} (h₁ : Star Beta t u₁) (h₂ : Star Beta t u₂)
    (n₁ : Normal u₁) (n₂ : Normal u₂) : u₁ = u₂ :=
  match church_rosser h₁ h₂ with
  | ⟨_, s₁, s₂⟩ => (normal_star n₁ s₁).trans (normal_star n₂ s₂).symm

end UL

end Found

#print axioms Found.UL.ren_ren
#print axioms Found.UL.sub_ren
#print axioms Found.UL.ren_sub
#print axioms Found.UL.sub_sub
#print axioms Found.UL.sub_var
#print axioms Found.UL.sub_inst
#print axioms Found.UL.ren_inst
#print axioms Found.UL.par_ren
#print axioms Found.UL.par_sub
#print axioms Found.UL.triangle
#print axioms Found.UL.par_diamond
#print axioms Found.UL.church_rosser
#print axioms Found.UL.nf_unique

#print axioms: 13 theorems, no axioms.

85.20 Gödel’s \(\beta \) function (existing file) and its arithmetic bridge

The existing BetaChain file (Chinese remainder theorem, Gödel’s \(\beta \) lemma) is built unchanged in the same project; its remainder and \(\beta \) are exactly the arithmetic formulas \(\mathrm {Rem}\), \(\mathrm {Beta}\) in the standard model. \(\mathbb {N}\models \mathrm {Beta}(c,d,i,y)\iff \beta (c,d,i)=y;\quad \forall a\,\forall n\,\exists c\,d\,\forall i\le n,\ \mathbb {N}\models \mathrm {Beta}(c,d,i,a_i)\).

found/ArithBridge.lean

/-
  found/ArithBridge — bridge from the existing coding file (BetaChain:
  Chinese remainder theorem and Gödel's β function, copied unchanged into
  found/BetaChain.lean) to the language of first-order arithmetic used by
  the PA/HA items (T83–T85).

  * First-order arithmetic: terms 0, S, +, ·, variables; formulas with =,
    ⊥, →, ∧, ∨, ∀, ∃; the standard model ℕ with Lean core operations.
  * BetaChain's hand-built operations agree with the core operations of
    the standard model: pre = pred, sb = monus, up = q·m + r (re-exported).
  * The remainder `BetaChain.rem` is defined in arithmetic by the Δ₀-shaped
    formula  Rem(m,n,r) :≡ ∃q ∃k (n = q·m + r ∧ r + S k = m), and β by
    Beta(c,d,i,y) :≡ Rem((i+1)·d+1, c, y): both are exact (↔) bridges.
  * Hence the β-lemma holds in the standard model of the arithmetic
    language: every finite sequence is coded by two numbers via the formula
    Beta.  Gödel's incompleteness itself is not in any existing file; it
    stays open as T85 (representability and diagonal lemma remain).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.BetaChain

namespace Found

namespace Arith

inductive Tm where
  | var : Nat → Tm
  | zero : Tm
  | succ : Tm → Tm
  | add : Tm → Tm → Tm
  | mul : Tm → Tm → Tm

inductive Fm where
  | eq : Tm → Tm → Fm
  | bot : Fm
  | imp : Fm → Fm → Fm
  | and : Fm → Fm → Fm
  | or : Fm → Fm → Fm
  | all : Fm → Fm
  | ex : Fm → Fm

def cons (x : Nat) (ρ : Nat → Nat) : Nat → Nat
  | 0 => x
  | n + 1 => ρ n

def eval (ρ : Nat → Nat) : Tm → Nat
  | .var n => ρ n
  | .zero => 0
  | .succ t => Nat.succ (eval ρ t)
  | .add a b => eval ρ a + eval ρ b
  | .mul a b => eval ρ a * eval ρ b

/-- truth in the standard model -/
def sat : (Nat → Nat) → Fm → Prop
  | ρ, .eq a b => eval ρ a = eval ρ b
  | _, .bot => False
  | ρ, .imp a b => sat ρ a → sat ρ b
  | ρ, .and a b => sat ρ a ∧ sat ρ b
  | ρ, .or a b => sat ρ a ∨ sat ρ b
  | ρ, .all a => ∀ x, sat (cons x ρ) a
  | ρ, .ex a => ∃ x, sat (cons x ρ) a

/-! ## BetaChain operations = core operations of the standard model -/

theorem pre_is_pred (k : Nat) : BetaChain.pre k = Nat.pred k := BetaChain.pre_eq k
theorem sb_is_sub (m n : Nat) : BetaChain.sb m n = m - n := BetaChain.sb_eq m n
theorem up_is_affine (m r q : Nat) : BetaChain.up m q r = q * m + r := BetaChain.up_eq m r q

/-! ## Rem and Beta as arithmetic formulas -/

/-- Rem(m, n, r) with m, n, r the variables 0, 1, 2:
    ∃q ∃k (n = q·m + r ∧ r + S k = m); under the two binders k = 0, q = 1,
    m = 2, n = 3, r = 4 -/
def RemF : Fm :=
  .ex (.ex (.and (.eq (.var 3) (.add (.mul (.var 1) (.var 2)) (.var 4)))
                 (.eq (.add (.var 4) (.succ (.var 0))) (.var 2))))

def env3 (a b c : Nat) : Nat → Nat := cons a (cons b (cons c (fun _ => 0)))

/-- the bridge for the remainder -/
theorem rem_bridge (m' n r : Nat) : sat (env3 (m' + 1) n r) RemF ↔ BetaChain.rem (m' + 1) n = r :=
  ⟨fun ⟨q, k, hn, hk⟩ => Eq.trans (congrArg (BetaChain.rem (m' + 1)) hn) (BetaChain.rem_div m' q r k hk),
   fun h => match BetaChain.rem_spec m' n with
     | ⟨q, r', k, hn, hk, hr⟩ =>
       have e : r' = r := Eq.trans (Eq.symm hr) h
       by cases e; exact ⟨q, k, hn, hk⟩⟩

/-- the modulus (i+1)·d+1 of the β function, as an arithmetic term in d, i -/
def mdT (d i : Tm) : Tm := .succ (.mul (.succ i) d)

theorem mdT_eval (ρ : Nat → Nat) (d i : Tm) :
    eval ρ (mdT d i) = BetaChain.md (eval ρ d) (eval ρ i) := rfl

/-- Beta(c, d, i, y) with variables 0..3:  Rem((i+1)·d+1, c, y), written out -/
def BetaF : Fm :=
  .ex (.ex (.and (.eq (.var 2) (.add (.mul (.var 1) (mdT (.var 3) (.var 4))) (.var 5)))
                 (.eq (.add (.var 5) (.succ (.var 0))) (mdT (.var 3) (.var 4)))))

def env4 (a b c e : Nat) : Nat → Nat := cons a (cons b (cons c (cons e (fun _ => 0))))

/-- the bridge for Gödel's β function -/
theorem beta_bridge (c d i y : Nat) : sat (env4 c d i y) BetaF ↔ BetaChain.beta c d i = y :=
  ⟨fun ⟨q, k, hn, hk⟩ =>
     Eq.trans (congrArg (BetaChain.rem (BetaChain.md d i)) hn)
       (BetaChain.rem_div ((i + 1) * d) q y k hk),
   fun h => match BetaChain.rem_spec ((i + 1) * d) c with
     | ⟨q, r', k, hn, hk, hr⟩ =>
       have e : r' = y := Eq.trans (Eq.symm hr) h
       by cases e; exact ⟨q, k, hn, hk⟩⟩

/-- the β-lemma in the standard model of arithmetic: every finite sequence
  a 0, …, a n is coded by c, d through the formula Beta -/
theorem beta_lemma_arith (a : Nat → Nat) (n : Nat) :
    ∃ c d, ∀ i e, i + e = n → sat (env4 c d i (a i)) BetaF :=
  match BetaChain.beta_lemma a n with
  | ⟨c, d, h⟩ => ⟨c, d, fun i e k => (beta_bridge c d i (a i)).mpr (h i e k)⟩

end Arith

end Found

#print axioms Found.Arith.pre_is_pred
#print axioms Found.Arith.sb_is_sub
#print axioms Found.Arith.up_is_affine
#print axioms Found.Arith.rem_bridge
#print axioms Found.Arith.mdT_eval
#print axioms Found.Arith.beta_bridge
#print axioms Found.Arith.beta_lemma_arith

#print axioms: 37 theorems (30 in BetaChain, 7 in the bridge), no axioms.

85.21 Non-well-founded sets (AFA)

Hypersets are pointed graphs up to bisimilarity; bisimilarity is coinductive and equals having the same members; every graph has a decoration, unique up to bisimilarity (AFA, final coalgebra of powerset); \(\Omega =\{\Omega \}\) refutes foundation; streams are the final \(A\times (-)\) coalgebra. \(x\approx y\iff \forall z\,(z\in x\leftrightarrow z\in y);\quad \exists !\,d,\ d(n)\approx \{d(c)\mid n\to c\}\).

found/AFA.lean

/-
  T105. found/AFA — non-well-founded sets: graphs, bisimulation, Aczel's
  anti-foundation axiom, final coalgebras, streams.  No quotient: hypersets
  are pointed graphs with bisimilarity as the setoid relation.

  * Hypersets: pointed graphs; x ≈ y : there is a bisimulation relating the
    roots; membership z ∈ x : z ≈ (x re-rooted at a child of its root).
  * ≈ is an equivalence; membership respects ≈.
  * Coinduction: every "set bisimulation" R (members of x matched by
    R-related members of y, and back) is contained in ≈.
  * Strong extensionality: x ≈ y ⟺ x and y have the same members.
  * AFA: every graph has a decoration n ↦ (graph rooted at n), and any two
    decorations agree up to ≈ (final coalgebra of the powerset functor).
  * Foundation fails: Ω = {Ω} exists (a one-node loop), Ω ∈ Ω.
  * Streams: functions ℕ → A with the unfold map form the final coalgebra
    of A × (−): unfold commutes and is unique up to pointwise equality.

  Lean 4 core only, hand-written proofs, no axioms.

  CIC dependence: bisimilarity ∃ S (quantification over relations = impredicative Prop).
-/

namespace Found

namespace AFA

structure HS where
  N : Type
  E : N → N → Prop
  root : N

def at' (x : HS) (n : x.N) : HS := ⟨x.N, x.E, n⟩

def Bisim (x y : HS) (S : x.N → y.N → Prop) : Prop :=
  ∀ a b, S a b → (∀ a', x.E a a' → ∃ b', y.E b b' ∧ S a' b') ∧ (∀ b', y.E b b' → ∃ a', x.E a a' ∧ S a' b')

def Eqv (x y : HS) : Prop := ∃ S, Bisim x y S ∧ S x.root y.root

def Mem (z x : HS) : Prop := ∃ c, x.E x.root c ∧ Eqv z (at' x c)

/-! ## ≈ is an equivalence -/

theorem eqv_refl (x : HS) : Eqv x x :=
  ⟨fun a b => a = b, fun a b e => by
    cases e
    exact ⟨fun a' h => ⟨a', h, rfl⟩, fun b' h => ⟨b', h, rfl⟩⟩, rfl⟩

theorem eqv_symm {x y : HS} (h : Eqv x y) : Eqv y x :=
  match h with
  | ⟨S, hS, r⟩ => ⟨fun b a => S a b, fun b a s =>
      ⟨fun b' e => match (hS a b s).2 b' e with | ⟨a', e', s'⟩ => ⟨a', e', s'⟩,
       fun a' e => match (hS a b s).1 a' e with | ⟨b', e', s'⟩ => ⟨b', e', s'⟩⟩, r⟩

theorem eqv_trans {x y z : HS} (h : Eqv x y) (k : Eqv y z) : Eqv x z :=
  match h, k with
  | ⟨S, hS, r⟩, ⟨T, hT, r'⟩ =>
    ⟨fun a c => ∃ b, S a b ∧ T b c, fun a c ⟨b, s, t⟩ =>
      ⟨fun a' e => match (hS a b s).1 a' e with
        | ⟨b', e', s'⟩ => match (hT b c t).1 b' e' with
          | ⟨c', e'', t'⟩ => ⟨c', e'', b', s', t'⟩,
       fun c' e => match (hT b c t).2 c' e with
        | ⟨b', e', t'⟩ => match (hS a b s).2 b' e' with
          | ⟨a', e'', s'⟩ => ⟨a', e'', b', s', t'⟩⟩,
     ⟨y.root, r, r'⟩⟩

/-- a bisimulation relates re-rooted graphs at related nodes -/
theorem eqv_at {x y : HS} {S : x.N → y.N → Prop} (hS : Bisim x y S) {a : x.N} {b : y.N} (s : S a b) :
    Eqv (at' x a) (at' y b) := ⟨S, hS, s⟩

/-- membership respects ≈ on the right -/
theorem mem_eqv {z x y : HS} (m : Mem z x) (h : Eqv x y) : Mem z y :=
  match m, h with
  | ⟨c, e, hz⟩, ⟨_, hS, r⟩ =>
    match (hS x.root y.root r).1 c e with
    | ⟨d, e', s⟩ => ⟨d, e', eqv_trans hz (eqv_at hS s)⟩

/-- membership respects ≈ on the left -/
theorem eqv_mem {z z' x : HS} (h : Eqv z z') (m : Mem z x) : Mem z' x :=
  match m with
  | ⟨c, e, hz⟩ => ⟨c, e, eqv_trans (eqv_symm h) hz⟩

theorem child_mem (x : HS) {c : x.N} (e : x.E x.root c) : Mem (at' x c) x := ⟨c, e, eqv_refl _⟩

/-! ## Coinduction -/

def SetBisim (R : HS → HS → Prop) : Prop :=
  ∀ x y, R x y → (∀ z, Mem z x → ∃ w, Mem w y ∧ R z w) ∧ (∀ w, Mem w y → ∃ z, Mem z x ∧ R z w)

theorem coinduction {R : HS → HS → Prop} (hR : SetBisim R) {x y : HS} (r : R x y) : Eqv x y := by
  refine ⟨fun a b => ∃ x' y', Eqv (at' x a) x' ∧ R x' y' ∧ Eqv y' (at' y b), ?_, ⟨x, y, eqv_refl x, r, eqv_refl y⟩⟩
  intro a b ⟨x', y', h1, r', h2⟩
  constructor
  · intro a' e
    have m : Mem (at' x a') x' := mem_eqv (child_mem (at' x a) e) h1
    match (hR x' y' r').1 _ m with
    | ⟨w, mw, rw⟩ =>
      match mem_eqv mw h2 with
      | ⟨b', e', hw⟩ => exact ⟨b', e', at' x a', w, eqv_refl _, rw, hw⟩
  · intro b' e
    have m : Mem (at' y b') y' := mem_eqv (child_mem (at' y b) e) (eqv_symm h2)
    match (hR x' y' r').2 _ m with
    | ⟨z, mz, rz⟩ =>
      match mem_eqv mz (eqv_symm h1) with
      | ⟨a', e', hz⟩ => exact ⟨a', e', z, at' y b', eqv_symm hz, rz, eqv_refl _⟩

/-- strong extensionality: bisimilar ⟺ same members -/
theorem ext_iff (x y : HS) : Eqv x y ↔ ∀ z, Mem z x ↔ Mem z y :=
  ⟨fun h _ => ⟨fun m => mem_eqv m h, fun m => mem_eqv m (eqv_symm h)⟩,
   fun h => coinduction (R := fun a b => ∀ z, Mem z a ↔ Mem z b)
     (fun _ _ k => ⟨fun z m => ⟨z, (k z).mp m, fun _ => Iff.rfl⟩,
                    fun w m => ⟨w, (k w).mpr m, fun _ => Iff.rfl⟩⟩) h⟩

/-! ## AFA: unique decorations -/

structure Graph where
  N : Type
  E : N → N → Prop

def dec (G : Graph) (n : G.N) : HS := ⟨G.N, G.E, n⟩

/-- the decoration: dec n has exactly the members dec c for children c -/
theorem dec_spec (G : Graph) (n : G.N) (z : HS) : Mem z (dec G n) ↔ ∃ c, G.E n c ∧ Eqv z (dec G c) :=
  Iff.rfl

def IsDecoration (G : Graph) (d : G.N → HS) : Prop :=
  ∀ n z, Mem z (d n) ↔ ∃ c, G.E n c ∧ Eqv z (d c)

theorem dec_is_decoration (G : Graph) : IsDecoration G (dec G) := dec_spec G

/-- AFA: any decoration agrees with dec up to ≈ -/
theorem decoration_unique (G : Graph) (d : G.N → HS) (hd : IsDecoration G d) (n : G.N) :
    Eqv (d n) (dec G n) :=
  coinduction (R := fun x y => ∃ m, Eqv x (d m) ∧ Eqv y (dec G m))
    (fun _ _ ⟨m, hx, hy⟩ =>
      ⟨fun z mz => match (hd m z).mp (mem_eqv mz hx) with
         | ⟨c, e, hz⟩ => ⟨dec G c, mem_eqv (child_mem (dec G m) e) (eqv_symm hy), c, hz, eqv_refl _⟩,
       fun _ mw => match mem_eqv mw hy with
         | ⟨c, e, hw⟩ => ⟨d c, mem_eqv ((hd m (d c)).mpr ⟨c, e, eqv_refl _⟩) (eqv_symm hx), c,
             eqv_refl _, hw⟩⟩)
    ⟨n, eqv_refl _, eqv_refl _⟩

/-! ## Foundation fails: Ω = {Ω} -/

def Omega : HS := ⟨Unit, fun _ _ => True, ()⟩

theorem omega_mem_self : Mem Omega Omega := ⟨(), trivial, eqv_refl _⟩

theorem omega_singleton (z : HS) : Mem z Omega ↔ Eqv z Omega :=
  ⟨fun ⟨_, _, h⟩ => h, fun h => ⟨(), trivial, h⟩⟩

theorem not_foundation : ¬ ∀ x : HS, ¬ Mem x x := fun h => h Omega omega_mem_self

/-! ## Streams: the final coalgebra of A × (−) -/

section Streams
variable {A : Type}

def Stream' (A : Type) : Type := Nat → A

def hd (s : Stream' A) : A := s 0
def tl (s : Stream' A) : Stream' A := fun n => s (n + 1)

def unfold {S : Type} (c : S → A × S) (x : S) : Stream' A
  | 0 => (c x).1
  | n + 1 => unfold c (c x).2 n

/-- unfold is a coalgebra map -/
theorem unfold_hd {S : Type} (c : S → A × S) (x : S) : hd (unfold c x) = (c x).1 := rfl
theorem unfold_tl {S : Type} (c : S → A × S) (x : S) (n : Nat) :
    tl (unfold c x) n = unfold c (c x).2 n := rfl

/-- and the unique one, up to pointwise equality (bisimilarity of streams) -/
theorem unfold_unique {S : Type} (c : S → A × S) (f : S → Stream' A)
    (hh : ∀ x, hd (f x) = (c x).1) (ht : ∀ x n, tl (f x) n = f (c x).2 n) :
    ∀ n x, f x n = unfold c x n
  | 0, x => hh x
  | n + 1, x => (ht x n).trans (unfold_unique c f hh ht n (c x).2)

end Streams

end AFA

end Found

#print axioms Found.AFA.eqv_refl
#print axioms Found.AFA.eqv_symm
#print axioms Found.AFA.eqv_trans
#print axioms Found.AFA.mem_eqv
#print axioms Found.AFA.eqv_mem
#print axioms Found.AFA.coinduction
#print axioms Found.AFA.ext_iff
#print axioms Found.AFA.dec_spec
#print axioms Found.AFA.decoration_unique
#print axioms Found.AFA.omega_mem_self
#print axioms Found.AFA.omega_singleton
#print axioms Found.AFA.not_foundation
#print axioms Found.AFA.unfold_hd
#print axioms Found.AFA.unfold_tl
#print axioms Found.AFA.unfold_unique

#print axioms: 15 theorems, no axioms.

85.22 Forcing as a local operator

Fixed points of a nucleus form a Heyting algebra; \(\neg \neg \) is a nucleus whose fixed points are Boolean and closed under arbitrary meets (Boolean-valued truth values); over bit strings the empty condition forces neither \(p\) nor \(\neg p\) but forces \(\neg \neg (p\vee \neg p)\). \(j(a\wedge b)=ja\wedge jb,\ a\le ja=jja;\quad \top \le \neg \neg (a\vee \neg a)\).

found/Forcing.lean

/-
  T108. found/Forcing — forcing as a local operator on Ω.

  * Nuclei (Lawvere–Tierney topologies on a Heyting algebra): j inflationary,
    idempotent, monotone, preserving ∧.  The fixed points form a Heyting
    algebra (the truth values of the sheaf subtopos).
  * j = ¬¬ is a nucleus on every Heyting algebra (the ∧ law is the T77
    Gödel–Gentzen lemma, read through soundness), and in its fixed points
    excluded middle holds: ¬¬-sheaves are Boolean.
  * Kripke/Cohen forcing over a poset of conditions: the ¬¬ nucleus on
    upsets is "densely often"; arbitrary meets of ¬¬-fixed upsets are fixed
    (a complete Boolean algebra of truth values: Boolean-valued model).
  * Cohen-style example: conditions = finite bit strings under extension,
    p = "the generic bit is 1": the empty condition forces neither p nor ¬p,
    but forces ¬¬(p ∨ ¬p) — the generic is undecided while the forced
    logic is classical.

  Lean 4 core only, hand-written proofs, no axioms.

  CIC dependence: truth values = Prop (UpHA), proof irrelevance.
-/
import found.DNTrans
import found.Modal


universe u

namespace Found

namespace Forcing

open Prp

structure Nucleus (H : HA.{u}) where
  j : H.car → H.car
  infl : ∀ a, H.le a (j a)
  idem : ∀ a, H.le (j (j a)) (j a)
  mono : ∀ {a b}, H.le a b → H.le (j a) (j b)
  meet : ∀ a b, H.le (H.meet (j a) (j b)) (j (H.meet a b))

namespace Nucleus
variable {H : HA.{u}} (n : Nucleus H)

/-- the fixed points of a nucleus form a Heyting algebra -/
def fixHA : HA.{u} where
  car := {a : H.car // H.le (n.j a) a}
  le a b := H.le a.val b.val
  le_refl a := H.le_refl a.val
  le_trans h k := H.le_trans h k
  top := ⟨H.top, H.le_top _⟩
  bot := ⟨n.j H.bot, n.idem _⟩
  meet a b := ⟨H.meet a.val b.val, H.le_trans (H.meet_univ (n.mono (H.meet_l _ _)) (n.mono (H.meet_r _ _)))
    (H.meet_univ (H.le_trans (H.meet_l _ _) a.property) (H.le_trans (H.meet_r _ _) b.property))⟩
  join a b := ⟨n.j (H.join a.val b.val), n.idem _⟩
  imp a b := ⟨H.imp a.val b.val, H.imp_adj.mp (H.le_trans
      (H.meet_univ (H.meet_l _ _) (H.le_trans (H.meet_r _ _) (n.infl _)))
      (H.le_trans (n.meet _ _) (H.le_trans (n.mono (H.mp _ _)) b.property)))⟩
  le_top _ := H.le_top _
  bot_le a := H.le_trans (n.mono (H.bot_le _)) a.property
  meet_l _ _ := H.meet_l _ _
  meet_r _ _ := H.meet_r _ _
  meet_univ h k := H.meet_univ h k
  join_l _ _ := H.le_trans (H.join_l _ _) (n.infl _)
  join_r _ _ := H.le_trans (H.join_r _ _) (n.infl _)
  join_univ {_ _ c} h k := H.le_trans (n.mono (H.join_univ h k)) c.property
  imp_adj := H.imp_adj

end Nucleus

/-! ## The double negation nucleus -/

section NegNeg
variable (H : HA.{u})

/-- an intuitionistic theorem `⊢ φ → ψ` gives `⟦φ⟧ ≤ ⟦ψ⟧` in every Heyting algebra -/
theorem le_of_thm {φ ψ : Form} (d : PD true (fun _ => False) (.imp φ ψ)) (v : Nat → H.car) :
    H.le (interp H v H.bot φ) (interp H v H.bot ψ) :=
  H.le_trans (H.meet_univ (H.le_top _) (H.le_refl _))
    (H.imp_adj.mpr (valid H d v H.bot (fun _ => H.bot_le)))

def negneg : Nucleus H where
  j a := H.neg (H.neg a)
  infl := H.le_negneg
  idem a := H.negnegneg (H.neg a)
  mono h := H.neg_antitone (H.neg_antitone h)
  meet a b := le_of_thm H ((gg_nn (.and (.var 0) (.var 1)) _).1)
    (fun k => match k with | 0 => a | _ => b)

/-- ⊢ ¬¬(p ∨ ¬p) intuitionistically -/
theorem nn_lem : PD true (fun _ => False) (N (.or (.var 0) (neg (.var 0)))) :=
  .impI (.impE h0 (.orI2 (.impI (.impE h1 (.orI1 h0)))))

/-- excluded middle holds under ¬¬: ⊤ ≤ ¬¬(a ∨ ¬a) -/
theorem negneg_lem (a : H.car) : H.le H.top (H.neg (H.neg (H.join a (H.neg a)))) :=
  valid H nn_lem (fun _ => a) H.bot (fun _ => H.bot_le)

/-- the ¬¬-fixed algebra is Boolean -/
theorem negneg_boolean (a : (negneg H).fixHA.car) :
    H.le (H.neg (H.neg a.val)) a.val := a.property

end NegNeg

/-! ## Forcing over a poset of conditions -/

section Poset
variable {W : Type} (R : W → W → Prop) (hr : Modal.Refl R) (ht : Modal.Trans R)

/-- ¬¬ on upsets is "densely often": for every extension there is a further one in U -/
theorem negneg_dense (U : Modal.Up R) (w : W) :
    ((Modal.UpHA R hr ht).neg ((Modal.UpHA R hr ht).neg U)).p w ↔
    ∀ v, R w v → ¬ ∀ u, R v u → ¬ U.p u := Iff.rfl

def meetUp {I : Type} (F : I → Modal.Up R) : Modal.Up R :=
  ⟨fun w => ∀ i, (F i).p w, fun w v r h i => (F i).up w v r (h i)⟩

include hr ht in
/-- arbitrary meets of ¬¬-fixed upsets are ¬¬-fixed: the regular upsets form a
  complete Boolean algebra (the truth values of a Boolean-valued model) -/
theorem fixed_meet {I : Type} (F : I → Modal.Up R)
    (hF : ∀ i, (Modal.UpHA R hr ht).le ((negneg (Modal.UpHA R hr ht)).j (F i)) (F i)) :
    ∀ w, ((negneg (Modal.UpHA R hr ht)).j (meetUp R F)).p w → ∀ i, (F i).p w :=
  fun w h i => hF i w ((negneg (Modal.UpHA R hr ht)).mono (a := meetUp R F) (b := F i)
    (fun _ x => x i) w h)

end Poset

/-! ## A Cohen-style example: finite bit strings -/

inductive Pre : List Bool → List Bool → Prop where
  | nil (l : List Bool) : Pre [] l
  | cons (b : Bool) {l l' : List Bool} : Pre l l' → Pre (b :: l) (b :: l')

theorem pre_refl : (l : List Bool) → Pre l l
  | [] => .nil []
  | b :: l => .cons b (pre_refl l)

theorem pre_trans {a b c : List Bool} (h : Pre a b) (k : Pre b c) : Pre a c := by
  induction h generalizing c with
  | nil _ => exact .nil c
  | cons x _ ih =>
    cases k with
    | cons _ k' => exact .cons x (ih k')

def startsTrue : List Bool → Prop
  | [] => False
  | true :: _ => True
  | false :: _ => False

/-- p = "the generic bit is 1" as an upset of conditions -/
def P : Modal.Up Pre :=
  ⟨startsTrue, fun w v r h => by
    cases r with
    | nil => exact h.elim
    | cons b _ => cases b with
      | false => exact h.elim
      | true => exact trivial⟩

abbrev H2 : HA.{0} := Modal.UpHA Pre (fun l => pre_refl l) (fun _ _ _ h k => pre_trans h k)

/-- the empty condition does not force p -/
theorem not_force_p : ¬ ((negneg H2).j P).p [] :=
  fun h => h [false] (.nil _) (fun u r hu => by
    cases r with
    | cons _ _ => exact hu)

/-- the empty condition does not force ¬p -/
theorem not_force_notp : ¬ (H2.neg P).p [] :=
  fun h => h [true] (.nil _) trivial

/-- but it forces p ∨ ¬p in the ¬¬ (Boolean) sense -/
theorem force_lem : ((negneg H2).j (H2.join P (H2.neg P))).p [] :=
  negneg_lem H2 P [] trivial

end Forcing

end Found

#print axioms Found.Forcing.Nucleus.fixHA
#print axioms Found.Forcing.le_of_thm
#print axioms Found.Forcing.negneg
#print axioms Found.Forcing.nn_lem
#print axioms Found.Forcing.negneg_lem
#print axioms Found.Forcing.negneg_boolean
#print axioms Found.Forcing.negneg_dense
#print axioms Found.Forcing.fixed_meet
#print axioms Found.Forcing.pre_trans
#print axioms Found.Forcing.not_force_p
#print axioms Found.Forcing.not_force_notp
#print axioms Found.Forcing.force_lem

#print axioms: 12 theorems, no axioms.

85.23 Realizability

Over any combinatory algebra, bracket abstraction gives combinatory completeness and realizability predicates form a Heyting algebra (pairs, tagged pairs, application), so intuitionistic theorems are uniformly realized; over the one-point algebra this is \(\Omega \). \((\lambda e)\cdot x=e[x];\quad \varphi \vdash \psi \iff \exists e\,\forall x\in \varphi ,\ e\cdot x\in \psi \).

found/Effective.lean

/-
  T96. found/Effective — realizability (the logic of the effective topos).

  * Combinatory algebras (A, ·, K, S) with K x y = x, S x y z = x z (y z).
  * Bracket abstraction on expressions with de Bruijn variables:
    (λ e) · x = e[x/0]  (combinatory completeness, by induction).
  * Realizability predicates A → Prop with  φ ⊢ ψ :⟺ ∃ e, ∀ x ∈ φ, e·x ∈ ψ
    form a Heyting (pre)algebra: ∧ by pairing, ∨ by tagged pairs, → by
    application.  Hence every intuitionistic theorem is realized (T65).
  * Condition: over the one-point algebra realizability collapses to
    Ω = (Prop, ↔) (the ordinary topos of sets); the effective topos is the
    case of Kleene's first algebra K1 (its construction needs T81: OPEN).

  Lean 4 core only, hand-written proofs, no axioms.

  CIC dependence: realizability predicates are Prop-valued.
-/
import found.Minimal


universe u

namespace Found

namespace Real

structure CA where
  A : Type u
  app : A → A → A
  k : A
  s : A
  k_ax : ∀ x y, app (app k x) y = x
  s_ax : ∀ x y z, app (app (app s x) y) z = app (app x z) (app y z)

namespace CA
variable (M : CA)

def i : M.A := M.app (M.app M.s M.k) M.k

theorem i_ax (x : M.A) : M.app M.i x = x :=
  (M.s_ax M.k M.k x).trans (M.k_ax x _)

/-! ## Bracket abstraction -/

inductive Ex (M : CA) where
  | var : Nat → Ex M
  | c : M.A → Ex M
  | ap : Ex M → Ex M → Ex M

def cons (x : M.A) (ρ : Nat → M.A) : Nat → M.A
  | 0 => x
  | n + 1 => ρ n

def eval (ρ : Nat → M.A) : Ex M → M.A
  | .var n => ρ n
  | .c a => a
  | .ap e f => M.app (eval ρ e) (eval ρ f)

def lam : Ex M → Ex M
  | .var 0 => .c M.i
  | .var (n + 1) => .ap (.c M.k) (.var n)
  | .c a => .ap (.c M.k) (.c a)
  | .ap e f => .ap (.ap (.c M.s) (lam e)) (lam f)

/-- combinatory completeness -/
theorem lam_beta (ρ : Nat → M.A) (x : M.A) : (e : Ex M) →
    M.app (M.eval ρ (M.lam e)) x = M.eval (M.cons x ρ) e
  | .var 0 => M.i_ax x
  | .var (_ + 1) => M.k_ax _ x
  | .c a => M.k_ax a x
  | .ap e f => (M.s_ax _ _ x).trans
      (congrArg₂' M.app (lam_beta ρ x e) (lam_beta ρ x f))
where
  congrArg₂' {α β γ : Sort _} (g : α → β → γ) {a a' : α} {b b' : β} (h1 : a = a') (h2 : b = b') :
      g a b = g a' b' := by
    cases h1
    cases h2
    rfl

def z0 : Nat → M.A := fun _ => M.k

/-- closed λ-terms -/
def L1 (e : Ex M) : M.A := M.eval M.z0 (M.lam e)
def L2 (e : Ex M) : M.A := M.eval M.z0 (M.lam (M.lam e))
def L3 (e : Ex M) : M.A := M.eval M.z0 (M.lam (M.lam (M.lam e)))

/-- the pair combinator λx y f. f x y -/
def P : M.A := M.L3 (.ap (.ap (.var 0) (.var 2)) (.var 1))

def ki : M.A := M.app M.k M.i

theorem pair_k (x y : M.A) : M.app (M.app (M.app M.P x) y) M.k = x := by
  unfold P L3
  rw [lam_beta, lam_beta, lam_beta]
  exact M.k_ax x y

theorem pair_ki (x y : M.A) : M.app (M.app (M.app M.P x) y) M.ki = y := by
  unfold P L3
  rw [lam_beta, lam_beta, lam_beta]
  show M.app (M.app (M.app M.k M.i) x) y = y
  rw [M.k_ax]
  exact M.i_ax y

end CA

/-! ## The realizability Heyting algebra -/

section RHA
variable (M : CA)

def Pr : Type := M.A → Prop

def rle (φ ψ : M.A → Prop) : Prop := ∃ e, ∀ x, φ x → ψ (M.app e x)

theorem mem_eq {φ : M.A → Prop} {x y : M.A} (h : x = y) (p : φ y) : φ x := h ▸ p

def rmeet (a b : M.A → Prop) : M.A → Prop := fun t => a (M.app t M.k) ∧ b (M.app t M.ki)

def rjoin (a b : M.A → Prop) : M.A → Prop :=
  fun t => (M.app t M.k = M.k ∧ a (M.app t M.ki)) ∨ (M.app t M.k = M.ki ∧ b (M.app t M.ki))

def rimp (a b : M.A → Prop) : M.A → Prop := fun f => ∀ x, a x → b (M.app f x)

def RHA : HA.{u} where
  car := M.A → Prop
  le := rle M
  le_refl _ := ⟨M.i, fun x h => mem_eq M (M.i_ax x) h⟩
  le_trans := fun ⟨e₁, h₁⟩ ⟨e₂, h₂⟩ =>
    ⟨M.L1 (.ap (.c e₂) (.ap (.c e₁) (.var 0))),
     fun x hx => mem_eq M (M.lam_beta _ x _) (h₂ _ (h₁ x hx))⟩
  top := fun _ => True
  bot := fun _ => False
  meet := rmeet M
  join := rjoin M
  imp := rimp M
  le_top _ := ⟨M.i, fun _ _ => trivial⟩
  bot_le _ := ⟨M.i, fun _ h => h.elim⟩
  meet_l _ _ := ⟨M.L1 (.ap (.var 0) (.c M.k)), fun x h => mem_eq M (M.lam_beta _ x _) h.1⟩
  meet_r _ _ := ⟨M.L1 (.ap (.var 0) (.c M.ki)), fun x h => mem_eq M (M.lam_beta _ x _) h.2⟩
  meet_univ := fun ⟨e₁, h₁⟩ ⟨e₂, h₂⟩ =>
    ⟨M.L1 (.ap (.ap (.c M.P) (.ap (.c e₁) (.var 0))) (.ap (.c e₂) (.var 0))),
     fun x hx => by
      have e : M.app (M.L1 (.ap (.ap (.c M.P) (.ap (.c e₁) (.var 0))) (.ap (.c e₂) (.var 0)))) x =
          M.app (M.app M.P (M.app e₁ x)) (M.app e₂ x) := M.lam_beta _ x _
      rw [e]
      exact ⟨mem_eq M (M.pair_k _ _) (h₁ x hx), mem_eq M (M.pair_ki _ _) (h₂ x hx)⟩⟩
  join_l _ _ := ⟨M.L1 (.ap (.ap (.c M.P) (.c M.k)) (.var 0)), fun x hx => by
      have e : M.app (M.L1 (.ap (.ap (.c M.P) (.c M.k)) (.var 0))) x = M.app (M.app M.P M.k) x :=
        M.lam_beta _ x _
      rw [e]
      exact Or.inl ⟨M.pair_k _ _, mem_eq M (M.pair_ki _ _) hx⟩⟩
  join_r _ _ := ⟨M.L1 (.ap (.ap (.c M.P) (.c M.ki)) (.var 0)), fun x hx => by
      have e : M.app (M.L1 (.ap (.ap (.c M.P) (.c M.ki)) (.var 0))) x = M.app (M.app M.P M.ki) x :=
        M.lam_beta _ x _
      rw [e]
      exact Or.inr ⟨M.pair_k _ _, mem_eq M (M.pair_ki _ _) hx⟩⟩
  join_univ := fun ⟨e₁, h₁⟩ ⟨e₂, h₂⟩ =>
    ⟨M.L1 (.ap (.ap (.ap (.var 0) (.c M.k)) (.ap (.c e₁) (.ap (.var 0) (.c M.ki))))
               (.ap (.c e₂) (.ap (.var 0) (.c M.ki)))),
     fun t ht => by
      have e : M.app (M.L1 (.ap (.ap (.ap (.var 0) (.c M.k)) (.ap (.c e₁) (.ap (.var 0) (.c M.ki))))
               (.ap (.c e₂) (.ap (.var 0) (.c M.ki))))) t =
          M.app (M.app (M.app t M.k) (M.app e₁ (M.app t M.ki))) (M.app e₂ (M.app t M.ki)) :=
        M.lam_beta _ t _
      rw [e]
      cases ht with
      | inl h =>
        rw [h.1, M.k_ax]
        exact h₁ _ h.2
      | inr h =>
        rw [h.1]
        unfold CA.ki
        rw [M.k_ax, M.i_ax]
        exact h₂ _ h.2⟩
  imp_adj := ⟨fun ⟨e, h⟩ =>
      ⟨M.L2 (.ap (.c e) (.ap (.ap (.c M.P) (.var 1)) (.var 0))), fun z hz x hx => by
        have q : M.app (M.app (M.L2 (.ap (.c e) (.ap (.ap (.c M.P) (.var 1)) (.var 0)))) z) x =
            M.app e (M.app (M.app M.P z) x) := by
          unfold CA.L2
          rw [M.lam_beta, M.lam_beta]
          rfl
        rw [q]
        exact h _ ⟨mem_eq M (M.pair_k _ _) hz, mem_eq M (M.pair_ki _ _) hx⟩⟩,
    fun ⟨e, h⟩ =>
      ⟨M.L1 (.ap (.ap (.c e) (.ap (.var 0) (.c M.k))) (.ap (.var 0) (.c M.ki))), fun t ht => by
        have q : M.app (M.L1 (.ap (.ap (.c e) (.ap (.var 0) (.c M.k))) (.ap (.var 0) (.c M.ki)))) t =
            M.app (M.app e (M.app t M.k)) (M.app t M.ki) := M.lam_beta _ t _
        rw [q]
        exact h _ ht.1 _ ht.2⟩⟩

/-- every intuitionistic propositional theorem is uniformly realized -/
theorem realized {φ : Prp.Form} (d : Prp.PD true (fun _ => False) φ) (v : Nat → M.A → Prop) :
    ∃ e, ∀ x : M.A, Prp.interp (RHA M) v (fun _ => False) φ (M.app e x) :=
  match Prp.valid (RHA M) d v (fun _ => False) (fun _ _ => ⟨M.i, fun _ h => h.elim⟩) with
  | ⟨e, h⟩ => ⟨e, fun x => h x trivial⟩

end RHA

/-! ## The one-point algebra: realizability collapses to Ω -/

def unitCA : CA where
  A := Unit
  app _ _ := ()
  k := ()
  s := ()
  k_ax _ _ := rfl
  s_ax _ _ _ := rfl

theorem unit_le_iff (φ ψ : Unit → Prop) : (RHA unitCA).le φ ψ ↔ (φ () → ψ ()) :=
  ⟨fun ⟨_, h⟩ p => h () p, fun h => ⟨(), fun _ p => h p⟩⟩

end Real

end Found

#print axioms Found.Real.CA.i_ax
#print axioms Found.Real.CA.lam_beta
#print axioms Found.Real.CA.pair_k
#print axioms Found.Real.CA.pair_ki
#print axioms Found.Real.RHA
#print axioms Found.Real.realized
#print axioms Found.Real.unit_le_iff

#print axioms: 7 theorems, no axioms.

85.24 The setoid model

Quotients of setoids by coarser relations have the universal property without Quot.sound; funext holds in setoid exponentials; the axiom of choice for setoids implies excluded middle, while \(\Sigma \)-choice holds outright. \(\mathrm {AC}_{\mathrm {setoid}}\Rightarrow \forall P,\ P\vee \neg P\).

found/Setoid.lean

/-
  T87. found/Setoid — the setoid model as the frame's set theory.

  * Quotients without Quot.sound: the quotient of a setoid by a coarser
    equivalence is the same carrier with the new relation; it has the
    universal property of the quotient (maps respecting R factor uniquely).
  * Function extensionality holds in the setoid exponential by construction
    (equality of maps is pointwise), unlike for plain types (T62).
  * Choice as a condition: the axiom of choice for setoids (every surjection
    has a section) implies excluded middle (Diaconescu–Goodman–Myhill), so
    choice is exactly what separates the setoid model from a Boolean one.
  * Type-theoretic choice (Σ form) holds outright.

  Lean 4 core only, hand-written proofs, no axioms.

  CIC dependence: Σ-choice without large elimination of Subtype; Diaconescu only through Bool decidability.
-/
import found.CCC

namespace Found

namespace SetoidModel

/-! ## Quotients as setoids -/

structure Coarser (X : Setd.{0}) where
  R : X.car → X.car → Prop
  refl : ∀ a, R a a
  symm : ∀ {a b}, R a b → R b a
  trans : ∀ {a b c}, R a b → R b c → R a c
  coarser : ∀ {a b}, X.eqv a b → R a b

def quot {X : Setd.{0}} (C : Coarser X) : Setd.{0} := ⟨X.car, C.R, C.refl, C.symm, C.trans⟩

def proj {X : Setd.{0}} (C : Coarser X) : SHom X (quot C) := ⟨fun x => x, fun h => C.coarser h⟩

/-- the projection identifies exactly the R-related elements -/
theorem proj_eqv {X : Setd.{0}} (C : Coarser X) (a b : X.car) :
    (quot C).eqv ((proj C).fn a) ((proj C).fn b) ↔ C.R a b := Iff.rfl

/-- universal property: a map respecting R factors through the quotient -/
def lift {X Y : Setd.{0}} (C : Coarser X) (f : SHom X Y) (hf : ∀ {a b}, C.R a b → Y.eqv (f.fn a) (f.fn b)) :
    SHom (quot C) Y := ⟨f.fn, hf⟩

theorem lift_comm {X Y : Setd.{0}} (C : Coarser X) (f : SHom X Y)
    (hf : ∀ {a b}, C.R a b → Y.eqv (f.fn a) (f.fn b)) :
    SetdCat.heq (SetdCat.comp (proj C) (lift C f hf)) f := fun x => Y.refl (f.fn x)

theorem lift_unique {X Y : Setd.{0}} (C : Coarser X) (f : SHom X Y)
    (hf : ∀ {a b}, C.R a b → Y.eqv (f.fn a) (f.fn b)) (g : SHom (quot C) Y)
    (hg : SetdCat.heq (SetdCat.comp (proj C) g) f) : SetdCat.heq g (lift C f hf) := hg

/-! ## Function extensionality in the setoid model -/

theorem setoid_funext {X Y : Setd.{0}} (f g : SHom X Y) (h : ∀ x, Y.eqv (f.fn x) (g.fn x)) :
    (expS X Y).eqv f g := h

/-! ## Choice ⇒ excluded middle -/

def Surj {X Y : Setd.{0}} (f : SHom X Y) : Prop := ∀ y, ∃ x, Y.eqv (f.fn x) y

def SetoidAC : Prop :=
  ∀ (X Y : Setd.{0}) (f : SHom X Y), Surj f → ∃ s : SHom Y X, ∀ y, Y.eqv (f.fn (s.fn y)) y

def boolEq : Setd.{0} := ⟨Bool, Eq, fun _ => rfl, fun h => h.symm, fun h k => h.trans k⟩

def boolP (P : Prop) : Setd.{0} where
  car := Bool
  eqv a b := a = b ∨ P
  refl _ := Or.inl rfl
  symm h := h.elim (fun e => Or.inl e.symm) Or.inr
  trans h k := h.elim (fun e => k.elim (fun e' => Or.inl (e.trans e')) Or.inr) Or.inr

/-- Diaconescu–Goodman–Myhill in the setoid model -/
theorem ac_lem (hAC : SetoidAC) (P : Prop) : P ∨ ¬ P :=
  match hAC boolEq (boolP P) ⟨fun b => b, fun e => Or.inl e⟩ (fun y => ⟨y, Or.inl rfl⟩) with
  | ⟨s, hs⟩ =>
    match hs true, hs false with
    | Or.inr p, _ => Or.inl p
    | _, Or.inr p => Or.inl p
    | Or.inl e1, Or.inl e2 =>
      Or.inr fun p =>
        have k : s.fn true = s.fn false := s.resp (Or.inr p)
        Bool.noConfusion (e1.symm.trans (k.trans e2))

/-- type-theoretic choice (Σ form) holds outright -/
theorem sigma_choice {A B : Type} (R : A → B → Prop) (h : ∀ a, {b // R a b}) :
    ∃ f : A → B, ∀ a, R a (f a) := ⟨fun a => (h a).val, fun a => (h a).property⟩

end SetoidModel

end Found

#print axioms Found.SetoidModel.proj_eqv
#print axioms Found.SetoidModel.lift
#print axioms Found.SetoidModel.lift_comm
#print axioms Found.SetoidModel.lift_unique
#print axioms Found.SetoidModel.setoid_funext
#print axioms Found.SetoidModel.ac_lem
#print axioms Found.SetoidModel.sigma_choice

#print axioms: 7 theorems, no axioms.

85.25 Mostowski collapse and Aczel’s V

On well-founded extensional graphs bisimulations are equality, so the collapse into hypersets is injective; Aczel’s tree universe is an extensional setoid with \(\in \)-induction and no \(x\in x\), in contrast with \(\Omega =\{\Omega \}\) under AFA. \(\mathrm {WF}+\mathrm {Ext}\Rightarrow (n\approx m\Rightarrow n=m);\quad \forall x\in V,\ x\notin x\).

found/Mostowski.lean

/-
  T109. found/Mostowski — the well-founded side: Mostowski collapse and
  Aczel's tree universe V (the initial algebra; T105 is the final coalgebra).

  * Graph level: on a well-founded (accessible) extensional graph every
    bisimulation is contained in equality — the Mostowski collapse
    n ↦ (set of collapses of children) is injective.  Well-founded graphs
    have no loops.
  * Aczel's V: well-founded trees sup (I, f) with bisimilarity defined by
    recursion (a setoid, no quotient); membership; extensionality holds by
    definition, and ∈-induction (foundation) holds: no x ∈ x, no 2-cycles.
  * Contrast with AFA (T105): there Ω ∈ Ω; here ¬ x ∈ x — initial algebra
    versus final coalgebra of the same powerset functor.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.AFA
import found.Base

namespace Found

namespace WF

/-! ## Graph level -/

section Graph
variable {N : Type} (E : N → N → Prop)

def Child (c n : N) : Prop := E n c

def WellFounded' : Prop := ∀ n, Acc (Child E) n

def Extensional : Prop :=
  ∀ n m, (∀ c, E n c → E m c) → (∀ c, E m c → E n c) → n = m

def GBisim (S : N → N → Prop) : Prop :=
  ∀ a b, S a b → (∀ a', E a a' → ∃ b', E b b' ∧ S a' b') ∧ (∀ b', E b b' → ∃ a', E a a' ∧ S a' b')

/-- Mostowski: on a well-founded extensional graph, bisimilar nodes are equal -/
theorem bisim_eq (hW : WellFounded' E) (hX : Extensional E) {S : N → N → Prop} (hS : GBisim E S) :
    ∀ n m, S n m → n = m := by
  intro n
  induction hW n with
  | intro n _ ih =>
    intro m s
    apply hX n m
    · intro c e
      match (hS n m s).1 c e with
      | ⟨d, e', s'⟩ => exact (ih c e d s') ▸ e'
    · intro d e
      match (hS n m s).2 d e with
      | ⟨c, e', s'⟩ => exact (ih c e' d s').symm ▸ e'

/-- the collapse is injective: equal decorations (in the AFA universe) only for equal nodes -/
theorem collapse_injective (hW : WellFounded' E) (hX : Extensional E) (n m : N)
    (h : AFA.Eqv (AFA.dec ⟨N, E⟩ n) (AFA.dec ⟨N, E⟩ m)) : n = m :=
  match h with
  | ⟨S, hS, s⟩ => bisim_eq E hW hX (S := S) hS n m s

/-- well-founded graphs have no loops -/
theorem no_loop (hW : WellFounded' E) (n : N) : ¬ E n n := by
  induction hW n with
  | intro n _ ih => exact fun e => ih n e e

end Graph

/-! ## Aczel's V: well-founded trees -/

universe uV

inductive V : Type (uV + 1) where
  | sup (I : Type uV) (f : I → V) : V

def V.I : V.{uV} → Type uV
  | .sup I _ => I

def V.f : (x : V.{uV}) → x.I → V.{uV}
  | .sup _ f => f

/-- bisimilarity of trees, by recursion -/
def Eq' : V.{uV} → V.{uV} → Prop
  | .sup _ f, .sup _ g => (∀ i, ∃ j, Eq' (f i) (g j)) ∧ (∀ j, ∃ i, Eq' (f i) (g j))

def Mem (x y : V.{uV}) : Prop := ∃ j, Eq' x (y.f j)

theorem eq_refl : (x : V.{uV}) → Eq' x x
  | .sup _ f => ⟨fun i => ⟨i, eq_refl (f i)⟩, fun j => ⟨j, eq_refl (f j)⟩⟩

theorem eq_symm : (x y : V.{uV}) → Eq' x y → Eq' y x
  | .sup _ _, .sup _ _, ⟨h1, h2⟩ =>
    ⟨fun j => match h2 j with | ⟨i, e⟩ => ⟨i, eq_symm _ _ e⟩,
     fun i => match h1 i with | ⟨j, e⟩ => ⟨j, eq_symm _ _ e⟩⟩

theorem eq_trans : (x y z : V.{uV}) → Eq' x y → Eq' y z → Eq' x z
  | .sup _ _, .sup _ _, .sup _ _, ⟨a1, a2⟩, ⟨b1, b2⟩ =>
    ⟨fun i => match a1 i with
       | ⟨j, e⟩ => match b1 j with
         | ⟨k, e'⟩ => ⟨k, eq_trans _ _ _ e e'⟩,
     fun k => match b2 k with
       | ⟨j, e'⟩ => match a2 j with
         | ⟨i, e⟩ => ⟨i, eq_trans _ _ _ e e'⟩⟩

/-- the trees with bisimilarity: Aczel's setoid model of sets -/
def VS : Found.Setd.{uV + 1} := ⟨V.{uV}, Eq', eq_refl, fun h => eq_symm _ _ h, fun h k => eq_trans _ _ _ h k⟩

theorem mem_resp_right {x y z : V.{uV}} (m : Mem x y) (e : Eq' y z) : Mem x z :=
  match y, z, m, e with
  | .sup _ _, .sup _ _, ⟨j, ex⟩, ⟨e1, _⟩ =>
    match e1 j with
    | ⟨k, e'⟩ => ⟨k, eq_trans _ _ _ ex e'⟩

theorem mem_resp_left {x x' y : V.{uV}} (e : Eq' x x') (m : Mem x y) : Mem x' y :=
  match m with
  | ⟨j, ex⟩ => ⟨j, eq_trans _ _ _ (eq_symm _ _ e) ex⟩

/-- extensionality -/
theorem extensionality (x y : V.{uV}) (h : ∀ z : V.{uV}, Mem z x ↔ Mem z y) : Eq' x y :=
  match x, y with
  | .sup _ f, .sup _ g =>
    ⟨fun i => (h (f i)).mp ⟨i, eq_refl _⟩,
     fun j => match (h (g j)).mpr ⟨j, eq_refl _⟩ with
       | ⟨i, e⟩ => ⟨i, eq_symm _ _ e⟩⟩

/-- ∈-induction (foundation as an induction principle, for respecting predicates) -/
theorem mem_induction (P : V.{uV} → Prop) (hP : ∀ x y, Eq' x y → P x → P y)
    (step : ∀ x : V.{uV}, (∀ y : V.{uV}, Mem y x → P y) → P x) : ∀ x : V.{uV}, P x
  | .sup _ f => step _ (fun _ ⟨i, e⟩ => hP _ _ (eq_symm _ _ e) (mem_induction P hP step (f i)))

/-- foundation: no set is a member of itself -/
theorem not_mem_self : ∀ x : V.{uV}, ¬ Mem x x :=
  mem_induction (fun x => ¬ Mem x x)
    (fun _ _ e h m => h (mem_resp_left (eq_symm _ _ e) (mem_resp_right m (eq_symm _ _ e))))
    (fun x ih m => ih x m m)

/-- the initial/final contrast: V.{uV} has foundation, the AFA universe does not -/
theorem wf_vs_afa : (∀ x : V.{uV}, ¬ Mem x x) ∧ ¬ (∀ x : AFA.HS, ¬ AFA.Mem x x) :=
  ⟨not_mem_self, AFA.not_foundation⟩

end WF

end Found

#print axioms Found.WF.bisim_eq
#print axioms Found.WF.collapse_injective
#print axioms Found.WF.no_loop
#print axioms Found.WF.eq_refl
#print axioms Found.WF.eq_symm
#print axioms Found.WF.eq_trans
#print axioms Found.WF.VS
#print axioms Found.WF.mem_resp_right
#print axioms Found.WF.mem_resp_left
#print axioms Found.WF.extensionality
#print axioms Found.WF.mem_induction
#print axioms Found.WF.not_mem_self
#print axioms Found.WF.wf_vs_afa

#print axioms: 13 theorems, no axioms.

85.26 Presheaf toposes and sheaf truth values

Sieves on an object form a Heyting algebra; the presheaf of sieves classifies stable subpresheaves with a unique characteristic map; a Grothendieck topology given as a nucleus on sieves has its closed sieves as sheaf truth values, Boolean for the dense topology. \(P(x)\iff \mathrm {id}\in \chi _P(x),\quad \chi '\simeq \chi _P;\quad \Omega _J(c)=\mathrm {Fix}(j_c)\).

found/Sheaf.lean

/-
  T95. found/Sheaf — presheaf toposes and sheaf truth values.

  * For a small E-category C, sieves on c (sets of arrows into c closed
    under precomposition, respecting ≈) form a Heyting algebra.
  * Ω is a setoid-valued presheaf (pullback of sieves), and it classifies
    subpresheaves: for a stable predicate P on a presheaf Q there is a
    natural χ_P : Q → Ω with  P x ⟺ id ∈ χ_P(x),  and any natural map with
    this property agrees with χ_P (uniqueness).  So Psh(C) is a topos in
    the frame, with no size condition on C beyond being an E-category.
  * Grothendieck topologies as nuclei on sieves (T108): the truth values of
    the sheaf subtopos are the fixed sieves, again a Heyting algebra; the
    dense (¬¬) topology is one example.  Sheafification is OPEN (L95a).

  Lean 4 core only, hand-written proofs, no axioms.

  CIC dependence: sieves = Prop-valued predicates (impredicative Prop).
-/
import found.Forcing
import found.Cat

namespace Found

namespace Sh

variable {C : ECat.{0, 0}}

structure Sieve (C : ECat.{0, 0}) (c : C.Ob) where
  S : {d : C.Ob} → C.Hom d c → Prop
  resp : ∀ {d} {f g : C.Hom d c}, C.heq f g → S f → S g
  stable : ∀ {d e} {f : C.Hom d c}, S f → ∀ (g : C.Hom e d), S (C.comp g f)

def SieveHA (C : ECat.{0, 0}) (c : C.Ob) : HA.{0} where
  car := Sieve C c
  le A B := ∀ d (f : C.Hom d c), A.S f → B.S f
  le_refl _ _ _ h := h
  le_trans h k d f x := k d f (h d f x)
  top := ⟨fun _ => True, fun _ _ => trivial, fun _ _ => trivial⟩
  bot := ⟨fun _ => False, fun _ h => h, fun h _ => h⟩
  meet A B := ⟨fun f => A.S f ∧ B.S f, fun e h => ⟨A.resp e h.1, B.resp e h.2⟩,
    fun h g => ⟨A.stable h.1 g, B.stable h.2 g⟩⟩
  join A B := ⟨fun f => A.S f ∨ B.S f,
    fun e h => h.elim (fun x => Or.inl (A.resp e x)) (fun y => Or.inr (B.resp e y)),
    fun h g => h.elim (fun x => Or.inl (A.stable x g)) (fun y => Or.inr (B.stable y g))⟩
  imp A B := ⟨fun {d} f => ∀ e (g : C.Hom e d), A.S (C.comp g f) → B.S (C.comp g f),
    fun {_} {_ _} e h x g a => B.resp (C.rcong g e) (h x g (A.resp (C.rcong g (C.hsymm e)) a)),
    fun {_ _} {f} h k x g a =>
      B.resp (C.assoc g k f) (h x (C.comp g k) (A.resp (C.hsymm (C.assoc g k f)) a))⟩
  le_top _ _ _ _ := trivial
  bot_le _ _ _ h := h.elim
  meet_l _ _ _ _ h := h.1
  meet_r _ _ _ _ h := h.2
  meet_univ h k d f x := ⟨h d f x, k d f x⟩
  join_l _ _ _ _ h := Or.inl h
  join_r _ _ _ _ h := Or.inr h
  join_univ h k d f x := x.elim (h d f) (k d f)
  imp_adj {A B R} := ⟨fun h _ f r e g a => h e (C.comp g f) ⟨R.stable r g, a⟩,
    fun h d f x => B.resp (C.id_comp f)
      (h d f x.1 d (C.id d) (A.resp (C.hsymm (C.id_comp f)) x.2))⟩

/-- Ω as a setoid-valued presheaf: sieves, acted on by pullback -/
def OmegaP (C : ECat.{0, 0}) : Psh.{0, 0, 0} C where
  obj c := ⟨Sieve C c, fun A B => ∀ d (f : C.Hom d c), A.S f ↔ B.S f,
    fun _ _ _ => Iff.rfl, fun h d f => (h d f).symm, fun h k d f => (h d f).trans (k d f)⟩
  map f A := ⟨fun g => A.S (C.comp g f), fun e h => A.resp (C.lcong e f) h,
    fun h g => A.resp (C.hsymm (C.assoc _ _ _)) (A.stable h g)⟩
  map_eqv f := fun {_ _} h _ g => h _ (C.comp g f)
  map_resp A e _ g := ⟨A.resp (C.rcong g e), A.resp (C.rcong g (C.hsymm e))⟩
  map_id _ A _ g := ⟨A.resp (C.comp_id g), A.resp (C.hsymm (C.comp_id g))⟩
  map_comp f g A _ h := ⟨A.resp (C.hsymm (C.assoc h f g)), A.resp (C.assoc h f g)⟩

/-! ## Ω classifies subpresheaves -/

section Classify
variable (Q : Psh.{0, 0, 0} C)

structure SubP where
  P : {c : C.Ob} → (Q.obj c).car → Prop
  resp : ∀ {c} {x y : (Q.obj c).car}, (Q.obj c).eqv x y → P x → P y
  stable : ∀ {c d} (f : C.Hom d c) {x : (Q.obj c).car}, P x → P (Q.map f x)

variable {Q}

def chi (P : SubP Q) : PNat Q (OmegaP C) where
  app _ x := ⟨fun f => P.P (Q.map f x),
    fun e h => P.resp (Q.map_resp x e) h,
    fun {_ _ f} h g => P.resp ((Q.obj _).symm (Q.map_comp g f x)) (P.stable g h)⟩
  app_eqv _ := fun {_ _} h _ f => ⟨P.resp (Q.map_eqv f h), P.resp (Q.map_eqv f ((Q.obj _).symm h))⟩
  nat f x _ g := ⟨P.resp ((Q.obj _).symm (Q.map_comp g f x)), P.resp (Q.map_comp g f x)⟩

/-- P x ⟺ the identity is in χ_P(x) -/
theorem chi_id (P : SubP Q) {c : C.Ob} (x : (Q.obj c).car) :
    P.P x ↔ ((chi P).app c x).S (C.id c) :=
  ⟨fun h => P.resp ((Q.obj c).symm (Q.map_id c x)) h, fun h => P.resp (Q.map_id c x) h⟩

/-- uniqueness: a natural map to Ω classifying P is χ_P -/
theorem chi_unique (P : SubP Q) (χ' : PNat Q (OmegaP C))
    (h : ∀ c (x : (Q.obj c).car), P.P x ↔ (χ'.app c x).S (C.id c)) :
    ∀ c (x : (Q.obj c).car) d (f : C.Hom d c), (χ'.app c x).S f ↔ ((chi P).app c x).S f :=
  fun c x d f =>
    have n := χ'.nat f x d (C.id d)
    ⟨fun k => (h d (Q.map f x)).mpr (n.mpr ((χ'.app c x).resp (C.hsymm (C.id_comp f)) k)),
     fun k => (χ'.app c x).resp (C.id_comp f) (n.mp ((h d (Q.map f x)).mp k))⟩

end Classify

/-! ## Sheaf truth values -/

/-- a Grothendieck topology given as a nucleus on the sieves of each object -/
def Topology (C : ECat.{0, 0}) : Type := (c : C.Ob) → Forcing.Nucleus (SieveHA C c)

/-- the truth values of the sheaf subtopos at c: the closed sieves -/
def SheafOmega (J : Topology C) (c : C.Ob) : HA.{0} := (J c).fixHA

/-- the dense (double negation) topology -/
def dense (C : ECat.{0, 0}) : Topology C := fun c => Forcing.negneg (SieveHA C c)

/-- in the dense topology, sheaf truth values are Boolean -/
theorem dense_boolean (c : C.Ob) (A : (SheafOmega (dense C) c).car) :
    (SieveHA C c).le ((SieveHA C c).neg ((SieveHA C c).neg A.val)) A.val :=
  Forcing.negneg_boolean (SieveHA C c) A

end Sh

end Found

#print axioms Found.Sh.SieveHA
#print axioms Found.Sh.OmegaP
#print axioms Found.Sh.chi
#print axioms Found.Sh.chi_id
#print axioms Found.Sh.chi_unique
#print axioms Found.Sh.SheafOmega
#print axioms Found.Sh.dense
#print axioms Found.Sh.dense_boolean

#print axioms: 8 theorems, no axioms.

85.27 Natural numbers objects

Natural numbers objects are stated for an arbitrary E-category with a terminal object and are unique up to isomorphism; the discrete setoid of naturals is one, and its iteration is the primitive recursion of the standard model of arithmetic. \(A,B\ \mathrm {NNO}\Rightarrow \mathrm {iter}_B\circ \mathrm {iter}_A\simeq \mathrm {id}\).

found/NNO.lean

/-
  T86. found/NNO — natural numbers objects as a parameter value, and the
  bridge to arithmetic.

  * General: an NNO in any E-category C with a terminal object
    (zero, succ, iteration, uniqueness up to ≈) — stated for the parameter C.
  * Instance: the discrete setoid of ℕ is an NNO in the setoid category.
  * Uniqueness: any two NNOs in the same C are isomorphic (general proof).
  * Bridge to arithmetic: iteration in the instance is primitive recursion,
    the operations of the standard model used by ArithBridge (T85a) — so
    Heyting arithmetic's standard model is the NNO instance of the
    category parameter.

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: structural recursion on Nat (iteration).
-/
import found.CCC

namespace Found

namespace NNOs

universe u v

structure NNO (C : ECat.{u, v}) (T : Terminal C) where
  N : C.Ob
  z : C.Hom T.one N
  s : C.Hom N N
  iter : {X : C.Ob} → C.Hom T.one X → C.Hom X X → C.Hom N X
  iter_z : ∀ {X} (x : C.Hom T.one X) (f : C.Hom X X), C.heq (C.comp z (iter x f)) x
  iter_s : ∀ {X} (x : C.Hom T.one X) (f : C.Hom X X),
    C.heq (C.comp s (iter x f)) (C.comp (iter x f) f)
  uniq : ∀ {X} (x : C.Hom T.one X) (f : C.Hom X X) (h : C.Hom N X),
    C.heq (C.comp z h) x → C.heq (C.comp s h) (C.comp h f) → C.heq h (iter x f)

/-- two NNOs are isomorphic (general, for any C) -/
theorem nno_iso {C : ECat.{u, v}} {T : Terminal C} (A B : NNO C T) :
    C.heq (C.comp (A.iter B.z B.s) (B.iter A.z A.s)) (C.id A.N) := by
  have h1 : C.heq (C.comp A.z (C.comp (A.iter B.z B.s) (B.iter A.z A.s))) A.z :=
    C.htrans (C.hsymm (C.assoc _ _ _)) (C.htrans (C.lcong (A.iter_z _ _) _) (B.iter_z _ _))
  have h2 : C.heq (C.comp A.s (C.comp (A.iter B.z B.s) (B.iter A.z A.s)))
      (C.comp (C.comp (A.iter B.z B.s) (B.iter A.z A.s)) A.s) :=
    C.htrans (C.hsymm (C.assoc _ _ _))
    (C.htrans (C.lcong (A.iter_s _ _) _)
    (C.htrans (C.assoc _ _ _)
    (C.htrans (C.rcong _ (B.iter_s _ _)) (C.hsymm (C.assoc _ _ _)))))
  have k1 := A.uniq A.z A.s _ h1 h2
  have k2 := A.uniq A.z A.s (C.id A.N) (C.comp_id A.z)
    (C.htrans (C.comp_id A.s) (C.hsymm (C.id_comp A.s)))
  exact C.htrans k1 (C.hsymm k2)

/-! ## Instance: ℕ in setoids -/

def natS : Setd.{0} := ⟨Nat, Eq, fun _ => rfl, fun h => h.symm, fun h k => h.trans k⟩

def iterF {X : Setd.{0}} (x0 : X.car) (f : SHom X X) : Nat → X.car
  | 0 => x0
  | n + 1 => f.fn (iterF x0 f n)

def natNNO : NNO SetdCat.{0} setdTerminal where
  N := natS
  z := ⟨fun _ => Nat.zero, fun _ => rfl⟩
  s := ⟨Nat.succ, fun h => congrArg Nat.succ h⟩
  iter x f := ⟨iterF (x.fn PUnit.unit) f, fun {a b} h => by cases h; exact Setd.refl _ _⟩
  iter_z {X} x _ _ := X.refl _
  iter_s {X} _ _ _ := X.refl _
  uniq {X} x f h hz hs := by
    intro n
    induction n with
    | zero => exact hz PUnit.unit
    | succ n ih => exact X.trans (hs n) (f.resp ih)

/-- the bridge: iteration of successor from zero is the identity on ℕ, and
  iteration of `+ m` computes addition — the standard model's operations -/
theorem iter_succ_id (n : Nat) : iterF (X := natS) Nat.zero ⟨Nat.succ, fun h => congrArg Nat.succ h⟩ n = n := by
  induction n with
  | zero => rfl
  | succ n ih => exact congrArg Nat.succ ih

end NNOs

end Found

#print axioms Found.NNOs.nno_iso
#print axioms Found.NNOs.natNNO
#print axioms Found.NNOs.iter_succ_id

#print axioms: 3 theorems, no axioms.

85.28 Model categories

Model structures are classes of weak equivalences, cofibrations and fibrations on the category parameter with 2-out-of-3, liftings and factorizations; every E-category carries the trivial one with isomorphisms as weak equivalences. \(W=\mathrm {Iso},\ \mathrm {Cof}=\mathrm {Fib}=\mathrm {all}\ \Rightarrow \ (W,\mathrm {Cof},\mathrm {Fib})\ \text {model}\).

found/ModelCat.lean

/-
  T133. found/ModelCat — Quillen model structures as a parameter value on
  the category parameter C (setoid homs, no quotient).

  * Isomorphisms, 2-out-of-3 for isomorphisms (general).
  * Lifting property of a square, model structure (W, Cof, Fib): W has
    2-out-of-3 and contains identities, Cof ∩ W ⧄ Fib, Cof ⧄ Fib ∩ W,
    both factorizations.
  * Instance, for every E-category C: the trivial model structure
    (W = isomorphisms, Cof = Fib = all maps).  Its homotopy category is C.
  Known range only (simplicial/Kan instance: T134; Shulman's path: T136).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Cat

namespace Found

namespace Model

universe u v

variable {C : ECat.{u, v}}

def IsIso {a b : C.Ob} (f : C.Hom a b) : Prop :=
  ∃ g : C.Hom b a, C.heq (C.comp f g) (C.id a) ∧ C.heq (C.comp g f) (C.id b)

theorem iso_id (a : C.Ob) : IsIso (C.id a) := ⟨C.id a, C.id_comp _, C.id_comp _⟩

theorem iso_comp {a b c : C.Ob} {f : C.Hom a b} {g : C.Hom b c} (hf : IsIso f) (hg : IsIso g) :
    IsIso (C.comp f g) :=
  match hf, hg with
  | ⟨f', f1, f2⟩, ⟨g', g1, g2⟩ =>
    ⟨C.comp g' f',
     C.htrans (C.assoc _ _ _) (C.htrans (C.rcong f (C.htrans (C.hsymm (C.assoc _ _ _))
       (C.htrans (C.lcong g1 f') (C.id_comp f')))) f1),
     C.htrans (C.assoc _ _ _) (C.htrans (C.rcong g' (C.htrans (C.hsymm (C.assoc _ _ _))
       (C.htrans (C.lcong f2 g) (C.id_comp g)))) g2)⟩

theorem iso_inv_left {a b c : C.Ob} {f : C.Hom a b} {f' : C.Hom b a} {g : C.Hom b c} {h : C.Hom c a}
    (f2 : C.heq (C.comp f' f) (C.id b)) (h1 : C.heq (C.comp (C.comp f g) h) (C.id a)) :
    C.heq (C.comp g (C.comp h f)) (C.id b) :=
  C.htrans (C.hsymm (C.id_comp _)) (C.htrans (C.lcong (C.hsymm f2) _)
    (C.htrans (C.assoc _ _ _) (C.htrans (C.rcong f' (C.htrans (C.hsymm (C.assoc _ _ _))
      (C.htrans (C.hsymm (C.assoc _ _ _)) (C.htrans (C.lcong h1 f) (C.id_comp f))))) f2)))

/-- 2-out-of-3: f and f ; g isomorphisms ⇒ g isomorphism -/
theorem iso_right {a b c : C.Ob} {f : C.Hom a b} {g : C.Hom b c} (hf : IsIso f)
    (hfg : IsIso (C.comp f g)) : IsIso g :=
  match hf, hfg with
  | ⟨_, _, f2⟩, ⟨h, h1, h2⟩ => ⟨C.comp h f, iso_inv_left f2 h1, C.htrans (C.assoc _ _ _) h2⟩

/-- lifting property of i against p -/
def Lifts {a b x y : C.Ob} (i : C.Hom a b) (p : C.Hom x y) : Prop :=
  ∀ (u : C.Hom a x) (w : C.Hom b y), C.heq (C.comp u p) (C.comp i w) →
    ∃ h : C.Hom b x, C.heq (C.comp i h) u ∧ C.heq (C.comp h p) w

def Cls (C : ECat.{u, v}) : Type (max u v) := ∀ {a b : C.Ob}, C.Hom a b → Prop

structure ModelStr (C : ECat.{u, v}) where
  W : Cls C
  Cof : Cls C
  Fib : Cls C
  W_id : ∀ a, W (C.id a)
  W_comp : ∀ {a b c} {f : C.Hom a b} {g : C.Hom b c}, W f → W g → W (C.comp f g)
  W_right : ∀ {a b c} {f : C.Hom a b} {g : C.Hom b c}, W f → W (C.comp f g) → W g
  lift1 : ∀ {a b x y} {i : C.Hom a b} {p : C.Hom x y}, Cof i → W i → Fib p → Lifts i p
  lift2 : ∀ {a b x y} {i : C.Hom a b} {p : C.Hom x y}, Cof i → Fib p → W p → Lifts i p
  fact1 : ∀ {a b} (f : C.Hom a b), ∃ m, ∃ i : C.Hom a m, ∃ p : C.Hom m b,
    Cof i ∧ W i ∧ Fib p ∧ C.heq (C.comp i p) f
  fact2 : ∀ {a b} (f : C.Hom a b), ∃ m, ∃ i : C.Hom a m, ∃ p : C.Hom m b,
    Cof i ∧ Fib p ∧ W p ∧ C.heq (C.comp i p) f

theorem lift_of_iso_left {a b x y : C.Ob} {i : C.Hom a b} (p : C.Hom x y) (hi : IsIso i) : Lifts i p :=
  fun u w e => match hi with
  | ⟨j, i1, i2⟩ =>
    ⟨C.comp j u,
     C.htrans (C.hsymm (C.assoc _ _ _)) (C.htrans (C.lcong i1 u) (C.id_comp u)),
     C.htrans (C.assoc _ _ _) (C.htrans (C.rcong j e)
       (C.htrans (C.hsymm (C.assoc _ _ _)) (C.htrans (C.lcong i2 w) (C.id_comp w))))⟩

theorem lift_of_iso_right {a b x y : C.Ob} (i : C.Hom a b) {p : C.Hom x y} (hp : IsIso p) : Lifts i p :=
  fun u w e => match hp with
  | ⟨q, p1, p2⟩ =>
    ⟨C.comp w q,
     C.htrans (C.hsymm (C.assoc _ _ _)) (C.htrans (C.lcong (C.hsymm e) q)
       (C.htrans (C.assoc _ _ _) (C.htrans (C.rcong u p1) (C.comp_id u)))),
     C.htrans (C.assoc _ _ _) (C.htrans (C.rcong w p2) (C.comp_id w))⟩

/-- every E-category carries the trivial model structure -/
def trivialModel (C : ECat.{u, v}) : ModelStr C where
  W := fun f => IsIso f
  Cof := fun _ => True
  Fib := fun _ => True
  W_id a := iso_id a
  W_comp hf hg := iso_comp hf hg
  W_right hf hfg := iso_right hf hfg
  lift1 _ hi _ := lift_of_iso_left _ hi
  lift2 _ _ hp := lift_of_iso_right _ hp
  fact1 f := ⟨_, C.id _, f, True.intro, iso_id _, True.intro, C.id_comp f⟩
  fact2 f := ⟨_, f, C.id _, True.intro, True.intro, iso_id _, C.comp_id f⟩

end Model

end Found

#print axioms Found.Model.iso_comp
#print axioms Found.Model.iso_right
#print axioms Found.Model.lift_of_iso_left
#print axioms Found.Model.lift_of_iso_right
#print axioms Found.Model.trivialModel

#print axioms: 5 theorems, no axioms.

85.29 ETCS as a point

In setoids maps are determined by global elements; with the natural numbers object reused, the ETCS conditions on the setoid coordinate reduce to choice, which already gives a Boolean \(\Omega \). \(\mathrm {AC}_{\mathrm {setoid}}\Rightarrow (\mathrm {LEM}\wedge \mathrm {AC})\Rightarrow \Omega \ \text {Boolean}\).

found/ETCS.lean

/-
  T107. found/ETCS — Lawvere's ETCS as a point: the setoid category with
  conditions on the coordinates.

  ETCS = topos (T63) + well-pointed + NNO (T86) + Boolean Ω (T66) + choice (T87).
  * Well-pointed: in setoids, maps are determined by global elements (proved).
  * NNO: the discrete ℕ (T86), reused.
  * Boolean Ω ⟺ excluded middle (T66, reused); choice ⇒ excluded middle (T87,
    reused): so the point ETCS sits over the condition "LEM + AC" on the
    setoid coordinate, and without them the same coordinate gives the
    constructive (IZF/CZF-like) point.
  * ETCS ↔ ZFC (bounded Zermelo with choice) is the known translation (cited,
    Lawvere/Mitchell); drawn as a line in the map, not re-proved.

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: Ω = Prop (T63).
-/
import found.NNO
import found.Setoid
import found.Classical

namespace Found

namespace ETCS

/-- global elements of a setoid -/
def pt {X : Setd.{0}} (x : X.car) : SHom unitS X := ⟨fun _ => x, fun _ => X.refl x⟩

/-- well-pointedness: maps agreeing on all global elements are equal -/
theorem well_pointed {X Y : Setd.{0}} (f g : SHom X Y)
    (h : ∀ x : SHom unitS X, SetdCat.heq (SetdCat.comp x f) (SetdCat.comp x g)) :
    SetdCat.heq f g :=
  fun x => h (pt x) PUnit.unit

/-- the terminal object is a generator and not initial: 1 has a point -/
theorem one_has_point : ∃ _ : SHom (unitS.{0}) (unitS.{0}), True := ⟨pt (X := unitS.{0}) PUnit.unit, trivial⟩

/-- the ETCS conditions on the setoid coordinate -/
structure Conditions : Prop where
  lem : ∀ p : Prop, p ∨ ¬ p
  ac : SetoidModel.SetoidAC

/-- under the conditions Ω is Boolean (reusing T66's condition) -/
theorem boolean_of (c : Conditions) : Prp.Boolean OmegaHA :=
  fun p hp => (c.lem p).elim id (fun np => (hp np).elim)

/-- and choice alone already forces the classical condition (reusing T87) -/
theorem lem_of_ac (ac : SetoidModel.SetoidAC) : ∀ p : Prop, p ∨ ¬ p := SetoidModel.ac_lem ac

/-- so the conditions reduce to choice -/
theorem conditions_of_ac (ac : SetoidModel.SetoidAC) : Conditions := ⟨lem_of_ac ac, ac⟩

/-- the NNO of the point (reused from T86) -/
def nno : NNOs.NNO SetdCat.{0} setdTerminal := NNOs.natNNO

end ETCS

end Found

#print axioms Found.ETCS.well_pointed
#print axioms Found.ETCS.one_has_point
#print axioms Found.ETCS.boolean_of
#print axioms Found.ETCS.lem_of_ac
#print axioms Found.ETCS.conditions_of_ac
#print axioms Found.ETCS.nno

#print axioms: 6 theorems, no axioms.

85.30 IZF and CZF as a point

In Aczel’s tree universe with bisimilarity as equality, empty set, pairing, union, full separation, power set (using impredicative Prop), infinity and \(\Sigma \)-collection hold as specifications up to bisimilarity; extensionality and \(\in \)-induction are reused. \(x\in \mathcal {P}(a)\iff x\subseteq a;\quad x\in \bigcup a\iff \exists y\in a,\ x\in y\).

found/IZF.lean

/-
  T88. found/IZF — IZF / CZF as a point: Aczel's tree universe V (T109)
  with bisimilarity as equality (no quotient).

  Axioms verified in V (each as an iff specification up to ≈):
    empty set, pairing, union, full separation (for ≈-respecting predicates),
    power set, infinity (ω with ∅ and successor), collection in Σ-form,
    ∈-induction and extensionality (reused from T109).
  Power set and full separation use that Prop is impredicative (CIC);
  without it one gets CZF's subset collection / bounded separation (known,
  Aczel) — drawn as the line IZF → CZF.

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: impredicative Prop (power set: a.I → Prop : Type; separation).
-/
import found.Mostowski


universe u

namespace Found

namespace IZF

open WF

def empty : V.{u} := .sup PEmpty.{u + 1} (fun e => nomatch e)

theorem empty_spec (x : V.{u}) : ¬ Mem x empty := fun ⟨j, _⟩ => nomatch j

def pair (a b : V.{u}) : V.{u} := .sup (ULift.{u} Bool) (fun t => match t.down with | true => a | false => b)

theorem pair_spec (a b x : V.{u}) : Mem x (pair a b) ↔ Eq' x a ∨ Eq' x b :=
  ⟨fun ⟨t, e⟩ => match t, e with
     | ⟨true⟩, e => Or.inl e
     | ⟨false⟩, e => Or.inr e,
   fun h => h.elim (fun e => ⟨⟨true⟩, e⟩) (fun e => ⟨⟨false⟩, e⟩)⟩

def union (a : V.{u}) : V.{u} := .sup ((i : a.I) × (a.f i).I) (fun p => (a.f p.1).f p.2)

theorem union_spec (a x : V.{u}) : Mem x (union a) ↔ ∃ y : V.{u}, Mem y a ∧ Mem x y :=
  ⟨fun ⟨⟨i, k⟩, e⟩ => ⟨a.f i, ⟨i, eq_refl _⟩, ⟨k, e⟩⟩,
   fun ⟨_, ⟨i, ey⟩, m⟩ => match mem_resp_right m ey with
     | ⟨k, e⟩ => ⟨⟨i, k⟩, e⟩⟩

def Resp (φ : V.{u} → Prop) : Prop := ∀ x y, Eq' x y → φ x → φ y

def sep (a : V.{u}) (φ : V.{u} → Prop) : V.{u} := .sup {i : a.I // φ (a.f i)} (fun p => a.f p.val)

theorem sep_spec (a : V.{u}) (φ : V.{u} → Prop) (hφ : Resp φ) (x : V.{u}) :
    Mem x (sep a φ) ↔ Mem x a ∧ φ x :=
  ⟨fun ⟨⟨i, h⟩, e⟩ => ⟨⟨i, e⟩, hφ _ _ (eq_symm _ _ e) h⟩,
   fun ⟨⟨i, e⟩, h⟩ => ⟨⟨i, hφ _ _ e h⟩, e⟩⟩

def power (a : V.{u}) : V.{u} := .sup (a.I → Prop) (fun P => .sup {i : a.I // P i} (fun p => a.f p.val))

theorem power_spec (a x : V.{u}) : Mem x (power a) ↔ ∀ z : V.{u}, Mem z x → Mem z a := by
  constructor
  · intro ⟨P, e⟩ z m
    match mem_resp_right m e with
    | ⟨⟨i, _⟩, e'⟩ => exact ⟨i, e'⟩
  · intro h
    refine ⟨fun i => Mem (a.f i) x, ?_⟩
    match x, h with
    | .sup J g, h =>
      exact ⟨fun j => match h (g j) ⟨j, eq_refl _⟩ with
               | ⟨i, e⟩ => ⟨⟨i, mem_resp_left e ⟨j, eq_refl _⟩⟩, e⟩,
             fun ⟨i, ⟨j, e⟩⟩ => ⟨j, eq_symm _ _ e⟩⟩

def succ (x : V.{u}) : V.{u} := .sup (Option x.I) (fun o => match o with | none => x | some i => x.f i)

theorem succ_resp : (x y : V.{u}) → Eq' x y → Eq' (succ x) (succ y)
  | .sup _ _, .sup _ _, ⟨e1, e2⟩ =>
    ⟨fun o => match o with
       | none => ⟨none, ⟨e1, e2⟩⟩
       | some i => match e1 i with | ⟨j, e⟩ => ⟨some j, e⟩,
     fun o => match o with
       | none => ⟨none, ⟨e1, e2⟩⟩
       | some j => match e2 j with | ⟨i, e⟩ => ⟨some i, e⟩⟩

def natV : Nat → V.{u}
  | 0 => empty
  | n + 1 => succ (natV n)

def omega : V.{u} := .sup (ULift.{u} Nat) (fun n => natV n.down)

theorem infinity : Mem empty omega ∧ ∀ x : V.{u}, Mem x omega → Mem (succ x) omega :=
  ⟨⟨⟨Nat.zero⟩, eq_refl _⟩, fun _ ⟨n, e⟩ => ⟨⟨Nat.succ n.down⟩, succ_resp _ _ e⟩⟩

/-- collection, Σ-form: a chosen witness for each index -/
theorem collection (a : V.{u}) (φ : V.{u} → V.{u} → Prop) (hφ : ∀ x x' y, Eq' x x' → φ x y → φ x' y)
    (h : (i : a.I) → {y : V.{u} // φ (a.f i) y}) :
    ∃ b : V.{u}, ∀ x : V.{u}, Mem x a → ∃ y : V.{u}, Mem y b ∧ φ x y :=
  ⟨.sup a.I (fun i => (h i).val), fun _ ⟨i, e⟩ =>
    ⟨(h i).val, ⟨i, eq_refl _⟩, hφ _ _ _ (eq_symm _ _ e) (h i).property⟩⟩

/-- ∈-induction and extensionality are T109's (reused) -/
theorem ext_reused (x y : V.{u}) (h : ∀ z : V.{u}, Mem z x ↔ Mem z y) : Eq' x y := extensionality x y h

end IZF

end Found

#print axioms Found.IZF.empty_spec
#print axioms Found.IZF.pair_spec
#print axioms Found.IZF.union_spec
#print axioms Found.IZF.sep_spec
#print axioms Found.IZF.power_spec
#print axioms Found.IZF.succ_resp
#print axioms Found.IZF.infinity
#print axioms Found.IZF.collection
#print axioms Found.IZF.ext_reused

#print axioms: 9 theorems, no axioms.

85.31 ZF and ZFC as points

In Aczel’s \(V\) every inhabited set has a doubly negated \(\in \)-minimal element constructively; under the classical condition it has one, and under setoid choice the condition holds (Diaconescu). \(\exists x\in a\Rightarrow \neg \neg \exists m\in a,\ m\cap a=\varnothing ;\quad \mathrm {LEM}\Rightarrow \exists m\).

found/ZF.lean

/-
  T89. found/ZF — ZF and ZFC as points: the IZF point (T88) with the
  classical condition on the truth-value coordinate.

  * ZF = IZF + excluded middle: under the condition LEM, foundation takes its
    classical form (every inhabited set has an ∈-minimal element), derived
    from ∈-induction (T109) — the constructive part needs no LEM, LEM is used
    only to remove a double negation.
  * Without LEM the same coordinate proves the double-negated form
    (constructively): the ZF ↪ IZF double-negation translation (Friedman,
    cited) is the line from this point to T88.
  * ZFC = ZF + choice; choice ⇒ LEM (Diaconescu, T87 reused at the setoid
    coordinate), so the ZFC condition reduces to choice.

  Lean 4 core only, hand-written proofs, no axioms (LEM is a hypothesis).
-/
import found.IZF
import found.Setoid


universe u

namespace Found

namespace ZF

open WF

def Minimal (a m : V.{u}) : Prop := Mem m a ∧ ¬ ∃ y : V.{u}, Mem y m ∧ Mem y a

/-- constructively: an inhabited set cannot lack ∈-minimal elements -/
theorem not_not_minimal (a : V.{u}) (h : ∃ x : V.{u}, Mem x a) : ¬ ¬ ∃ m : V.{u}, Minimal a m := by
  intro hn
  have all : ∀ x : V.{u}, ¬ Mem x a :=
    mem_induction (fun x => ¬ Mem x a)
      (fun x y e hx hy => hx (mem_resp_left (eq_symm _ _ e) hy))
      (fun x ih hx => hn ⟨x, hx, fun ⟨y, hy, hya⟩ => ih y hy hya⟩)
  match h with
  | ⟨x, hx⟩ => exact all x hx

/-- with the classical condition: foundation in its ZF form -/
theorem foundation_classical (lem : ∀ p : Prop, p ∨ ¬ p) (a : V.{u}) (h : ∃ x : V.{u}, Mem x a) :
    ∃ m : V.{u}, Minimal a m :=
  (lem (∃ m : V.{u}, Minimal a m)).elim id (fun n => (not_not_minimal a h n).elim)

/-- the ZFC condition reduces to choice (Diaconescu at the setoid coordinate, T87) -/
theorem zfc_condition (ac : SetoidModel.SetoidAC) (a : V.{u}) (h : ∃ x : V.{u}, Mem x a) : ∃ m : V.{u}, Minimal a m :=
  foundation_classical (SetoidModel.ac_lem ac) a h

end ZF

end Found

#print axioms Found.ZF.not_not_minimal
#print axioms Found.ZF.foundation_classical
#print axioms Found.ZF.zfc_condition

#print axioms: 3 theorems, no axioms.

85.32 Kripke–Platek as a point

\(\Delta _0\) formulas over Aczel’s \(V\) respect bisimilarity, proved once by recursion; \(\Delta _0\)-separation is the instance of the IZF separation, so KP sits inside CZF and IZF by restricting the formulas. \(x\in \{y\in a\mid \varphi \}\iff x\in a\wedge \varphi (x),\ \varphi \in \Delta _0\).

found/KP.lean

/-
  T90. found/KP — Kripke–Platek as a point: the Δ₀ fragment of the IZF point.

  * Δ₀ formulas over V with variables (de Bruijn environment), bounded
    quantifiers ∀y∈x, ∃y∈x, ∈ and ≈ atoms.
  * Every Δ₀ formula respects ≈ in its free variables (needed for
    separation), proved once by recursion on formulas.
  * Δ₀-separation is the instance of T88's separation (not re-proved);
    Δ₀-collection is T88's Σ-collection restricted; ∈-induction (T109).
  So KP ⊂ CZF ⊂ IZF (as conditions on which formulas may be used), the
  known inclusion lines of the map.

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: ≈ on V is Prop-valued (T109).
-/
import found.IZF


universe u

namespace Found

namespace KP

open WF

inductive D0 where
  | mem : Nat → Nat → D0
  | eq : Nat → Nat → D0
  | bot : D0
  | and : D0 → D0 → D0
  | or : D0 → D0 → D0
  | imp : D0 → D0 → D0
  | ball : Nat → D0 → D0      -- ∀ y ∈ x_n, φ  (y = variable 0 inside)
  | bex : Nat → D0 → D0       -- ∃ y ∈ x_n, φ

def cons (x : V.{u}) (ρ : Nat → V.{u}) : Nat → V.{u}
  | 0 => x
  | n + 1 => ρ n

def sat : D0 → (Nat → V.{u}) → Prop
  | .mem i j, ρ => Mem (ρ i) (ρ j)
  | .eq i j, ρ => Eq' (ρ i) (ρ j)
  | .bot, _ => False
  | .and a b, ρ => sat a ρ ∧ sat b ρ
  | .or a b, ρ => sat a ρ ∨ sat b ρ
  | .imp a b, ρ => sat a ρ → sat b ρ
  | .ball n a, ρ => ∀ j : (ρ n).I, sat a (cons ((ρ n).f j) ρ)
  | .bex n a, ρ => ∃ j : (ρ n).I, sat a (cons ((ρ n).f j) ρ)

def EnvEq (ρ σ : Nat → V.{u}) : Prop := ∀ n, Eq' (ρ n) (σ n)

theorem envEq_cons {ρ σ : Nat → V.{u}} (h : EnvEq ρ σ) {x y : V.{u}} (e : Eq' x y) : EnvEq (cons x ρ) (cons y σ)
  | 0 => e
  | _ + 1 => h _

theorem envEq_symm {ρ σ : Nat → V.{u}} (h : EnvEq ρ σ) : EnvEq σ ρ := fun n => eq_symm _ _ (h n)

theorem ball_tr : {x y : V.{u}} → Eq' x y → (P Q : V.{u} → Prop) → (∀ u v, Eq' u v → P u → Q v) →
    (∀ j : x.I, P (x.f j)) → ∀ k : y.I, Q (y.f k)
  | .sup _ _, .sup _ _, ⟨_, e2⟩, _, _, t, h, k => match e2 k with | ⟨j, e⟩ => t _ _ e (h j)

theorem bex_tr : {x y : V.{u}} → Eq' x y → (P Q : V.{u} → Prop) → (∀ u v, Eq' u v → P u → Q v) →
    (∃ j : x.I, P (x.f j)) → ∃ k : y.I, Q (y.f k)
  | .sup _ _, .sup _ _, ⟨e1, _⟩, _, _, t, ⟨j, h⟩ => match e1 j with | ⟨k, e⟩ => ⟨k, t _ _ e h⟩

/-- Δ₀ formulas respect ≈ -/
theorem sat_resp : (φ : D0) → ∀ {ρ σ : Nat → V.{u}}, EnvEq ρ σ → sat φ ρ → sat φ σ
  | .mem i j, _, _, h, m => mem_resp_right (mem_resp_left (h i) m) (h j)
  | .eq i j, _, _, h, e => eq_trans _ _ _ (eq_symm _ _ (h i)) (eq_trans _ _ _ e (h j))
  | .bot, _, _, _, x => x
  | .and a b, _, _, h, x => ⟨sat_resp a h x.1, sat_resp b h x.2⟩
  | .or a b, _, _, h, x => x.elim (fun y => Or.inl (sat_resp a h y)) (fun y => Or.inr (sat_resp b h y))
  | .imp a b, _, _, h, x => fun y => sat_resp b h (x (sat_resp a (envEq_symm h) y))
  | .ball n a, ρ, σ, h, x =>
      ball_tr (h n) (fun u => sat a (cons u ρ)) (fun v => sat a (cons v σ))
        (fun _ _ e => sat_resp a (envEq_cons h e)) x
  | .bex n a, ρ, σ, h, x =>
      bex_tr (h n) (fun u => sat a (cons u ρ)) (fun v => sat a (cons v σ))
        (fun _ _ e => sat_resp a (envEq_cons h e)) x

/-- Δ₀-separation: the instance of T88's separation -/
theorem d0_separation (φ : D0) (ρ : Nat → V.{u}) (a x : V.{u}) :
    Mem x (IZF.sep a (fun y => sat φ (cons y ρ))) ↔ Mem x a ∧ sat φ (cons x ρ) :=
  IZF.sep_spec a _ (fun _ _ e h => sat_resp φ (envEq_cons (fun _ => eq_refl _) e) h) x

end KP

end Found

#print axioms Found.KP.sat_resp
#print axioms Found.KP.d0_separation

#print axioms: 2 theorems, no axioms.

85.33 NBG and Morse–Kelley as points

Classes over Aczel’s \(V\) are bisimulation-respecting predicates; Morse–Kelley comprehension holds, subclasses of sets are sets by separation, and Russell’s class equals the universe, which is a proper class. \(R=\{x\mid x\notin x\}=V,\quad \neg \exists s\,\forall x\,(x\in s)\).

found/NBG.lean

/-
  T91. found/NBG — NBG and Morse–Kelley as points: classes over the IZF
  point V (T88) are ≈-respecting predicates.

  * Classes, class extensionality (a setoid), sets as classes.
  * Comprehension: every respecting predicate is a class — Morse–Kelley's
    impredicative comprehension holds because predicates live in Prop
    (CIC); NBG restricts comprehension to formulas quantifying over sets
    only (its conservativity over ZF is the known line NBG → ZF, cited).
  * A subclass of a set is a set (separation, T88 reused).
  * The universal class (= Russell's class, by foundation T109) is proper.

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: impredicative Prop (MK comprehension).
-/
import found.IZF


universe u

namespace Found

namespace NBG

open WF

structure Cls where
  p : V.{u} → Prop
  resp : IZF.Resp p

def ClsEq (A B : Cls) : Prop := ∀ x : V.{u}, A.p x ↔ B.p x

theorem clsEq_refl (A : Cls) : ClsEq A A := fun _ => Iff.rfl
theorem clsEq_symm {A B : Cls} (h : ClsEq A B) : ClsEq B A := fun x => (h x).symm
theorem clsEq_trans {A B C : Cls} (h : ClsEq A B) (k : ClsEq B C) : ClsEq A C := fun x => (h x).trans (k x)

/-- every set is a class -/
def ofSet (a : V.{u}) : Cls := ⟨fun z => Mem z a, fun _ _ e m => mem_resp_left e m⟩

/-- comprehension (Morse–Kelley form): any respecting predicate is a class -/
def compr (φ : V.{u} → Prop) (h : IZF.Resp φ) : Cls := ⟨φ, h⟩

theorem compr_spec (φ : V.{u} → Prop) (h : IZF.Resp φ) (x : V.{u}) : (compr φ h).p x ↔ φ x := Iff.rfl

/-- a subclass of a set is a set (separation reused) -/
theorem subclass_set (A : Cls) (a : V.{u}) (hA : ∀ x : V.{u}, A.p x → Mem x a) :
    ∃ s : V.{u}, ∀ x : V.{u}, Mem x s ↔ A.p x :=
  ⟨IZF.sep a A.p, fun x => ⟨fun m => ((IZF.sep_spec a A.p A.resp x).mp m).2,
    fun h => (IZF.sep_spec a A.p A.resp x).mpr ⟨hA x h, h⟩⟩⟩

def univ : Cls := ⟨fun _ => True, fun _ _ _ _ => trivial⟩

def russell : Cls := ⟨fun x => ¬ Mem x x,
  fun _ _ e h m => h (mem_resp_left (eq_symm _ _ e) (mem_resp_right m (eq_symm _ _ e)))⟩

/-- by foundation, Russell's class is the universe -/
theorem russell_univ : ClsEq russell univ := fun x => ⟨fun _ => trivial, fun _ => not_mem_self x⟩

/-- the universe is a proper class -/
theorem univ_proper : ¬ ∃ s : V.{u}, ∀ x : V.{u}, Mem x s ↔ univ.p x :=
  fun ⟨s, h⟩ => not_mem_self s ((h s).mpr trivial)

end NBG

end Found

#print axioms Found.NBG.clsEq_trans
#print axioms Found.NBG.ofSet
#print axioms Found.NBG.compr_spec
#print axioms Found.NBG.subclass_set
#print axioms Found.NBG.russell
#print axioms Found.NBG.russell_univ
#print axioms Found.NBG.univ_proper

#print axioms: 7 theorems, no axioms.

85.34 Deontic logic

The deontic axiom \(\Box p\to \Diamond p\) holds on a frame iff its relation is serial; reflexive frames are serial, so D lies between K and T on the relation coordinate. \(\Box p\to \Diamond p\iff \forall w\,\exists v,\ wRv\).

found/ModalExt.lean

/-
  T113. found/ModalExt — deontic logic and extensions as points on the
  relation coordinate R (T67, T72 reused).

  * Deontic D: □p → ◇p  ⟺  R serial (every world has a successor).
  * D is the condition "seriality" on R, between K (none) and T (reflexive):
    reflexive ⇒ serial.  Deontic modalities are the same □ with this value.
  * Epistemic/temporal extensions are T72's (common knowledge, tense
    adjunctions) — reused, not re-proved.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.TemporalEpistemic

namespace Found

namespace Modal

universe u

variable {W : Type u} (R : W → W → Prop)

def Serial : Prop := ∀ w, ∃ v, R w v

theorem d_iff_serial :
    (∀ (V : W → Nat → Prop) w, sat R V w (.imp (.box (.var 0)) (.dia (.var 0)))) ↔ Serial R :=
  ⟨fun h w => match h (fun _ _ => True) w (fun _ _ => trivial) with
     | ⟨v, r, _⟩ => ⟨v, r⟩,
   fun hs _ w x => match hs w with
     | ⟨v, r⟩ => ⟨v, r, x v r⟩⟩

theorem refl_serial (hr : Refl R) : Serial R := fun w => ⟨w, hr w⟩

end Modal

end Found

#print axioms Found.Modal.d_iff_serial
#print axioms Found.Modal.refl_serial

#print axioms: 2 theorems, no axioms.

85.35 Synthetic differential geometry

On a ring coordinate with only the needed conditions, Kock–Lawvere uniqueness forbids all infinitesimals to vanish, Kock’s field condition makes each infinitesimal not-not zero, and excluded middle on \(D\) then forces \(0=1\). \(\mathrm {KL}\wedge \mathrm {Field}\wedge \forall d\in D\,(d=0\vee d\ne 0)\Rightarrow 0=1\).

found/SDG.lean

/-
  T119. found/SDG — synthetic differential geometry as a point: a ring
  coordinate R with the Kock–Lawvere condition on D = {d | d² = 0}.

  * Minimal ring conditions (only those used): 0, 1, +, ·, x + 0 = x,
    0·x = 0, x·0 = 0, 1·x = x, associativity of ·.
  * Kock–Lawvere (uniqueness half): maps D → R have at most one slope.
  * KL ⇒ not every infinitesimal is 0 (unless 0 = 1).
  * Kock's field condition (x ≠ 0 ⇒ x invertible) ⇒ every infinitesimal is
    not-not 0; with excluded middle on D this gives d = 0, hence 0 = 1:
    SDG's point lies off the classical condition — the known incompatibility
    of KL with LEM, as a condition clash on the truth-value coordinate.

  Lean 4 core only, hand-written proofs, no axioms (all conditions are hypotheses).
-/

namespace Found

namespace SDG

universe u

structure Ring where
  R : Type u
  zero : R
  one : R
  add : R → R → R
  mul : R → R → R
  add_zero : ∀ x, add x zero = x
  zero_mul : ∀ x, mul zero x = zero
  mul_zero : ∀ x, mul x zero = zero
  one_mul : ∀ x, mul one x = x
  mul_assoc : ∀ x y z, mul (mul x y) z = mul x (mul y z)

variable (K : Ring.{u})

def D : Type u := {d : K.R // K.mul d d = K.zero}

def d0 : D K := ⟨K.zero, K.zero_mul _⟩

/-- Kock–Lawvere, uniqueness of slopes -/
def KLuniq : Prop :=
  ∀ (g : D K → K.R) (b b' : K.R), (∀ d : D K, g d = K.add (g (d0 K)) (K.mul b d.val)) →
    (∀ d : D K, g d = K.add (g (d0 K)) (K.mul b' d.val)) → b = b'

/-- KL ⇒ not all infinitesimals vanish, unless 0 = 1 -/
theorem kl_not_all_zero (kl : KLuniq K) (h : ∀ d : D K, d.val = K.zero) : K.zero = K.one :=
  kl (fun _ => K.zero) K.zero K.one
    (fun d => by
      show K.zero = K.add K.zero (K.mul K.zero d.val)
      rw [K.zero_mul, K.add_zero])
    (fun d => by
      show K.zero = K.add K.zero (K.mul K.one d.val)
      rw [h d, K.mul_zero, K.add_zero])

/-- Kock's field condition -/
def FieldCond : Prop := ∀ x : K.R, ¬ x = K.zero → ∃ e, K.mul e x = K.one

/-- field condition ⇒ every infinitesimal is not-not zero -/
theorem nn_zero (hf : FieldCond K) (d : D K) : ¬ ¬ d.val = K.zero :=
  fun hne => match hf d.val hne with
  | ⟨e, he⟩ => hne (by
      have : d.val = K.mul (K.mul e d.val) d.val := by rw [he, K.one_mul]
      rw [this, K.mul_assoc, d.property, K.mul_zero])

/-- the clash: KL + field condition + excluded middle on D ⇒ 0 = 1 -/
theorem kl_lem_clash (kl : KLuniq K) (hf : FieldCond K)
    (lem : ∀ d : D K, d.val = K.zero ∨ ¬ d.val = K.zero) : K.zero = K.one :=
  kl_not_all_zero K kl (fun d => (lem d).elim id (fun n => (nn_zero K hf d n).elim))

end SDG

end Found

#print axioms Found.SDG.kl_not_all_zero
#print axioms Found.SDG.nn_zero
#print axioms Found.SDG.kl_lem_clash

#print axioms: 3 theorems, no axioms.

85.36 Quantum logic

A distributive ortholattice is a Boolean Heyting algebra with \(a\to b:=a'\vee b\); the six-element MO2 is orthomodular but not distributive. \(\mathrm {OL}+\mathrm {distributive}\Rightarrow \mathrm {Boolean};\quad \mathrm {MO}_2\ \mathrm {orthomodular},\ a\wedge (b\vee b')\not \le (a\wedge b)\vee (a\wedge b')\).

found/Quantum.lean

/-
  T111. found/Quantum — quantum logic as a point: the ortholattice
  coordinate (orthocomplemented lattice, preorder form).

  * Orthomodularity and distributivity as two conditions on the coordinate.
  * General: a distributive ortholattice is a Boolean Heyting algebra
    (a → b := a' ∨ b) — classical logic (T66) is the distributive value;
    the line quantum → classical is "add distributivity".
  * Instance MO2 (0 < a, a', b, b' < 1): orthomodular and not distributive —
    the quantum point.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Classical

namespace Found

namespace Quantum

universe u

structure OL where
  car : Type u
  le : car → car → Prop
  le_refl : ∀ a, le a a
  le_trans : ∀ {a b c}, le a b → le b c → le a c
  top : car
  bot : car
  meet : car → car → car
  join : car → car → car
  comp : car → car
  le_top : ∀ a, le a top
  bot_le : ∀ a, le bot a
  meet_l : ∀ a b, le (meet a b) a
  meet_r : ∀ a b, le (meet a b) b
  meet_univ : ∀ {a b c}, le c a → le c b → le c (meet a b)
  join_l : ∀ a b, le a (join a b)
  join_r : ∀ a b, le b (join a b)
  join_univ : ∀ {a b c}, le a c → le b c → le (join a b) c
  comp_anti : ∀ {a b}, le a b → le (comp b) (comp a)
  comp_inv1 : ∀ a, le a (comp (comp a))
  comp_inv2 : ∀ a, le (comp (comp a)) a
  comp_meet : ∀ a, le (meet a (comp a)) bot
  comp_join : ∀ a, le top (join a (comp a))

def Orthomodular (L : OL.{u}) : Prop := ∀ a b, L.le a b → L.le b (L.join a (L.meet b (L.comp a)))

def Distributive (L : OL.{u}) : Prop :=
  ∀ a b c, L.le (L.meet a (L.join b c)) (L.join (L.meet a b) (L.meet a c))

/-- a distributive ortholattice is a Heyting algebra with a → b := a' ∨ b -/
def toHA (L : OL.{u}) (hd : Distributive L) : HA.{u} where
  car := L.car
  le := L.le
  le_refl := L.le_refl
  le_trans := L.le_trans
  top := L.top
  bot := L.bot
  meet := L.meet
  join := L.join
  imp a b := L.join (L.comp a) b
  le_top := L.le_top
  bot_le := L.bot_le
  meet_l := L.meet_l
  meet_r := L.meet_r
  meet_univ := L.meet_univ
  join_l := L.join_l
  join_r := L.join_r
  join_univ := L.join_univ
  imp_adj {a b c} :=
    ⟨fun h => L.le_trans (L.meet_univ (L.le_refl c) (L.le_trans (L.le_top c) (L.comp_join a)))
      (L.le_trans (hd c a (L.comp a))
        (L.join_univ (L.le_trans h (L.join_r _ _)) (L.le_trans (L.meet_r _ _) (L.join_l _ _)))),
     fun h => L.le_trans (L.meet_univ (L.le_trans (L.meet_l _ _) h) (L.meet_r _ _))
      (L.le_trans (L.le_trans (L.meet_univ (L.meet_r _ _) (L.meet_l _ _)) (hd a (L.comp a) b))
        (L.join_univ (L.le_trans (L.comp_meet a) (L.bot_le b)) (L.meet_r _ _)))⟩

/-- and it is Boolean: the classical value -/
theorem toHA_boolean (L : OL.{u}) (hd : Distributive L) : Prp.Boolean (toHA L hd) :=
  fun a => L.join_univ
    (L.le_trans (L.comp_anti (L.join_l (L.comp a) L.bot)) (L.comp_inv2 a))
    (L.bot_le a)

/-! ## MO2: orthomodular, not distributive -/

inductive MO where
  | z : MO
  | a : MO
  | na : MO
  | b : MO
  | nb : MO
  | o : MO

namespace MO

def le : MO → MO → Prop
  | z, z => True
  | z, a => True
  | z, na => True
  | z, b => True
  | z, nb => True
  | z, o => True
  | a, z => False
  | a, a => True
  | a, na => False
  | a, b => False
  | a, nb => False
  | a, o => True
  | na, z => False
  | na, a => False
  | na, na => True
  | na, b => False
  | na, nb => False
  | na, o => True
  | b, z => False
  | b, a => False
  | b, na => False
  | b, b => True
  | b, nb => False
  | b, o => True
  | nb, z => False
  | nb, a => False
  | nb, na => False
  | nb, b => False
  | nb, nb => True
  | nb, o => True
  | o, z => False
  | o, a => False
  | o, na => False
  | o, b => False
  | o, nb => False
  | o, o => True

def meet : MO → MO → MO
  | z, z => z
  | z, a => z
  | z, na => z
  | z, b => z
  | z, nb => z
  | z, o => z
  | a, z => z
  | a, a => a
  | a, na => z
  | a, b => z
  | a, nb => z
  | a, o => a
  | na, z => z
  | na, a => z
  | na, na => na
  | na, b => z
  | na, nb => z
  | na, o => na
  | b, z => z
  | b, a => z
  | b, na => z
  | b, b => b
  | b, nb => z
  | b, o => b
  | nb, z => z
  | nb, a => z
  | nb, na => z
  | nb, b => z
  | nb, nb => nb
  | nb, o => nb
  | o, z => z
  | o, a => a
  | o, na => na
  | o, b => b
  | o, nb => nb
  | o, o => o

def join : MO → MO → MO
  | z, z => z
  | z, a => a
  | z, na => na
  | z, b => b
  | z, nb => nb
  | z, o => o
  | a, z => a
  | a, a => a
  | a, na => o
  | a, b => o
  | a, nb => o
  | a, o => o
  | na, z => na
  | na, a => o
  | na, na => na
  | na, b => o
  | na, nb => o
  | na, o => o
  | b, z => b
  | b, a => o
  | b, na => o
  | b, b => b
  | b, nb => o
  | b, o => o
  | nb, z => nb
  | nb, a => o
  | nb, na => o
  | nb, b => o
  | nb, nb => nb
  | nb, o => o
  | o, z => o
  | o, a => o
  | o, na => o
  | o, b => o
  | o, nb => o
  | o, o => o

def comp : MO → MO
  | z => o
  | a => na
  | na => a
  | b => nb
  | nb => b
  | o => z

def L : OL.{0} where
  car := MO
  le := le
  le_refl x := by cases x <;> exact trivial
  le_trans {x y w} := by
    cases x <;> cases y <;> cases w <;> intro p q <;> first | exact trivial | exact p.elim | exact q.elim
  top := o
  bot := z
  meet := meet
  join := join
  comp := comp
  le_top x := by cases x <;> exact trivial
  bot_le x := by cases x <;> exact trivial
  meet_l x y := by cases x <;> cases y <;> exact trivial
  meet_r x y := by cases x <;> cases y <;> exact trivial
  meet_univ {x y w} := by
    cases x <;> cases y <;> cases w <;> intro p q <;> first | exact trivial | exact p.elim | exact q.elim
  join_l x y := by cases x <;> cases y <;> exact trivial
  join_r x y := by cases x <;> cases y <;> exact trivial
  join_univ {x y w} := by
    cases x <;> cases y <;> cases w <;> intro p q <;> first | exact trivial | exact p.elim | exact q.elim
  comp_anti {x y} := by cases x <;> cases y <;> intro p <;> first | exact trivial | exact p.elim
  comp_inv1 x := by cases x <;> exact trivial
  comp_inv2 x := by cases x <;> exact trivial
  comp_meet x := by cases x <;> exact trivial
  comp_join x := by cases x <;> exact trivial

theorem orthomodular : Orthomodular L := fun x y => by
  cases x <;> cases y <;> intro p <;> first | exact trivial | exact p.elim

theorem not_distributive : ¬ Distributive L := fun h => h a b nb

end MO

end Quantum

end Found

#print axioms Found.Quantum.toHA
#print axioms Found.Quantum.toHA_boolean
#print axioms Found.Quantum.MO.L
#print axioms Found.Quantum.MO.orthomodular
#print axioms Found.Quantum.MO.not_distributive

#print axioms: 5 theorems, no axioms.

85.37 The core: seven operations

Setoids in every universe are closed under sums and products, function spaces, subobjects and power (\(\Omega \)), quotients, W-types and streams, the universe of small setoids, and localization at any relation, each with its universal property; the same statements check in Cubical Agda, where \(\Omega \) is one universe larger. \(+,\times ,\Rightarrow ,\Omega ,/R,\ W,\ \nu ,\ \mathcal {U},\ X[R^{-1}]\) with existence and uniqueness of the induced maps.

found/Core.lean

/-
  T59. found/Core — the core: the stem (setoids, any universe u, maps
  respecting ≈, equality of maps pointwise) is closed under the seven
  operations, each with its universal property.

    1. products, sums            (prodS from CCC; sumS here)
    2. function spaces           (expS / setdCCC from CCC, universe-polymorphic)
    3. subobjects, power (Ω)     (subU, OmegaU = ULift Prop with ↔; power = X ⇒ Ω)
    4. quotients                 (by any coarser equivalence)
    5. induction, coinduction    (W-types: initial algebras; streams: final coalgebras)
    6. universes                 (the setoid of small setoids, ≈ = isomorphism)
    7. sheaves, localization     (localization at any relation; nuclei: T108)

  The same statements are checked in Cubical Agda: work/agda/Core.agda.
  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: Ω = ULift Prop (impredicative Prop) in 3; W-types are Lean inductives.
-/
import found.CCC

namespace Found

namespace Core

universe u

/-! ## 1. Sums (products: prodS, CCC) -/

def sumEqv (X Y : Setd.{u}) : X.car ⊕ Y.car → X.car ⊕ Y.car → Prop
  | .inl a, .inl b => X.eqv a b
  | .inl _, .inr _ => False
  | .inr _, .inl _ => False
  | .inr a, .inr b => Y.eqv a b

def sumS (X Y : Setd.{u}) : Setd.{u} where
  car := X.car ⊕ Y.car
  eqv := sumEqv X Y
  refl p := by cases p with
    | inl a => exact X.refl a
    | inr b => exact Y.refl b
  symm {p q} h := by
    cases p <;> cases q
    · exact X.symm h
    · exact h.elim
    · exact h.elim
    · exact Y.symm h
  trans {p q r} h k := by
    cases p <;> cases q <;> cases r
    · exact X.trans h k
    · exact k.elim
    · exact h.elim
    · exact h.elim
    · exact h.elim
    · exact h.elim
    · exact k.elim
    · exact Y.trans h k

def inl (X Y : Setd.{u}) : SHom X (sumS X Y) := ⟨Sum.inl, fun h => h⟩
def inr (X Y : Setd.{u}) : SHom Y (sumS X Y) := ⟨Sum.inr, fun h => h⟩

def copair {X Y Z : Setd.{u}} (f : SHom X Z) (g : SHom Y Z) : SHom (sumS X Y) Z where
  fn p := match p with
    | .inl a => f.fn a
    | .inr b => g.fn b
  resp {p q} h := by
    cases p <;> cases q
    · exact f.resp h
    · exact h.elim
    · exact h.elim
    · exact g.resp h

theorem copair_inl {X Y Z : Setd.{u}} (f : SHom X Z) (g : SHom Y Z) :
    SetdCat.heq (SetdCat.comp (inl X Y) (copair f g)) f := fun a => Z.refl (f.fn a)

theorem copair_inr {X Y Z : Setd.{u}} (f : SHom X Z) (g : SHom Y Z) :
    SetdCat.heq (SetdCat.comp (inr X Y) (copair f g)) g := fun b => Z.refl (g.fn b)

theorem copair_uniq {X Y Z : Setd.{u}} (f : SHom X Z) (g : SHom Y Z) (h : SHom (sumS X Y) Z)
    (hf : SetdCat.heq (SetdCat.comp (inl X Y) h) f) (hg : SetdCat.heq (SetdCat.comp (inr X Y) h) g) :
    SetdCat.heq h (copair f g)
  | .inl a => hf a
  | .inr b => hg b

/-- products are the CCC's (universe-polymorphic) -/
def prod (X Y : Setd.{u}) : Product SetdCat.{u} X Y := setdProduct X Y

/-! ## 2. Function spaces -/

def ccc : CCC SetdCat.{u} := setdCCC

/-! ## 3. Subobjects and power -/

def OmegaU : Setd.{u} :=
  ⟨ULift.{u} Prop, fun p q => (p.down ↔ q.down), fun _ => Iff.rfl, fun h => h.symm, fun h k => h.trans k⟩

def RespP (X : Setd.{u}) (φ : X.car → Prop) : Prop := ∀ {x y}, X.eqv x y → φ x → φ y

def subU (X : Setd.{u}) (φ : X.car → Prop) : Setd.{u} :=
  ⟨{x // φ x}, fun a b => X.eqv a.val b.val, fun a => X.refl a.val, fun h => X.symm h, fun h k => X.trans h k⟩

def chiU {X : Setd.{u}} (φ : X.car → Prop) (h : RespP X φ) : SHom X OmegaU :=
  ⟨fun x => ⟨φ x⟩, fun e => ⟨h e, h (X.symm e)⟩⟩

/-- classification: membership in the subobject is truth of χ -/
theorem chiU_spec {X : Setd.{u}} (φ : X.car → Prop) (h : RespP X φ) (x : X.car) :
    (∃ s : (subU X φ).car, X.eqv s.val x) ↔ ((chiU φ h).fn x).down :=
  ⟨fun ⟨s, e⟩ => h e s.property, fun p => ⟨⟨x, p⟩, X.refl x⟩⟩

/-- uniqueness of χ: predicates with equivalent characteristic maps agree -/
theorem chiU_uniq {X : Setd.{u}} (φ ψ : X.car → Prop) (hφ : RespP X φ) (hψ : RespP X ψ)
    (e : SetdCat.heq (chiU φ hφ) (chiU ψ hψ)) (x : X.car) : φ x ↔ ψ x := e x

def power (X : Setd.{u}) : Setd.{u} := expS X OmegaU

/-! ## 4. Quotients -/

structure Coarser (X : Setd.{u}) where
  R : X.car → X.car → Prop
  refl : ∀ a, R a a
  symm : ∀ {a b}, R a b → R b a
  trans : ∀ {a b c}, R a b → R b c → R a c
  coarser : ∀ {a b}, X.eqv a b → R a b

def quot {X : Setd.{u}} (C : Coarser X) : Setd.{u} := ⟨X.car, C.R, C.refl, C.symm, C.trans⟩

def proj {X : Setd.{u}} (C : Coarser X) : SHom X (quot C) := ⟨fun x => x, fun h => C.coarser h⟩

def qlift {X Y : Setd.{u}} (C : Coarser X) (f : SHom X Y) (hf : ∀ {a b}, C.R a b → Y.eqv (f.fn a) (f.fn b)) :
    SHom (quot C) Y := ⟨f.fn, hf⟩

theorem qlift_comm {X Y : Setd.{u}} (C : Coarser X) (f : SHom X Y)
    (hf : ∀ {a b}, C.R a b → Y.eqv (f.fn a) (f.fn b)) :
    SetdCat.heq (SetdCat.comp (proj C) (qlift C f hf)) f := fun x => Y.refl (f.fn x)

theorem qlift_uniq {X Y : Setd.{u}} (C : Coarser X) (f : SHom X Y)
    (hf : ∀ {a b}, C.R a b → Y.eqv (f.fn a) (f.fn b)) (g : SHom (quot C) Y)
    (hg : SetdCat.heq (SetdCat.comp (proj C) g) f) : SetdCat.heq g (qlift C f hf) := hg

/-! ## 5a. Induction: W-types are initial algebras -/

inductive W (A : Type u) (B : A → Type u) : Type u where
  | sup (a : A) (f : B a → W A B) : W A B

def WS (A : Type u) (B : A → Type u) : Setd.{u} :=
  ⟨W A B, Eq, fun _ => rfl, fun h => h.symm, fun h k => h.trans k⟩

/-- an algebra for the polynomial functor on a setoid -/
structure Alg (A : Type u) (B : A → Type u) where
  X : Setd.{u}
  alg : (a : A) → (B a → X.car) → X.car

def fold {A : Type u} {B : A → Type u} (M : Alg A B) : W A B → M.X.car
  | .sup a f => M.alg a (fun b => fold M (f b))

theorem fold_eq {A : Type u} {B : A → Type u} (M : Alg A B) (a : A) (f : B a → W A B) :
    fold M (.sup a f) = M.alg a (fun b => fold M (f b)) := rfl

/-- uniqueness of the fold (algebra map), up to ≈, when alg respects pointwise ≈ -/
theorem fold_uniq {A : Type u} {B : A → Type u} (M : Alg A B)
    (hM : ∀ a (g g' : B a → M.X.car), (∀ b, M.X.eqv (g b) (g' b)) → M.X.eqv (M.alg a g) (M.alg a g'))
    (h : W A B → M.X.car) (hh : ∀ a f, M.X.eqv (h (.sup a f)) (M.alg a (fun b => h (f b)))) :
    ∀ w, M.X.eqv (h w) (fold M w)
  | .sup a f => M.X.trans (hh a f) (hM a _ _ (fun b => fold_uniq M hM h hh (f b)))

/-! ## 5b. Coinduction: streams are final coalgebras -/

def StreamS (A : Setd.{u}) : Setd.{u} :=
  ⟨Nat → A.car, fun s t => ∀ n, A.eqv (s n) (t n), fun s n => A.refl (s n),
   fun h n => A.symm (h n), fun h k n => A.trans (h n) (k n)⟩

def unfold {A : Setd.{u}} {S : Type u} (c : S → A.car × S) (x : S) : Nat → A.car
  | 0 => (c x).1
  | n + 1 => unfold c (c x).2 n

theorem unfold_uniq {A : Setd.{u}} {S : Type u} (c : S → A.car × S) (f : S → Nat → A.car)
    (hh : ∀ x, A.eqv (f x 0) (c x).1) (ht : ∀ x n, A.eqv (f x (n + 1)) (f (c x).2 n)) :
    ∀ n x, A.eqv (f x n) (unfold c x n)
  | 0, x => hh x
  | n + 1, x => A.trans (ht x n) (unfold_uniq c f hh ht n (c x).2)

/-! ## 6. Universes: the setoid of small setoids -/

def Iso' (X Y : Setd.{u}) : Prop :=
  ∃ f : SHom X Y, ∃ g : SHom Y X, (∀ x, X.eqv (g.fn (f.fn x)) x) ∧ (∀ y, Y.eqv (f.fn (g.fn y)) y)

theorem iso_refl (X : Setd.{u}) : Iso' X X :=
  ⟨⟨fun x => x, fun h => h⟩, ⟨fun x => x, fun h => h⟩, fun x => X.refl x, fun x => X.refl x⟩

theorem iso_symm {X Y : Setd.{u}} (h : Iso' X Y) : Iso' Y X :=
  match h with
  | ⟨f, g, a, b⟩ => ⟨g, f, b, a⟩

theorem iso_trans {X Y Z : Setd.{u}} (h : Iso' X Y) (k : Iso' Y Z) : Iso' X Z :=
  match h, k with
  | ⟨f, g, a, b⟩, ⟨f', g', a', b'⟩ =>
    ⟨SetdCat.comp f f', SetdCat.comp g' g,
     fun x => X.trans (g.resp (a' (f.fn x))) (a x),
     fun z => Z.trans (f'.resp (b (g'.fn z))) (b' z)⟩

def USetd : Setd.{u + 1} := ⟨Setd.{u}, Iso', iso_refl, iso_symm, iso_trans⟩

/-- the universe is closed under products, up to its own equality -/
theorem prod_resp {X X' Y Y' : Setd.{u}} (h : Iso' X X') (k : Iso' Y Y') :
    Iso' (prodS X Y) (prodS X' Y') :=
  match h, k with
  | ⟨f, g, a, b⟩, ⟨f', g', a', b'⟩ =>
    ⟨⟨fun p => (f.fn p.1, f'.fn p.2), fun e => ⟨f.resp e.1, f'.resp e.2⟩⟩,
     ⟨fun p => (g.fn p.1, g'.fn p.2), fun e => ⟨g.resp e.1, g'.resp e.2⟩⟩,
     fun p => ⟨a p.1, a' p.2⟩, fun p => ⟨b p.1, b' p.2⟩⟩

/-! ## 7. Localization at a relation -/

inductive Gen (X : Setd.{u}) (R : X.car → X.car → Prop) : X.car → X.car → Prop where
  | base {a b} : X.eqv a b → Gen X R a b
  | rel {a b} : R a b → Gen X R a b
  | symm {a b} : Gen X R a b → Gen X R b a
  | trans {a b c} : Gen X R a b → Gen X R b c → Gen X R a c

def loc (X : Setd.{u}) (R : X.car → X.car → Prop) : Setd.{u} :=
  ⟨X.car, Gen X R, fun a => .base (X.refl a), fun h => .symm h, fun h k => .trans h k⟩

def locMap (X : Setd.{u}) (R : X.car → X.car → Prop) : SHom X (loc X R) := ⟨fun x => x, fun h => .base h⟩

theorem gen_resp {X Y : Setd.{u}} (R : X.car → X.car → Prop) (f : SHom X Y)
    (hf : ∀ {a b}, R a b → Y.eqv (f.fn a) (f.fn b)) {a b : X.car} (h : Gen X R a b) :
    Y.eqv (f.fn a) (f.fn b) := by
  induction h with
  | base e => exact f.resp e
  | rel r => exact hf r
  | symm _ ih => exact Y.symm ih
  | trans _ _ ih₁ ih₂ => exact Y.trans ih₁ ih₂

/-- a map inverting R (sending R-related points to ≈-related ones) factors through the localization -/
def locLift {X Y : Setd.{u}} (R : X.car → X.car → Prop) (f : SHom X Y)
    (hf : ∀ {a b}, R a b → Y.eqv (f.fn a) (f.fn b)) : SHom (loc X R) Y :=
  ⟨f.fn, fun h => gen_resp R f hf h⟩

theorem locLift_comm {X Y : Setd.{u}} (R : X.car → X.car → Prop) (f : SHom X Y)
    (hf : ∀ {a b}, R a b → Y.eqv (f.fn a) (f.fn b)) :
    SetdCat.heq (SetdCat.comp (locMap X R) (locLift R f hf)) f := fun x => Y.refl (f.fn x)

theorem locLift_uniq {X Y : Setd.{u}} (R : X.car → X.car → Prop) (f : SHom X Y)
    (hf : ∀ {a b}, R a b → Y.eqv (f.fn a) (f.fn b)) (g : SHom (loc X R) Y)
    (hg : SetdCat.heq (SetdCat.comp (locMap X R) g) f) : SetdCat.heq g (locLift R f hf) := hg

/-- the localization makes R invertible (R-related points become equal) -/
theorem loc_inverts {X : Setd.{u}} (R : X.car → X.car → Prop) {a b : X.car} (r : R a b) :
    (loc X R).eqv ((locMap X R).fn a) ((locMap X R).fn b) := .rel r

end Core

end Found

#print axioms Found.Core.sumS
#print axioms Found.Core.copair_inl
#print axioms Found.Core.copair_inr
#print axioms Found.Core.copair_uniq
#print axioms Found.Core.prod
#print axioms Found.Core.ccc
#print axioms Found.Core.chiU_spec
#print axioms Found.Core.chiU_uniq
#print axioms Found.Core.power
#print axioms Found.Core.qlift_comm
#print axioms Found.Core.qlift_uniq
#print axioms Found.Core.fold_eq
#print axioms Found.Core.fold_uniq
#print axioms Found.Core.unfold_uniq
#print axioms Found.Core.iso_trans
#print axioms Found.Core.USetd
#print axioms Found.Core.prod_resp
#print axioms Found.Core.locLift
#print axioms Found.Core.locLift_comm
#print axioms Found.Core.locLift_uniq
#print axioms Found.Core.loc_inverts

#print axioms: 21 theorems, no axioms.

85.38 Provability logic GL

Löb’s axiom holds on a frame exactly when its relation is transitive and conversely well-founded; both directions are constructive, using accessibility and the semantic derivation of axiom 4; such frames are irreflexive. \(\Box (\Box p\to p)\to \Box p\iff \mathrm {Trans}(R)\wedge \forall w\,\mathrm {Acc}(R^{-1},w)\).

found/GL.lean

/-
  T137. found/GL — provability logic GL as a point on the relation
  coordinate R (T67's semantics reused).

  Löb's axiom □(□p → p) → □p is valid on a frame  ⟺  R is transitive and
  conversely well-founded (every world is accessible for "has a successor
  chain"), both directions constructive:
  * ⇐ by Acc-induction;
  * ⇒ well-foundedness from the valuation p := Acc, transitivity via the
    axiom 4 (derived semantically from Löb) and T67's 4 ⟺ transitive.

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: elimination of Acc from Prop (structural).
-/
import found.Modal

namespace Found

namespace Modal

universe u

variable {W : Type u} (R : W → W → Prop)

def Succ (y x : W) : Prop := R x y

def CWF : Prop := ∀ w, Acc (Succ R) w

def LobValid : Prop :=
  ∀ (V : W → Nat → Prop) w,
    sat R V w (.imp (.box (.imp (.box (.var 0)) (.var 0))) (.box (.var 0)))

theorem lob_of_frame (ht : Trans R) (hw : CWF R) : LobValid R := by
  intro V w h
  have key : ∀ v, Acc (Succ R) v → R w v → V v 0 := by
    intro v acc
    induction acc with
    | intro v _ ih =>
      intro r
      exact h v r (fun u r' => ih u r' (ht w v u r r'))
  exact fun v r => key v (hw v) r

theorem cwf_of_lob (hl : LobValid R) : CWF R := by
  intro w
  have hb := hl (fun v _ => Acc (Succ R) v) w
    (fun v _ hv => Acc.intro v (fun u r => hv u r))
  exact Acc.intro w (fun u r => hb u r)

theorem four_of_lob (hl : LobValid R) :
    ∀ (V : W → Nat → Prop) w, sat R V w (.imp (.box (.var 0)) (.box (.box (.var 0)))) := by
  intro V w hp
  -- apply Löb to q := p ∧ □p, encoded as a valuation of variable 0
  have hq := hl (fun v _ => V v 0 ∧ ∀ u, R v u → V u 0) w
    (fun v r hv => ⟨hp v r, fun u r' => (hv u r').1⟩)
  exact fun v r u r' => (hq v r).2 u r'

theorem trans_of_lob (hl : LobValid R) : Trans R :=
  (four_iff_trans R).mp (four_of_lob R hl)

/-- GL frames: Löb ⟺ transitive and conversely well-founded -/
theorem gl_iff : LobValid R ↔ Trans R ∧ CWF R :=
  ⟨fun hl => ⟨trans_of_lob R hl, cwf_of_lob R hl⟩, fun ⟨ht, hw⟩ => lob_of_frame R ht hw⟩

/-- GL is irreflexive on its frames (contrast with T and S4) -/
theorem gl_irrefl (hw : CWF R) (w : W) : ¬ R w w := by
  induction hw w with
  | intro w _ ih => exact fun r => ih w r r

end Modal

end Found

#print axioms Found.Modal.lob_of_frame
#print axioms Found.Modal.cwf_of_lob
#print axioms Found.Modal.four_of_lob
#print axioms Found.Modal.trans_of_lob
#print axioms Found.Modal.gl_iff
#print axioms Found.Modal.gl_irrefl

#print axioms: 6 theorems, no axioms.

85.39 Strong Kleene logic

With the three-valued tables of LP and designated value \(1\) only, K3 has no tautologies and is explosive; its consequence is dual to LP’s: \(\varphi \models _{K3}\psi \iff \neg \psi \models _{LP}\neg \varphi \). \(\varphi \models _{K3}\psi \iff \neg \psi \models _{LP}\neg \varphi \).

found/Kleene3.lean

/-
  T140. found/Kleene3 — strong Kleene three-valued logic K3 as a point:
  the same three-valued tables as LP (T70, reused), with designated set {1}
  instead of {½, 1}.

  * K3 has no tautologies: the all-½ valuation keeps every formula at ½.
  * K3 is explosive (p, ¬p ⊨ q), unlike LP.
  * The line K3 ↔ LP: φ ⊨_K3 ψ  ⟺  ¬ψ ⊨_LP ¬φ (designation duality),
    constructively, by cases on the three values.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Paracons

namespace Found

namespace Para

def DesK (x : T3) : Prop := x = .o

theorem half_closed : (φ : LF) → lval (fun _ => .h) φ = .h
  | .var _ => rfl
  | .neg a => by rw [lval, half_closed a]; rfl
  | .and a b => by rw [lval, half_closed a, half_closed b]; rfl
  | .or a b => by rw [lval, half_closed a, half_closed b]; rfl

/-- K3 has no tautologies -/
theorem k3_no_tautology (φ : LF) : ¬ ∀ v, DesK (lval v φ) :=
  fun h => T3.noConfusion ((half_closed φ).symm.trans (h (fun _ => .h)))

/-- K3 is explosive: no valuation designates both p and ¬p -/
theorem k3_explosive (v : Nat → T3) (p : LF) (h1 : DesK (lval v p)) (h2 : DesK (lval v (.neg p))) : False := by
  unfold DesK at h1 h2
  rw [lval, h1] at h2
  exact T3.noConfusion h2

def EntK (φ ψ : LF) : Prop := ∀ v, DesK (lval v φ) → DesK (lval v ψ)
def EntLP (φ ψ : LF) : Prop := ∀ v, Des (lval v φ) → Des (lval v ψ)

theorem des_neg_iff (x : T3) : Des (lneg x) ↔ ¬ DesK x := by
  cases x
  · exact ⟨fun _ e => T3.noConfusion e, fun _ e => T3.noConfusion e⟩
  · exact ⟨fun _ e => T3.noConfusion e, fun _ e => T3.noConfusion e⟩
  · exact ⟨fun h _ => h rfl, fun h _ => h rfl⟩

theorem desK_dec (x : T3) : DesK x ∨ ¬ DesK x := by
  cases x
  · exact Or.inr (fun e => T3.noConfusion e)
  · exact Or.inr (fun e => T3.noConfusion e)
  · exact Or.inl rfl

/-- designation duality: φ ⊨_K3 ψ ⟺ ¬ψ ⊨_LP ¬φ -/
theorem k3_lp_dual (φ ψ : LF) : EntK φ ψ ↔ EntLP (.neg ψ) (.neg φ) :=
  ⟨fun h v hn => (des_neg_iff _).mpr (fun hφ => (des_neg_iff _).mp hn (h v hφ)),
   fun h v hφ => (desK_dec (lval v ψ)).elim id
     (fun nψ => ((des_neg_iff _).mp (h v ((des_neg_iff _).mpr nψ)) hφ).elim)⟩

end Para

end Found

#print axioms Found.Para.half_closed
#print axioms Found.Para.k3_no_tautology
#print axioms Found.Para.k3_explosive
#print axioms Found.Para.k3_lp_dual

#print axioms: 4 theorems, no axioms.

85.40 Hilbert systems

The Hilbert calculus with K, S, the connective axioms, ex falso and modus ponens satisfies the deduction theorem and proves exactly what intuitionistic natural deduction proves, from the same set of hypotheses. \(\Gamma ,a\vdash _H b\Rightarrow \Gamma \vdash _H a\to b;\quad \Gamma \vdash _H\varphi \iff \Gamma \vdash _{ND}\varphi \).

found/Hilbert.lean

/-
  T143. found/Hilbert — Hilbert systems as a point of proof theory, and the
  line Hilbert ⟺ natural deduction (T65's PD, set contexts).

  * Hilbert calculus HD: axioms K, S, ∧/∨ introduction-elimination axioms,
    ex falso; the only rule is modus ponens.
  * Deduction theorem (by induction on Hilbert derivations).
  * HD Γ φ ⟺ PD true Γ φ (both directions).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Minimal

namespace Found

namespace Prp

inductive HD (Γ : Form → Prop) : Form → Prop where
  | hyp {a} : Γ a → HD Γ a
  | k (a b : Form) : HD Γ (.imp a (.imp b a))
  | s (a b c : Form) : HD Γ (.imp (.imp a (.imp b c)) (.imp (.imp a b) (.imp a c)))
  | andI (a b : Form) : HD Γ (.imp a (.imp b (.and a b)))
  | andE1 (a b : Form) : HD Γ (.imp (.and a b) a)
  | andE2 (a b : Form) : HD Γ (.imp (.and a b) b)
  | orI1 (a b : Form) : HD Γ (.imp a (.or a b))
  | orI2 (a b : Form) : HD Γ (.imp b (.or a b))
  | orE (a b c : Form) : HD Γ (.imp (.imp a c) (.imp (.imp b c) (.imp (.or a b) c)))
  | efq (a : Form) : HD Γ (.imp .bot a)
  | mp {a b} : HD Γ (.imp a b) → HD Γ a → HD Γ b

theorem hd_id (Γ : Form → Prop) (a : Form) : HD Γ (.imp a a) :=
  .mp (.mp (.s a (.imp a a) a) (.k a (.imp a a))) (.k a a)

/-- the deduction theorem -/
theorem deduction {Γ : Form → Prop} {a b : Form} (d : HD (ext Γ a) b) : HD Γ (.imp a b) := by
  induction d with
  | hyp g => exact g.elim (fun e => e ▸ hd_id Γ a) (fun g' => .mp (.k _ a) (.hyp g'))
  | k x y => exact .mp (.k _ a) (.k x y)
  | s x y z => exact .mp (.k _ a) (.s x y z)
  | andI x y => exact .mp (.k _ a) (.andI x y)
  | andE1 x y => exact .mp (.k _ a) (.andE1 x y)
  | andE2 x y => exact .mp (.k _ a) (.andE2 x y)
  | orI1 x y => exact .mp (.k _ a) (.orI1 x y)
  | orI2 x y => exact .mp (.k _ a) (.orI2 x y)
  | orE x y z => exact .mp (.k _ a) (.orE x y z)
  | efq x => exact .mp (.k _ a) (.efq x)
  | mp _ _ ihf iha => exact .mp (.mp (.s _ _ _) ihf) iha

/-- Hilbert ⇒ natural deduction -/
theorem hd_pd {Γ : Form → Prop} {φ : Form} (d : HD Γ φ) : PD true Γ φ := by
  induction d with
  | hyp g => exact .hyp g
  | k => exact .impI (.impI (.hyp (Or.inr (Or.inl rfl))))
  | s => exact .impI (.impI (.impI (.impE (.impE (.hyp (Or.inr (Or.inr (Or.inl rfl)))) (.hyp (Or.inl rfl)))
      (.impE (.hyp (Or.inr (Or.inl rfl))) (.hyp (Or.inl rfl))))))
  | andI => exact .impI (.impI (.andI (.hyp (Or.inr (Or.inl rfl))) (.hyp (Or.inl rfl))))
  | andE1 => exact .impI (.andE1 (.hyp (Or.inl rfl)))
  | andE2 => exact .impI (.andE2 (.hyp (Or.inl rfl)))
  | orI1 => exact .impI (.orI1 (.hyp (Or.inl rfl)))
  | orI2 => exact .impI (.orI2 (.hyp (Or.inl rfl)))
  | orE => exact .impI (.impI (.impI (.orE (.hyp (Or.inl rfl))
      (.impE (.hyp (Or.inr (Or.inr (Or.inr (Or.inl rfl))))) (.hyp (Or.inl rfl)))
      (.impE (.hyp (Or.inr (Or.inr (Or.inl rfl)))) (.hyp (Or.inl rfl))))))
  | efq => exact .impI (.botE rfl (.hyp (Or.inl rfl)))
  | mp _ _ ihf iha => exact .impE ihf iha

/-- natural deduction ⇒ Hilbert -/
theorem pd_hd {Γ : Form → Prop} {φ : Form} (d : PD true Γ φ) : HD Γ φ := by
  induction d with
  | hyp g => exact .hyp g
  | botE _ _ ih => exact .mp (.efq _) ih
  | andI _ _ iha ihb => exact .mp (.mp (.andI _ _) iha) ihb
  | andE1 _ ih => exact .mp (.andE1 _ _) ih
  | andE2 _ ih => exact .mp (.andE2 _ _) ih
  | orI1 _ ih => exact .mp (.orI1 _ _) ih
  | orI2 _ ih => exact .mp (.orI2 _ _) ih
  | orE _ _ _ ih iha ihb => exact .mp (.mp (.mp (.orE _ _ _) (deduction iha)) (deduction ihb)) ih
  | impI _ ih => exact deduction ih
  | impE _ _ ihf iha => exact .mp ihf iha

theorem hilbert_iff_nd (Γ : Form → Prop) (φ : Form) : HD Γ φ ↔ PD true Γ φ := ⟨hd_pd, pd_hd⟩

end Prp

end Found

#print axioms Found.Prp.hd_id
#print axioms Found.Prp.deduction
#print axioms Found.Prp.hd_pd
#print axioms Found.Prp.pd_hd
#print axioms Found.Prp.hilbert_iff_nd

#print axioms: 5 theorems, no axioms.

85.41 Closed monoidal structure

A closed structure on the category parameter is an adjunction \((-\otimes b)\dashv (b\multimap -)\) for each \(b\); every cartesian closed category and every residuated order with \(!\) (as a thin category) carries one, linking linear logic to closed monoidal categories. \(\mathrm {Hom}(a\otimes b,c)\simeq \mathrm {Hom}(a,b\multimap c)\) for CCCs and residuated orders.

found/MonoidalClosed.lean

/-
  T150. found/MonoidalClosed — closed (monoidal) structure as a value on the
  category parameter: for each object b an adjunction (− ⊗ b) ⊣ (b ⊸ −)
  (T61's Adj; coherence of ⊗ is not needed for the statements here).

  Instances (no re-proofs):
  * every CCC (T62): ⊗ = ×, ⊸ = ⇒, the adjunction K.adj;
  * every residuated order with ! (T68's CRL) seen as a thin category:
    the linear-logic models are exactly the order shadows — the line
    linear logic (T68) ↔ closed monoidal categories.

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: homs of a thin category = PLift (Prop) (morphism equivalence = True by proof irrelevance).
-/
import found.CCC
import found.Linear

namespace Found

namespace MonClosed

universe u v

structure Closed (C : ECat.{u, v}) where
  F : C.Ob → EFun C C
  G : C.Ob → EFun C C
  adj : ∀ b, Adj (F b) (G b)

/-- every CCC is closed -/
def ofCCC {C : ECat.{u, v}} (K : CCC C) : Closed C :=
  ⟨K.prodF, K.expF, K.adj⟩

/-! ## a preorder as a thin category -/

def thin (M : Lin.CRL.{u}) : ECat.{u, 0} where
  Ob := M.car
  Hom a b := PLift (M.le a b)
  heq _ _ := True
  hrefl _ := trivial
  hsymm _ := trivial
  htrans _ _ := trivial
  id a := ⟨M.le_refl a⟩
  comp f g := ⟨M.le_trans f.down g.down⟩
  comp_resp _ _ := trivial
  id_comp _ := trivial
  comp_id _ := trivial
  assoc _ _ _ := trivial

def tensF (M : Lin.CRL.{u}) (b : M.car) : EFun (thin M) (thin M) where
  obj a := M.tens a b
  map h := ⟨M.tens_mono h.down (M.le_refl b)⟩
  map_resp _ := trivial
  map_id _ := trivial
  map_comp _ _ := trivial

def lolliF (M : Lin.CRL.{u}) (b : M.car) : EFun (thin M) (thin M) where
  obj c := M.lolli b c
  map h := ⟨M.adj.mp (M.le_trans (M.adj.mpr (M.le_refl _)) h.down)⟩
  map_resp _ := trivial
  map_id _ := trivial
  map_comp _ _ := trivial

/-- every residuated order is closed (as a thin category) -/
def ofCRL (M : Lin.CRL.{u}) : Closed (thin M) where
  F := tensF M
  G := lolliF M
  adj b :=
    { phi := fun h => ⟨M.adj.mp (M.le_trans (M.tens_comm b _) h.down)⟩
      psi := fun h => ⟨M.le_trans (M.tens_comm _ b) (M.adj.mpr h.down)⟩
      phi_resp := fun _ => trivial
      psi_resp := fun _ => trivial
      phi_psi := fun _ => trivial
      psi_phi := fun _ => trivial
      nat_l := fun _ _ => trivial
      nat_r := fun _ _ => trivial }

/-- the residuation law read back from the closed structure -/
theorem residuation (M : Lin.CRL.{u}) (a b c : M.car) :
    M.le (M.tens a b) c → M.le a (M.lolli b c) :=
  fun h => ((ofCRL M).adj b).phi (a := a) (b := c) ⟨h⟩ |>.down

end MonClosed

end Found

#print axioms Found.MonClosed.ofCCC
#print axioms Found.MonClosed.thin
#print axioms Found.MonClosed.ofCRL
#print axioms Found.MonClosed.residuation

#print axioms: 4 theorems, no axioms.

85.42 Lambek calculus

Lambek algebras are preorders with an associative product and two residuals; languages with concatenation form one, which is not commutative, and with exchange the two residuals coincide, which is the linear (commutative) case. \(a\otimes b\le c\iff b\le a\backslash c\iff a\le c/b;\quad \mathrm {exch}\Rightarrow a\backslash c\simeq c/a\).

found/Lambek.lean

/-
  T112. found/Lambek — the Lambek calculus as a point: residuated monoids
  without exchange (two residuals \ and /), a free parameter.

  * Lambek algebra: preorder, associative ⊗, a ⊗ b ≤ c ⟺ b ≤ a \ c ⟺ a ≤ c / b.
  * Instance: languages over any alphabet (Prop-valued sets of words) with
    concatenation — the standard model; it is not commutative.
  * Line to linear logic (T68): with exchange (a⊗b ≤ b⊗a) the two residuals
    coincide up to ≤ both ways, which is the CRL case.

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Lambek

universe u

structure LA where
  car : Type u
  le : car → car → Prop
  le_refl : ∀ a, le a a
  le_trans : ∀ {a b c}, le a b → le b c → le a c
  tens : car → car → car
  under : car → car → car     -- a \ c
  over : car → car → car      -- c / b
  res_r : ∀ {a b c}, le (tens a b) c ↔ le b (under a c)
  res_l : ∀ {a b c}, le (tens a b) c ↔ le a (over c b)

/-- with exchange the two residuals agree -/
theorem exchange_residuals (L : LA.{u}) (exch : ∀ a b, L.le (L.tens a b) (L.tens b a)) (a c : L.car) :
    L.le (L.under a c) (L.over c a) ∧ L.le (L.over c a) (L.under a c) :=
  ⟨L.res_l.mp (L.le_trans (exch _ _) (L.res_r.mpr (L.le_refl _))),
   L.res_r.mp (L.le_trans (exch _ _) (L.res_l.mpr (L.le_refl _)))⟩

/-! ## languages -/

section Lang
variable (α : Type u)

def Lang : Type u := List α → Prop

def cat (L K : Lang α) : Lang α := fun w => ∃ x y, w = x ++ y ∧ L x ∧ K y
def under (L K : Lang α) : Lang α := fun y => ∀ x, L x → K (x ++ y)
def over (K L : Lang α) : Lang α := fun x => ∀ y, L y → K (x ++ y)
def sub (L K : Lang α) : Prop := ∀ w, L w → K w

def langLA : LA.{u} where
  car := Lang α
  le := sub α
  le_refl _ _ h := h
  le_trans h k w x := k w (h w x)
  tens := cat α
  under := under α
  over := over α
  res_r := ⟨fun h y m x l => h _ ⟨x, y, rfl, l, m⟩,
            fun h _ ⟨x, y, e, l, m⟩ => e ▸ h y m x l⟩
  res_l := ⟨fun h x l y m => h _ ⟨x, y, rfl, l, m⟩,
            fun h _ ⟨x, y, e, l, m⟩ => e ▸ h x l y m⟩

end Lang

def single {α : Type} (w : List α) : Lang α := fun v => v = w

/-- the language model is not commutative: {a}{b} ⊄ {b}{a} for a ≠ b -/
theorem not_commutative : ¬ sub Bool (cat Bool (single [true]) (single [false]))
    (cat Bool (single [false]) (single [true])) := by
  intro h
  match h [true, false] ⟨[true], [false], rfl, rfl, rfl⟩ with
  | ⟨x, y, e, hx, hy⟩ =>
    cases hx
    cases hy
    exact Bool.noConfusion (List.cons.inj e).1

end Lambek

end Found

#print axioms Found.Lambek.exchange_residuals
#print axioms Found.Lambek.langLA
#print axioms Found.Lambek.not_commutative

#print axioms: 3 theorems, no axioms.

85.43 Dynamic and temporal logic

Program boxes satisfy \([\alpha ;\beta ]=[\alpha ][\beta ]\), \([\alpha \cup \beta ]=[\alpha ]\wedge [\beta ]\), the star fixed point and induction; on paths, \(G\) and \(F\) unfold through \(X\) and \(G\neg =\neg F\). \([\alpha ^*]p\iff p\wedge [\alpha ][\alpha ^*]p;\quad Gp\iff p\wedge XGp\).

found/Dynamic.lean

/-
  T138. found/Dynamic — dynamic and temporal logics as points: programs are
  values of the relation coordinate (closed under ;, ∪, *), time is the
  core's stream (coinduction, T59).

  * PDL: [α;β]p ⟺ [α][β]p, [α∪β]p ⟺ [α]p ∧ [β]p, [α*]p ⟺ p ∧ [α][α*]p
    (fixed point) and the induction rule for *.
  * LTL on paths ℕ → S: G p ⟺ p ∧ X G p, F p ⟺ p ∨ X F p, p U q unfolds;
    CTL's A/E over paths are the relation-coordinate box/diamond on paths
    (stated for the path relation).

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Dyn

universe u

variable {S : Type u}

def Rel (S : Type u) : Type u := S → S → Prop

def seq (a b : Rel S) : Rel S := fun x z => ∃ y, a x y ∧ b y z
def alt (a b : Rel S) : Rel S := fun x y => a x y ∨ b x y

inductive star (a : Rel S) : Rel S where
  | refl (x : S) : star a x x
  | step {x y z : S} : a x y → star a y z → star a x z

def box (a : Rel S) (p : S → Prop) : S → Prop := fun x => ∀ y, a x y → p y

theorem box_seq (a b : Rel S) (p : S → Prop) (x : S) :
    box (seq a b) p x ↔ box a (box b p) x :=
  ⟨fun h y r z r' => h z ⟨y, r, r'⟩, fun h z ⟨y, r, r'⟩ => h y r z r'⟩

theorem box_alt (a b : Rel S) (p : S → Prop) (x : S) :
    box (alt a b) p x ↔ box a p x ∧ box b p x :=
  ⟨fun h => ⟨fun y r => h y (Or.inl r), fun y r => h y (Or.inr r)⟩,
   fun h y r => r.elim (h.1 y) (h.2 y)⟩

theorem box_star (a : Rel S) (p : S → Prop) (x : S) :
    box (star a) p x ↔ p x ∧ box a (box (star a) p) x :=
  ⟨fun h => ⟨h x (.refl x), fun y r z r' => h z (.step r r')⟩,
   fun h y r => by
     cases r with
     | refl => exact h.1
     | step r₁ r₂ => exact h.2 _ r₁ y r₂⟩

/-- the induction rule: an α-invariant true at x holds along α* -/
theorem star_induction (a : Rel S) (p : S → Prop) (inv : ∀ x, p x → box a p x) :
    ∀ x, p x → box (star a) p x := by
  intro x hx y r
  induction r with
  | refl => exact hx
  | step r₁ _ ih => exact ih (inv _ hx _ r₁)

/-! ## LTL on paths -/

def Path (S : Type u) : Type u := Nat → S

def shift (π : Path S) : Path S := fun n => π (n + 1)
def drop (π : Path S) : Nat → Path S
  | 0 => π
  | k + 1 => drop (shift π) k

def G (p : Path S → Prop) (π : Path S) : Prop := ∀ k, p (drop π k)
def F (p : Path S → Prop) (π : Path S) : Prop := ∃ k, p (drop π k)
def X (p : Path S → Prop) (π : Path S) : Prop := p (shift π)

theorem G_unfold (p : Path S → Prop) (π : Path S) : G p π ↔ p π ∧ X (G p) π :=
  ⟨fun h => ⟨h 0, fun k => h (k + 1)⟩,
   fun h k => match k with
     | 0 => h.1
     | k + 1 => h.2 k⟩

theorem F_unfold (p : Path S → Prop) (π : Path S) : F p π ↔ p π ∨ X (F p) π :=
  ⟨fun ⟨k, h⟩ => match k, h with
     | 0, h => Or.inl h
     | k + 1, h => Or.inr ⟨k, h⟩,
   fun h => h.elim (fun h0 => ⟨0, h0⟩) (fun ⟨k, hk⟩ => ⟨k + 1, hk⟩)⟩

/-- duality G ¬p ⟺ ¬ F p (constructive direction) -/
theorem G_not_F (p : Path S → Prop) (π : Path S) : G (fun σ => ¬ p σ) π ↔ ¬ F p π :=
  ⟨fun h ⟨k, hk⟩ => h k hk, fun h k hk => h ⟨k, hk⟩⟩

end Dyn

end Found

#print axioms Found.Dyn.box_seq
#print axioms Found.Dyn.box_alt
#print axioms Found.Dyn.box_star
#print axioms Found.Dyn.star_induction
#print axioms Found.Dyn.G_unfold
#print axioms Found.Dyn.F_unfold
#print axioms Found.Dyn.G_not_F

#print axioms: 7 theorems, no axioms.

85.44 Domain theory

On any \(\omega \)-chain complete pointed preorder, a Scott-continuous map has \(\sup _n f^n(\bot )\) as a fixed point below every pre-fixed point. \(\mathrm {fix}\,f=\sup _n f^n\bot ,\quad f(\mathrm {fix}\,f)\simeq \mathrm {fix}\,f,\quad f x\le x\Rightarrow \mathrm {fix}\,f\le x\).

found/Domain.lean

/-
  T116. found/Domain — Scott domain theory as a point: ω-chain complete
  pointed preorders (a free parameter) and the Kleene fixed point theorem.

  * ωCPO: preorder with ⊥ and a sup for every increasing chain ℕ → D.
  * Scott-continuous maps: monotone and preserving sups of chains.
  * Kleene: for continuous f, fix f := sup (fⁿ ⊥) is a fixed point (up to ≤
    both ways) and below every pre-fixed point — the least fixed point.
  * This is the semantics of recursion used by PCF (T144) and by the λ-models
    of T78 (D ≅ D^D) — lines to computation.

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Dom

universe u

structure CPO where
  D : Type u
  le : D → D → Prop
  le_refl : ∀ a, le a a
  le_trans : ∀ {a b c}, le a b → le b c → le a c
  bot : D
  bot_le : ∀ a, le bot a
  sup : (Nat → D) → D
  sup_ub : ∀ (c : Nat → D), (∀ n, le (c n) (c (n + 1))) → ∀ n, le (c n) (sup c)
  sup_least : ∀ (c : Nat → D), (∀ n, le (c n) (c (n + 1))) → ∀ x, (∀ n, le (c n) x) → le (sup c) x

variable (P : CPO.{u})

structure Cont where
  f : P.D → P.D
  mono : ∀ {a b}, P.le a b → P.le (f a) (f b)
  cont : ∀ (c : Nat → P.D), (∀ n, P.le (c n) (c (n + 1))) → P.le (f (P.sup c)) (P.sup (fun n => f (c n)))

variable {P}

def iter (g : Cont P) : Nat → P.D
  | 0 => P.bot
  | n + 1 => g.f (iter g n)

theorem iter_chain (g : Cont P) : ∀ n, P.le (iter g n) (iter g (n + 1))
  | 0 => P.bot_le _
  | n + 1 => g.mono (iter_chain g n)

def fix (g : Cont P) : P.D := P.sup (iter g)

theorem fix_le (g : Cont P) : P.le (g.f (fix g)) (fix g) :=
  P.le_trans (g.cont _ (iter_chain g))
    (P.sup_least _ (fun n => g.mono (iter_chain g n)) _ (fun n => P.sup_ub _ (iter_chain g) (n + 1)))

theorem le_fix (g : Cont P) : P.le (fix g) (g.f (fix g)) :=
  P.sup_least _ (iter_chain g) _ (fun n => match n with
    | 0 => P.bot_le _
    | n + 1 => g.mono (P.sup_ub _ (iter_chain g) n))

/-- least among pre-fixed points -/
theorem fix_least (g : Cont P) (x : P.D) (hx : P.le (g.f x) x) : P.le (fix g) x :=
  P.sup_least _ (iter_chain g) x (fun n => below n)
where
  below : ∀ n, P.le (iter g n) x
    | 0 => P.bot_le x
    | n + 1 => P.le_trans (g.mono (below n)) hx

end Dom

end Found

#print axioms Found.Dom.iter_chain
#print axioms Found.Dom.fix_le
#print axioms Found.Dom.le_fix
#print axioms Found.Dom.fix_least

#print axioms: 4 theorems, no axioms.

85.45 Coalgebras and final coalgebras

For any endofunctor on the category parameter, coalgebra homomorphisms compose, final coalgebras are unique up to isomorphism, and the structure map of a final coalgebra is invertible (Lambek). \(\zeta :Z\to FZ\ \text {final}\Rightarrow \zeta \ \text {iso}\).

found/Coalgebra.lean

/-
  T156. found/Coalgebra — coalgebras of an endofunctor F on the category
  parameter C (any E-category), generally.

  * Coalgebras, homomorphisms (identity and composites are homomorphisms).
  * Final coalgebras are unique up to isomorphism.
  * Lambek's lemma: the structure map of a final coalgebra is an isomorphism.
  Instances proved elsewhere and not re-proved: streams (T59 core, unfold
  uniqueness) and hypersets (T105, unique decorations = finality of the
  powerset coalgebra); the dual (initial algebras) is the core's W (T59) and
  the NNO (T86).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Cat

namespace Found

namespace Coalg

universe u v

variable {C : ECat.{u, v}} (F : EFun C C)

structure Co where
  X : C.Ob
  str : C.Hom X (F.obj X)

def IsHom (A B : Co F) (h : C.Hom A.X B.X) : Prop :=
  C.heq (C.comp A.str (F.map h)) (C.comp h B.str)

theorem id_hom (A : Co F) : IsHom F A A (C.id A.X) :=
  C.htrans (C.rcong _ (F.map_id _)) (C.htrans (C.comp_id _) (C.hsymm (C.id_comp _)))

theorem comp_hom {A B D : Co F} {h : C.Hom A.X B.X} {k : C.Hom B.X D.X}
    (hh : IsHom F A B h) (hk : IsHom F B D k) : IsHom F A D (C.comp h k) :=
  C.htrans (C.rcong _ (F.map_comp h k))
  (C.htrans (C.hsymm (C.assoc _ _ _))
  (C.htrans (C.lcong hh _)
  (C.htrans (C.assoc _ _ _)
  (C.htrans (C.rcong h hk) (C.hsymm (C.assoc _ _ _))))))

structure Final where
  Z : Co F
  out : (A : Co F) → C.Hom A.X Z.X
  out_hom : ∀ A, IsHom F A Z (out A)
  uniq : ∀ A (h : C.Hom A.X Z.X), IsHom F A Z h → C.heq h (out A)

variable {F}

theorem endo_id (T : Final F) (h : C.Hom T.Z.X T.Z.X) (hh : IsHom F T.Z T.Z h) :
    C.heq h (C.id T.Z.X) :=
  C.htrans (T.uniq _ h hh) (C.hsymm (T.uniq _ _ (id_hom F T.Z)))

/-- final coalgebras are unique up to isomorphism -/
theorem final_iso (T S : Final F) :
    C.heq (C.comp (S.out T.Z) (T.out S.Z)) (C.id T.Z.X) :=
  endo_id T _ (comp_hom F (S.out_hom T.Z) (T.out_hom S.Z))

/-- Lambek's lemma: the structure map of a final coalgebra is invertible -/
theorem lambek (T : Final F) :
    C.heq (C.comp T.Z.str (T.out ⟨F.obj T.Z.X, F.map T.Z.str⟩)) (C.id T.Z.X) ∧
    C.heq (C.comp (T.out ⟨F.obj T.Z.X, F.map T.Z.str⟩) T.Z.str) (C.id (F.obj T.Z.X)) := by
  let A : Co F := ⟨F.obj T.Z.X, F.map T.Z.str⟩
  have hu : IsHom F A T.Z (T.out A) := T.out_hom A
  have hz : IsHom F T.Z A T.Z.str := C.hrefl _
  have h1 : C.heq (C.comp T.Z.str (T.out A)) (C.id T.Z.X) := endo_id T _ (comp_hom F hz hu)
  refine ⟨h1, ?_⟩
  exact C.htrans (C.hsymm hu)
    (C.htrans (C.hsymm (F.map_comp _ _)) (C.htrans (F.map_resp h1) (F.map_id _)))

end Coalg

end Found

#print axioms Found.Coalg.id_hom
#print axioms Found.Coalg.comp_hom
#print axioms Found.Coalg.endo_id
#print axioms Found.Coalg.final_iso
#print axioms Found.Coalg.lambek

#print axioms: 5 theorems, no axioms.

85.46 Locales and pointless topology

Every frame is a Heyting algebra with \(a\to b=\bigvee \{c\mid c\wedge a\le b\}\), and the opens of any topological space form a frame, so spaces and locales give Heyting truth values. \(c\wedge a\le b\iff c\le \bigvee \{x\mid x\wedge a\le b\}\).

found/Locale.lean

/-
  T115. found/Locale — locales (pointless topology) as a point: frames are a
  free parameter (preorder, finite meets, joins of every family, infinite
  distributivity).

  * Every frame is a Heyting algebra (a → b := ⋁{c | c ∧ a ≤ b}) — the line
    frames → Heyting values → intuitionistic logic (T65), and sheaf truth
    values (T95).
  * Instance: the opens of any topological space (Prop-valued predicates
    closed under all unions and finite intersections) form a frame.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Topos

namespace Found

namespace Loc

universe u

structure Frame where
  car : Type u
  le : car → car → Prop
  le_refl : ∀ a, le a a
  le_trans : ∀ {a b c}, le a b → le b c → le a c
  top : car
  meet : car → car → car
  le_top : ∀ a, le a top
  meet_l : ∀ a b, le (meet a b) a
  meet_r : ∀ a b, le (meet a b) b
  meet_univ : ∀ {a b c}, le c a → le c b → le c (meet a b)
  sup : {I : Type u} → (I → car) → car
  sup_ub : ∀ {I : Type u} (f : I → car) (i : I), le (f i) (sup f)
  sup_least : ∀ {I : Type u} (f : I → car) (c : car), (∀ i, le (f i) c) → le (sup f) c
  distrib : ∀ {I : Type u} (a : car) (f : I → car), le (meet a (sup f)) (sup (fun i => meet a (f i)))

variable (L : Frame.{u})

def toHA : HA.{u} where
  car := L.car
  le := L.le
  le_refl := L.le_refl
  le_trans := L.le_trans
  top := L.top
  bot := L.sup (fun e : PEmpty.{u + 1} => nomatch e)
  meet := L.meet
  join a b := L.sup (fun t : ULift.{u} Bool => match t.down with | true => a | false => b)
  imp a b := L.sup (fun c : {c : L.car // L.le (L.meet c a) b} => c.val)
  le_top := L.le_top
  bot_le c := L.sup_least _ c (fun e => nomatch e)
  meet_l := L.meet_l
  meet_r := L.meet_r
  meet_univ := L.meet_univ
  join_l a b := L.sup_ub (fun t : ULift.{u} Bool => match t.down with | true => a | false => b) ⟨true⟩
  join_r a b := L.sup_ub (fun t : ULift.{u} Bool => match t.down with | true => a | false => b) ⟨false⟩
  join_univ {_ _ c} ha hb := L.sup_least _ c (fun t => match t with
    | ⟨true⟩ => ha
    | ⟨false⟩ => hb)
  imp_adj {a b c} :=
    ⟨fun h => L.sup_ub (fun c : {c : L.car // L.le (L.meet c a) b} => c.val) ⟨c, h⟩,
     fun h => L.le_trans (L.meet_univ (L.meet_r _ _) (L.le_trans (L.meet_l _ _) h))
       (L.le_trans (L.distrib a _)
         (L.sup_least _ b (fun i => L.le_trans (L.meet_univ (L.meet_r _ _) (L.meet_l _ _)) i.property)))⟩

/-! ## opens of a topological space -/

structure Top (X : Type u) where
  isOpen : (X → Prop) → Prop
  univ_open : isOpen (fun _ => True)
  inter_open : ∀ {U V}, isOpen U → isOpen V → isOpen (fun x => U x ∧ V x)
  union_open : ∀ {I : Type u} (f : I → X → Prop), (∀ i, isOpen (f i)) → isOpen (fun x => ∃ i, f i x)

def opens {X : Type u} (T : Top X) : Frame.{u} where
  car := {U : X → Prop // T.isOpen U}
  le U V := ∀ x, U.val x → V.val x
  le_refl _ _ h := h
  le_trans h k x a := k x (h x a)
  top := ⟨fun _ => True, T.univ_open⟩
  meet U V := ⟨fun x => U.val x ∧ V.val x, T.inter_open U.property V.property⟩
  le_top _ _ _ := trivial
  meet_l _ _ _ h := h.1
  meet_r _ _ _ h := h.2
  meet_univ h k x a := ⟨h x a, k x a⟩
  sup f := ⟨fun x => ∃ i, (f i).val x, T.union_open _ (fun i => (f i).property)⟩
  sup_ub _ i _ h := ⟨i, h⟩
  sup_least _ _ h x := fun ⟨i, hi⟩ => h i x hi
  distrib _ _ _ := fun ⟨ha, i, hi⟩ => ⟨i, ha, hi⟩

/-- the opens of a space give Heyting truth values -/
def spaceHA {X : Type u} (T : Top X) : HA.{u} := toHA (opens T)

end Loc

end Found

#print axioms Found.Loc.toHA
#print axioms Found.Loc.opens
#print axioms Found.Loc.spaceHA

#print axioms: 3 theorems, no axioms.

85.47 Free, infinitary and hybrid logic

Free logic quantifies over an existence predicate, so instantiation needs \(E\,t\) and fails without it; countable conjunctions and disjunctions distribute and satisfy De Morgan; nominals and satisfaction operators obey the hybrid laws. \(\forall _E\varphi \wedge E t\Rightarrow \varphi t;\quad @_i@_j\varphi \iff @_j\varphi \).

found/FreeInfHybrid.lean

/-
  T141. found/FreeInfHybrid — free logic, infinitary logic, hybrid logic as
  points on existing coordinates (semantics as predicates on a domain or on
  worlds of the relation coordinate).

  * Free logic: quantifiers range over an existence predicate E; instantiation
    needs E t; plain instantiation fails (countermodel); with E empty
    (inclusive free logic) ∃x (x = x) fails.
  * Infinitary logic L_ω₁ω: countable conjunctions/disjunctions are ∀n/∃n over
    ℕ-indexed families; distributivity and De Morgan (constructive direction).
  * Hybrid logic: nominals true at exactly one world, @_i; laws
    @_i @_j φ ⟺ @_j φ and (@_i j ∧ @_j φ) → @_i φ.

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace FreeL

universe u

variable {M : Type u} (E : M → Prop)

def fall (φ : M → Prop) : Prop := ∀ x, E x → φ x
def fex (φ : M → Prop) : Prop := ∃ x, E x ∧ φ x

theorem free_inst (φ : M → Prop) (t : M) (h : fall E φ) (ht : E t) : φ t := h t ht

theorem plain_inst_fails :
    ¬ ∀ (φ : Bool → Prop) (t : Bool), fall (fun b => b = true) φ → φ t :=
  fun h => Bool.noConfusion (h (fun b => b = true) false (fun _ e => e))

theorem inclusive_empty : ¬ fex (fun (_ : Bool) => False) (fun x => x = x) :=
  fun ⟨_, e, _⟩ => e

end FreeL

namespace InfL

/-- countable conjunction and disjunction -/
def bigAnd (φ : Nat → Prop) : Prop := ∀ n, φ n
def bigOr (φ : Nat → Prop) : Prop := ∃ n, φ n

theorem and_bigOr (p : Prop) (φ : Nat → Prop) : (p ∧ bigOr φ) ↔ bigOr (fun n => p ∧ φ n) :=
  ⟨fun ⟨hp, n, h⟩ => ⟨n, hp, h⟩, fun ⟨n, hp, h⟩ => ⟨hp, n, h⟩⟩

theorem not_bigOr (φ : Nat → Prop) : ¬ bigOr φ ↔ bigAnd (fun n => ¬ φ n) :=
  ⟨fun h n hn => h ⟨n, hn⟩, fun h ⟨n, hn⟩ => h n hn⟩

end InfL

namespace Hybrid

universe u

variable {W : Type u}

/-- a nominal: true at exactly one world -/
structure Nominal (W : Type u) where
  w : W

def holds (i : Nominal W) (v : W) : Prop := v = i.w

def at_ (i : Nominal W) (φ : W → Prop) : W → Prop := fun _ => φ i.w

theorem at_at (i j : Nominal W) (φ : W → Prop) (v : W) : at_ i (at_ j φ) v ↔ at_ j φ v := Iff.rfl

theorem at_nominal (i j : Nominal W) (φ : W → Prop) (v : W) :
    at_ i (holds j) v → at_ j φ v → at_ i φ v :=
  fun e h => by
    show φ i.w
    rw [show i.w = j.w from e]
    exact h

theorem nominal_unique (i : Nominal W) (v v' : W) (h : holds i v) (h' : holds i v') : v = v' :=
  h.trans h'.symm

end Hybrid

end Found

#print axioms Found.FreeL.free_inst
#print axioms Found.FreeL.plain_inst_fails
#print axioms Found.FreeL.inclusive_empty
#print axioms Found.InfL.and_bigOr
#print axioms Found.InfL.not_bigOr
#print axioms Found.Hybrid.at_at
#print axioms Found.Hybrid.at_nominal
#print axioms Found.Hybrid.nominal_unique

#print axioms: 8 theorems, no axioms.

85.48 Da Costa’s C-systems

Bivaluations with classical binary connectives and a negation that need only satisfy \(v(a)=0\Rightarrow v(\neg a)=1\) and \(v(\neg \neg a)=1\Rightarrow v(a)=1\) validate excluded middle, while an explicit bivaluation makes \(p\) and \(\neg p\) true and \(q\) false. \(\models a\vee \neg a;\quad p,\neg p\not \models q\).

found/DaCosta.lean

/-
  T139. found/DaCosta — da Costa's Cω as a point: negation is not
  truth-functional; semantics by bivaluations v : formulas → Bool with
    classical ∧, ∨, →;   v a = 0 ⇒ v(¬a) = 1;   v(¬¬a) = 1 ⇒ v a = 1.
  * Excluded middle is valid (every bivaluation), explosion is not:
    an explicit bivaluation with p, ¬p true and q false.
  * Line to LP (T70) / classical (T66): restricting bivaluations to
    truth-functional ¬ gives classical logic.

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace DaCosta

inductive DF where
  | var : Nat → DF
  | neg : DF → DF
  | and : DF → DF → DF
  | or : DF → DF → DF
  | imp : DF → DF → DF

structure Biv where
  v : DF → Bool
  and_ : ∀ a b, v (.and a b) = (v a && v b)
  or_ : ∀ a b, v (.or a b) = (v a || v b)
  imp_ : ∀ a b, v (.imp a b) = (!v a || v b)
  neg0 : ∀ a, v a = false → v (.neg a) = true
  negneg : ∀ a, v (.neg (.neg a)) = true → v a = true

/-- excluded middle is valid in Cω -/
theorem lem (B : Biv) (a : DF) : B.v (.or a (.neg a)) = true := by
  rw [B.or_]
  cases h : B.v a with
  | true => rfl
  | false => rw [B.neg0 a h]; rfl

def isP0 : DF → Bool
  | .var 0 => true
  | .var (_ + 1) => false
  | .neg _ => false
  | .and _ _ => false
  | .or _ _ => false
  | .imp _ _ => false

def v0 : DF → Bool
  | .var 0 => true
  | .var (_ + 1) => false
  | .neg a => isP0 a || !(v0 a)
  | .and a b => v0 a && v0 b
  | .or a b => v0 a || v0 b
  | .imp a b => !(v0 a) || v0 b

theorem isP0_v0 : (a : DF) → isP0 a = true → v0 a = true
  | .var 0, _ => rfl
  | .var (_ + 1), h => Bool.noConfusion h
  | .neg _, h => Bool.noConfusion h
  | .and _ _, h => Bool.noConfusion h
  | .or _ _, h => Bool.noConfusion h
  | .imp _ _, h => Bool.noConfusion h

def B0 : Biv where
  v := v0
  and_ _ _ := rfl
  or_ _ _ := rfl
  imp_ _ _ := rfl
  neg0 a h := by
    show (isP0 a || !(v0 a)) = true
    rw [h]
    cases isP0 a <;> rfl
  negneg a h := by
    have h' : (isP0 (.neg a) || !(isP0 a || !(v0 a))) = true := h
    cases hp : isP0 a with
    | true => exact isP0_v0 a hp
    | false =>
      rw [hp] at h'
      cases hv : v0 a with
      | true => rfl
      | false => rw [hv] at h'; exact Bool.noConfusion h'

/-- explosion fails: p, ¬p true and q false under B0 -/
theorem no_explosion :
    B0.v (.var 0) = true ∧ B0.v (.neg (.var 0)) = true ∧ B0.v (.var 1) = false :=
  ⟨rfl, rfl, rfl⟩

end DaCosta

end Found

#print axioms Found.DaCosta.lem
#print axioms Found.DaCosta.isP0_v0
#print axioms Found.DaCosta.B0
#print axioms Found.DaCosta.no_explosion

#print axioms: 4 theorems, no axioms.

85.49 Subobject classifiers

A classifier is a setoid with a point classifying every respecting predicate by a unique map; the core’s \(\Omega \) is one and any two classifiers are isomorphic. \(\Omega ,\Omega '\ \text {classifiers}\Rightarrow \Omega \cong \Omega '\).

found/Classifier.lean

/-
  T97. found/Classifier — subobject classifiers in the setoid stem, in
  general: any two are isomorphic (core's Iso', T59).

  A classifier is a setoid Ω with a point t such that every ≈-respecting
  predicate φ on any setoid X has a characteristic map χ : X → Ω with
  φ x ⟺ χ x ≈ t, unique up to pointwise ≈.
  * The core's OmegaU (ULift Prop, ↔) with t = True is one (T59 chiU).
  * Any two classifiers are isomorphic.
  The Heyting structure on Ω (T63), Lawvere–Tierney topologies as nuclei
  (T108) and sheaf truth values (T95) are reused, not re-proved;
  sheafification stays OPEN (L95a).

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: OmegaU = ULift Prop.
-/
import found.Core

namespace Found

namespace Classif

open Core

universe u

structure Classifier where
  Om : Setd.{u}
  t : Om.car
  chi : {X : Setd.{u}} → (φ : X.car → Prop) → RespP X φ → SHom X Om
  spec : ∀ {X : Setd.{u}} (φ : X.car → Prop) (h : RespP X φ) (x : X.car), φ x ↔ Om.eqv ((chi φ h).fn x) t
  uniq : ∀ {X : Setd.{u}} (φ : X.car → Prop) (h : RespP X φ) (g : SHom X Om),
    (∀ x, φ x ↔ Om.eqv (g.fn x) t) → ∀ x, Om.eqv (g.fn x) ((chi φ h).fn x)

/-- the core's Ω is a classifier -/
def coreOmega : Classifier.{u} where
  Om := OmegaU
  t := ⟨True⟩
  chi φ h := chiU φ h
  spec _ _ _ := ⟨fun p => ⟨fun _ => trivial, fun _ => p⟩, fun e => e.mpr trivial⟩
  uniq _ _ _ hg x := ⟨fun p => (hg x).mpr ⟨fun _ => trivial, fun _ => p⟩,
                     fun p => ((hg x).mp p).mpr trivial⟩

def isT (A : Classifier.{u}) : A.Om.car → Prop := fun y => A.Om.eqv y A.t

theorem isT_resp (A : Classifier.{u}) : RespP A.Om (isT A) :=
  fun e h => A.Om.trans (A.Om.symm e) h

/-- any two classifiers are isomorphic -/
theorem unique (A B : Classifier.{u}) : Iso' A.Om B.Om := by
  let f := B.chi (isT A) (isT_resp A)
  let g := A.chi (isT B) (isT_resp B)
  refine ⟨f, g, ?_, ?_⟩
  · intro y
    have key : ∀ z, isT A z ↔ A.Om.eqv ((SetdCat.comp f g).fn z) A.t := fun z =>
      ((B.spec (isT A) (isT_resp A) z).trans (A.spec (isT B) (isT_resp B) _))
    have k1 := A.uniq (isT A) (isT_resp A) (SetdCat.comp f g) key y
    have k2 := A.uniq (isT A) (isT_resp A) (SetdCat.id A.Om) (fun _ => Iff.rfl) y
    exact A.Om.trans k1 (A.Om.symm k2)
  · intro y
    have key : ∀ z, isT B z ↔ B.Om.eqv ((SetdCat.comp g f).fn z) B.t := fun z =>
      ((A.spec (isT B) (isT_resp B) z).trans (B.spec (isT A) (isT_resp A) _))
    have k1 := B.uniq (isT B) (isT_resp B) (SetdCat.comp g f) key y
    have k2 := B.uniq (isT B) (isT_resp B) (SetdCat.id B.Om) (fun _ => Iff.rfl) y
    exact B.Om.trans k1 (B.Om.symm k2)

end Classif

end Found

#print axioms Found.Classif.coreOmega
#print axioms Found.Classif.isT_resp
#print axioms Found.Classif.unique

#print axioms: 3 theorems, no axioms.

85.50 Grothendieck universes

Lifting Aczel’s trees from one type universe to the next gives a set \(U\) in the larger \(V\) that is transitive and closed under pairing, union and power set, i.e. a Grothendieck universe. \(x\in y\in U\Rightarrow x\in U;\quad x,y\in U\Rightarrow \{x,y\},\bigcup x,\mathcal {P}(x)\in U\).

found/Grothendieck.lean

/-
  T104. found/Grothendieck — Grothendieck universes as a point: the type
  universe levels of the meta-language give a universe set inside the next
  level of Aczel's V (T109, now universe-polymorphic).

  U := { lift a | a ∈ V.{0} } ∈ V.{1}.
  * lift respects ≈; membership in a lifted set is lifting of members.
  * U is transitive, and closed under pairing, union and power set (each via
    extensionality), so U is a Grothendieck universe; an inaccessible-like
    point in the set-theory coordinate.
  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: universe levels Type 0 : Type 1 (the meta-language's hierarchy), impredicative Prop (power).
-/
import found.IZF

namespace Found

namespace Groth

open WF

def lift : V.{0} → V.{1}
  | .sup I f => .sup (ULift I) (fun i => lift (f i.down))

theorem lift_eq : (x y : V.{0}) → Eq' x y → Eq' (lift x) (lift y)
  | .sup _ _, .sup _ _, ⟨e1, e2⟩ =>
    ⟨fun i => match e1 i.down with | ⟨j, e⟩ => ⟨⟨j⟩, lift_eq _ _ e⟩,
     fun j => match e2 j.down with | ⟨i, e⟩ => ⟨⟨i⟩, lift_eq _ _ e⟩⟩

theorem mem_lift (z : V.{1}) (w : V.{0}) : Mem z (lift w) ↔ ∃ v : V.{0}, Mem v w ∧ Eq' z (lift v) := by
  cases w with
  | sup I f =>
    exact ⟨fun ⟨i, e⟩ => ⟨f i.down, ⟨i.down, eq_refl _⟩, e⟩,
           fun ⟨_, ⟨i, ev⟩, e⟩ => ⟨⟨i⟩, eq_trans _ _ _ e (lift_eq _ _ ev)⟩⟩

def U : V.{1} := .sup V.{0} lift

theorem mem_U (x : V.{1}) : Mem x U ↔ ∃ a : V.{0}, Eq' x (lift a) := Iff.rfl

/-- U is transitive -/
theorem U_trans (x y : V.{1}) (m : Mem x y) (hy : Mem y U) : Mem x U :=
  match hy with
  | ⟨a, e⟩ => match (mem_lift x a).mp (mem_resp_right m e) with
    | ⟨v, _, ev⟩ => ⟨v, ev⟩

/-- closure under pairing -/
theorem U_pair (x y : V.{1}) (hx : Mem x U) (hy : Mem y U) : Mem (IZF.pair x y) U :=
  match hx, hy with
  | ⟨a, ea⟩, ⟨b, eb⟩ => ⟨IZF.pair a b, extensionality _ _ (fun z =>
      ⟨fun m => match (IZF.pair_spec x y z).mp m with
         | Or.inl e => (mem_lift z _).mpr ⟨a, (IZF.pair_spec a b a).mpr (Or.inl (eq_refl _)), eq_trans _ _ _ e ea⟩
         | Or.inr e => (mem_lift z _).mpr ⟨b, (IZF.pair_spec a b b).mpr (Or.inr (eq_refl _)), eq_trans _ _ _ e eb⟩,
       fun m => match (mem_lift z _).mp m with
         | ⟨v, mv, e⟩ => (IZF.pair_spec x y z).mpr (((IZF.pair_spec a b v).mp mv).elim
             (fun ev => Or.inl (eq_trans _ _ _ e (eq_trans _ _ _ (lift_eq _ _ ev) (eq_symm _ _ ea))))
             (fun ev => Or.inr (eq_trans _ _ _ e (eq_trans _ _ _ (lift_eq _ _ ev) (eq_symm _ _ eb)))))⟩)⟩

/-- closure under union -/
theorem U_union (x : V.{1}) (hx : Mem x U) : Mem (IZF.union x) U :=
  match hx with
  | ⟨a, ea⟩ => ⟨IZF.union a, extensionality _ _ (fun z =>
      ⟨fun m => match (IZF.union_spec x z).mp m with
         | ⟨y, my, mz⟩ => match (mem_lift y a).mp (mem_resp_right my ea) with
           | ⟨v, mv, ev⟩ => match (mem_lift z v).mp (mem_resp_right mz ev) with
             | ⟨u, mu, eu⟩ => (mem_lift z _).mpr ⟨u, (IZF.union_spec a u).mpr ⟨v, mv, mu⟩, eu⟩,
       fun m => match (mem_lift z _).mp m with
         | ⟨u, mu, eu⟩ => match (IZF.union_spec a u).mp mu with
           | ⟨v, mv, muv⟩ => (IZF.union_spec x z).mpr ⟨lift v,
               mem_resp_right ((mem_lift (lift v) a).mpr ⟨v, mv, eq_refl _⟩) (eq_symm _ _ ea),
               mem_resp_left (eq_symm _ _ eu) ((mem_lift (lift u) v).mpr ⟨u, muv, eq_refl _⟩)⟩⟩)⟩

/-- closure under power set -/
theorem U_power (x : V.{1}) (hx : Mem x U) : Mem (IZF.power x) U :=
  match hx with
  | ⟨a, ea⟩ => ⟨IZF.power a, extensionality _ _ (fun z =>
      ⟨fun m =>
        have sub : ∀ w, Mem w z → Mem w x := (IZF.power_spec x z).mp m
        let φ : V.{0} → Prop := fun u => Mem (lift u) z
        have hφ : IZF.Resp φ := fun _ _ e h => mem_resp_left (lift_eq _ _ e) h
        (mem_lift z _).mpr ⟨IZF.sep a φ,
          (IZF.power_spec a _).mpr (fun u mu => ((IZF.sep_spec a φ hφ u).mp mu).1),
          extensionality _ _ (fun w =>
            ⟨fun mw => match (mem_lift w a).mp (mem_resp_right (sub w mw) ea) with
               | ⟨u, mu, eu⟩ => (mem_lift w _).mpr ⟨u, (IZF.sep_spec a φ hφ u).mpr
                   ⟨mu, mem_resp_left eu mw⟩, eu⟩,
             fun mw => match (mem_lift w _).mp mw with
               | ⟨u, mu, eu⟩ => mem_resp_left (eq_symm _ _ eu) ((IZF.sep_spec a φ hφ u).mp mu).2⟩)⟩,
       fun m => match (mem_lift z _).mp m with
         | ⟨v, mv, ev⟩ => (IZF.power_spec x z).mpr (fun w mw =>
             match (mem_lift w v).mp (mem_resp_right mw ev) with
             | ⟨u, mu, eu⟩ => mem_resp_right ((mem_lift w a).mpr
                 ⟨u, (IZF.power_spec a v).mp mv u mu, eu⟩) (eq_symm _ _ ea))⟩)⟩

end Groth

end Found

#print axioms Found.Groth.lift_eq
#print axioms Found.Groth.mem_lift
#print axioms Found.Groth.U_trans
#print axioms Found.Groth.U_pair
#print axioms Found.Groth.U_union
#print axioms Found.Groth.U_power

#print axioms: 6 theorems, no axioms.

85.51 Modal mu-calculus

Monotone operators on the predicate lattice of a frame have least and greatest fixed points with induction and coinduction rules, and \(\mu X.\,p\vee \Diamond X\) is exactly reachability of \(p\) along \(R^*\). \(\mu X.\,p\vee \Diamond X\ =\ \{w\mid \exists v,\ wR^*v\wedge p(v)\}\).

found/ModalMu.lean

/-
  T171. found/ModalMu — the modal μ-calculus as a point: least and greatest
  fixed points of monotone operators on the predicate lattice Ω^W of the
  relation coordinate (Knaster–Tarski, impredicative form).

  * lfp f := ⋂ {P | f P ⊆ P}, gfp f := ⋃ {P | P ⊆ f P}; fixed points, least /
    greatest, induction and coinduction rules.
  * EF p = μX. p ∨ ◇X is reachability along R* (T138's star) — the line
    μ-calculus ↔ CTL/PDL.

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: impredicative Prop (the ∀ P in lfp).
-/
import found.Dynamic

namespace Found

namespace Mu

universe u

variable {W : Type u}

def Le (P Q : W → Prop) : Prop := ∀ w, P w → Q w

def Mono (f : (W → Prop) → (W → Prop)) : Prop := ∀ {P Q}, Le P Q → Le (f P) (f Q)

def lfp (f : (W → Prop) → (W → Prop)) : W → Prop := fun w => ∀ P, Le (f P) P → P w
def gfp (f : (W → Prop) → (W → Prop)) : W → Prop := fun w => ∃ P, Le P (f P) ∧ P w

variable {f : (W → Prop) → (W → Prop)} (hf : Mono f)

theorem lfp_induct (P : W → Prop) (h : Le (f P) P) : Le (lfp f) P := fun _ x => x P h

include hf in
theorem f_lfp_le : Le (f (lfp f)) (lfp f) :=
  fun _ x P hP => hP _ (hf (lfp_induct P hP) _ x)

include hf in
theorem lfp_le_f : Le (lfp f) (f (lfp f)) :=
  lfp_induct _ (hf (f_lfp_le hf))

theorem gfp_coinduct (P : W → Prop) (h : Le P (f P)) : Le P (gfp f) := fun _ x => ⟨P, h, x⟩

include hf in
theorem gfp_le_f : Le (gfp f) (f (gfp f)) :=
  fun w ⟨P, hP, x⟩ => hf (gfp_coinduct P hP) w (hP w x)

include hf in
theorem f_le_gfp : Le (f (gfp f)) (gfp f) :=
  gfp_coinduct _ (hf (gfp_le_f hf))

/-! ## EF p = μX. p ∨ ◇X = reachability -/

variable (R : W → W → Prop) (p : W → Prop)

def efOp (X : W → Prop) : W → Prop := fun w => p w ∨ ∃ v, R w v ∧ X v

theorem efOp_mono : Mono (efOp R p) :=
  fun h _ x => x.elim Or.inl (fun ⟨v, r, hv⟩ => Or.inr ⟨v, r, h v hv⟩)

def reach (w : W) : Prop := ∃ v, Dyn.star R w v ∧ p v

theorem ef_eq_reach (w : W) : lfp (efOp R p) w ↔ reach R p w := by
  constructor
  · intro h
    exact h (reach R p) (fun x hx => hx.elim (fun hp => ⟨x, .refl x, hp⟩)
      (fun ⟨v, r, ⟨u, s, hu⟩⟩ => ⟨u, .step r s, hu⟩))
  · intro ⟨v, s, hv⟩
    induction s with
    | refl x => exact f_lfp_le (efOp_mono R p) x (Or.inl hv)
    | step r _ ih => exact f_lfp_le (efOp_mono R p) _ (Or.inr ⟨_, r, ih hv⟩)

end Mu

end Found

#print axioms Found.Mu.lfp_induct
#print axioms Found.Mu.f_lfp_le
#print axioms Found.Mu.lfp_le_f
#print axioms Found.Mu.gfp_coinduct
#print axioms Found.Mu.gfp_le_f
#print axioms Found.Mu.f_le_gfp
#print axioms Found.Mu.ef_eq_reach

#print axioms: 7 theorems, no axioms.

85.52 Fixed-point logic

Least fixed points of positive operators on pairs (reusing the \(\mu \)-calculus lfp) define transitive closure: \(\mu T.\,E(x,y)\vee \exists z\,(E(x,z)\wedge T(z,y))\) is exactly \(E^+\). \(\mathrm {TC}(E)=\mu T.\,E\vee E;T=E^+\).

found/FixpointLogic.lean

/-
  T177. found/FixpointLogic — least fixed-point logic (LFP) as a point:
  first-order formulas plus least fixed points of positive operators; the
  fixed point is T171's lfp on pairs (reused), and transitive closure is
  LFP-definable: TC = μT. E(x,y) ∨ ∃z (E(x,z) ∧ T(z,y)) equals E⁺.

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: impredicative Prop (the lfp of T171).
-/
import found.ModalMu

namespace Found

namespace LFP

universe u

variable {A : Type u} (E : A → A → Prop)

inductive Plus : A → A → Prop where
  | one {x y} : E x y → Plus x y
  | step {x z y} : E x z → Plus z y → Plus x y

def tcOp (T : A × A → Prop) : A × A → Prop :=
  fun p => E p.1 p.2 ∨ ∃ z, E p.1 z ∧ T (z, p.2)

theorem tcOp_mono : Mu.Mono (tcOp E) :=
  fun h _ x => x.elim Or.inl (fun ⟨z, e, t⟩ => Or.inr ⟨z, e, h _ t⟩)

theorem tc_lfp (x y : A) : Mu.lfp (tcOp E) (x, y) ↔ Plus E x y := by
  constructor
  · intro h
    exact h (fun p => Plus E p.1 p.2) (fun p hp => hp.elim (fun e => .one e)
      (fun ⟨z, e, t⟩ => .step e t))
  · intro h
    induction h with
    | one e => exact Mu.f_lfp_le (tcOp_mono E) _ (Or.inl e)
    | step e _ ih => exact Mu.f_lfp_le (tcOp_mono E) _ (Or.inr ⟨_, e, ih⟩)

end LFP

end Found

#print axioms Found.LFP.tcOp_mono
#print axioms Found.LFP.tc_lfp

#print axioms: 2 theorems, no axioms.

85.53 Description logic

Concepts of ALC over a domain with a role relation translate into modal formulas (\(\exists R.C\mapsto \Diamond C\), \(\forall R.C\mapsto \Box C\)) with exactly the same extensions, so subsumption is validity of an implication in K. \(x\in C^{\mathcal {I}}\iff x\models \mathrm {tr}(C);\quad C\sqsubseteq D\iff \models _K \mathrm {tr}(C)\to \mathrm {tr}(D)\).

found/Description.lean

/-
  T176. found/Description — description logic ALC as a point: concepts are
  predicates on a domain, roles are values of the relation coordinate.
  The line ALC ↔ modal K (Schild): the translation ∃R.C ↦ ◇C, ∀R.C ↦ □C,
  ¬C ↦ C → ⊥ preserves extensions exactly (one role; several roles are the
  multimodal case).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Modal

namespace Found

namespace DL

universe u

inductive Concept where
  | atom : Nat → Concept
  | top : Concept
  | neg : Concept → Concept
  | and : Concept → Concept → Concept
  | or : Concept → Concept → Concept
  | some : Concept → Concept     -- ∃R.C
  | all : Concept → Concept      -- ∀R.C

variable {D : Type u} (R : D → D → Prop) (A : Nat → D → Prop)

def ext : Concept → D → Prop
  | .atom n, x => A n x
  | .top, _ => True
  | .neg c, x => ¬ ext c x
  | .and c d, x => ext c x ∧ ext d x
  | .or c d, x => ext c x ∨ ext d x
  | .some c, x => ∃ y, R x y ∧ ext c y
  | .all c, x => ∀ y, R x y → ext c y

def tr : Concept → Modal.MForm
  | .atom n => .var n
  | .top => .imp .bot .bot
  | .neg c => .imp (tr c) .bot
  | .and c d => .and (tr c) (tr d)
  | .or c d => .or (tr c) (tr d)
  | .some c => .dia (tr c)
  | .all c => .box (tr c)

theorem tr_correct : (c : Concept) → ∀ x, ext R A c x ↔ Modal.sat R (fun w n => A n w) x (tr c)
  | .atom _, _ => Iff.rfl
  | .top, _ => ⟨fun _ h => h, fun _ => trivial⟩
  | .neg c, x => ⟨fun h hc => h ((tr_correct c x).mpr hc), fun h hc => h ((tr_correct c x).mp hc)⟩
  | .and c d, x => ⟨fun h => ⟨(tr_correct c x).mp h.1, (tr_correct d x).mp h.2⟩,
                    fun h => ⟨(tr_correct c x).mpr h.1, (tr_correct d x).mpr h.2⟩⟩
  | .or c d, x => ⟨fun h => h.elim (fun a => Or.inl ((tr_correct c x).mp a)) (fun b => Or.inr ((tr_correct d x).mp b)),
                   fun h => h.elim (fun a => Or.inl ((tr_correct c x).mpr a)) (fun b => Or.inr ((tr_correct d x).mpr b))⟩
  | .some c, _ => ⟨fun ⟨y, r, h⟩ => ⟨y, r, (tr_correct c y).mp h⟩, fun ⟨y, r, h⟩ => ⟨y, r, (tr_correct c y).mpr h⟩⟩
  | .all c, _ => ⟨fun h y r => (tr_correct c y).mp (h y r), fun h y r => (tr_correct c y).mpr (h y r)⟩

/-- subsumption C ⊑ D is K-validity of the translated implication on the frame -/
theorem subsumption_iff (c d : Concept) :
    (∀ x, ext R A c x → ext R A d x) ↔ ∀ x, Modal.sat R (fun w n => A n w) x (.imp (tr c) (tr d)) :=
  ⟨fun h x hc => (tr_correct R A d x).mp (h x ((tr_correct R A c x).mpr hc)),
   fun h x hc => (tr_correct R A d x).mpr (h x ((tr_correct R A c x).mp hc))⟩

end DL

end Found

#print axioms Found.DL.tr_correct
#print axioms Found.DL.subsumption_iff

#print axioms: 2 theorems, no axioms.

85.54 Conditional logic

With a selection function satisfying success, \(A>A\) always holds while antecedent strengthening fails in a two-world model, so the conditional is not strict implication. \(A>A;\quad (A>C)\not \Rightarrow ((A\wedge B)>C)\).

found/Conditional.lean

/-
  T172. found/Conditional — conditional / counterfactual logic as a point:
  a selection function on the relation-coordinate worlds,
  A > B at w :⟺ f(w, A) ⊆ B, with success f(w, A) ⊆ A.
  * Identity A > A holds; antecedent strengthening fails (countermodel),
    so > is not strict implication (□(A → B) would strengthen).

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Cond

universe u

variable {W : Type u}

structure Sel (W : Type u) where
  f : W → (W → Prop) → (W → Prop)
  success : ∀ w A x, f w A x → A x

def cond (S : Sel W) (A B : W → Prop) (w : W) : Prop := ∀ x, S.f w A x → B x

theorem identity (S : Sel W) (A : W → Prop) (w : W) : cond S A A w := fun x h => S.success w A x h

/-- prefer the world `true` whenever the antecedent allows it -/
def sel : Sel Bool where
  f _ P x := P x ∧ (P true → x = true)
  success _ _ _ h := h.1

theorem no_strengthening :
    cond sel (fun _ => True) (fun x => x = true) false ∧
    ¬ cond sel (fun x => True ∧ x = false) (fun x => x = true) false :=
  ⟨fun _ h => h.2 trivial,
   fun h => Bool.noConfusion (h false ⟨⟨trivial, rfl⟩, fun hp => Bool.noConfusion hp.2⟩)⟩

end Cond

end Found

#print axioms Found.Cond.identity
#print axioms Found.Cond.no_strengthening

#print axioms: 2 theorems, no axioms.

85.55 Nonmonotonic logic

Preferential consequence (minimal \(A\)-worlds are \(B\)-worlds) is reflexive and closed under right weakening and conjunction, fails monotonicity in the bird/penguin model, and coincides with classical consequence for the empty preference. \(A\mathrel {|\!\sim }B,\ \not \Rightarrow \ A\wedge C\mathrel {|\!\sim }B\).

found/NonMono.lean

/-
  T173. found/NonMono — nonmonotonic reasoning as a point: preferential
  models (KLM) on the relation coordinate (a preference relation on worlds);
  A |~ B :⟺ every preferred-minimal A-world is a B-world.
  * Reflexivity, right weakening, And hold; monotonicity fails (the
    bird/penguin countermodel) — the line to classical consequence is
    "empty preference" (all A-worlds minimal).

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace NonMono

universe u

variable {W : Type u} (lt : W → W → Prop)

def Minimal (A : W → Prop) (w : W) : Prop := A w ∧ ∀ v, lt v w → ¬ A v

def nm (A B : W → Prop) : Prop := ∀ w, Minimal lt A w → B w

theorem refl (A : W → Prop) : nm lt A A := fun _ h => h.1

theorem right_weak (A B C : W → Prop) (h : nm lt A B) (hBC : ∀ w, B w → C w) : nm lt A C :=
  fun w m => hBC w (h w m)

theorem and_rule (A B C : W → Prop) (h1 : nm lt A B) (h2 : nm lt A C) : nm lt A (fun w => B w ∧ C w) :=
  fun w m => ⟨h1 w m, h2 w m⟩

/-- empty preference gives classical consequence -/
theorem classical_of_empty (A B : W → Prop) : nm (fun _ _ => False) A B ↔ ∀ w, A w → B w :=
  ⟨fun h w a => h w ⟨a, fun _ f => f.elim⟩, fun h w m => h w m.1⟩

/-- worlds: `true` = penguin, `false` = normal bird; normal is preferred -/
def pref (v w : Bool) : Prop := v = false ∧ w = true

theorem not_monotone :
    nm pref (fun _ => True) (fun w => w = false) ∧
    ¬ nm pref (fun w => True ∧ w = true) (fun w => w = false) := by
  constructor
  · intro w m
    cases w with
    | false => rfl
    | true => exact (m.2 false ⟨rfl, rfl⟩ trivial).elim
  · intro h
    exact Bool.noConfusion (h true ⟨⟨trivial, rfl⟩, fun v hv hA => Bool.noConfusion (hv.1.symm.trans hA.2)⟩)

end NonMono

end Found

#print axioms Found.NonMono.refl
#print axioms Found.NonMono.right_weak
#print axioms Found.NonMono.and_rule
#print axioms Found.NonMono.classical_of_empty
#print axioms Found.NonMono.not_monotone

#print axioms: 5 theorems, no axioms.

85.56 Dependence logic

On teams of assignments the dependence atom and the split disjunction are downward closed; the atom holds on singletons but not on their union, so dependence logic is not flat, unlike first-order logic. \(T'\subseteq T\models {=}(x,y)\Rightarrow T'\models {=}(x,y)\); \(\{s\},\{s'\}\models {=}(x,y)\not \Rightarrow \{s,s'\}\models {=}(x,y)\).

found/Dependence.lean

/-
  T175. found/Dependence — dependence (and IF) logic as a point: team
  semantics, truth of a formula on a set of assignments (a team).
  * Dependence atom =(x, y): on the team, the value of x determines y.
  * Downward closure for the atom, conjunction and the split disjunction.
  * Not flat: =(x, y) holds on every singleton team but not on their union
    (countermodel) — the line to first-order logic is "flat formulas".

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Team

universe u

variable {D : Type u}

def Team (D : Type u) : Type u := (Nat → D) → Prop

def dep (x y : Nat) (T : Team D) : Prop := ∀ s s', T s → T s' → s x = s' x → s y = s' y

def sub (T T' : Team D) : Prop := ∀ s, T s → T' s

theorem dep_down {x y : Nat} {T T' : Team D} (h : sub T T') (d : dep x y T') : dep x y T :=
  fun s s' hs hs' => d s s' (h s hs) (h s' hs')

/-- split (tensor) disjunction -/
def tensor (P Q : Team D → Prop) (T : Team D) : Prop :=
  ∃ T₁ T₂ : Team D, (∀ s, T s → T₁ s ∨ T₂ s) ∧ P T₁ ∧ Q T₂

def Down (P : Team D → Prop) : Prop := ∀ T T', sub T T' → P T' → P T

theorem tensor_down (P Q : Team D → Prop) (hP : Down P) (hQ : Down Q) : Down (tensor P Q) :=
  fun T _ h ⟨T₁, T₂, cov, p, q⟩ =>
    ⟨fun s => T s ∧ T₁ s, fun s => T s ∧ T₂ s,
     fun s hs => (cov s (h s hs)).elim (fun a => Or.inl ⟨hs, a⟩) (fun b => Or.inr ⟨hs, b⟩),
     hP _ _ (fun _ a => a.2) p, hQ _ _ (fun _ a => a.2) q⟩

def single (s0 : Nat → Bool) : Team Bool := fun s => ∀ n, s n = s0 n

theorem dep_single (s0 : Nat → Bool) (x y : Nat) : dep x y (single s0) :=
  fun _ _ hs hs' _ => (hs y).trans (hs' y).symm

/-- not flat: two singletons satisfy =(0,1), their union does not -/
theorem not_flat :
    ¬ dep 0 1 (fun s => single (fun _ => false) s ∨ single (fun n => match n with | 1 => true | _ => false) s) :=
  fun h => Bool.noConfusion (h (fun _ => false) (fun n => match n with | 1 => true | _ => false)
    (Or.inl (fun _ => rfl)) (Or.inr (fun _ => rfl)) rfl)

end Team

end Found

#print axioms Found.Team.dep_down
#print axioms Found.Team.tensor_down
#print axioms Found.Team.dep_single
#print axioms Found.Team.not_flat

#print axioms: 4 theorems, no axioms.

85.57 Justification logic

In Fitting models, where \(t{:}A\) means evidence for \(A\) plus \(\Box A\), the application, sum and (on reflexive frames) reflection principles hold, and forgetting terms sends \(t{:}A\) to \(\Box A\). \(s{:}(A\to B)\wedge t{:}A\Rightarrow (s\cdot t){:}B;\quad t{:}A\Rightarrow \Box A\).

found/Justification.lean

/-
  T178. found/Justification — justification logic (Artemov's LP) as a point:
  Fitting models = worlds of the relation coordinate plus an evidence
  function; t : A holds at w iff t is evidence for A at w and A holds at all
  R-successors.
  * Application t:(A→B) → s:A → (t·s):B, sum s:A → (s+t):A, and reflection
    t:A → A on reflexive frames are valid (under the evidence closure
    conditions, which are the parameters' conditions).
  * Forgetful projection: t:A ⇒ □A — the line LP → S4 (Artemov's
    realization theorem, the converse, is cited).

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Just

universe u

inductive Tm where
  | c : Nat → Tm
  | app : Tm → Tm → Tm
  | sum : Tm → Tm → Tm

variable {W : Type u} (R : W → W → Prop)

structure Ev (W : Type u) where
  E : Tm → (W → Prop) → W → Prop
  app : ∀ s t (A B : W → Prop) w, E s (fun v => A v → B v) w → E t A w → E (.app s t) B w
  sumL : ∀ s t A w, E s A w → E (.sum s t) A w
  sumR : ∀ s t A w, E t A w → E (.sum s t) A w

def box (A : W → Prop) (w : W) : Prop := ∀ v, R w v → A v

def jt (M : Ev W) (t : Tm) (A : W → Prop) (w : W) : Prop := M.E t A w ∧ box R A w

theorem application (M : Ev W) (s t : Tm) (A B : W → Prop) (w : W)
    (h1 : jt R M s (fun v => A v → B v) w) (h2 : jt R M t A w) : jt R M (.app s t) B w :=
  ⟨M.app s t A B w h1.1 h2.1, fun v r => h1.2 v r (h2.2 v r)⟩

theorem sum_left (M : Ev W) (s t : Tm) (A : W → Prop) (w : W) (h : jt R M s A w) : jt R M (.sum s t) A w :=
  ⟨M.sumL s t A w h.1, h.2⟩

theorem reflection (hr : ∀ w, R w w) (M : Ev W) (t : Tm) (A : W → Prop) (w : W) (h : jt R M t A w) : A w :=
  h.2 w (hr w)

/-- forgetful projection: justification ⇒ necessity -/
theorem forget (M : Ev W) (t : Tm) (A : W → Prop) (w : W) (h : jt R M t A w) : box R A w := h.2

end Just

end Found

#print axioms Found.Just.application
#print axioms Found.Just.sum_left
#print axioms Found.Just.reflection
#print axioms Found.Just.forget

#print axioms: 4 theorems, no axioms.

85.58 Automata

For a nondeterministic automaton on any state type, the deterministic automaton on predicates of states accepts exactly the same words. \(w\in L(\mathcal {P}N)\iff w\in L(N)\).

found/Automata.lean

/-
  T182. found/Automata — finite automata as a point on the relation
  coordinate (transition relations labelled by letters).
  * NFA (any state type) and its subset construction (states = predicates on
    states, i.e. the core's power Ω^Q): the DFA accepts exactly the NFA's
    language (by induction on words).
  * Pushdown and cellular automata are further values (stack / grid state
    types) — recorded as lines, not re-proved here.

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: subset states = Q → Prop (Prop-valued predicates, not impredicative Prop).
-/

namespace Found

namespace Auto

universe u v

structure NFA (α : Type u) where
  Q : Type v
  start : Q → Prop
  δ : Q → α → Q → Prop
  acc : Q → Prop

variable {α : Type u}

/-- NFA runs: reach q' from q reading w -/
inductive Run (N : NFA.{u, v} α) : N.Q → List α → N.Q → Prop where
  | nil (q : N.Q) : Run N q [] q
  | cons {q q' q''} (a : α) (w : List α) : N.δ q a q' → Run N q' w q'' → Run N q (a :: w) q''

def accepts (N : NFA.{u, v} α) (w : List α) : Prop := ∃ q q', N.start q ∧ Run N q w q' ∧ N.acc q'

/-- the subset DFA: a state is a set of NFA states -/
def step (N : NFA.{u, v} α) (S : N.Q → Prop) (a : α) : N.Q → Prop := fun q' => ∃ q, S q ∧ N.δ q a q'

def run (N : NFA.{u, v} α) : (N.Q → Prop) → List α → (N.Q → Prop)
  | S, [] => S
  | S, a :: w => run N (step N S a) w

def daccepts (N : NFA.{u, v} α) (w : List α) : Prop := ∃ q, run N N.start w q ∧ N.acc q

theorem run_spec (N : NFA.{u, v} α) : (w : List α) → ∀ (S : N.Q → Prop) (q' : N.Q),
    run N S w q' ↔ ∃ q, S q ∧ Run N q w q'
  | [], S, q' => ⟨fun h => ⟨q', h, .nil q'⟩, fun ⟨_, hs, r⟩ => by cases r; exact hs⟩
  | a :: w, S, q' =>
    ⟨fun h => match (run_spec N w (step N S a) q').mp h with
       | ⟨q1, ⟨q0, hs, d⟩, r⟩ => ⟨q0, hs, .cons a w d r⟩,
     fun ⟨q0, hs, r⟩ => by
       cases r with
       | cons _ _ d r' => exact (run_spec N w (step N S a) q').mpr ⟨_, ⟨q0, hs, d⟩, r'⟩⟩

/-- the subset construction accepts exactly the NFA language -/
theorem subset_construction (N : NFA.{u, v} α) (w : List α) : daccepts N w ↔ accepts N w :=
  ⟨fun ⟨q', h, a⟩ => match (run_spec N w N.start q').mp h with
     | ⟨q, s, r⟩ => ⟨q, q', s, r, a⟩,
   fun ⟨q, q', s, r, a⟩ => ⟨q', (run_spec N w N.start q').mpr ⟨q, s, r⟩, a⟩⟩

end Auto

end Found

#print axioms Found.Auto.run_spec
#print axioms Found.Auto.subset_construction

#print axioms: 2 theorems, no axioms.

85.59 Process calculi

Strong bisimilarity on any labelled transition system is an equivalence, and bisimilar states satisfy the same Hennessy–Milner formulas, linking process calculi to multimodal logic. \(p\sim q\Rightarrow (p\models \varphi \iff q\models \varphi )\ \text {for HML}\ \varphi \).

found/Process.lean

/-
  T183. found/Process — process calculi (CCS, CSP, π) as a point: labelled
  transition systems on the relation coordinate; processes are states up
  to strong bisimilarity (the same coinductive quotient as T105, labelled).
  * Bisimilarity is an equivalence.
  * Hennessy–Milner (invariance): bisimilar states satisfy the same
    Hennessy–Milner formulas — the line processes ↔ multimodal K.
  The concrete calculi are syntaxes whose operational semantics is an LTS
  (recorded as lines; not re-proved).

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: bisimilarity ∃ S (impredicative Prop).
-/

namespace Found

namespace Proc

universe u v

variable {L : Type u} {S : Type v} (T : S → L → S → Prop)

def Bisim (B : S → S → Prop) : Prop :=
  ∀ p q, B p q → (∀ a p', T p a p' → ∃ q', T q a q' ∧ B p' q') ∧ (∀ a q', T q a q' → ∃ p', T p a p' ∧ B p' q')

def Bisimilar (p q : S) : Prop := ∃ B, Bisim T B ∧ B p q

theorem bis_refl (p : S) : Bisimilar T p p :=
  ⟨fun a b => a = b, fun a b e => by
    cases e
    exact ⟨fun c a' h => ⟨a', h, rfl⟩, fun c a' h => ⟨a', h, rfl⟩⟩, rfl⟩

theorem bis_symm {p q : S} (h : Bisimilar T p q) : Bisimilar T q p :=
  match h with
  | ⟨B, hB, b⟩ => ⟨fun x y => B y x, fun x y bxy =>
      ⟨fun a x' t => match (hB y x bxy).2 a x' t with | ⟨y', t', b'⟩ => ⟨y', t', b'⟩,
       fun a y' t => match (hB y x bxy).1 a y' t with | ⟨x', t', b'⟩ => ⟨x', t', b'⟩⟩, b⟩

theorem bis_trans {p q r : S} (h : Bisimilar T p q) (k : Bisimilar T q r) : Bisimilar T p r :=
  match h, k with
  | ⟨B, hB, b⟩, ⟨C, hC, c⟩ =>
    ⟨fun x z => ∃ y, B x y ∧ C y z, fun x z ⟨y, bxy, cyz⟩ =>
      ⟨fun a x' t => match (hB x y bxy).1 a x' t with
         | ⟨y', t', b'⟩ => match (hC y z cyz).1 a y' t' with
           | ⟨z', t'', c'⟩ => ⟨z', t'', y', b', c'⟩,
       fun a z' t => match (hC y z cyz).2 a z' t with
         | ⟨y', t', c'⟩ => match (hB x y bxy).2 a y' t' with
           | ⟨x', t'', b'⟩ => ⟨x', t'', y', b', c'⟩⟩, ⟨q, b, c⟩⟩

/-- Hennessy–Milner formulas -/
inductive HML (L : Type u) where
  | tt : HML L
  | neg : HML L → HML L
  | and : HML L → HML L → HML L
  | dia : L → HML L → HML L

def sat : S → HML L → Prop
  | _, .tt => True
  | p, .neg φ => ¬ sat p φ
  | p, .and φ ψ => sat p φ ∧ sat p ψ
  | p, .dia a φ => ∃ p', T p a p' ∧ sat p' φ

/-- invariance: bisimilar states satisfy the same HML formulas -/
theorem hm_invariance (B : S → S → Prop) (hB : Bisim T B) :
    (φ : HML L) → ∀ p q, B p q → (sat T p φ ↔ sat T q φ)
  | .tt, _, _, _ => Iff.rfl
  | .neg φ, p, q, b => ⟨fun h hq => h ((hm_invariance B hB φ p q b).mpr hq),
                        fun h hp => h ((hm_invariance B hB φ p q b).mp hp)⟩
  | .and φ ψ, p, q, b => ⟨fun h => ⟨(hm_invariance B hB φ p q b).mp h.1, (hm_invariance B hB ψ p q b).mp h.2⟩,
                          fun h => ⟨(hm_invariance B hB φ p q b).mpr h.1, (hm_invariance B hB ψ p q b).mpr h.2⟩⟩
  | .dia a φ, p, q, b =>
    ⟨fun ⟨p', t, h⟩ => match (hB p q b).1 a p' t with
       | ⟨q', t', b'⟩ => ⟨q', t', (hm_invariance B hB φ p' q' b').mp h⟩,
     fun ⟨q', t, h⟩ => match (hB p q b).2 a q' t with
       | ⟨p', t', b'⟩ => ⟨p', t', (hm_invariance B hB φ p' q' b').mpr h⟩⟩

end Proc

end Found

#print axioms Found.Proc.bis_refl
#print axioms Found.Proc.bis_symm
#print axioms Found.Proc.bis_trans
#print axioms Found.Proc.hm_invariance

#print axioms: 4 theorems, no axioms.

85.60 Markov’s principle

Markov’s principle for decidable predicates on the naturals follows from excluded middle, is the double-negation stability of \(\Sigma ^0_1\) statements, and turns non-refutation of \(\forall \neg \) into a witness. \(\mathrm {Dec}(P)\wedge \neg \neg \exists n\,P(n)\Rightarrow \exists n\,P(n)\).

found/Markov.lean

/-
  T198. found/Markov — Russian constructivism as a point: Markov's principle
  as a condition on the truth-value coordinate (for decidable predicates on
  ℕ, the core's NNO).
  * MP: P decidable ∧ ¬¬∃n P n ⇒ ∃n P n.
  * LEM ⇒ MP; MP ⟺ ¬¬-stability of Σ⁰₁ statements (decidable P).
  * Kleene realizability over K1 validates MP (cited; T96b) — the line
    Russian constructivism ↔ effective topos; Brouwer (T197) rejects it.

  Lean 4 core only, hand-written proofs, no axioms (MP, LEM are hypotheses).
-/

namespace Found

namespace Markov

def Dec (P : Nat → Prop) : Prop := ∀ n, P n ∨ ¬ P n

def MP : Prop := ∀ P : Nat → Prop, Dec P → ¬ ¬ (∃ n, P n) → ∃ n, P n

theorem lem_mp (lem : ∀ p : Prop, p ∨ ¬ p) : MP :=
  fun P _ h => (lem (∃ n, P n)).elim id (fun n => (h n).elim)

def Sigma1Stable : Prop := ∀ P : Nat → Prop, Dec P → (¬ ¬ ∃ n, P n) → ∃ n, P n

theorem mp_iff : MP ↔ Sigma1Stable := Iff.rfl

/-- MP gives: a decidable predicate that is not everywhere false has a witness -/
theorem mp_not_all (hm : MP) (P : Nat → Prop) (hd : Dec P) (h : ¬ ∀ n, ¬ P n) : ∃ n, P n :=
  hm P hd (fun ne => h (fun n hn => ne ⟨n, hn⟩))

end Markov

end Found

#print axioms Found.Markov.lem_mp
#print axioms Found.Markov.mp_iff
#print axioms Found.Markov.mp_not_all

#print axioms: 3 theorems, no axioms.

85.61 Mereology

On inhabited predicates with inclusion, strong supplementation holds constructively by singleton parts, and every inhabited family has a fusion given by its union. \((\forall z\le x,\ z\circ y)\Rightarrow x\le y;\quad \bigsqcup _i F_i\).

found/Mereology.lean

/-
  T201. found/Mereology — mereology as a point: a parthood preorder (free
  parameter) with overlap, supplementation and fusion.
  * General: overlap is reflexive on inhabited parts and symmetric.
  * Instance: inhabited predicates on any type with inclusion; strong
    supplementation (if every part of x overlaps y then x is part of y)
    holds constructively (singleton parts), and every family has a fusion
    (its union) — the line mereology ↔ Boolean algebras without ⊥ (cited).

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Mereo

universe u

structure Parthood where
  E : Type u
  P : E → E → Prop
  refl : ∀ x, P x x
  trans : ∀ {x y z}, P x y → P y z → P x z

variable (M : Parthood.{u})

def Ov (x y : M.E) : Prop := ∃ z, M.P z x ∧ M.P z y

theorem ov_refl (x : M.E) : Ov M x x := ⟨x, M.refl x, M.refl x⟩
theorem ov_symm {x y : M.E} (h : Ov M x y) : Ov M y x := match h with | ⟨z, a, b⟩ => ⟨z, b, a⟩

/-! ## instance: inhabited predicates -/

variable (A : Type u)

def setsM : Parthood.{u} where
  E := {S : A → Prop // ∃ a, S a}
  P x y := ∀ a, x.val a → y.val a
  refl _ _ h := h
  trans h k a x := k a (h a x)

/-- strong supplementation holds for inhabited predicates -/
theorem strong_supp (x y : (setsM A).E) (h : ∀ z, (setsM A).P z x → Ov (setsM A) z y) :
    (setsM A).P x y := fun a ha =>
  match h ⟨fun b => b = a, a, rfl⟩ (fun _ e => e ▸ ha) with
  | ⟨w, hz1, hz2⟩ => match w.property with
    | ⟨b, hb⟩ => hz1 b hb ▸ hz2 b hb

/-- fusion: every inhabited family has a least upper bound (its union) -/
def fusion {I : Type u} (F : I → (setsM A).E) (i0 : I) : (setsM A).E :=
  ⟨fun a => ∃ i, (F i).val a, match (F i0).property with | ⟨a, h⟩ => ⟨a, i0, h⟩⟩

theorem fusion_ub {I : Type u} (F : I → (setsM A).E) (i0 : I) (i : I) : (setsM A).P (F i) (fusion A F i0) :=
  fun _ h => ⟨i, h⟩

theorem fusion_least {I : Type u} (F : I → (setsM A).E) (i0 : I) (y : (setsM A).E)
    (h : ∀ i, (setsM A).P (F i) y) : (setsM A).P (fusion A F i0) y :=
  fun a ⟨i, hi⟩ => h i a hi

end Mereo

end Found

#print axioms Found.Mereo.ov_symm
#print axioms Found.Mereo.strong_supp
#print axioms Found.Mereo.fusion_ub
#print axioms Found.Mereo.fusion_least

#print axioms: 4 theorems, no axioms.

85.62 Algebraic logic

Formulas preordered by provable implication form a Heyting algebra (no quotient), in which every formula evaluates to itself; hence intuitionistic derivability coincides with validity in all Heyting algebras. \(\vdash _i\varphi \iff \forall H\,\forall v,\ \top \le \llbracket \varphi \rrbracket ^H_v\).

found/AlgebraicLogic.lean

/-
  T191. found/AlgebraicLogic — algebraic logic as a point: the
  Lindenbaum–Tarski algebra of a theory Γ (formulas, a ≤ b :⟺ Γ ⊢ a → b)
  is a Heyting algebra (preorder form, so no quotient is needed).
  * Algebraic completeness: a formula valid in every Heyting algebra is
    intuitionistically derivable (soundness is T65) — Heyting-valued
    semantics ↔ intuitionistic derivability.
  * The same construction with the DNE hypotheses (T66) gives the Boolean
    case; Stone duality and cylindric/polyadic algebras are cited lines.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Classical

namespace Found

namespace Prp

def LT (Γ : Form → Prop) : HA.{0} where
  car := Form
  le a b := PD true Γ (.imp a b)
  le_refl _ := .impI h0
  le_trans h k := .impI (.impE (wk k) (.impE (wk h) h0))
  top := .imp .bot .bot
  bot := .bot
  meet := .and
  join := .or
  imp := .imp
  le_top _ := .impI (.impI h0)
  bot_le _ := .impI (.botE rfl h0)
  meet_l _ _ := .impI (.andE1 h0)
  meet_r _ _ := .impI (.andE2 h0)
  meet_univ h k := .impI (.andI (.impE (wk h) h0) (.impE (wk k) h0))
  join_l _ _ := .impI (.orI1 h0)
  join_r _ _ := .impI (.orI2 h0)
  join_univ h k := .impI (.orE h0 (.impE (wk (wk h)) h0) (.impE (wk (wk k)) h0))
  imp_adj := ⟨fun h => .impI (.impI (.impE (wk (wk h)) (.andI h1 h0))),
              fun h => .impI (.impE (.impE (wk h) (.andE1 h0)) (.andE2 h0))⟩

theorem interp_LT (Γ : Form → Prop) : (φ : Form) → interp (LT Γ) Form.var Form.bot φ = φ
  | .var _ => rfl
  | .bot => rfl
  | .and a b => by
    show Form.and (interp (LT Γ) Form.var Form.bot a) (interp (LT Γ) Form.var Form.bot b) = _
    rw [interp_LT Γ a, interp_LT Γ b]
  | .or a b => by
    show Form.or (interp (LT Γ) Form.var Form.bot a) (interp (LT Γ) Form.var Form.bot b) = _
    rw [interp_LT Γ a, interp_LT Γ b]
  | .imp a b => by
    show Form.imp (interp (LT Γ) Form.var Form.bot a) (interp (LT Γ) Form.var Form.bot b) = _
    rw [interp_LT Γ a, interp_LT Γ b]

/-- algebraic completeness: valid in every Heyting algebra ⇒ derivable -/
theorem completeness (φ : Form)
    (h : ∀ (H : HA.{0}) (v : Nat → H.car), H.le H.top (interp H v H.bot φ)) :
    PD true (fun _ => False) φ := by
  have k : PD true (fun _ => False) (.imp (.imp .bot .bot) (interp (LT (fun _ => False)) Form.var Form.bot φ)) :=
    h (LT (fun _ => False)) Form.var
  rw [interp_LT] at k
  exact .impE k (.impI h0)

/-- and soundness (T65) closes the circle -/
theorem heyting_iff (φ : Form) :
    PD true (fun _ => False) φ ↔ ∀ (H : HA.{0}) (v : Nat → H.car), H.le H.top (interp H v H.bot φ) :=
  ⟨fun d H v => valid H d v H.bot (fun _ => H.bot_le), completeness φ⟩

end Prp

end Found

#print axioms Found.Prp.LT
#print axioms Found.Prp.interp_LT
#print axioms Found.Prp.completeness
#print axioms Found.Prp.heyting_iff

#print axioms: 4 theorems, no axioms.

85.63 Truth and diagonalization

If \(A\to (A\to B)\) is point-surjective then every endomap of \(B\) has a fixed point; hence Cantor’s theorem for predicates and the undefinability of a truth predicate that commutes with diagonal substitution. \(e:A\to B^A\ \text {point-surjective}\Rightarrow \forall f:B\to B\ \exists b,\ b\simeq f(b)\).

found/Truth.lean

/-
  T192. found/Truth — theories of truth as a point, via Lawvere's
  fixed-point theorem on the function-space operation (T59, op 2).

  * Lawvere: if e : A → (A → B) is point-surjective (every g : A → B is
    e a up to pointwise ≈), then every f : B → B has a fixed point up to ≈.
  * Corollaries: Cantor (no point-surjection A → (A → Prop) up to ↔),
    and Tarski-style undefinability: no "truth predicate" T on codes with
    T(code φ) ↔ φ for all predicates φ obtained by diagonalisation; liar.
  * Kripke's partial truth (fixed points of the Kleene jump, T140) is the
    line to three-valued logic (cited).

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Truth

universe u v

/-- Lawvere's fixed-point theorem, with an arbitrary equivalence on B -/
theorem lawvere {A : Type u} {B : Type v} (R : B → B → Prop)
    (e : A → A → B) (surj : ∀ g : A → B, ∃ a, ∀ x, R (e a x) (g x)) (f : B → B) :
    ∃ b, R b (f b) :=
  match surj (fun x => f (e x x)) with
  | ⟨a, h⟩ => ⟨e a a, h a⟩

/-- Cantor: no point-surjection A → (A → Prop) up to ↔ -/
theorem cantor {A : Type u} (e : A → A → Prop) : ¬ ∀ g : A → Prop, ∃ a, ∀ x, (e a x ↔ g x) :=
  fun surj => match lawvere (fun p q : Prop => p ↔ q) e surj Not with
  | ⟨b, h⟩ => have n : ¬ b := fun hb => h.mp hb hb
              n (h.mpr n)

/-- Tarski-style undefinability: a "truth predicate" T on codes A with a
  diagonal substitution sub (sub a x codes "e a applied to x") cannot satisfy
  T (sub a x) ↔ e a x for every a, x, when every predicate on A is some e a -/
theorem undefinable {A : Type u} (e : A → A → Prop) (T : A → Prop) (sub : A → A → A)
    (hT : ∀ a x, T (sub a x) ↔ e a x)
    (hrep : ∀ g : A → Prop, ∃ a, ∀ x, (e a x ↔ g x)) : False :=
  match hrep (fun x => ¬ T (sub x x)) with
  | ⟨a, h⟩ =>
    have k : T (sub a a) ↔ ¬ T (sub a a) := (hT a a).trans (h a)
    have n : ¬ T (sub a a) := fun t => k.mp t t
    n (k.mpr n)

end Truth

end Found

#print axioms Found.Truth.lawvere
#print axioms Found.Truth.cantor
#print axioms Found.Truth.undefinable

#print axioms: 3 theorems, no axioms.

85.64 Second-order logic

With the second-order quantifier ranging over a parameter family of predicates, Henkin validity implies standard validity, comprehension holds in the standard semantics, and it fails in the Henkin model whose only predicate is empty. \(\models _{H}\varphi \Rightarrow \models _{S}\varphi ;\quad \models _S\exists P\forall x(Px\leftrightarrow x=x),\ \not \models _{\{\varnothing \}}\).

found/SecondOrder2.lean

/-
  T142. found/SecondOrder2 — second-order logic as a point: the second-order
  quantifier ranges over a parameter D₂ ⊆ (A → Prop) (power operation of
  the core, or a sub-family of it).
  * Standard semantics: D₂ = all predicates; Henkin semantics: any D₂.
  * Henkin-valid ⇒ standard-valid (the standard model is one Henkin model).
  * Comprehension holds in the standard semantics and can fail in a Henkin
    model (D₂ = {∅}) — the line second-order (standard) ↔ many-sorted
    first-order (Henkin), cited for completeness.

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: the ∀ P : A → Prop of standard semantics (impredicative Prop).
-/

namespace Found

namespace SO

universe u

inductive Fm where
  | app : Nat → Nat → Fm        -- P_i(x_j)
  | eq : Nat → Nat → Fm
  | neg : Fm → Fm
  | and : Fm → Fm → Fm
  | all1 : Fm → Fm              -- ∀x (de Bruijn on individual variables)
  | all2 : Fm → Fm              -- ∀P (de Bruijn on predicate variables)

variable {A : Type u}

def cons {α : Sort _} (x : α) (ρ : Nat → α) : Nat → α
  | 0 => x
  | n + 1 => ρ n

def sat (D2 : (A → Prop) → Prop) : (Nat → A) → (Nat → A → Prop) → Fm → Prop
  | ρ, σ, .app i j => σ i (ρ j)
  | ρ, _, .eq i j => ρ i = ρ j
  | ρ, σ, .neg φ => ¬ sat D2 ρ σ φ
  | ρ, σ, .and φ ψ => sat D2 ρ σ φ ∧ sat D2 ρ σ ψ
  | ρ, σ, .all1 φ => ∀ x, sat D2 (cons x ρ) σ φ
  | ρ, σ, .all2 φ => ∀ P, D2 P → sat D2 ρ (cons P σ) φ

def full : (A → Prop) → Prop := fun _ => True

/-- Henkin-valid ⇒ standard-valid -/
theorem henkin_to_standard (φ : Fm) (h : ∀ D2 : (A → Prop) → Prop, ∀ ρ σ, sat D2 ρ σ φ) (ρ : Nat → A)
    (σ : Nat → A → Prop) : sat full ρ σ φ := h full ρ σ

/-- comprehension instance ∃P ∀x (P x ↔ x = x), written ¬∀P ¬∀x (P x ↔ x = x) with ↔ as two ∧'d ¬(·∧¬·) -/
def compr : Fm :=
  .neg (.all2 (.neg (.all1 (.and (.neg (.and (.app 0 0) (.neg (.eq 0 0))))
                                 (.neg (.and (.eq 0 0) (.neg (.app 0 0))))))))

theorem compr_standard (ρ : Nat → A) (σ : Nat → A → Prop) : sat full ρ σ compr :=
  fun h => h (fun _ => True) trivial (fun _ => ⟨fun k => k.2 rfl, fun k => k.2 trivial⟩)

/-- in the Henkin model D₂ = {∅} on an inhabited domain, comprehension fails -/
theorem compr_henkin_fails (a : A) (ρ : Nat → A) (σ : Nat → A → Prop) :
    ¬ sat (fun P => ∀ x, ¬ P x) ρ σ compr :=
  fun h => h (fun _ hP hall => (hall a).2 ⟨rfl, fun p => hP a p⟩)

end SO

end Found

#print axioms Found.SO.henkin_to_standard
#print axioms Found.SO.compr_standard
#print axioms Found.SO.compr_henkin_fails

#print axioms: 3 theorems, no axioms.

85.65 Many-sorted logic

Quantifying over a sort is quantifying over the total space relativized by the sort predicate, and Henkin second-order domains are two-sorted structures with an application relation. \(\forall x{:}C_s\,\psi \iff \forall y{:}\Sigma _s C_s,\ \pi _1 y=s\to \psi \).

found/ManySorted.lean

/-
  T170. found/ManySorted — many-sorted logic as a point: a family of
  carriers C : S → Type (a parameter); relativization to one sort.
  * Quantifying over a sort = quantifying over the total space Σ s, C s
    relativized by the sort predicate (both directions).
  * Henkin second-order logic (T142) is the two-sorted case: individuals
    and a family D₂ of predicates with an application relation.

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace MS

universe u v

variable {S : Type u} (C : S → Type v)

def Tot : Type (max u v) := (s : S) × C s

theorem relativize (s : S) (ψ : Tot C → Prop) :
    (∀ x : C s, ψ ⟨s, x⟩) ↔ (∀ y : Tot C, y.1 = s → ψ y) :=
  ⟨fun h y e => by
     cases y with
     | mk s' x =>
       cases e
       exact h x,
   fun h x => h ⟨s, x⟩ rfl⟩

theorem relativize_ex (s : S) (ψ : Tot C → Prop) :
    (∃ x : C s, ψ ⟨s, x⟩) ↔ (∃ y : Tot C, y.1 = s ∧ ψ y) :=
  ⟨fun ⟨x, h⟩ => ⟨⟨s, x⟩, rfl, h⟩,
   fun ⟨y, e, h⟩ => by
     cases y with
     | mk s' x =>
       cases e
       exact ⟨x, h⟩⟩

/-- Henkin structures as two-sorted structures: individuals, predicate
  objects, and application -/
structure Henkin2 where
  Ind : Type u
  Pr : Type u
  ap : Pr → Ind → Prop

/-- every Henkin second-order domain D₂ ⊆ (A → Prop) is a two-sorted structure -/
def ofD2 {A : Type u} (D2 : (A → Prop) → Prop) : Henkin2.{u} :=
  ⟨A, {P : A → Prop // D2 P}, fun P x => P.val x⟩

theorem ofD2_all {A : Type u} (D2 : (A → Prop) → Prop) (φ : (A → Prop) → Prop) :
    (∀ P, D2 P → φ P) ↔ (∀ P : (ofD2 D2).Pr, φ P.val) :=
  ⟨fun h P => h P.val P.property, fun h P hP => h ⟨P, hP⟩⟩

end MS

end Found

#print axioms Found.MS.relativize
#print axioms Found.MS.relativize_ex
#print axioms Found.MS.ofD2_all

#print axioms: 3 theorems, no axioms.

85.66 Foundation versus anti-foundation

On the graph coordinate, well-founded extensional graphs decorate to sets that are not members of themselves, while any loop decorates to a self-member: foundation and anti-foundation are two values of one condition. \(\mathrm {WF}\wedge \mathrm {Ext}\Rightarrow d(n)\notin d(n);\quad nEn\Rightarrow d(n)\in d(n)\).

found/WellFounded.lean

/-
  T125. found/WellFounded — foundation versus anti-foundation as a
  condition on the same graph coordinate (T105, T109 reused).
  * Condition WF + extensional on a graph: no decoration is a member of
    itself (foundation holds on the decorated part).
  * Condition "has a loop": the decoration of the looping node is a member
    of itself (an Ω).
  So the initial-algebra point (V, T109) and the final-coalgebra point
  (AFA, T105) are the two values of one condition on (N, E).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Mostowski

namespace Found

namespace WFvsAFA

open AFA

variable {N : Type} (E : N → N → Prop)

theorem wf_no_self_member (hW : WF.WellFounded' E) (hX : WF.Extensional E) (n : N) :
    ¬ Mem (dec ⟨N, E⟩ n) (dec ⟨N, E⟩ n) :=
  fun ⟨c, e, h⟩ => match h with
  | ⟨S, hS, s⟩ =>
    have eq : n = c := WF.bisim_eq E hW hX (S := S) hS n c s
    WF.no_loop E hW n (eq ▸ e)

theorem loop_self_member (n : N) (h : E n n) : Mem (dec ⟨N, E⟩ n) (dec ⟨N, E⟩ n) :=
  ⟨n, h, eqv_refl _⟩

end WFvsAFA

end Found

#print axioms Found.WFvsAFA.wf_no_self_member
#print axioms Found.WFvsAFA.loop_self_member

#print axioms: 2 theorems, no axioms.

85.67 Mac Lane, Zermelo and TG

On Aczel’s trees, the Mac Lane axioms (pairing, union, power, infinity, \(\Delta _0\)-separation), Zermelo’s full separation and the Tarski–Grothendieck universe condition are collected from the proved IZF, KP and universe results. \(\mathrm {MacLane}\subseteq \mathrm {Z}\subseteq \mathrm {ZF};\quad \forall a\in V_0,\ \mathrm {lift}\,a\in U\).

found/MacLane.lean

/-
  T163 / T146 / T162. found/MacLane — Zermelo-style points on the tree
  coordinate V, assembled from proved pieces (no re-proofs):
  * Mac Lane set theory (Z with Δ₀-separation): pairing, union, power,
    infinity (T88) + Δ₀-separation (T90) — the point equiconsistent with
    ETCS (line to T107, cited);
  * Zermelo Z: the same with full separation (T88) and, classically, LEM (T89);
  * Tarski–Grothendieck: every set of V.{0} lies in the universe U ∈ V.{1}
    (T104), which is closed under the operations.

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: impredicative Prop of T88/T104.
-/
import found.KP
import found.Grothendieck

namespace Found

namespace Zermelo

open WF

universe u

/-- the Mac Lane axioms hold in V (collected) -/
theorem maclane (a b x : V.{u}) (φ : KP.D0) (ρ : Nat → V.{u}) :
    (Mem x (IZF.pair a b) ↔ Eq' x a ∨ Eq' x b) ∧
    (Mem x (IZF.union a) ↔ ∃ y : V.{u}, Mem y a ∧ Mem x y) ∧
    (Mem x (IZF.power a) ↔ ∀ z : V.{u}, Mem z x → Mem z a) ∧
    (Mem IZF.empty IZF.omega ∧ ∀ y : V.{u}, Mem y IZF.omega → Mem (IZF.succ y) IZF.omega) ∧
    (Mem x (IZF.sep a (fun y => KP.sat φ (KP.cons y ρ))) ↔ Mem x a ∧ KP.sat φ (KP.cons x ρ)) :=
  ⟨IZF.pair_spec a b x, IZF.union_spec a x, IZF.power_spec a x, IZF.infinity, KP.d0_separation φ ρ a x⟩

/-- Zermelo: full separation for any respecting predicate -/
theorem zermelo_sep (a x : V.{u}) (φ : V.{u} → Prop) (hφ : IZF.Resp φ) :
    Mem x (IZF.sep a φ) ↔ Mem x a ∧ φ x := IZF.sep_spec a φ hφ x

/-- Tarski–Grothendieck: every set of V.{0} is (lifted) in the universe U -/
theorem tg (a : V.{0}) : Mem (Groth.lift a) Groth.U := ⟨a, eq_refl _⟩

end Zermelo

end Found

#print axioms Found.Zermelo.maclane
#print axioms Found.Zermelo.zermelo_sep
#print axioms Found.Zermelo.tg

#print axioms: 3 theorems, no axioms.

85.68 Recursive functions

Primitive recursive terms on argument lists evaluate by structural recursion, so they are total; addition is primitive recursive with the expected values; the graph of unbounded minimisation is deterministic. \(\mathrm {eval}(\mathrm {add})[n,y]=n+y;\quad \mu f(\vec a)=n\wedge \mu f(\vec a)=n'\Rightarrow n=n'\).

found/Recursive.lean

/-
  T81. found/Recursive — recursive functions as a point: primitive
  recursion is the core's induction (T59 fold on ℕ), μ is unbounded search.
  * PR terms on argument lists; evaluation by structural recursion
    (so every primitive recursive function is total).
  * Example: addition is primitive recursive and evaluates to +.
  * μ-recursion as a graph relation: the least zero; the graph is
    deterministic.
  Turing / register machines and the equivalences (T82, T145) are lines.

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Rec

inductive PR where
  | zero : PR
  | succ : PR
  | proj : Nat → PR
  | comp : PR → List PR → PR
  | prec : PR → PR → PR

def nth : List Nat → Nat → Nat
  | [], _ => 0
  | a :: _, 0 => a
  | _ :: l, n + 1 => nth l n

def precIter (F G : List Nat → Nat) : Nat → List Nat → Nat
  | 0, rest => F rest
  | n + 1, rest => G (n :: precIter F G n rest :: rest)

mutual
def eval : PR → List Nat → Nat
  | .zero, _ => 0
  | .succ, args => nth args 0 + 1
  | .proj i, args => nth args i
  | .comp f gs, args => eval f (evalList gs args)
  | .prec f g, args => match args with
    | [] => eval f []
    | n :: rest => precIter (eval f) (eval g) n rest
def evalList : List PR → List Nat → List Nat
  | [], _ => []
  | g :: gs, args => eval g args :: evalList gs args
end

/-- addition: add(0, y) = y, add(n+1, y) = succ(add(n, y)) -/
def addPR : PR := .prec (.proj 0) (.comp .succ [.proj 1])

theorem add_correct (y : Nat) : ∀ n, eval addPR [n, y] = n + y
  | 0 => (Nat.zero_add y).symm
  | n + 1 => by
    show precIter (eval (.proj 0)) (eval (.comp .succ [.proj 1])) (n + 1) [y] = n + 1 + y
    show precIter (eval (.proj 0)) (eval (.comp .succ [.proj 1])) n [y] + 1 = _
    have ih : precIter (eval (.proj 0)) (eval (.comp .succ [.proj 1])) n [y] = n + y := add_correct y n
    rw [ih, Nat.succ_add]

/-- μ: the least n with f(n :: args) = 0 -/
def MuGraph (f : PR) (args : List Nat) (n : Nat) : Prop :=
  eval f (n :: args) = 0 ∧ ∀ m, m < n → eval f (m :: args) ≠ 0

theorem lt_or_ge' : (a b : Nat) → a < b ∨ b ≤ a
  | 0, 0 => Or.inr (Nat.le_refl 0)
  | 0, _ + 1 => Or.inl (Nat.succ_pos _)
  | _ + 1, 0 => Or.inr (Nat.zero_le _)
  | a + 1, b + 1 => (lt_or_ge' a b).elim (fun h => Or.inl (Nat.succ_lt_succ h)) (fun h => Or.inr (Nat.succ_le_succ h))

theorem le_antisymm' {a b : Nat} (h : a ≤ b) (k : b ≤ a) : a = b := Nat.le_antisymm h k

/-- the μ-graph is deterministic -/
theorem mu_det (f : PR) (args : List Nat) (n n' : Nat) (h : MuGraph f args n) (h' : MuGraph f args n') : n = n' :=
  (lt_or_ge' n n').elim (fun lt => (h'.2 n lt h.1).elim)
    (fun ge => (lt_or_ge' n' n).elim (fun lt => (h.2 n' lt h'.1).elim) (fun ge' => le_antisymm' ge' ge))

end Rec

end Found

#print axioms Found.Rec.eval
#print axioms Found.Rec.add_correct
#print axioms Found.Rec.lt_or_ge'
#print axioms Found.Rec.mu_det

#print axioms: 4 theorems, no axioms.

85.69 Register machines

Two-counter machines with increment and decrement-or-jump have a small-step semantics; the three-instruction addition program runs from \((0,x,y)\) to the halting configuration with \(r_0=x+y\). \((0,x,y)\to ^*(2,x+y,0)\).

found/Register.lean

/-
  T145. found/Register — register machines as a point: two-counter Minsky
  machines (universal, Minsky, cited) with small-step semantics on the
  relation coordinate.
  * Instructions: inc r, decjz r j (decrement, or jump to j if zero), halt.
  * An addition program: from (pc 0, x, y) it reaches halt with r₀ = x + y
    (by induction on y) — the line to μ-recursive addition (T81).

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Reg

inductive Ins where
  | inc0 : Nat → Ins          -- r0 += 1, goto
  | dec1 : Nat → Nat → Ins    -- if r1 = 0 goto a else (r1 -= 1, goto b)
  | halt : Ins

structure Conf where
  pc : Nat
  r0 : Nat
  r1 : Nat

def fetch : List Ins → Nat → Ins
  | [], _ => .halt
  | i :: _, 0 => i
  | _ :: is, k + 1 => fetch is k

inductive Step (prog : List Ins) : Conf → Conf → Prop where
  | inc {c : Conf} {g : Nat} : fetch prog c.pc = .inc0 g → Step prog c ⟨g, c.r0 + 1, c.r1⟩
  | zero {c : Conf} {a b : Nat} : fetch prog c.pc = .dec1 a b → c.r1 = 0 → Step prog c ⟨a, c.r0, c.r1⟩
  | dec {c : Conf} {a b : Nat} {k : Nat} : fetch prog c.pc = .dec1 a b → c.r1 = k + 1 → Step prog c ⟨b, c.r0, k⟩

inductive Steps (prog : List Ins) : Conf → Conf → Prop where
  | refl (c : Conf) : Steps prog c c
  | step {a b c : Conf} : Step prog a b → Steps prog b c → Steps prog a c

theorem steps_trans {prog : List Ins} {a b c : Conf} (h : Steps prog a b) (k : Steps prog b c) : Steps prog a c := by
  induction h with
  | refl => exact k
  | step s _ ih => exact .step s (ih k)

/-- 0: if r1 = 0 goto 2 else (r1 -= 1, goto 1);  1: r0 += 1, goto 0;  2: halt -/
def addProg : List Ins := [.dec1 2 1, .inc0 0, .halt]

theorem add_runs (x : Nat) : ∀ y, Steps addProg ⟨0, x, y⟩ ⟨2, x + y, 0⟩
  | 0 => .step (.zero (a := 2) (b := 1) rfl rfl) (.refl _)
  | y + 1 => by
    have h1 : Step addProg ⟨0, x, y + 1⟩ ⟨1, x, y⟩ := .dec (a := 2) (b := 1) rfl rfl
    have h2 : Step addProg ⟨1, x, y⟩ ⟨0, x + 1, y⟩ := .inc (g := 0) rfl
    have ih := add_runs (x + 1) y
    rw [Nat.add_assoc, Nat.add_comm 1 y] at ih
    exact .step h1 (.step h2 ih)

theorem halts_at (x y : Nat) : fetch addProg (⟨2, x + y, 0⟩ : Conf).pc = .halt := rfl

end Reg

end Found

#print axioms Found.Reg.steps_trans
#print axioms Found.Reg.add_runs
#print axioms Found.Reg.halts_at

#print axioms: 3 theorems, no axioms.

85.70 Weak arithmetics

Presburger and Skolem arithmetic are the multiplication-free and addition-free fragments of the arithmetic language, and truth of bounded (\(\Delta _0\)) formulas in the standard model is decidable constructively by bounded search. \(\forall \varphi \in \Delta _0\ \forall \rho ,\ \mathbb {N}\models \varphi [\rho ]\vee \mathbb {N}\not \models \varphi [\rho ]\).

found/Presburger.lean

/-
  T186. found/Presburger — weak arithmetics as points: the arithmetic
  language (T85a) restricted to + only (Presburger), · only (Skolem), or to
  bounded quantifiers (Δ₀, the base of IΔ₀ and Buss's S¹₂).
  * Fragments: predicates on terms (mul-free / add-free), closed under the
    arithmetic language's evaluation (reused).
  * Δ₀ truth in ℕ is decidable, constructively, by bounded search
    (structural recursion) — the reason bounded arithmetic is "feasible".
  Decidability of Presburger (quantifier elimination) is cited.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.ArithBridge

namespace Found

namespace Weak

open Arith

def mulFree : Tm → Prop
  | .var _ => True
  | .zero => True
  | .succ t => mulFree t
  | .add a b => mulFree a ∧ mulFree b
  | .mul _ _ => False

def addFree : Tm → Prop
  | .var _ => True
  | .zero => True
  | .succ t => addFree t
  | .add _ _ => False
  | .mul a b => addFree a ∧ addFree b

inductive D0 where
  | eq : Tm → Tm → D0
  | neg : D0 → D0
  | and : D0 → D0 → D0
  | or : D0 → D0 → D0
  | ball : Tm → D0 → D0      -- ∀x < t (x = variable 0 inside)
  | bex : Tm → D0 → D0       -- ∃x < t

def sat : (Nat → Nat) → D0 → Prop
  | ρ, .eq a b => eval ρ a = eval ρ b
  | ρ, .neg φ => ¬ sat ρ φ
  | ρ, .and φ ψ => sat ρ φ ∧ sat ρ ψ
  | ρ, .or φ ψ => sat ρ φ ∨ sat ρ ψ
  | ρ, .ball t φ => ∀ x, x < eval ρ t → sat (cons x ρ) φ
  | ρ, .bex t φ => ∃ x, x < eval ρ t ∧ sat (cons x ρ) φ

def Dec (p : Prop) : Prop := p ∨ ¬ p

theorem nat_dec_eq : (a b : Nat) → Dec (a = b)
  | 0, 0 => Or.inl rfl
  | 0, _ + 1 => Or.inr (fun e => Nat.noConfusion e)
  | _ + 1, 0 => Or.inr (fun e => Nat.noConfusion e)
  | a + 1, b + 1 => (nat_dec_eq a b).elim (fun e => Or.inl (congrArg Nat.succ e))
      (fun n => Or.inr (fun e => n (Nat.succ.inj e)))

theorem lt_succ_cases {x n : Nat} (h : x < n + 1) : x < n ∨ x = n :=
  match Nat.lt_or_ge x n with
  | Or.inl l => Or.inl l
  | Or.inr g => Or.inr (Nat.le_antisymm (Nat.le_of_lt_succ h) g)

theorem bounded_all (P : Nat → Prop) (hP : ∀ x, Dec (P x)) : ∀ n, Dec (∀ x, x < n → P x)
  | 0 => Or.inl (fun _ h => (Nat.not_lt_zero _ h).elim)
  | n + 1 => (bounded_all P hP n).elim
      (fun h => (hP n).elim
        (fun pn => Or.inl (fun x hx => (lt_succ_cases hx).elim (h x) (fun e => e ▸ pn)))
        (fun npn => Or.inr (fun k => npn (k n (Nat.lt_succ_self n)))))
      (fun nh => Or.inr (fun k => nh (fun x hx => k x (Nat.lt_succ_of_lt hx))))

theorem bounded_ex (P : Nat → Prop) (hP : ∀ x, Dec (P x)) : ∀ n, Dec (∃ x, x < n ∧ P x)
  | 0 => Or.inr (fun ⟨_, h, _⟩ => Nat.not_lt_zero _ h)
  | n + 1 => (bounded_ex P hP n).elim
      (fun ⟨x, hx, px⟩ => Or.inl ⟨x, Nat.lt_succ_of_lt hx, px⟩)
      (fun nh => (hP n).elim (fun pn => Or.inl ⟨n, Nat.lt_succ_self n, pn⟩)
        (fun npn => Or.inr (fun ⟨x, hx, px⟩ => (lt_succ_cases hx).elim
          (fun l => nh ⟨x, l, px⟩) (fun e => npn (e ▸ px)))))

/-- Δ₀ truth in ℕ is decidable -/
theorem d0_decidable : (φ : D0) → ∀ ρ, Dec (sat ρ φ)
  | .eq _ _, _ => nat_dec_eq _ _
  | .neg φ, ρ => (d0_decidable φ ρ).elim (fun h => Or.inr (fun n => n h)) (fun n => Or.inl n)
  | .and φ ψ, ρ => (d0_decidable φ ρ).elim
      (fun h => (d0_decidable ψ ρ).elim (fun k => Or.inl ⟨h, k⟩) (fun nk => Or.inr (fun p => nk p.2)))
      (fun nh => Or.inr (fun p => nh p.1))
  | .or φ ψ, ρ => (d0_decidable φ ρ).elim (fun h => Or.inl (Or.inl h))
      (fun nh => (d0_decidable ψ ρ).elim (fun k => Or.inl (Or.inr k))
        (fun nk => Or.inr (fun p => p.elim nh nk)))
  | .ball _ φ, ρ => bounded_all _ (fun x => d0_decidable φ (cons x ρ)) _
  | .bex _ φ, ρ => bounded_ex _ (fun x => d0_decidable φ (cons x ρ)) _

end Weak

end Found

#print axioms Found.Weak.nat_dec_eq
#print axioms Found.Weak.lt_succ_cases
#print axioms Found.Weak.bounded_all
#print axioms Found.Weak.bounded_ex
#print axioms Found.Weak.d0_decidable

#print axioms: 5 theorems, no axioms.

85.71 Completeness

Intuitionistic propositional derivability coincides with validity in all Heyting algebras, and classical derivability with validity in all Boolean ones, the latter through the Boolean Lindenbaum algebra of the double-negation theory. \(\vdash _c\varphi \iff \forall H\ \text {Boolean}\ \forall v,\ \top \le \llbracket \varphi \rrbracket \).

found/Completeness.lean

/-
  T93. found/Completeness — completeness as a point of model theory,
  propositional and algebraic (known range; first-order Gödel/Kripke
  completeness is cited and needs prime filters / LEM in the metatheory).
  * Intuitionistic: ⊢ φ ⟺ valid in every Heyting algebra (T191, reused).
  * Classical: ⊢_c φ ⟺ valid in every Boolean Heyting algebra: soundness
    T66, completeness via the Lindenbaum algebra of the DNE theory, which is
    Boolean.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.AlgebraicLogic

namespace Found

namespace Prp

/-- the Lindenbaum algebra of the DNE theory is Boolean -/
theorem lt_dne_boolean : Boolean (LT (DNE (fun _ => False))) :=
  fun a => .hyp (dne_has _ a)

theorem interp_LT' (φ : Form) : interp (LT (DNE (fun _ => False))) Form.var Form.bot φ = φ :=
  interp_LT _ φ

/-- classical completeness for Boolean algebras -/
theorem classical_completeness (φ : Form)
    (h : ∀ (H : HA.{0}), Boolean H → ∀ v : Nat → H.car, H.le H.top (interp H v H.bot φ)) :
    CD (fun _ => False) φ := by
  have k : PD true (DNE (fun _ => False)) (.imp (.imp .bot .bot) (interp (LT (DNE (fun _ => False))) Form.var Form.bot φ)) :=
    h _ lt_dne_boolean Form.var
  rw [interp_LT'] at k
  exact .impE k (.impI h0)

theorem classical_iff (φ : Form) :
    CD (fun _ => False) φ ↔ ∀ (H : HA.{0}), Boolean H → ∀ v : Nat → H.car, H.le H.top (interp H v H.bot φ) :=
  ⟨fun d H hB v => cd_sound H hB d v, classical_completeness φ⟩

theorem intuitionistic_iff (φ : Form) :
    PD true (fun _ => False) φ ↔ ∀ (H : HA.{0}) (v : Nat → H.car), H.le H.top (interp H v H.bot φ) :=
  heyting_iff φ

end Prp

end Found

#print axioms Found.Prp.lt_dne_boolean
#print axioms Found.Prp.classical_completeness
#print axioms Found.Prp.classical_iff
#print axioms Found.Prp.intuitionistic_iff

#print axioms: 4 theorems, no axioms.

85.72 Compactness

Every derivation uses finitely many hypotheses, extracted constructively; with strong completeness via the Lindenbaum algebra of the theory, Heyting-valued consequence from a set of formulas is consequence from a finite subset. \(\Gamma \models \varphi \Rightarrow \exists \Gamma _0\subseteq _{\mathrm {fin}}\Gamma ,\ \Gamma _0\models \varphi \).

found/Compactness.lean

/-
  T94. found/Compactness — compactness as a point (propositional, known
  range; Löwenheim–Skolem and first-order compactness are cited).
  * Finiteness: a derivation from Γ uses a finite list of hypotheses from Γ
    (constructive extraction by Prop-elimination on the cases).
  * Strong completeness: Γ ⊢ φ ⟺ φ is ⊤ in every Heyting algebra under every
    valuation that makes all of Γ ⊤ (Lindenbaum algebra of Γ, T191).
  * Compactness: semantic consequence from Γ is consequence from a finite
    subset.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.AlgebraicLogic

namespace Found

namespace Prp

theorem mem_app_l {α : Type} {x : α} {l₁ l₂ : List α} (h : x ∈ l₁) : x ∈ l₁ ++ l₂ := by
  induction h with
  | head => exact .head _
  | tail _ _ ih => exact .tail _ ih

theorem mem_app_r {α : Type} {x : α} (l₁ : List α) {l₂ : List α} (h : x ∈ l₂) : x ∈ l₁ ++ l₂ := by
  induction l₁ with
  | nil => exact h
  | cons _ _ ih => exact .tail _ ih

theorem mem_app_inv {α : Type} {x : α} : (l₁ l₂ : List α) → x ∈ l₁ ++ l₂ → x ∈ l₁ ∨ x ∈ l₂
  | [], _, h => Or.inr h
  | _ :: l, l₂, h => by
    cases h with
    | head => exact Or.inl (.head _)
    | tail _ h' => exact (mem_app_inv l l₂ h').elim (fun k => Or.inl (.tail _ k)) Or.inr

/-- drop the discharged hypothesis -/
theorem prune {Γ : Form → Prop} (a : Form) : (l : List Form) → (∀ x, x ∈ l → x = a ∨ Γ x) →
    ∃ l' : List Form, (∀ x, x ∈ l' → Γ x) ∧ ∀ x, x ∈ l → x = a ∨ x ∈ l'
  | [], _ => ⟨[], (fun _ (h : _ ∈ ([] : List Form)) => nomatch h), (fun _ (h : _ ∈ ([] : List Form)) => nomatch h)⟩
  | y :: l, h =>
    match prune a l (fun x m => h x (.tail _ m)) with
    | ⟨l', h1, h2⟩ =>
      (h y (.head _)).elim
        (fun e => ⟨l', h1, fun x m => by
          cases m with
          | head => exact Or.inl e
          | tail _ m' => exact h2 x m'⟩)
        (fun g => ⟨y :: l', fun x m => by
            cases m with
            | head => exact g
            | tail _ m' => exact h1 x m',
          fun x m => by
            cases m with
            | head => exact Or.inr (.head _)
            | tail _ m' => exact (h2 x m').elim Or.inl (fun k => Or.inr (.tail _ k))⟩)

/-- finiteness of derivations -/
theorem finite_hyps {I : Bool} {Γ : Form → Prop} {φ : Form} (d : PD I Γ φ) :
    ∃ l : List Form, (∀ x, x ∈ l → Γ x) ∧ PD I (fun x => x ∈ l) φ := by
  induction d with
  | @hyp _ a g =>
    refine ⟨[a], ⟨fun x (m : x ∈ [a]) => ?_, .hyp (.head _)⟩⟩
    cases m with
    | head => exact g
    | tail _ m' => exact nomatch m'
  | botE e _ ih => match ih with | ⟨l, h, d⟩ => exact ⟨l, h, .botE e d⟩
  | andI _ _ iha ihb => match iha, ihb with
    | ⟨l₁, h₁, d₁⟩, ⟨l₂, h₂, d₂⟩ =>
      exact ⟨l₁ ++ l₂, fun x m => (mem_app_inv l₁ l₂ m).elim (h₁ x) (h₂ x),
        .andI (mono d₁ (fun _ k => mem_app_l k)) (mono d₂ (fun _ k => mem_app_r l₁ k))⟩
  | andE1 _ ih => match ih with | ⟨l, h, d⟩ => exact ⟨l, h, .andE1 d⟩
  | andE2 _ ih => match ih with | ⟨l, h, d⟩ => exact ⟨l, h, .andE2 d⟩
  | orI1 _ ih => match ih with | ⟨l, h, d⟩ => exact ⟨l, h, .orI1 d⟩
  | orI2 _ ih => match ih with | ⟨l, h, d⟩ => exact ⟨l, h, .orI2 d⟩
  | @orE _ a b _ _ _ _ ih iha ihb =>
    match ih, iha, ihb with
    | ⟨l, h, d⟩, ⟨la, ha, da⟩, ⟨lb, hb, db⟩ =>
      match prune a la ha, prune b lb hb with
      | ⟨la', ha1, ha2⟩, ⟨lb', hb1, hb2⟩ =>
        exact ⟨l ++ (la' ++ lb'),
          fun x m => (mem_app_inv _ _ m).elim (h x) (fun m' => (mem_app_inv _ _ m').elim (ha1 x) (hb1 x)),
          .orE (mono d (fun _ k => mem_app_l k))
            (mono da (fun x k => (ha2 x k).elim Or.inl (fun k' => Or.inr (mem_app_r l (mem_app_l k')))))
            (mono db (fun x k => (hb2 x k).elim Or.inl (fun k' => Or.inr (mem_app_r l (mem_app_r la' k')))))⟩
  | @impI _ a _ _ ih =>
    match ih with
    | ⟨l, h, d⟩ => match prune a l h with
      | ⟨l', h1, h2⟩ => exact ⟨l', h1, .impI (mono d (fun x k => (h2 x k).elim Or.inl Or.inr))⟩
  | impE _ _ ihf iha => match ihf, iha with
    | ⟨l₁, h₁, d₁⟩, ⟨l₂, h₂, d₂⟩ =>
      exact ⟨l₁ ++ l₂, fun x m => (mem_app_inv l₁ l₂ m).elim (h₁ x) (h₂ x),
        .impE (mono d₁ (fun _ k => mem_app_l k)) (mono d₂ (fun _ k => mem_app_r l₁ k))⟩

/-- semantic consequence in all Heyting algebras -/
def Cons (Γ : Form → Prop) (φ : Form) : Prop :=
  ∀ (H : HA.{0}) (v : Nat → H.car), (∀ ψ, Γ ψ → H.le H.top (interp H v H.bot ψ)) →
    H.le H.top (interp H v H.bot φ)

/-- strong completeness -/
theorem strong_completeness (Γ : Form → Prop) (φ : Form) : Cons Γ φ → PD true Γ φ := by
  intro h
  have k : PD true Γ (.imp (.imp .bot .bot) (interp (LT Γ) Form.var Form.bot φ)) :=
    h (LT Γ) Form.var (fun ψ g => by
      show PD true Γ (.imp (.imp .bot .bot) (interp (LT Γ) Form.var Form.bot ψ))
      rw [interp_LT]
      exact .impI (.hyp (Or.inr g)))
  rw [interp_LT] at k
  exact .impE k (.impI h0)

/-- compactness: consequence from Γ is consequence from a finite part of Γ -/
theorem compactness (Γ : Form → Prop) (φ : Form) (h : Cons Γ φ) :
    ∃ l : List Form, (∀ x, x ∈ l → Γ x) ∧ Cons (fun x => x ∈ l) φ :=
  match finite_hyps (strong_completeness Γ φ h) with
  | ⟨l, hl, d⟩ => ⟨l, hl, fun H v hv => soundness H d v H.bot (fun _ => H.bot_le) H.top hv⟩

end Prp

end Found

#print axioms Found.Prp.prune
#print axioms Found.Prp.finite_hyps
#print axioms Found.Prp.strong_completeness
#print axioms Found.Prp.compactness

#print axioms: 4 theorems, no axioms.

85.73 Q, PA, HA, PRA

Robinson’s axioms and full induction are conditions on an arithmetic structure; the natural numbers satisfy both, a one-point structure violates Q, and in every such structure each element is zero or a successor. \(\mathbb {N}\models \mathrm {Q}+\mathrm {Ind};\quad \{\ast \}\not \models \mathrm {Q}\).

found/PAHA.lean

/-
  T83. found/PAHA — arithmetic theories as conditions on an arithmetic
  structure (M, 0, S, +, ·), a free parameter.
  * Robinson Q: the seven axioms; PA/HA = Q + induction for all predicates
    (HA when read with intuitionistic logic, PA with the classical
    condition, T66; the double-negation line PA → HA is T77).
  * PRA = primitive recursive functions (T81) with quantifier-free
    induction (cited as the finitist point, T200).
  * The standard ℕ (the core's NNO, T86) satisfies Q and full induction;
    a one-point structure fails Q (0 ≠ S x).

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace PA

universe u

structure ArStr where
  M : Type u
  z : M
  s : M → M
  add : M → M → M
  mul : M → M → M

def Q (A : ArStr.{u}) : Prop :=
  (∀ x, A.s x ≠ A.z) ∧ (∀ x y, A.s x = A.s y → x = y) ∧ (∀ x, x = A.z ∨ ∃ y, x = A.s y) ∧
  (∀ x, A.add x A.z = x) ∧ (∀ x y, A.add x (A.s y) = A.s (A.add x y)) ∧
  (∀ x, A.mul x A.z = A.z) ∧ (∀ x y, A.mul x (A.s y) = A.add (A.mul x y) x)

def Ind (A : ArStr.{u}) : Prop := ∀ P : A.M → Prop, P A.z → (∀ x, P x → P (A.s x)) → ∀ x, P x

def PAStr (A : ArStr.{u}) : Prop := Q A ∧ Ind A

def natStr : ArStr.{0} := ⟨Nat, 0, Nat.succ, Nat.add, Nat.mul⟩

theorem nat_Q : Q natStr :=
  ⟨fun _ e => Nat.noConfusion e, fun _ _ e => Nat.succ.inj e,
   fun (x : Nat) => match x with | 0 => Or.inl rfl | y + 1 => Or.inr ⟨y, rfl⟩,
   fun _ => rfl, fun _ _ => rfl, fun _ => rfl, fun _ _ => rfl⟩

theorem nat_Ind : Ind natStr := fun P h0 hs x => by
  induction x with
  | zero => exact h0
  | succ n ih => exact hs n ih

theorem nat_PA : PAStr natStr := ⟨nat_Q, nat_Ind⟩

def oneStr : ArStr.{0} := ⟨Unit, (), fun _ => (), fun _ _ => (), fun _ _ => ()⟩

theorem one_not_Q : ¬ Q oneStr := fun h => h.1 () rfl

/-- in any PA structure, every element is reached from 0 (induction) -/
theorem reach (A : ArStr.{u}) (h : PAStr A) : ∀ x : A.M, x = A.z ∨ ∃ y, x = A.s y :=
  h.2 _ (Or.inl rfl) (fun x _ => Or.inr ⟨x, rfl⟩)

end PA

end Found

#print axioms Found.PA.nat_Q
#print axioms Found.PA.nat_Ind
#print axioms Found.PA.nat_PA
#print axioms Found.PA.one_not_Q
#print axioms Found.PA.reach

#print axioms: 5 theorems, no axioms.

85.74 Second-order arithmetic and reverse mathematics

Comprehension for a class of predicates is a condition on the family \(D\) of an \(\omega \)-model; it is monotone in the class, giving the chain from full comprehension to \(\Sigma ^0_1\) to decidable comprehension; the full model satisfies all and the empty one none. \(\mathrm {Comp}(\text {all})\Rightarrow \mathrm {Comp}(\Sigma ^0_1)\Rightarrow \mathrm {Comp}(\mathrm {Dec})\).

found/SecondOrder.lean

/-
  T84. found/SecondOrder — second-order arithmetic and reverse mathematics
  as points: ω-models (ℕ, D) with D ⊆ P(ℕ) (the power operation of the core
  restricted by a parameter), comprehension for a class of predicates.
  * Classes: decidable (Δ⁰₀/recursive, RCA₀'s base), Σ⁰₁ (∃ over decidable,
    the ACA₀ direction), all predicates (Z₂).
  * Comprehension is monotone in the class: Z₂ ⇒ Σ⁰₁ ⇒ decidable — the
    inclusion chain RCA₀ ⊆ ACA₀ ⊆ … ⊆ Z₂ as conditions on D.
  * The full ω-model D = P(ℕ) satisfies all; the empty D fails even
    decidable comprehension. WKL₀, ATR₀, Π¹₁-CA₀ are further class values
    (cited).

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: D ⊆ (ℕ → Prop) (Prop-valued predicates).
-/

namespace Found

namespace RM

def DecP (P : Nat → Prop) : Prop := ∀ n, P n ∨ ¬ P n

def Sigma1 (P : Nat → Prop) : Prop := ∃ Q : Nat → Nat → Prop, (∀ n m, Q n m ∨ ¬ Q n m) ∧ ∀ n, P n ↔ ∃ m, Q n m

def Comp (C : (Nat → Prop) → Prop) (D : (Nat → Prop) → Prop) : Prop :=
  ∀ P, C P → ∃ X, D X ∧ ∀ n, X n ↔ P n

theorem comp_mono {C C' : (Nat → Prop) → Prop} (h : ∀ P, C P → C' P) (D : (Nat → Prop) → Prop) :
    Comp C' D → Comp C D := fun k P hP => k P (h P hP)

theorem dec_sigma1 (P : Nat → Prop) (h : DecP P) : Sigma1 P :=
  ⟨fun n _ => P n, fun n _ => h n, fun _ => ⟨fun p => ⟨0, p⟩, fun ⟨_, p⟩ => p⟩⟩

/-- the chain: Z₂-comprehension ⇒ Σ⁰₁ ⇒ decidable -/
theorem chain (D : (Nat → Prop) → Prop) (h : Comp (fun _ => True) D) :
    Comp Sigma1 D ∧ Comp DecP D :=
  ⟨comp_mono (fun _ _ => trivial) D h, comp_mono (fun _ _ => trivial) D h⟩

theorem full_model : Comp (fun _ => True) (fun _ => True) := fun P _ => ⟨P, trivial, fun _ => Iff.rfl⟩

theorem empty_fails : ¬ Comp DecP (fun _ => False) :=
  fun h => match h (fun _ => True) (fun _ => Or.inl trivial) with
  | ⟨_, f, _⟩ => f

end RM

end Found

#print axioms Found.RM.comp_mono
#print axioms Found.RM.dec_sigma1
#print axioms Found.RM.chain
#print axioms Found.RM.full_model
#print axioms Found.RM.empty_fails

#print axioms: 5 theorems, no axioms.

85.75 Hyperdoctrines

A hyperdoctrine assigns Heyting algebras of predicates to objects with reindexing and both quantifier adjoints; setoids with respecting predicates form one, and the quantifiers are monotone in any hyperdoctrine. \(\exists _f\dashv f^*\dashv \forall _f\Rightarrow \exists _f,\forall _f\ \text {monotone}\).

found/Fibration.lean

/-
  T151. found/Fibration — Lawvere's hyperdoctrines as a structure on the
  category parameter C: for each object a Heyting algebra of "predicates",
  reindexing along maps, and left/right adjoints ∃_f ⊣ f* ⊣ ∀_f.
  (Fibrations in general are the Grothendieck construction of such indexed
  data — cited; here the indexed form.)
  * Instance: the setoid stem with respecting predicates (T63 SubHA) and
    T73's ∃/∀ (no re-proofs).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.HigherOrder

namespace Found

namespace Hyper

universe u v w

structure Hyperdoctrine (C : ECat.{u, v}) where
  P : C.Ob → HA.{w}
  pull : {a b : C.Ob} → C.Hom a b → (P b).car → (P a).car
  ex : {a b : C.Ob} → C.Hom a b → (P a).car → (P b).car
  all : {a b : C.Ob} → C.Hom a b → (P a).car → (P b).car
  ex_adj : ∀ {a b} (f : C.Hom a b) (φ : (P a).car) (ψ : (P b).car),
    (P b).le (ex f φ) ψ ↔ (P a).le φ (pull f ψ)
  all_adj : ∀ {a b} (f : C.Hom a b) (ψ : (P b).car) (φ : (P a).car),
    (P a).le (pull f ψ) φ ↔ (P b).le ψ (all f φ)

/-- the setoid hyperdoctrine -/
def setoidHD : Hyperdoctrine SetdCat.{0} where
  P X := SubHA X
  pull f ψ := HO.pull f ψ
  ex f φ := HO.exF f φ
  all f φ := HO.allF f φ
  ex_adj f φ ψ := HO.ex_adj f φ ψ
  all_adj f ψ φ := HO.all_adj f ψ φ

/-- in any hyperdoctrine, ∃_f is monotone (from the adjunction alone) -/
theorem ex_mono {C : ECat.{u, v}} (H : Hyperdoctrine.{u, v, w} C) {a b : C.Ob} (f : C.Hom a b)
    {φ φ' : (H.P a).car} (h : (H.P a).le φ φ') : (H.P b).le (H.ex f φ) (H.ex f φ') :=
  (H.ex_adj f φ _).mpr ((H.P a).le_trans h ((H.ex_adj f φ' _).mp ((H.P b).le_refl _)))

/-- and ∀_f is monotone -/
theorem all_mono {C : ECat.{u, v}} (H : Hyperdoctrine.{u, v, w} C) {a b : C.Ob} (f : C.Hom a b)
    {φ φ' : (H.P a).car} (h : (H.P a).le φ φ') : (H.P b).le (H.all f φ) (H.all f φ') :=
  (H.all_adj f _ φ').mp ((H.P a).le_trans ((H.all_adj f _ φ).mpr ((H.P b).le_refl _)) h)

end Hyper

end Found

#print axioms Found.Hyper.setoidHD
#print axioms Found.Hyper.ex_mono
#print axioms Found.Hyper.all_mono

#print axioms: 3 theorems, no axioms.

85.76 Nominal sets and FM set theory

Sets with an action of atom permutations in which each element has a finite support form nominal sets; the atoms are nominal and products of nominal sets are nominal, with the union of supports. \(\mathrm {supp}(x,y)\subseteq \mathrm {supp}(x)\cup \mathrm {supp}(y)\).

found/Nominal.lean

/-
  T110. found/Nominal — Fraenkel–Mostowski / nominal sets as a point: a set
  with an action of atom permutations (a parameter) in which every element
  has a finite support.
  * Permutations of atoms (functions with a two-sided inverse, compared
    pointwise — no funext).
  * Nominal sets; the atoms are nominal (support {a}); products of nominal
    sets are nominal (support = union).
  The Schanuel topos and FM set theory (atoms + finite support) are the
  known lines (cited).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Compactness

namespace Found

namespace Nom

structure Perm where
  f : Nat → Nat
  g : Nat → Nat
  fg : ∀ a, f (g a) = a
  gf : ∀ a, g (f a) = a

structure NSet where
  X : Type
  act : Perm → X → X
  resp : ∀ π σ, (∀ a, π.f a = σ.f a) → ∀ x, act π x = act σ x

def Fixes (π : Perm) (S : List Nat) : Prop := ∀ a, a ∈ S → π.f a = a

def Supports (N : NSet) (S : List Nat) (x : N.X) : Prop := ∀ π, Fixes π S → N.act π x = x

def Nominal (N : NSet) : Prop := ∀ x, ∃ S, Supports N S x

def atoms : NSet := ⟨Nat, fun π a => π.f a, fun _ _ h a => h a⟩

theorem atoms_nominal : Nominal atoms := fun a => ⟨[a], fun _ h => h a (.head _)⟩

def prod (N M : NSet) : NSet :=
  ⟨N.X × M.X, fun π p => (N.act π p.1, M.act π p.2),
   fun π σ h p => by
     show (N.act π p.1, M.act π p.2) = (N.act σ p.1, M.act σ p.2)
     rw [N.resp π σ h p.1, M.resp π σ h p.2]⟩

theorem prod_nominal (N M : NSet) (hN : Nominal N) (hM : Nominal M) : Nominal (prod N M) :=
  fun p => match hN p.1, hM p.2 with
  | ⟨S, hS⟩, ⟨T, hT⟩ => ⟨S ++ T, fun π h => by
      show (N.act π p.1, M.act π p.2) = p
      rw [hS π (fun a m => h a (Prp.mem_app_l m)), hT π (fun a m => h a (Prp.mem_app_r S m))]
      rfl⟩

end Nom

end Found

#print axioms Found.Nom.atoms_nominal
#print axioms Found.Nom.prod_nominal

#print axioms: 2 theorems, no axioms.

85.77 Brouwer’s intuitionism

Under the weak continuity principle for choice sequences, excluded middle for the statement that a sequence is identically zero fails: the classical and Brouwerian conditions clash. \(\mathrm {WC\text {-}N}\Rightarrow \neg \forall \alpha \,(\forall k\,\alpha k=0\vee \neg \forall k\,\alpha k=0)\).

found/Brouwer.lean

/-
  T197. found/Brouwer — Brouwer's intuitionism as a point: choice sequences
  (Baire space ℕ → ℕ, the core's function space on the NNO) with the weak
  continuity condition WC-N as a parameter condition.
  * WC-N: if ∀α ∃n P(α,n) then for each α there are m, n such that every β
    agreeing with α below m has P(β,n).
  * WC-N refutes excluded middle for "α is identically 0" (Π⁰₁ LEM):
    the clash Brouwer ⟂ classical, as a condition clash.
  Fan theorem / bar induction are further conditions (cited); Markov's
  principle (T198) is the Russian point that Brouwer rejects.

  Lean 4 core only, hand-written proofs, no axioms (WC-N is a hypothesis).
-/

namespace Found

namespace Brouwer

def Agree (α β : Nat → Nat) (m : Nat) : Prop := ∀ k, k < m → α k = β k

def WCN : Prop :=
  ∀ P : (Nat → Nat) → Nat → Prop, (∀ α, ∃ n, P α n) →
    ∀ α, ∃ m n, ∀ β, Agree α β m → P β n

def zero : Nat → Nat := fun _ => 0

/-- β: zero below m, one from m on -/
def bump : Nat → Nat → Nat
  | 0, _ => 1
  | _ + 1, 0 => 0
  | m + 1, k + 1 => bump m k

theorem bump_lt : (m k : Nat) → k < m → bump m k = 0
  | 0, _, h => (Nat.not_lt_zero _ h).elim
  | _ + 1, 0, _ => rfl
  | m + 1, k + 1, h => bump_lt m k (Nat.lt_of_succ_lt_succ h)

theorem bump_self : (m : Nat) → bump m m = 1
  | 0 => rfl
  | m + 1 => bump_self m

theorem bump_agree (m : Nat) : Agree zero (bump m) m := fun k h => (bump_lt m k h).symm

theorem bump_not_zero (m : Nat) : ¬ ∀ k, bump m k = 0 := fun h =>
  Nat.noConfusion ((bump_self m).symm.trans (h m))

/-- WC-N refutes ∀α (α ≡ 0 ∨ ¬ α ≡ 0) -/
theorem wcn_not_lem (hw : WCN) : ¬ ∀ α : Nat → Nat, (∀ k, α k = 0) ∨ ¬ (∀ k, α k = 0) := by
  intro lem
  let P : (Nat → Nat) → Nat → Prop := fun α n =>
    (n = 0 ∧ ∀ k, α k = 0) ∨ (n = 1 ∧ ¬ ∀ k, α k = 0)
  have hP : ∀ α, ∃ n, P α n := fun α =>
    (lem α).elim (fun h => ⟨0, Or.inl ⟨rfl, h⟩⟩) (fun h => ⟨1, Or.inr ⟨rfl, h⟩⟩)
  match hw P hP zero with
  | ⟨m, n, h⟩ =>
    have hz : P zero n := h zero (fun _ _ => rfl)
    have hb : P (bump m) n := h (bump m) (bump_agree m)
    exact hz.elim
      (fun ⟨e0, _⟩ => hb.elim (fun ⟨_, hk⟩ => bump_not_zero m hk)
        (fun ⟨e1, _⟩ => Nat.noConfusion (e0.symm.trans e1)))
      (fun ⟨_, nz⟩ => nz (fun _ => rfl))

end Brouwer

end Found

#print axioms Found.Brouwer.bump_lt
#print axioms Found.Brouwer.bump_agree
#print axioms Found.Brouwer.bump_not_zero
#print axioms Found.Brouwer.wcn_not_lem

#print axioms: 4 theorems, no axioms.

85.78 Positive set theory

On the same structure parameter as NF, comprehension for positive formulas yields a universal set containing itself and binary unions and intersections; Russell’s formula is not positive. \(\exists V\,(\forall x\,x\in V)\wedge V\in V;\quad a\cup b,\ a\cap b\).

found/GPK.lean

/-
  T164. found/GPK — positive set theory as a point: comprehension for
  positive formulas (no negation, no implication) on a structure (M, ∈),
  the same free parameter as NF (T106).
  * Positive formulas: ∈, =, ∧, ∨, ∀, ∃.
  * Consequences: a universal set with V ∈ V, binary unions and
    intersections; Russell's formula is not positive (and its comprehension
    is contradictory, T106 reused).
  Models of GPK⁺ (Esser, topological) are cited.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.NF

namespace Found

namespace GPK

universe u

inductive PF where
  | mem : Nat → Nat → PF
  | eq : Nat → Nat → PF
  | and : PF → PF → PF
  | or : PF → PF → PF
  | all : Nat → PF → PF
  | ex : Nat → PF → PF

variable {M : Type u} (mem : M → M → Prop)

def sat : (Nat → M) → PF → Prop
  | ρ, .mem i j => mem (ρ i) (ρ j)
  | ρ, .eq i j => ρ i = ρ j
  | ρ, .and a b => sat ρ a ∧ sat ρ b
  | ρ, .or a b => sat ρ a ∨ sat ρ b
  | ρ, .all n a => ∀ m, sat (NF.upd ρ n m) a
  | ρ, .ex n a => ∃ m, sat (NF.upd ρ n m) a

def PosComp : Prop := ∀ φ : PF, ∀ ρ : Nat → M, ∃ y, ∀ x, mem x y ↔ sat mem (NF.upd ρ 0 x) φ

variable {mem}

theorem univ (h : PosComp mem) (m : M) : ∃ V, (∀ x, mem x V) ∧ mem V V :=
  match h (.eq 0 0) (fun _ => m) with
  | ⟨V, hV⟩ => ⟨V, fun x => (hV x).mpr rfl, (hV V).mpr rfl⟩

theorem union (h : PosComp mem) (a b : M) : ∃ c, ∀ x, mem x c ↔ mem x a ∨ mem x b :=
  match h (.or (.mem 0 1) (.mem 0 2)) (fun k => match k with | 1 => a | _ => b) with
  | ⟨c, hc⟩ => ⟨c, hc⟩

theorem inter (h : PosComp mem) (a b : M) : ∃ c, ∀ x, mem x c ↔ mem x a ∧ mem x b :=
  match h (.and (.mem 0 1) (.mem 0 2)) (fun k => match k with | 1 => a | _ => b) with
  | ⟨c, hc⟩ => ⟨c, hc⟩

end GPK

end Found

#print axioms Found.GPK.univ
#print axioms Found.GPK.union
#print axioms Found.GPK.inter

#print axioms: 3 theorems, no axioms.

85.79 Dialectica interpretation

De Paiva’s Dialectica category, with objects \((U,X,\alpha )\) and morphisms \((f,F)\) satisfying \(\alpha (u,Fuy)\to \beta (fu,y)\), is an E-category, and its morphisms are exactly Gödel’s Dialectica translation of implication. \(\mathrm {Hom}(A,B)\ne \varnothing \iff \exists f,F\,\forall u,y,\ \alpha (u,Fuy)\to \beta (fu,y)\).

found/Dialectica.lean

/-
  T180. found/Dialectica — Gödel's Dialectica interpretation as a point:
  de Paiva's Dialectica category Dial is an instance of the category
  parameter (setoid homs, pointwise).
  * Objects (U, X, α ⊆ U × X): a formula ∃u ∀x α(u, x) in Dialectica form.
  * Morphisms (f : U → V, F : U → Y → X) with α(u, F u y) → β(f u, y):
    exactly the Dialectica translation of implication (∃f,F ∀u,y).
  * Dial is an E-category; it is a model of linear logic (cited), the line
    Dialectica ↔ linear logic (T68); modified realizability is the
    analogous construction with realizers (T96).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Base

namespace Found

namespace Dial

universe u

structure Obj where
  U : Type u
  X : Type u
  α : U → X → Prop

structure Hom (A B : Obj.{u}) where
  f : A.U → B.U
  F : A.U → B.X → A.X
  cond : ∀ u y, A.α u (F u y) → B.α (f u) y

def Dial : ECat.{u + 1, u} where
  Ob := Obj.{u}
  Hom := Hom
  heq h k := (∀ u, h.f u = k.f u) ∧ ∀ u y, h.F u y = k.F u y
  hrefl _ := ⟨fun _ => rfl, fun _ _ => rfl⟩
  hsymm h := ⟨fun u => (h.1 u).symm, fun u y => (h.2 u y).symm⟩
  htrans h k := ⟨fun u => (h.1 u).trans (k.1 u), fun u y => (h.2 u y).trans (k.2 u y)⟩
  id _ := ⟨fun u => u, fun _ x => x, fun _ _ h => h⟩
  comp h k := ⟨fun u => k.f (h.f u), fun u z => h.F u (k.F (h.f u) z),
    fun u z a => k.cond (h.f u) z (h.cond u (k.F (h.f u) z) a)⟩
  comp_resp {_ _ _ h h' k k'} e e' :=
    ⟨fun u => (congrArg k.f (e.1 u)).trans (e'.1 (h'.f u)),
     fun u z => (congrArg (h.F u) ((congrArg (fun v => k.F v z) (e.1 u)).trans (e'.2 (h'.f u) z))).trans
       (e.2 u (k'.F (h'.f u) z))⟩
  id_comp _ := ⟨fun _ => rfl, fun _ _ => rfl⟩
  comp_id _ := ⟨fun _ => rfl, fun _ _ => rfl⟩
  assoc _ _ _ := ⟨fun _ => rfl, fun _ _ => rfl⟩

/-- the Dialectica reading of a morphism: ∃ f F, ∀ u y, α(u, F u y) → β(f u, y) -/
theorem hom_is_dialectica (A B : Obj.{u}) :
    Nonempty (Hom A B) ↔ ∃ (f : A.U → B.U) (F : A.U → B.X → A.X), ∀ u y, A.α u (F u y) → B.α (f u) y :=
  ⟨fun ⟨h⟩ => ⟨h.f, h.F, h.cond⟩, fun ⟨f, F, c⟩ => ⟨⟨f, F, c⟩⟩⟩

end Dial

end Found

#print axioms Found.Dial.Dial
#print axioms Found.Dial.hom_is_dialectica

#print axioms: 2 theorems, no axioms.

85.80 CIC (Lean) as a point

The meta-language is one point: its impredicative Prop, definitional proof irrelevance, uniqueness of identity proofs, transport by subsingleton elimination and universe hierarchy are each shown, matching the CIC marks on the other files. \(p,q:P\Rightarrow p\equiv q;\quad p,q:a=b\Rightarrow p=q\).

found/CIC.lean

/-
  T99. found/CIC — the calculus of inductive constructions (Lean itself) as
  one point among the others; we use it as the meta-language (marked on the
  map). Its distinguishing conditions, each shown here:
  * impredicative Prop (∀ over Prop stays in Prop);
  * definitional proof irrelevance (any two proofs of P are equal by rfl);
  * subsingleton (large) elimination only: Eq can transport data; this is
    the CIC fact used for UIP;
  * universes are a hierarchy Type u : Type (u+1) (T104 uses it).
  These are exactly the "CIC dependence" marks in the other files; Cubical Agda
  (predicative, proof-relevant) is the contrasting point (agda/Core.agda).

  Lean 4 core only, no axioms.
  CIC dependence: this whole file is about the properties of CIC themselves.
-/

namespace Found

namespace CICPoint

universe u

/-- impredicativity: a proposition quantifying over all propositions -/
def ImpProp : Prop := ∀ P : Prop, P → P

theorem impProp_holds : ImpProp := fun _ p => p

/-- definitional proof irrelevance -/
theorem proof_irrel (P : Prop) (p q : P) : p = q := rfl

/-- uniqueness of identity proofs follows -/
theorem uip {A : Sort u} {a b : A} (p q : a = b) : p = q := rfl

/-- subsingleton elimination: Eq transports data -/
def transport {A : Sort u} (B : A → Sort u) {a b : A} (e : a = b) (x : B a) : B b := e ▸ x

theorem transport_refl {A : Sort u} (B : A → Sort u) (a : A) (x : B a) : transport B rfl x = x := rfl

/-- the universe hierarchy -/
def tower : Type 1 := Type

end CICPoint

end Found

#print axioms Found.CICPoint.impProp_holds
#print axioms Found.CICPoint.proof_irrel
#print axioms Found.CICPoint.uip
#print axioms Found.CICPoint.transport_refl

#print axioms: 4 theorems, no axioms.

85.81 Finitism

Finitist (primitive recursive) arithmetic contains multiplication, defined by primitive recursion from addition, with the expected values. \(\mathrm {eval}(\mathrm {mul})[n,y]=n\cdot y\).

found/Finitism.lean

/-
  T200. found/Finitism — finitism as a point: Tait's thesis identifies
  finitist functions with the primitive recursive ones (PRA); the
  ultrafinitist point drops totality of iteration (cited).
  * Multiplication is primitive recursive, built on addition (T81), with
    the expected values: the finitist arithmetic is closed under the core's
    induction on ℕ (T59) used only through PR schemes.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Recursive

namespace Found

namespace Rec

/-- mul(0, y) = 0, mul(n+1, y) = add(mul(n, y), y) -/
def mulPR : PR := .prec .zero (.comp addPR [.proj 1, .proj 2])

theorem mul_correct (y : Nat) : ∀ n, eval mulPR [n, y] = n * y
  | 0 => (Nat.zero_mul y).symm
  | n + 1 => by
    show precIter (eval .zero) (eval (.comp addPR [.proj 1, .proj 2])) (n + 1) [y] = (n + 1) * y
    show eval addPR [precIter (eval .zero) (eval (.comp addPR [.proj 1, .proj 2])) n [y], y] = _
    have ih : precIter (eval .zero) (eval (.comp addPR [.proj 1, .proj 2])) n [y] = n * y := mul_correct y n
    rw [ih, add_correct, Nat.succ_mul]

end Rec

end Found

#print axioms Found.Rec.mul_correct

#print axioms: 1 theorems, no axioms.

85.82 Two-level type theory

Outer strict equality yields inner interval paths and strictly constant paths yield outer equalities, while on the two-point interval the identity is an inner path between distinct points. \(a=b\Rightarrow \mathrm {Path}(a,b);\quad \mathrm {Path}_{\mathbf 2}(0,1)\ne \varnothing ,\ 0\ne 1\).

found/TwoLevel.lean

/-
  T122. found/TwoLevel — two-level type theory as a point: an outer strict
  equality (Lean's Eq, with UIP — T99) and an inner path equality given by
  an interval parameter (T127 OP1).
  * Strict equality gives inner paths (ofEq), compatible with composition
    by Eq: the outer level controls the inner one.
  * Inner paths need not be strict: on the two-point interval a non-constant
    map gives a path between distinct points (the outer/inner split).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.OrtonPitts

namespace Found

namespace TwoL

open OP

/-- outer equality ⇒ inner path -/
def outerToInner (J : Interval) {A : Type} {a b : A} (e : a = b) : Path J A a b := ofEq J e

/-- a path that is strictly constant comes from an outer equality -/
theorem innerConstToOuter (J : Interval) {A : Type} {a b : A} (q : Path J A a b)
    (h : ∀ i, q.p i = q.p J.i0) : a = b := eq_of_const J q h

/-- on the two-point interval, the identity map is an inner path between the distinct
  endpoints — inner paths are finer than outer equality -/
def nonstrict : Path two Two Two.o Two.l := ⟨fun i => i, rfl, rfl⟩

theorem nonstrict_distinct : (Two.o : Two) ≠ Two.l := fun e => Two.noConfusion e

end TwoL

end Found

#print axioms Found.TwoL.outerToInner
#print axioms Found.TwoL.innerConstToOuter
#print axioms Found.TwoL.nonstrict
#print axioms Found.TwoL.nonstrict_distinct

#print axioms: 4 theorems, no axioms.

85.83 Observational type theory

Equality defined by type structure is the setoid equality of the core: pointwise on functions, componentwise on pairs and logical equivalence on propositions, so function and propositional extensionality hold by definition. \(f\approx _{X\Rightarrow Y}g\iff \forall x,\ fx\approx gx;\quad p\approx _\Omega q\iff (p\leftrightarrow q)\).

found/OTT.lean

/-
  T121. found/OTT — observational type theory as a point: equality is
  defined by the structure of the type (on Π pointwise, on Σ componentwise,
  on Prop by ↔), which is exactly the core's setoid stem (T59).
  * On function setoids the observational equality is pointwise: funext is
    a definitional theorem (Lean's Eq would need the funext axiom, T62).
  * On Ω it is ↔: propositional extensionality is definitional too.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Core

namespace Found

namespace OTT

open Core

universe u

theorem funext_obs {X Y : Setd.{u}} (f g : SHom X Y) (h : ∀ x, Y.eqv (f.fn x) (g.fn x)) :
    (expS X Y).eqv f g := h

theorem prop_ext_obs (p q : Prop) (h : p ↔ q) : (OmegaU.{u}).eqv ⟨p⟩ ⟨q⟩ := h

theorem pair_obs {X Y : Setd.{u}} (a b : (prodS X Y).car) (h1 : X.eqv a.1 b.1) (h2 : Y.eqv a.2 b.2) :
    (prodS X Y).eqv a b := ⟨h1, h2⟩

end OTT

end Found

#print axioms Found.OTT.funext_obs
#print axioms Found.OTT.prop_ext_obs
#print axioms Found.OTT.pair_obs

#print axioms: 3 theorems, no axioms.

85.84 Beth semantics

On the binary tree of bit strings, holding on a bar above a node is a nucleus on upsets, so Beth truth values (its fixed points) form a Heyting algebra in which every intuitionistic theorem holds. \(j(U)(w)\iff \forall \alpha \ni w\ \exists m,\ \alpha {\restriction }m\in U;\quad \vdash _i\varphi \Rightarrow \top \le \llbracket \varphi \rrbracket _{\mathrm {Beth}}\).

found/Beth.lean

/-
  T148. found/Beth — Beth semantics as a point: on the binary tree of finite
  bit strings (T108's conditions), "U holds on a bar above w" (every infinite
  path through w eventually enters U) is a nucleus on upsets; Beth truth
  values are its fixed points (T108 fixHA), a Heyting algebra — so
  intuitionistic logic is sound for Beth models (T65), and Beth = sheaves for
  the bar topology (T95 line).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Forcing

namespace Found

namespace Beth

open Forcing

def shift (α : Nat → Bool) : Nat → Bool := fun k => α (k + 1)

def pfx : (Nat → Bool) → Nat → List Bool
  | _, 0 => []
  | α, n + 1 => α 0 :: pfx (shift α) n

theorem pre_pfx : (w : List Bool) → ∀ (α : Nat → Bool) (n : Nat), Pre w (pfx α n) → ∃ n', pfx α n' = w
  | [], _, _, _ => ⟨0, rfl⟩
  | b :: w, α, n, h => by
    cases n with
    | zero => cases h
    | succ n =>
      cases h with
      | cons _ h' =>
        match pre_pfx w (shift α) n h' with
        | ⟨n', e⟩ => exact ⟨n' + 1, congrArg (List.cons (α 0)) e⟩

theorem pfx_mono : (m k : Nat) → ∀ α, Pre (pfx α m) (pfx α (m + k))
  | 0, _, _ => .nil _
  | m + 1, k, α => by
    rw [Nat.add_right_comm]
    exact .cons (α 0) (pfx_mono m k (shift α))

def bar (U : Modal.Up Pre) (w : List Bool) : Prop :=
  ∀ α : Nat → Bool, (∃ n, pfx α n = w) → ∃ m, U.p (pfx α m)

def barUp (U : Modal.Up Pre) : Modal.Up Pre :=
  ⟨bar U, fun w _ r h α ⟨n, e⟩ =>
    match pre_pfx w α n (e ▸ r) with
    | ⟨n', e'⟩ => h α ⟨n', e'⟩⟩

def barNucleus : Nucleus H2 where
  j := barUp
  infl U w hU α := fun ⟨n, e⟩ => ⟨n, e ▸ hU⟩
  idem U w h α hα := match h α hα with
    | ⟨m, hm⟩ => hm α ⟨m, rfl⟩
  mono {U V} hUV w h α hα := match h α hα with
    | ⟨m, hm⟩ => ⟨m, hUV _ hm⟩
  meet U V w h α hα := match h.1 α hα, h.2 α hα with
    | ⟨m1, h1⟩, ⟨m2, h2⟩ =>
      ⟨m1 + m2, U.up _ _ (pfx_mono m1 m2 α) h1,
        V.up _ _ (by rw [Nat.add_comm]; exact pfx_mono m2 m1 α) h2⟩

/-- Beth truth values: a Heyting algebra -/
def bethHA : HA.{0} := barNucleus.fixHA

/-- soundness of intuitionistic logic in Beth models -/
theorem beth_sound {φ : Prp.Form} (d : Prp.PD true (fun _ => False) φ) (v : Nat → bethHA.car) :
    bethHA.le bethHA.top (Prp.interp bethHA v bethHA.bot φ) :=
  Prp.valid bethHA d v bethHA.bot (fun _ => bethHA.bot_le)

end Beth

end Found

#print axioms Found.Beth.pre_pfx
#print axioms Found.Beth.pfx_mono
#print axioms Found.Beth.barNucleus
#print axioms Found.Beth.bethHA
#print axioms Found.Beth.beth_sound

#print axioms: 5 theorems, no axioms.

85.85 Sets as a topos

Setoids have equalizers with the universal property, and together with the terminal object, products, exponentials, the subobject classifier and the natural numbers object they form an elementary topos with NNO. \(\mathrm {Setoid}\models \text {finite limits}+\Rightarrow +\Omega +\mathbb {N}\).

found/SetTopos.lean

/-
  T92. found/SetTopos — sets ↔ toposes: the setoid stem is an elementary
  topos with a natural numbers object, assembled from the core:
  * finite limits: terminal and products (T62), equalizers (here, a
    subobject from the core);
  * exponentials (T62's setdCCC); subobject classifier (T97, unique);
  * NNO (T86).
  With the classical condition and choice this is the ETCS point (T107);
  the other direction (a well-pointed topos with NNO and choice gives a
  model of bounded Zermelo, Mac Lane) is the line T209.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Classifier
import found.NNO

namespace Found

namespace SetTopos

open Core

/-- equalizers in setoids -/
def eqz {X Y : Setd.{0}} (f g : SHom X Y) : Setd.{0} := Core.subU X (fun x => Y.eqv (f.fn x) (g.fn x))

def eqzMap {X Y : Setd.{0}} (f g : SHom X Y) : SHom (eqz f g) X := ⟨fun x => x.val, fun h => h⟩

theorem eqz_comm {X Y : Setd.{0}} (f g : SHom X Y) :
    SetdCat.heq (SetdCat.comp (eqzMap f g) f) (SetdCat.comp (eqzMap f g) g) := fun x => x.property

def eqzLift {X Y Z : Setd.{0}} (f g : SHom X Y) (h : SHom Z X)
    (hh : SetdCat.heq (SetdCat.comp h f) (SetdCat.comp h g)) : SHom Z (eqz f g) :=
  ⟨fun z => ⟨h.fn z, hh z⟩, fun e => h.resp e⟩

theorem eqzLift_comm {X Y Z : Setd.{0}} (f g : SHom X Y) (h : SHom Z X)
    (hh : SetdCat.heq (SetdCat.comp h f) (SetdCat.comp h g)) :
    SetdCat.heq (SetdCat.comp (eqzLift f g h hh) (eqzMap f g)) h := fun z => X.refl (h.fn z)

theorem eqzLift_uniq {X Y Z : Setd.{0}} (f g : SHom X Y) (h : SHom Z X)
    (hh : SetdCat.heq (SetdCat.comp h f) (SetdCat.comp h g)) (k : SHom Z (eqz f g))
    (hk : SetdCat.heq (SetdCat.comp k (eqzMap f g)) h) : SetdCat.heq k (eqzLift f g h hh) := hk

/-- the topos data, assembled -/
structure ToposNNO where
  term : Terminal SetdCat.{0}
  prod : ∀ X Y : Setd.{0}, Product SetdCat.{0} X Y
  ccc : CCC SetdCat.{0}
  omega : Classif.Classifier.{0}
  nno : NNOs.NNO SetdCat.{0} setdTerminal

def setoids : ToposNNO := ⟨setdTerminal, setdProduct, setdCCC, Classif.coreOmega, NNOs.natNNO⟩

end SetTopos

end Found

#print axioms Found.SetTopos.eqz_comm
#print axioms Found.SetTopos.eqzLift_comm
#print axioms Found.SetTopos.eqzLift_uniq
#print axioms Found.SetTopos.setoids

#print axioms: 4 theorems, no axioms.

85.86 SEAR

With sets as setoids and relations as respecting binary predicates, every relation is tabulated by the subobject of related pairs with jointly monic projections, and relations to the point are the points of the power set. \(R(x,y)\iff \exists t\in |R|,\ \pi _1t\approx x\wedge \pi _2t\approx y\).

found/SEAR.lean

/-
  T147. found/SEAR — Shulman's SEAR (sets, elements, relations) as a point:
  sets = setoids of the core, relations = ≈-respecting binary predicates.
  * Relational comprehension: every respecting predicate on X × Y is a
    relation.
  * Tabulation: every relation is tabulated by a set (the subobject of the
    product, core op 3) with two projections that are jointly monic.
  * Power sets: relations from X to 1 ↔ points of the core's power X ⇒ Ω.
  SEAR ↔ ETCS ↔ ZFC (bounded) are the known equivalences (lines T107, T209).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Core

namespace Found

namespace SEAR

open Core

universe u

structure Rel (X Y : Setd.{u}) where
  R : X.car → Y.car → Prop
  resp : ∀ {x x' y y'}, X.eqv x x' → Y.eqv y y' → R x y → R x' y'

/-- tabulation: the set of related pairs -/
def tab {X Y : Setd.{u}} (r : Rel X Y) : Setd.{u} := Core.subU (prodS X Y) (fun p => r.R p.1 p.2)

def p1 {X Y : Setd.{u}} (r : Rel X Y) : SHom (tab r) X := ⟨fun p => p.val.1, fun h => h.1⟩
def p2 {X Y : Setd.{u}} (r : Rel X Y) : SHom (tab r) Y := ⟨fun p => p.val.2, fun h => h.2⟩

theorem tab_spec {X Y : Setd.{u}} (r : Rel X Y) (x : X.car) (y : Y.car) :
    r.R x y ↔ ∃ t : (tab r).car, X.eqv ((p1 r).fn t) x ∧ Y.eqv ((p2 r).fn t) y :=
  ⟨fun h => ⟨⟨(x, y), h⟩, X.refl x, Y.refl y⟩,
   fun ⟨t, e1, e2⟩ => r.resp e1 e2 t.property⟩

/-- the projections are jointly monic -/
theorem jointly_monic {X Y : Setd.{u}} (r : Rel X Y) (s t : (tab r).car)
    (h1 : X.eqv ((p1 r).fn s) ((p1 r).fn t)) (h2 : Y.eqv ((p2 r).fn s) ((p2 r).fn t)) :
    (tab r).eqv s t := ⟨h1, h2⟩

/-- relations to the one-point set are points of the power set -/
def toPower {X : Setd.{u}} (r : Rel X (unitS.{u})) : (power X).car :=
  ⟨fun x => ⟨r.R x PUnit.unit⟩, fun e => ⟨r.resp e trivial, r.resp (X.symm e) trivial⟩⟩

theorem toPower_spec {X : Setd.{u}} (r : Rel X (unitS.{u})) (x : X.car) :
    ((toPower r).fn x).down ↔ r.R x PUnit.unit := Iff.rfl

end SEAR

end Found

#print axioms Found.SEAR.tab_spec
#print axioms Found.SEAR.jointly_monic
#print axioms Found.SEAR.toPower_spec

#print axioms: 3 theorems, no axioms.

85.87 Universal logic

A logic is a set of formulas with a consequence relation; natural deduction and every truth-preservation consequence over a class of valuations satisfy reflexivity, monotonicity and cut, while preferential consequence fails monotonicity. \(\Gamma \subseteq \Delta \Rightarrow (\Gamma \vdash \varphi \Rightarrow \Delta \vdash \varphi )\) for Tarskian logics; fails for \(\mathrel {|\!\sim }\).

found/UniversalLogic.lean

/-
  T206. found/UniversalLogic — universal logic (Béziau) as a point: a logic
  is any set of formulas with a consequence relation; Tarskian logics satisfy
  reflexivity, monotonicity and cut (a free parameter with conditions).
  * Intuitionistic natural deduction (T65) is Tarskian.
  * Every semantic consequence (truth-preservation in a class of
    valuations: LP, K3, Heyting) is Tarskian.
  * Preferential consequence (T173) is not monotone: it sits outside the
    Tarskian class — the coordinate "monotonicity" separates them.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Minimal
import found.NonMono

namespace Found

namespace UL2

universe u v

structure Logic where
  F : Type u
  cons : (F → Prop) → F → Prop

def Reflexive (L : Logic.{u}) : Prop := ∀ Γ φ, Γ φ → L.cons Γ φ
def Monotone (L : Logic.{u}) : Prop := ∀ Γ Δ φ, (∀ x, Γ x → Δ x) → L.cons Γ φ → L.cons Δ φ
def Cut (L : Logic.{u}) : Prop := ∀ Γ Δ φ, (∀ x, Δ x → L.cons Γ x) → L.cons Δ φ → L.cons Γ φ

structure Tarskian (L : Logic.{u}) : Prop where
  refl : Reflexive L
  mono : Monotone L
  cut : Cut L

/-- intuitionistic natural deduction is Tarskian -/
def nd : Logic.{0} := ⟨Prp.Form, fun Γ φ => Prp.PD true Γ φ⟩

theorem nd_tarskian : Tarskian nd :=
  ⟨fun _ _ g => .hyp g, fun _ _ _ h d => Prp.mono d h, fun _ _ _ h d => Prp.cut d h⟩

/-- semantic consequence over any class of valuations is Tarskian -/
def sem (F : Type u) (Val : Type v) (holds : Val → F → Prop) : Logic.{u} :=
  ⟨F, fun Γ φ => ∀ v, (∀ x, Γ x → holds v x) → holds v φ⟩

theorem sem_tarskian (F : Type u) (Val : Type v) (holds : Val → F → Prop) : Tarskian (sem F Val holds) :=
  ⟨fun _ _ g _ h => h _ g,
   fun _ _ _ h c v hv => c v (fun x g => hv x (h x g)),
   fun _ _ _ h c v hv => c v (fun x g => h x g v hv)⟩

/-- preferential consequence (bird/penguin, T173) is not monotone -/
def prefLogic : Logic.{0} :=
  ⟨Bool → Prop, fun Γ φ => NonMono.nm NonMono.pref (fun w => ∀ ψ, Γ ψ → ψ w) φ⟩

theorem pref_not_monotone : ¬ Monotone prefLogic := fun h =>
  have k := h (fun ψ => ψ = (fun _ => True)) (fun ψ => ψ = (fun _ => True) ∨ ψ = (fun w => w = true))
    (fun w => w = false) (fun _ e => Or.inl e)
    (fun w m => match w, m with
      | false, _ => rfl
      | true, m => (m.2 false ⟨rfl, rfl⟩ (fun _ e => e ▸ trivial)).elim)
  Bool.noConfusion (k true ⟨fun _ e => e.elim (fun e1 => e1 ▸ trivial) (fun e2 => e2 ▸ rfl),
    fun _ hv hA => Bool.noConfusion (hv.1.symm.trans (hA (fun w => w = true) (Or.inr rfl)))⟩)

end UL2

end Found

#print axioms Found.UL2.nd_tarskian
#print axioms Found.UL2.sem_tarskian
#print axioms Found.UL2.pref_not_monotone

#print axioms: 3 theorems, no axioms.

85.88 Institutions

An institution has signatures, sentence and model functors and the satisfaction condition; propositional logic with renamings and reducts is one, the condition proved by induction on formulas. \(M\models \sigma (\varphi )\iff M{\restriction }_\sigma \models \varphi \).

found/Institutions.lean

/-
  T157. found/Institutions — Goguen–Burstall institutions as a point: a
  category of signatures, a sentence functor, a model functor and the
  satisfaction condition (truth is invariant under change of notation).
  * Abstract structure (signatures and morphisms as a parameter).
  * Instance: propositional logic — signatures = atom types, morphisms =
    renamings, sentences = formulas, models = Prop-valuations, reduct =
    precomposition; the satisfaction condition holds (by induction).
  Every logic point of the map with a signature notion is an institution;
  comorphisms are the translations (lines).

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Inst

universe u v w

structure Institution where
  Sig : Type u
  Hom : Sig → Sig → Type v
  Sen : Sig → Type w
  Mod : Sig → Type w
  sen : {S₁ S₂ : Sig} → Hom S₁ S₂ → Sen S₁ → Sen S₂
  red : {S₁ S₂ : Sig} → Hom S₁ S₂ → Mod S₂ → Mod S₁
  sat : (S : Sig) → Mod S → Sen S → Prop
  condition : ∀ {S₁ S₂} (σ : Hom S₁ S₂) (M : Mod S₂) (φ : Sen S₁),
    sat S₂ M (sen σ φ) ↔ sat S₁ (red σ M) φ

inductive PF (A : Type) where
  | atom : A → PF A
  | bot : PF A
  | and : PF A → PF A → PF A
  | or : PF A → PF A → PF A
  | imp : PF A → PF A → PF A

def ren {A B : Type} (σ : A → B) : PF A → PF B
  | .atom a => .atom (σ a)
  | .bot => .bot
  | .and p q => .and (ren σ p) (ren σ q)
  | .or p q => .or (ren σ p) (ren σ q)
  | .imp p q => .imp (ren σ p) (ren σ q)

def sat {A : Type} (v : A → Prop) : PF A → Prop
  | .atom a => v a
  | .bot => False
  | .and p q => sat v p ∧ sat v q
  | .or p q => sat v p ∨ sat v q
  | .imp p q => sat v p → sat v q

theorem condition {A B : Type} (σ : A → B) (v : B → Prop) :
    (φ : PF A) → (sat v (ren σ φ) ↔ sat (fun a => v (σ a)) φ)
  | .atom _ => Iff.rfl
  | .bot => Iff.rfl
  | .and p q => ⟨fun h => ⟨(condition σ v p).mp h.1, (condition σ v q).mp h.2⟩,
                 fun h => ⟨(condition σ v p).mpr h.1, (condition σ v q).mpr h.2⟩⟩
  | .or p q => ⟨fun h => h.elim (fun a => Or.inl ((condition σ v p).mp a)) (fun b => Or.inr ((condition σ v q).mp b)),
                fun h => h.elim (fun a => Or.inl ((condition σ v p).mpr a)) (fun b => Or.inr ((condition σ v q).mpr b))⟩
  | .imp p q => ⟨fun h x => (condition σ v q).mp (h ((condition σ v p).mpr x)),
                 fun h x => (condition σ v q).mpr (h ((condition σ v p).mp x))⟩

def propInst : Institution.{1, 0, 1} where
  Sig := Type
  Hom A B := A → B
  Sen A := ULift (PF A)
  Mod A := ULift (A → Prop)
  sen σ φ := ⟨ren σ φ.down⟩
  red σ M := ⟨fun a => M.down (σ a)⟩
  sat _ M φ := sat M.down φ.down
  condition σ M φ := condition σ M.down φ.down

end Inst

end Found

#print axioms Found.Inst.condition
#print axioms Found.Inst.propInst

#print axioms: 2 theorems, no axioms.

85.89 Combinatory logic

Translating \(K\mapsto \lambda xy.x\) and \(S\mapsto \lambda xyz.xz(yz)\), every weak-reduction step of combinatory logic becomes a \(\beta \)-reduction sequence; bracket abstraction gives the converse direction. \(a\rhd _w b\Rightarrow \mathrm {tr}(a)\to _\beta ^*\mathrm {tr}(b)\).

found/SK.lean

/-
  T80. found/SK — SK combinators as a point and the line SK ↔ λ.
  * CL terms with weak reduction (K x y ▷ x, S x y z ▷ x z (y z), congruences).
  * Translation into the untyped λ-calculus (T78): K ↦ λxy.x,
    S ↦ λxyz.xz(yz); every weak step becomes β-reduction (simulation).
  * The converse direction, λ → SK by bracket abstraction with
    (λe)·x = e[x], is the combinatory completeness of T96 (lam_beta), reused.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.ChurchNum

namespace Found

namespace UL

theorem sub_single_ren {Γ : List Unit} (u : T Γ) (t : T Γ) : sub (single u) (ren V.s t) = t :=
  (sub_ren t _ V.s).trans ((sub_ext t (τ := T.var) (fun _ => rfl)).trans (sub_var t))

theorem sub_liftS_ren {Γ Δ : List Unit} (σ : V Γ → T Δ) (w : T Γ) :
    sub (liftS σ) (ren V.s w) = ren V.s (sub σ w) :=
  (sub_ren w (liftS σ) V.s).trans (ren_sub w V.s σ).symm

def Kt {Γ : List Unit} : T Γ := .lam (.lam (.var (.s .z)))
def St {Γ : List Unit} : T Γ := .lam (.lam (.lam (.app (.app (.var (.s (.s .z))) (.var .z)) (.app (.var (.s .z)) (.var .z)))))

theorem K_beta {Γ : List Unit} (x y : T Γ) : Star Beta (.app (.app Kt x) y) x := by
  have s1 : Beta (.app (Kt (Γ := Γ)) x) (.lam (ren V.s x)) := .beta _ _
  have s2 : Beta (.app (.lam (ren V.s x)) y) x := by
    have b := Beta.beta (ren V.s x) y
    have e : inst (ren V.s x) y = x := sub_single_ren y x
    rw [e] at b
    exact b
  exact .step (.appL y s1) (.one s2)

theorem S_beta {Γ : List Unit} (x y z : T Γ) :
    Star Beta (.app (.app (.app St x) y) z) (.app (.app x z) (.app y z)) := by
  have s1 : Beta (.app (St (Γ := Γ)) x)
      (.lam (.lam (.app (.app (ren V.s (ren V.s x)) (.var .z)) (.app (.var (.s .z)) (.var .z))))) := .beta _ _
  have s2 : Beta (.app (.lam (.lam (.app (.app (ren V.s (ren V.s x)) (.var .z)) (.app (.var (.s .z)) (.var .z))))) y)
      (.lam (.app (.app (ren V.s x) (.var .z)) (.app (ren V.s y) (.var .z)))) := by
    have b := Beta.beta (.lam (.app (.app (ren V.s (ren V.s x)) (.var .z)) (.app (.var (.s .z)) (.var .z)))) y
    have e : inst (.lam (.app (.app (ren V.s (ren V.s x)) (.var .z)) (.app (.var (.s .z)) (.var .z)))) y =
        .lam (.app (.app (ren V.s x) (.var .z)) (.app (ren V.s y) (.var .z))) := by
      show T.lam (T.app (T.app (sub (liftS (single y)) (ren V.s (ren V.s x))) (T.var V.z))
        (T.app (ren V.s y) (T.var V.z))) = _
      rw [sub_liftS_ren, sub_single_ren]
    rw [e] at b
    exact b
  have s3 : Beta (.app (.lam (.app (.app (ren V.s x) (.var .z)) (.app (ren V.s y) (.var .z)))) z)
      (.app (.app x z) (.app y z)) := by
    have b := Beta.beta (.app (.app (ren V.s x) (.var .z)) (.app (ren V.s y) (.var .z))) z
    have e : inst (.app (.app (ren V.s x) (.var .z)) (.app (ren V.s y) (.var .z))) z = .app (.app x z) (.app y z) := by
      show T.app (T.app (sub (single z) (ren V.s x)) z) (T.app (sub (single z) (ren V.s y)) z) = _
      rw [sub_single_ren, sub_single_ren]
    rw [e] at b
    exact b
  exact .step (.appL z (.appL y s1)) (.step (.appL z s2) (.one s3))

end UL

namespace CL

inductive C where
  | K : C
  | S : C
  | app : C → C → C

inductive W : C → C → Prop where
  | k (x y : C) : W (.app (.app .K x) y) x
  | s (x y z : C) : W (.app (.app (.app .S x) y) z) (.app (.app x z) (.app y z))
  | appL {x x'} (y : C) : W x x' → W (.app x y) (.app x' y)
  | appR (x : C) {y y'} : W y y' → W (.app x y) (.app x y')

def tr {Γ : List Unit} : C → UL.T Γ
  | .K => UL.Kt
  | .S => UL.St
  | .app a b => .app (tr a) (tr b)

/-- weak reduction is simulated by β-reduction -/
theorem simulate {Γ : List Unit} {a b : C} (h : W a b) : UL.Star UL.Beta (tr (Γ := Γ) a) (tr b) := by
  induction h with
  | k x y => exact UL.K_beta _ _
  | s x y z => exact UL.S_beta _ _ _
  | appL y _ ih => exact UL.star_appL _ ih
  | appR x _ ih => exact UL.star_appR _ ih

end CL

end Found

#print axioms Found.UL.sub_single_ren
#print axioms Found.UL.sub_liftS_ren
#print axioms Found.UL.K_beta
#print axioms Found.UL.S_beta
#print axioms Found.CL.simulate

#print axioms: 5 theorems, no axioms.

85.90 HOL

Simple types over individuals and propositions interpret in the setoid stem with propositions as \(\Omega \) and arrows as exponentials, where functional and Boolean extensionality hold; HOL’s classical axiom is the excluded-middle condition. \(f\approx g\iff \forall x,\ fx\approx gx;\quad p\approx _o q\iff (p\leftrightarrow q)\).

found/HOL.lean

/-
  T205. found/HOL — Church's simple type theory / HOL as a point: types
  over ι (individuals, a parameter) and o (propositions) interpreted in the
  core's setoid stem: o ↦ Ω, σ → τ ↦ exponential (T59).
  * Extensionality (functional and Boolean) holds in the model by the core's
    equality (no funext/propext axioms).
  * HOL's classical axiom is the LEM condition on Ω (T66); the Hilbert ε
    of Isabelle/HOL is the choice condition (T87) — both as parameters.

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: Ω = ULift Prop.
-/
import found.Core
import found.Classical

namespace Found

namespace HOL

open Core

inductive Ty where
  | ι : Ty
  | o : Ty
  | arr : Ty → Ty → Ty

def interp (I : Setd.{0}) : Ty → Setd.{0}
  | .ι => I
  | .o => OmegaU
  | .arr a b => expS (interp I a) (interp I b)

/-- functional extensionality in every function type -/
theorem fun_ext (I : Setd.{0}) (a b : Ty) (f g : (interp I (.arr a b)).car)
    (h : ∀ x, (interp I b).eqv (f.fn x) (g.fn x)) : (interp I (.arr a b)).eqv f g := h

/-- Boolean extensionality: propositions equal iff equivalent -/
theorem bool_ext (I : Setd.{0}) (p q : (interp I .o).car) (h : p.down ↔ q.down) : (interp I .o).eqv p q := h

/-- the classical axiom of HOL is the LEM condition, i.e. Ω Boolean (T66) -/
theorem classical_condition (lem : ∀ p : Prop, p ∨ ¬ p) : Prp.Boolean OmegaHA :=
  fun p hp => (lem p).elim id (fun n => (hp n).elim)

end HOL

end Found

#print axioms Found.HOL.fun_ext
#print axioms Found.HOL.bool_ext
#print axioms Found.HOL.classical_condition

#print axioms: 3 theorems, no axioms.

85.91 Probability logic

On a finite list of outcomes with Boolean events, the counting measure satisfies inclusion–exclusion, the complement law and monotonicity, proved by induction and hand rearrangement. \(\mu (A\vee B)+\mu (A\wedge B)=\mu A+\mu B;\quad \mu A+\mu \neg A=|\Omega |\).

found/ProbLogic.lean

/-
  T174. found/ProbLogic — probability logic as a point: a finite outcome
  space (a list, a parameter), events = Boolean predicates (the classical
  truth values on decidable events), the counting measure (numerator over
  the length of the list).
  * Inclusion–exclusion: μ(A ∨ B) + μ(A ∧ B) = μ(A) + μ(B).
  * Complement: μ(A) + μ(¬A) = |Ω|.  Monotonicity: A ⊆ B ⇒ μ(A) ≤ μ(B).
  Real-valued and σ-additive probability (Kolmogorov) and probabilistic
  logics with ℝ are lines to Bishop's analysis (T118, cited).

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Prob

universe u

variable {Ω : Type u}

def ind (b : Bool) : Nat := match b with | true => 1 | false => 0

def mu (A : Ω → Bool) : List Ω → Nat
  | [] => 0
  | w :: l => ind (A w) + mu A l

theorem rearr (c x d y : Nat) : (c + x) + (d + y) = (c + d) + (x + y) := by
  rw [Nat.add_assoc, Nat.add_left_comm x d y, ← Nat.add_assoc]

theorem incl_excl (A B : Ω → Bool) : (l : List Ω) →
    mu (fun w => A w || B w) l + mu (fun w => A w && B w) l = mu A l + mu B l
  | [] => rfl
  | w :: l => by
    have ih := incl_excl A B l
    show (ind (A w || B w) + mu (fun w => A w || B w) l) + (ind (A w && B w) + mu (fun w => A w && B w) l) =
        (ind (A w) + mu A l) + (ind (B w) + mu B l)
    rw [rearr (ind (A w || B w)) _ (ind (A w && B w)) _, rearr (ind (A w)) _ (ind (B w)) _, ih]
    cases A w <;> cases B w <;> rfl

theorem complement (A : Ω → Bool) : (l : List Ω) → mu A l + mu (fun w => !A w) l = l.length
  | [] => rfl
  | w :: l => by
    have ih := complement A l
    show (ind (A w) + mu A l) + (ind (!A w) + mu (fun w => !A w) l) = l.length + 1
    rw [rearr (ind (A w)) _ (ind (!A w)) _, ih]
    cases A w
    · show 0 + 1 + l.length = l.length + 1
      rw [Nat.add_comm]
    · show 1 + 0 + l.length = l.length + 1
      rw [Nat.add_comm]

theorem monotone (A B : Ω → Bool) (h : ∀ w, A w = true → B w = true) : (l : List Ω) → mu A l ≤ mu B l
  | [] => Nat.le_refl 0
  | w :: l => by
    have ih := monotone A B h l
    show ind (A w) + mu A l ≤ ind (B w) + mu B l
    cases ha : A w with
    | true => rw [h w ha]; exact Nat.add_le_add (Nat.le_refl 1) ih
    | false => exact Nat.add_le_add (Nat.zero_le _) ih

end Prob

end Found

#print axioms Found.Prob.rearr
#print axioms Found.Prob.incl_excl
#print axioms Found.Prob.complement
#print axioms Found.Prob.monotone

#print axioms: 4 theorems, no axioms.

85.92 2-categories

Natural transformations between functors of E-categories compose horizontally, the horizontal composite is natural, and the interchange law holds up to the hom equivalence. \((\beta '\circ \beta )*(\alpha '\circ \alpha )\simeq (\beta '*\alpha ')\circ (\beta *\alpha )\).

found/Higher2.lean

/-
  T193. found/Higher2 — 2-categories as a point: E-categories, functors and
  natural transformations (T61) form a strict 2-category up to ≈.
  * Horizontal composition β ∗ α and its naturality.
  * The interchange law (β' ∘ β) ∗ (α' ∘ α) ≈ (β' ∗ α') ∘ (β ∗ α).
  Double, enriched and multicategories/operads and string diagrams are the
  known variations (cited lines).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Cat

namespace Found

namespace TwoCat

universe u v u' v' u'' v''

variable {C : ECat.{u, v}} {D : ECat.{u', v'}} {E : ECat.{u'', v''}}

/-- horizontal composition component: H(α_a) ; β_{G a} -/
def hcomp {F G : EFun C D} {H K : EFun D E} (α : NatTr F G) (β : NatTr H K) (a : C.Ob) :
    E.Hom (H.obj (F.obj a)) (K.obj (G.obj a)) :=
  E.comp (H.map (α.app a)) (β.app (G.obj a))

/-- the interchange law -/
theorem interchange {F G G' : EFun C D} {H K K' : EFun D E}
    (α : NatTr F G) (α' : NatTr G G') (β : NatTr H K) (β' : NatTr K K') (a : C.Ob) :
    E.heq (hcomp (NatTr.vcomp α α') (NatTr.vcomp β β') a)
      (E.comp (hcomp α β a) (hcomp α' β' a)) := by
  show E.heq (E.comp (H.map (D.comp (α.app a) (α'.app a))) (E.comp (β.app (G'.obj a)) (β'.app (G'.obj a))))
    (E.comp (E.comp (H.map (α.app a)) (β.app (G.obj a))) (E.comp (K.map (α'.app a)) (β'.app (G'.obj a))))
  exact E.htrans (E.lcong (H.map_comp _ _) _)
    (E.htrans (E.assoc _ _ _)
    (E.htrans (E.rcong _ (E.hsymm (E.assoc _ _ _)))
    (E.htrans (E.rcong _ (E.lcong (β.nat (α'.app a)) _))
    (E.htrans (E.rcong _ (E.assoc _ _ _))
    (E.hsymm (E.assoc _ _ _))))))

/-- horizontal composites are natural -/
theorem hcomp_nat {F G : EFun C D} {H K : EFun D E} (α : NatTr F G) (β : NatTr H K) {a b : C.Ob}
    (f : C.Hom a b) :
    E.heq (E.comp (H.map (F.map f)) (hcomp α β b)) (E.comp (hcomp α β a) (K.map (G.map f))) := by
  show E.heq (E.comp (H.map (F.map f)) (E.comp (H.map (α.app b)) (β.app (G.obj b))))
    (E.comp (E.comp (H.map (α.app a)) (β.app (G.obj a))) (K.map (G.map f)))
  exact E.htrans (E.hsymm (E.assoc _ _ _))
    (E.htrans (E.lcong (E.hsymm (H.map_comp _ _)) _)
    (E.htrans (E.lcong (H.map_resp (α.nat f)) _)
    (E.htrans (E.lcong (H.map_comp _ _) _)
    (E.htrans (E.assoc _ _ _)
    (E.htrans (E.rcong _ (β.nat (G.map f)))
    (E.hsymm (E.assoc _ _ _)))))))

end TwoCat

end Found

#print axioms Found.TwoCat.interchange
#print axioms Found.TwoCat.hcomp_nat

#print axioms: 2 theorems, no axioms.

85.93 HA\(\omega \) and Gödel’s T

Intrinsically typed terms of Gödel’s T over finite types evaluate in the standard model, satisfy the recursor equations definitionally, and define addition correctly. \(R\,a\,f\,0=a,\quad R\,a\,f\,(Sn)=f\,n\,(R\,a\,f\,n)\).

found/HAomega.lean

/-
  T187. found/HAomega — higher-type arithmetic HAω and Gödel's T as a point:
  finite types over ℕ (the core's function space on the NNO), intrinsically
  typed terms with 0, S and the recursor, evaluated in the standard model
  (types ↦ Lean types).
  * Every T-term denotes (totality of Gödel's T in the standard model).
  * The recursor equations hold: R a f 0 = a, R a f (S n) = f n (R a f n).
  * Primitive recursion (T81) is the first-order part; Dialectica (T180)
    interprets HA in T (cited line).

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace GodelT

inductive Ty where
  | nat : Ty
  | arr : Ty → Ty → Ty

def den : Ty → Type
  | .nat => Nat
  | .arr a b => den a → den b

inductive Var : List Ty → Ty → Type where
  | z {Γ a} : Var (a :: Γ) a
  | s {Γ a b} : Var Γ a → Var (b :: Γ) a

inductive Tm : List Ty → Ty → Type where
  | var {Γ a} : Var Γ a → Tm Γ a
  | lam {Γ a b} : Tm (a :: Γ) b → Tm Γ (.arr a b)
  | app {Γ a b} : Tm Γ (.arr a b) → Tm Γ a → Tm Γ b
  | zero {Γ} : Tm Γ .nat
  | succ {Γ} : Tm Γ (.arr .nat .nat)
  | recT {Γ a} : Tm Γ a → Tm Γ (.arr .nat (.arr a a)) → Tm Γ (.arr .nat a)

def Env : List Ty → Type
  | [] => Unit
  | a :: Γ => den a × Env Γ

def look : {Γ : List Ty} → {a : Ty} → Var Γ a → Env Γ → den a
  | _ :: _, _, .z, ρ => ρ.1
  | _ :: _, _, .s v, ρ => look v ρ.2

def recF {A : Type} (a : A) (f : Nat → A → A) : Nat → A
  | 0 => a
  | n + 1 => f n (recF a f n)

def eval : {Γ : List Ty} → {a : Ty} → Tm Γ a → Env Γ → den a
  | _, _, .var v, ρ => look v ρ
  | _, _, .lam t, ρ => fun x => eval t (x, ρ)
  | _, _, .app t u, ρ => (eval t ρ) (eval u ρ)
  | _, _, .zero, _ => (0 : Nat)
  | _, _, .succ, _ => fun (n : Nat) => n + 1
  | _, _, .recT a f, ρ => recF (eval a ρ) (eval f ρ)

theorem rec_zero {Γ : List Ty} {a : Ty} (x : Tm Γ a) (f : Tm Γ (.arr .nat (.arr a a))) (ρ : Env Γ) :
    eval (.app (.recT x f) .zero) ρ = eval x ρ := rfl

theorem rec_succ {Γ : List Ty} {a : Ty} (x : Tm Γ a) (f : Tm Γ (.arr .nat (.arr a a))) (n : Tm Γ .nat) (ρ : Env Γ) :
    eval (.app (.recT x f) (.app .succ n)) ρ = eval f ρ (eval n ρ) (eval (.app (.recT x f) n) ρ) := rfl

/-- addition in T: add = λm. R m (λ_ r. S r) — denotes + -/
def addT : Tm [] (.arr .nat (.arr .nat .nat)) :=
  .lam (.recT (.var .z) (.lam (.lam (.app .succ (.var .z)))))

theorem addT_correct (m : Nat) : ∀ n : Nat, (eval addT () m n : Nat) = m + n
  | 0 => rfl
  | n + 1 => congrArg (fun k : Nat => k + 1) (addT_correct m n)

end GodelT

end Found

#print axioms Found.GodelT.rec_zero
#print axioms Found.GodelT.rec_succ
#print axioms Found.GodelT.addT_correct

#print axioms: 3 theorems, no axioms.

85.94 Categories with families and MLTT

Categories with families are a parameter; the model with types as contexts and families as types satisfies the laws definitionally, interprets \(\Pi \) and \(\Sigma \) with \(\beta \) and \(\eta \), and its identity types reflect into judgmental equality with UIP. \(\mathrm {app}(\lambda t,u)=t[u],\ \lambda (\mathrm {app}\,t)=t;\quad \mathrm {Id}(a,b)\Rightarrow a=b\).

found/CwF.lean

/-
  T152 / T98. found/CwF — semantics of dependent type theory as points:
  categories with families (a free parameter) and the family model of MLTT.
  * CwF: contexts, substitutions, types and terms with substitution actions
    and context extension (p, q, pairing) satisfying the CwF laws.
  * The family model: contexts = types, substitutions = functions,
    types over Γ = families Γ → Type, terms = sections; all laws hold
    definitionally (rfl), no funext.
  * MLTT type formers in the family model: Π and Σ with β and η, Id as
    PLift of Lean's Eq (UIP — the extensional point, T120 line), so MLTT is
    an instance of the CwF parameter.

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: definitional eta (functions, structures), Id = PLift Eq (UIP).
-/

namespace Found

namespace CwF

universe u v

structure CwF where
  Ctx : Type u
  Sub : Ctx → Ctx → Type v
  id : (Γ : Ctx) → Sub Γ Γ
  comp : {Γ Δ Θ : Ctx} → Sub Γ Δ → Sub Δ Θ → Sub Γ Θ
  Ty : Ctx → Type u
  tySub : {Γ Δ : Ctx} → Ty Δ → Sub Γ Δ → Ty Γ
  Tm : (Γ : Ctx) → Ty Γ → Type v
  tmSub : {Γ Δ : Ctx} → {A : Ty Δ} → Tm Δ A → (σ : Sub Γ Δ) → Tm Γ (tySub A σ)
  ext : (Γ : Ctx) → Ty Γ → Ctx
  p : {Γ : Ctx} → (A : Ty Γ) → Sub (ext Γ A) Γ
  ty_id : ∀ {Γ} (A : Ty Γ), tySub A (id Γ) = A
  ty_comp : ∀ {Γ Δ Θ} (A : Ty Θ) (σ : Sub Γ Δ) (τ : Sub Δ Θ), tySub A (comp σ τ) = tySub (tySub A τ) σ

/-! ## the family model -/

def Fam : CwF.{1, 0} where
  Ctx := Type
  Sub Γ Δ := Γ → Δ
  id _ := fun γ => γ
  comp σ τ := fun γ => τ (σ γ)
  Ty Γ := Γ → Type
  tySub A σ := fun γ => A (σ γ)
  Tm Γ A := (γ : Γ) → A γ
  tmSub t σ := fun γ => t (σ γ)
  ext Γ A := (γ : Γ) × A γ
  p {Γ} A := fun (x : (γ : Γ) × A γ) => x.1
  ty_id _ := rfl
  ty_comp _ _ _ := rfl

/-! ## MLTT type formers in the family model -/

variable {Γ : Type}

def Pi (A : Γ → Type) (B : ((γ : Γ) × A γ) → Type) : Γ → Type := fun γ => (x : A γ) → B ⟨γ, x⟩
def lam {A : Γ → Type} {B : ((γ : Γ) × A γ) → Type} (t : (g : (γ : Γ) × A γ) → B g) : (γ : Γ) → Pi A B γ :=
  fun γ x => t ⟨γ, x⟩
def app {A : Γ → Type} {B : ((γ : Γ) × A γ) → Type} (t : (γ : Γ) → Pi A B γ) (u : (γ : Γ) → A γ) :
    (γ : Γ) → B ⟨γ, u γ⟩ := fun γ => t γ (u γ)

theorem pi_beta {A : Γ → Type} {B : ((γ : Γ) × A γ) → Type} (t : (g : (γ : Γ) × A γ) → B g) (u : (γ : Γ) → A γ)
    (γ : Γ) : app (lam t) u γ = t ⟨γ, u γ⟩ := rfl

theorem pi_eta {A : Γ → Type} {B : ((γ : Γ) × A γ) → Type} (t : (γ : Γ) → Pi A B γ) (γ : Γ) :
    lam (fun g => t g.1 g.2) γ = t γ := rfl

def Sig (A : Γ → Type) (B : ((γ : Γ) × A γ) → Type) : Γ → Type := fun γ => (x : A γ) × B ⟨γ, x⟩

theorem sig_beta {A : Γ → Type} {B : ((γ : Γ) × A γ) → Type} (a : (γ : Γ) → A γ) (b : (γ : Γ) → B ⟨γ, a γ⟩) (γ : Γ) :
    (⟨a γ, b γ⟩ : Sig A B γ).1 = a γ := rfl

theorem sig_eta {A : Γ → Type} {B : ((γ : Γ) × A γ) → Type} (s : (γ : Γ) → Sig A B γ) (γ : Γ) :
    (⟨(s γ).1, (s γ).2⟩ : Sig A B γ) = s γ := rfl

def Id (A : Γ → Type) (a b : (γ : Γ) → A γ) : Γ → Type := fun γ => PLift (a γ = b γ)

def refl' (A : Γ → Type) (a : (γ : Γ) → A γ) : (γ : Γ) → Id A a a γ := fun _ => ⟨rfl⟩

/-- the extensional point: Id reflects into judgmental (Lean) equality, and UIP -/
theorem id_reflect (A : Γ → Type) (a b : (γ : Γ) → A γ) (h : (γ : Γ) → Id A a b γ) (γ : Γ) : a γ = b γ := (h γ).down

theorem plift_eq {P : Prop} (x y : PLift P) : x = y := by
  cases x
  cases y
  rfl

theorem id_uip (A : Γ → Type) (a b : (γ : Γ) → A γ) (h k : (γ : Γ) → Id A a b γ) (γ : Γ) : h γ = k γ :=
  plift_eq _ _

end CwF

end Found

#print axioms Found.CwF.Fam
#print axioms Found.CwF.pi_beta
#print axioms Found.CwF.pi_eta
#print axioms Found.CwF.sig_eta
#print axioms Found.CwF.id_reflect
#print axioms Found.CwF.id_uip

#print axioms: 6 theorems, no axioms.

85.95 Extensional and intensional MLTT

Uniqueness of identity proofs separates the two: it holds in the family model where identities reflect, and fails in the groupoid reading of the universe, where Bool has two distinct self-equivalences. \(\mathrm {id}_{\mathbb 2}\ne \neg :\ \mathbb 2\simeq \mathbb 2\), UIP fails; family model: UIP.

found/MLTTVariants.lean

/-
  T120. found/MLTTVariants — extensional versus intensional MLTT as two
  values of one condition (UIP) on the identity types of the CwF parameter.
  * Extensional: the family model (T152) — identity reflects, UIP holds.
  * Intensional: the groupoid (Hofmann–Streicher) reading of the universe —
    identities between types are equivalences (data), and UIP fails: Bool
    has two distinct self-identifications (identity and negation).
    Univalence makes these the paths of the universe (Agda: ua, T127).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.CwF

namespace Found

namespace MLTTV

universe u

structure Equiv (A B : Type u) where
  fwd : A → B
  bwd : B → A
  left : ∀ a, bwd (fwd a) = a
  right : ∀ b, fwd (bwd b) = b

def idE (A : Type u) : Equiv A A := ⟨fun a => a, fun a => a, fun _ => rfl, fun _ => rfl⟩

def notE : Equiv Bool Bool :=
  ⟨fun b => !b, fun b => !b, fun b => by cases b <;> rfl, fun b => by cases b <;> rfl⟩

/-- UIP fails for identities-as-equivalences -/
theorem not_uip : (idE Bool).fwd true ≠ notE.fwd true := fun e => Bool.noConfusion e

/-- while in the extensional family model all identity proofs agree (T152) -/
theorem uip_extensional {Γ : Type} (A : Γ → Type) (a b : (γ : Γ) → A γ)
    (h k : (γ : Γ) → CwF.Id A a b γ) (γ : Γ) : h γ = k γ := CwF.id_uip A a b h k γ

end MLTTV

end Found

#print axioms Found.MLTTV.not_uip
#print axioms Found.MLTTV.uip_extensional

#print axioms: 2 theorems, no axioms.

85.96 Meta-frameworks

LF’s judgments-as-types encoding is adequate for Hilbert/natural-deduction derivability; Dedukti’s rewrite rule for implication holds definitionally; Pure’s rules are those of higher-order intuitionistic logic; MMT morphisms compose with satisfaction; Hilbert derivability is closed under substitution (Metamath); Mizar’s foundation is Tarski–Grothendieck with classical logic. \(\mathrm {pf}\,\varphi \iff \vdash \varphi ;\quad \vdash \varphi \Rightarrow \vdash \varphi [s]\).

found/MetaFrameworks.lean

/-
  T158–T161, T203, T204. found/MetaFrameworks — other people's meta-
  frameworks as points of the same coordinates (known range):
  * LF (T160): judgments as types — `pf φ` is the type of derivations; the
    encoding is adequate: pf φ ⟺ Hilbert/ND derivability (T143).
  * Dedukti / λΠ-modulo (T159): rewrite rules are definitional equations;
    the shallow embedding prf (a ⇒ b) ⟶ (prf a → prf b) holds by rfl.
  * Isabelle/Pure (T161): the meta-logic ⋀, ⟹ is intuitionistic higher-order
    logic on Ω (T73, T114); its rules are sound (introduction/elimination).
  * MMT (T158): theory graphs = institutions (T157) with composable
    morphisms; satisfaction is functorial along composites.
  * Metamath (T203): proofs are substitution instances of schemes plus MP;
    Hilbert derivability is closed under substitution of formulas for
    variables.
  * Mizar (T204): Tarski–Grothendieck (T162) with classical logic (T66, T89).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Hilbert
import found.Institutions
import found.MacLane
import found.ZF

namespace Found

namespace Meta

open Prp

/-! ## LF -/

def pf (φ : Form) : Prop := HD (fun _ => False) φ

theorem lf_adequate (φ : Form) : pf φ ↔ PD true (fun _ => False) φ := hilbert_iff_nd _ φ

/-! ## Dedukti: rewriting as definitional equality -/

def prf (v : Nat → Prop) : Form → Prop
  | .var n => v n
  | .bot => False
  | .and a b => prf v a ∧ prf v b
  | .or a b => prf v a ∨ prf v b
  | .imp a b => prf v a → prf v b

theorem dedukti_rule (v : Nat → Prop) (a b : Form) : prf v (.imp a b) = (prf v a → prf v b) := rfl

/-! ## Isabelle/Pure -/

theorem pure_imp_intro {A B : Prop} (h : A → B) : A → B := h
theorem pure_imp_elim {A B : Prop} (h : A → B) (a : A) : B := h a
theorem pure_all_intro {α : Type} {P : α → Prop} (h : ∀ x, P x) : ∀ x, P x := h
theorem pure_all_elim {α : Type} {P : α → Prop} (h : ∀ x, P x) (t : α) : P t := h t

/-! ## MMT: theory morphisms compose -/

theorem mmt_compose {A B C : Type} (σ : A → B) (τ : B → C) (v : C → Prop) (φ : Inst.PF A) :
    Inst.sat v (Inst.ren τ (Inst.ren σ φ)) ↔ Inst.sat (fun a => v (τ (σ a))) φ :=
  (Inst.condition τ v _).trans (Inst.condition σ (fun b => v (τ b)) φ)

/-! ## Metamath: closure under substitution -/

def subst (s : Nat → Form) : Form → Form
  | .var n => s n
  | .bot => .bot
  | .and a b => .and (subst s a) (subst s b)
  | .or a b => .or (subst s a) (subst s b)
  | .imp a b => .imp (subst s a) (subst s b)

theorem metamath_subst (s : Nat → Form) {φ : Form} (d : HD (fun _ => False) φ) :
    HD (fun _ => False) (subst s φ) := by
  induction d with
  | hyp g => exact g.elim
  | k a b => exact .k _ _
  | s a b c => exact .s _ _ _
  | andI a b => exact .andI _ _
  | andE1 a b => exact .andE1 _ _
  | andE2 a b => exact .andE2 _ _
  | orI1 a b => exact .orI1 _ _
  | orI2 a b => exact .orI2 _ _
  | orE a b c => exact .orE _ _ _
  | efq a => exact .efq _
  | mp _ _ ihf iha => exact .mp ihf iha

/-! ## Mizar: TG + classical -/

theorem mizar (lem : ∀ p : Prop, p ∨ ¬ p) (a : WF.V.{0}) :
    WF.Mem (Groth.lift a) Groth.U ∧ ((∃ x, WF.Mem x a) → ∃ m, ZF.Minimal a m) :=
  ⟨Zermelo.tg a, ZF.foundation_classical lem a⟩

end Meta

end Found

#print axioms Found.Meta.lf_adequate
#print axioms Found.Meta.dedukti_rule
#print axioms Found.Meta.pure_all_elim
#print axioms Found.Meta.mmt_compose
#print axioms Found.Meta.metamath_subst
#print axioms Found.Meta.mizar

#print axioms: 6 theorems, no axioms.

85.97 Determinacy

Finite alternating games on Booleans with a decidable payoff are determined, constructively by induction on the length, and never won by both players; full determinacy is a condition on infinite games incompatible with choice. \(\forall n\,t\,h,\ \mathrm {Win}_I\vee \mathrm {Win}_{II},\quad \neg (\mathrm {Win}_I\wedge \mathrm {Win}_{II})\).

found/AD.lean

/-
  T168. found/AD — determinacy as a point: games are a parameter (moves,
  length, payoff); the axiom of determinacy is the condition "every game
  is determined".
  * Finite games on Bool (alternating moves, decidable payoff) are
    determined, constructively, by induction on the length (Zermelo).
  * Full AD (infinite games on ℕ) is the condition that contradicts choice
    (ZF + AD ⊢ ¬AC, Mycielski–Steinhaus) — a line to T87/T89 (cited).

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Det

/-- I wins from history h with n moves left; `turnI` says whose move it is -/
def WinI (P : List Bool → Bool) : Nat → Bool → List Bool → Prop
  | 0, _, h => P h = true
  | n + 1, true, h => WinI P n false (true :: h) ∨ WinI P n false (false :: h)
  | n + 1, false, h => WinI P n true (true :: h) ∧ WinI P n true (false :: h)

def WinII (P : List Bool → Bool) : Nat → Bool → List Bool → Prop
  | 0, _, h => P h = false
  | n + 1, true, h => WinII P n false (true :: h) ∧ WinII P n false (false :: h)
  | n + 1, false, h => WinII P n true (true :: h) ∨ WinII P n true (false :: h)

/-- Zermelo: every finite game on Bool is determined -/
theorem determined (P : List Bool → Bool) : ∀ n t h, WinI P n t h ∨ WinII P n t h
  | 0, _, h => by
    cases e : P h
    · exact Or.inr e
    · exact Or.inl e
  | n + 1, true, h =>
    (determined P n false (true :: h)).elim (fun w => Or.inl (Or.inl w))
      (fun l1 => (determined P n false (false :: h)).elim (fun w => Or.inl (Or.inr w))
        (fun l2 => Or.inr ⟨l1, l2⟩))
  | n + 1, false, h =>
    (determined P n true (true :: h)).elim
      (fun w1 => (determined P n true (false :: h)).elim (fun w2 => Or.inl ⟨w1, w2⟩)
        (fun l2 => Or.inr (Or.inr l2)))
      (fun l1 => Or.inr (Or.inl l1))

/-- and not both -/
theorem not_both (P : List Bool → Bool) : ∀ n t h, ¬ (WinI P n t h ∧ WinII P n t h)
  | 0, _, _, ⟨a, b⟩ => Bool.noConfusion (a.symm.trans b)
  | n + 1, true, _, ⟨a, b⟩ => a.elim (fun w => not_both P n false _ ⟨w, b.1⟩) (fun w => not_both P n false _ ⟨w, b.2⟩)
  | n + 1, false, _, ⟨a, b⟩ => b.elim (fun l => not_both P n true _ ⟨a.1, l⟩) (fun l => not_both P n true _ ⟨a.2, l⟩)

/-- the AD condition for a class of (infinite) games, as a parameter -/
def AD (Game : Type) (WinsI WinsII : Game → Prop) : Prop := ∀ g, WinsI g ∨ WinsII g

end Det

end Found

#print axioms Found.Det.determined
#print axioms Found.Det.not_both

#print axioms: 2 theorems, no axioms.

85.98 Game semantics

In Hintikka’s evaluation game the verifier has a winning strategy exactly when the formula is true and the falsifier exactly when it is false, so the game is determined. \(V\ \mathrm {wins}\ \varphi \iff v(\varphi )=1;\quad F\ \mathrm {wins}\iff v(\varphi )=0\).

found/Game.lean

/-
  T117. found/Game — game semantics as a point: Hintikka's evaluation game
  for propositional formulas under a Bool valuation (verifier chooses at ∨,
  falsifier at ∧, roles swap at ¬).
  * The verifier has a winning strategy iff the formula is true, and the
    falsifier iff it is false (constructive, by induction) — truth = winning,
    the game is determined (line to T168).
  Lorenzen dialogues (intuitionistic) and game models of linear logic
  (Blass, Abramsky–Jagadeesan) are the further values (cited).

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace GameSem

inductive F where
  | var : Nat → F
  | neg : F → F
  | and : F → F → F
  | or : F → F → F

def val (v : Nat → Bool) : F → Bool
  | .var n => v n
  | .neg a => !val v a
  | .and a b => val v a && val v b
  | .or a b => val v a || val v b

mutual
/-- the verifier wins the game on φ -/
def VWin (v : Nat → Bool) : F → Prop
  | .var n => v n = true
  | .neg a => FWin v a
  | .and a b => VWin v a ∧ VWin v b
  | .or a b => VWin v a ∨ VWin v b
/-- the falsifier wins -/
def FWin (v : Nat → Bool) : F → Prop
  | .var n => v n = false
  | .neg a => VWin v a
  | .and a b => FWin v a ∨ FWin v b
  | .or a b => FWin v a ∧ FWin v b
end

theorem band_t : (a b : Bool) → ((a && b) = true ↔ a = true ∧ b = true)
  | true, true => ⟨fun _ => ⟨rfl, rfl⟩, fun _ => rfl⟩
  | true, false => ⟨fun h => Bool.noConfusion h, fun h => Bool.noConfusion h.2⟩
  | false, _ => ⟨fun h => Bool.noConfusion h, fun h => Bool.noConfusion h.1⟩

theorem band_f : (a b : Bool) → ((a && b) = false ↔ a = false ∨ b = false)
  | true, true => ⟨fun h => Bool.noConfusion h, fun h => h.elim (fun e => Bool.noConfusion e) (fun e => Bool.noConfusion e)⟩
  | true, false => ⟨fun _ => Or.inr rfl, fun _ => rfl⟩
  | false, _ => ⟨fun _ => Or.inl rfl, fun _ => rfl⟩

theorem bor_t : (a b : Bool) → ((a || b) = true ↔ a = true ∨ b = true)
  | true, _ => ⟨fun _ => Or.inl rfl, fun _ => rfl⟩
  | false, true => ⟨fun _ => Or.inr rfl, fun _ => rfl⟩
  | false, false => ⟨fun h => Bool.noConfusion h, fun h => h.elim (fun e => Bool.noConfusion e) (fun e => Bool.noConfusion e)⟩

theorem bor_f : (a b : Bool) → ((a || b) = false ↔ a = false ∧ b = false)
  | true, _ => ⟨fun h => Bool.noConfusion h, fun h => Bool.noConfusion h.1⟩
  | false, true => ⟨fun h => Bool.noConfusion h, fun h => Bool.noConfusion h.2⟩
  | false, false => ⟨fun _ => ⟨rfl, rfl⟩, fun _ => rfl⟩

theorem bnot_t : (a : Bool) → ((!a) = true ↔ a = false)
  | true => ⟨fun h => Bool.noConfusion h, fun h => Bool.noConfusion h⟩
  | false => ⟨fun _ => rfl, fun _ => rfl⟩

theorem bnot_f : (a : Bool) → ((!a) = false ↔ a = true)
  | true => ⟨fun _ => rfl, fun _ => rfl⟩
  | false => ⟨fun h => Bool.noConfusion h, fun h => Bool.noConfusion h⟩

theorem and_iff {p q p' q' : Prop} (h1 : p ↔ p') (h2 : q ↔ q') : (p ∧ q) ↔ (p' ∧ q') :=
  ⟨fun h => ⟨h1.mp h.1, h2.mp h.2⟩, fun h => ⟨h1.mpr h.1, h2.mpr h.2⟩⟩

theorem or_iff {p q p' q' : Prop} (h1 : p ↔ p') (h2 : q ↔ q') : (p ∨ q) ↔ (p' ∨ q') :=
  ⟨fun h => h.elim (fun a => Or.inl (h1.mp a)) (fun b => Or.inr (h2.mp b)),
   fun h => h.elim (fun a => Or.inl (h1.mpr a)) (fun b => Or.inr (h2.mpr b))⟩

theorem win_iff (v : Nat → Bool) : (φ : F) →
    (VWin v φ ↔ val v φ = true) ∧ (FWin v φ ↔ val v φ = false)
  | .var _ => ⟨Iff.rfl, Iff.rfl⟩
  | .neg a => ⟨(win_iff v a).2.trans (bnot_t _).symm, (win_iff v a).1.trans (bnot_f _).symm⟩
  | .and a b => ⟨(and_iff (win_iff v a).1 (win_iff v b).1).trans (band_t _ _).symm,
                 (or_iff (win_iff v a).2 (win_iff v b).2).trans (band_f _ _).symm⟩
  | .or a b => ⟨(or_iff (win_iff v a).1 (win_iff v b).1).trans (bor_t _ _).symm,
                (and_iff (win_iff v a).2 (win_iff v b).2).trans (bor_f _ _).symm⟩

/-- the evaluation game is determined -/
theorem determined (v : Nat → Bool) (φ : F) : VWin v φ ∨ FWin v φ := by
  cases h : val v φ
  · exact Or.inr ((win_iff v φ).2.mpr h)
  · exact Or.inl ((win_iff v φ).1.mpr h)

end GameSem

end Found

#print axioms Found.GameSem.win_iff
#print axioms Found.GameSem.determined

#print axioms: 2 theorems, no axioms.

85.99 Internal set theory

With a standardness predicate on the natural numbers, the idealization instance for \(<\), whose finite premise always holds, yields a number above every standard one, hence nonstandard. \(\mathrm {I}_{<}\Rightarrow \exists y\,\neg \mathrm {st}(y)\).

found/IST.lean

/-
  T165. found/IST — Nelson's internal set theory as a point: a new predicate
  `st` (standard) on the existing universe (here on ℕ, the core's NNO) with
  IST's principles as conditions on the parameter.
  * Idealization (instance for <): if every finite list of standard numbers
    has a common strict upper bound, then some y exceeds every standard x.
  * Consequence: there is a nonstandard natural number (st y fails).
  * Transfer/standardization are further conditions (cited); IST is a
    conservative extension of ZFC (line to T89, cited).

  Lean 4 core only, hand-written proofs, no axioms (conditions are hypotheses).
-/

namespace Found

namespace IST

def Ideal (st : Nat → Prop) : Prop :=
  (∀ S : List Nat, (∀ x, x ∈ S → st x) → ∃ y, ∀ x, x ∈ S → x < y) →
    ∃ y, ∀ x, st x → x < y

/-- every finite list has a strict upper bound (classical arithmetic fact, here constructive) -/
theorem bound : (S : List Nat) → ∃ y, ∀ x, x ∈ S → x < y
  | [] => ⟨0, fun _ h => nomatch h⟩
  | a :: S => match bound S with
    | ⟨y, hy⟩ => ⟨a + y + 1, fun x m => by
        cases m with
        | head => exact Nat.lt_succ_of_le (Nat.le_add_right a y)
        | tail _ m' => exact Nat.lt_succ_of_le (Nat.le_trans (Nat.le_of_lt (hy x m')) (Nat.le_add_left y a))⟩

/-- idealization yields a nonstandard number -/
theorem nonstandard (st : Nat → Prop) (hI : Ideal st) : ∃ y, ¬ st y :=
  match hI (fun S _ => bound S) with
  | ⟨y, hy⟩ => ⟨y, fun s => Nat.lt_irrefl y (hy y s)⟩

end IST

end Found

#print axioms Found.IST.bound
#print axioms Found.IST.nonstandard

#print axioms: 2 theorems, no axioms.

85.100 Large cardinals: the universe tower

Lifting trees through the meta-language’s universe hierarchy gives universes \(U_u\in V_{u+1}\) containing every lifted set, with each \(U_u\) lifted into \(U_{u+1}\): an inaccessible-like tower at every level. \(\mathrm {lift}\,U_u\in U_{u+1}\).

found/LargeCardinals.lean

/-
  T188. found/LargeCardinals — large cardinals as a point, in the form
  available from the coordinates: the meta-language's universe hierarchy
  gives a tower of universes in Aczel's V (generalizing T104 to every level).
  * liftU : V_u → V_{u+1}, respecting ≈.
  * U_u := {liftU a | a ∈ V_u} ∈ V_{u+1}; every lifted set lies in U_u.
  * Tower: the lift of U_u lies in U_{u+1} (an inaccessible-like hierarchy:
    "every set lies in a universe", TG, at every level).
  Specific large-cardinal axioms (measurable, Woodin, …) are further
  conditions (cited).

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: universe hierarchy.
-/
import found.Mostowski

namespace Found

namespace LC

open WF

universe u

def liftU : V.{u} → V.{u + 1}
  | .sup I f => .sup (ULift.{u + 1} I) (fun i => liftU (f i.down))

theorem liftU_eq : (x y : V.{u}) → Eq' x y → Eq' (liftU x) (liftU y)
  | .sup _ _, .sup _ _, ⟨e1, e2⟩ =>
    ⟨fun i => match e1 i.down with | ⟨j, e⟩ => ⟨⟨j⟩, liftU_eq _ _ e⟩,
     fun j => match e2 j.down with | ⟨i, e⟩ => ⟨⟨i⟩, liftU_eq _ _ e⟩⟩

def U : V.{u + 1} := .sup V.{u} liftU

theorem in_U (a : V.{u}) : Mem (liftU a) U.{u} := ⟨a, eq_refl _⟩

/-- the tower: U_u (lifted) is a member of U_{u+1} -/
theorem tower : Mem (liftU U.{u}) U.{u + 1} := in_U U.{u}

theorem U_resp {a b : V.{u}} (h : Eq' a b) : Eq' (liftU a) (liftU b) := liftU_eq a b h

end LC

end Found

#print axioms Found.LC.liftU_eq
#print axioms Found.LC.in_U
#print axioms Found.LC.tower

#print axioms: 3 theorems, no axioms.

85.101 Higher-order intuitionistic logic

Higher-order intuitionistic logic is the simple type model over the setoid stem with no condition on \(\Omega \); \(\Omega \) is Boolean exactly under excluded middle, so HOL is HOIL plus that condition, while \(\neg \neg (p\vee \neg p)\) holds unconditionally. \(\Omega \ \text {Boolean}\iff \forall p,\ p\vee \neg p\).

found/HOIL.lean

/-
  T114. found/HOIL — higher-order intuitionistic logic as a point: the
  simple type model of T205 (types over ι and o in the setoid stem) with no
  condition on Ω.
  * Comprehension (standard, T142) and extensionality (T205) hold; the
    quantifiers are the adjoints of T73 (reused).
  * Ω is Boolean ⟺ excluded middle — so HOL (T205) = HOIL + the Boolean
    condition, and topos internal languages are HOIL (T64, T73).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.HOL

namespace Found

namespace HOIL

/-- excluded middle from double negation elimination on Ω -/
theorem lem_of_boolean (hB : Prp.Boolean OmegaHA) (p : Prop) : p ∨ ¬ p :=
  hB (p ∨ ¬ p) (fun n => n (Or.inr (fun hp => n (Or.inl hp))))

theorem boolean_iff_lem : Prp.Boolean OmegaHA ↔ ∀ p : Prop, p ∨ ¬ p :=
  ⟨lem_of_boolean, HOL.classical_condition⟩

/-- the intuitionistic part needs no condition: ¬¬(p ∨ ¬p) holds -/
theorem nn_lem (p : Prop) : ¬ ¬ (p ∨ ¬ p) := fun n => n (Or.inr (fun hp => n (Or.inl hp)))

end HOIL

end Found

#print axioms Found.HOIL.lem_of_boolean
#print axioms Found.HOIL.boolean_iff_lem
#print axioms Found.HOIL.nn_lem

#print axioms: 3 theorems, no axioms.

85.102 Simplicial sets

The simplex category is an instance of the category parameter, simplicial sets are setoid presheaves on it, the nerve of a preorder is one, and its inner horn \(\Lambda ^2_1\) always fills by transitivity. \(\Lambda ^2_1\to N(P)\ \text {extends to}\ \Delta ^2\to N(P)\).

found/Simplicial.lean

/-
  T134. found/Simplicial — simplicial sets as a point: the simplex category
  Δ is a value of the category parameter, simplicial sets are setoid
  presheaves on Δ (T61's Psh), representables Δ[n] = yo Δ n.
  * Δ: objects n ↦ [n] = {0,…,n}; maps = monotone, bounded functions,
    compared pointwise on [n].
  * The nerve of a preorder: n-simplices = chains c₀ ≤ … ≤ cₙ.
  * Inner horn Λ²₁ fills in every nerve (composition = transitivity): the
    quasi-category condition in dimension 2.  Kan complexes and higher horns
    are the known continuation (cited).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Cat

namespace Found

namespace Simp

structure DHom (n m : Nat) where
  f : Nat → Nat
  mono : ∀ i, i < n → f i ≤ f (i + 1)
  bound : ∀ i, i ≤ n → f i ≤ m

def Delta : ECat.{0, 0} where
  Ob := Nat
  Hom := DHom
  heq {n _} g h := ∀ i, i ≤ n → g.f i = h.f i
  hrefl _ _ _ := rfl
  hsymm h i hi := (h i hi).symm
  htrans h k i hi := (h i hi).trans (k i hi)
  id n := ⟨fun i => i, fun _ _ => Nat.le_succ _, fun _ h => h⟩
  comp g h := ⟨fun i => h.f (g.f i),
    fun i hi => mono_of_succ h (g.mono i hi) (g.bound (i + 1) hi),
    fun i hi => h.bound _ (g.bound i hi)⟩
  comp_resp {_ _ _ g g' h h'} e e' i hi := by
    show h.f (g.f i) = h'.f (g'.f i)
    rw [e i hi]
    exact e' _ (g'.bound i hi)
  id_comp _ _ _ := rfl
  comp_id _ _ _ := rfl
  assoc _ _ _ _ _ := rfl
where
  mono_of_succ {n m : Nat} (h : DHom n m) {a b : Nat} (hab : a ≤ b) (hb : b ≤ n) : h.f a ≤ h.f b := by
    induction hab with
    | refl => exact Nat.le_refl _
    | step hle ih =>
      exact Nat.le_trans (ih (Nat.le_trans (Nat.le_succ _) hb)) (h.mono _ (Nat.lt_of_succ_le hb))

/-! ## the nerve of a preorder -/

structure Preorder' where
  P : Type
  le : P → P → Prop
  refl : ∀ a, le a a
  trans : ∀ {a b c}, le a b → le b c → le a c

structure Chain (Q : Preorder') (n : Nat) where
  c : Nat → Q.P
  mono : ∀ i, i < n → Q.le (c i) (c (i + 1))

theorem chain_le {Q : Preorder'} {n : Nat} (x : Chain Q n) {a b : Nat} (hab : a ≤ b) (hb : b ≤ n) :
    Q.le (x.c a) (x.c b) := by
  induction hab with
  | refl => exact Q.refl _
  | step hle ih => exact Q.trans (ih (Nat.le_trans (Nat.le_succ _) hb)) (x.mono _ (Nat.lt_of_succ_le hb))

def nerve (Q : Preorder') : Psh.{0, 0, 0} Delta where
  obj := fun (n : Nat) => ⟨Chain Q n, fun x y => ∀ i : Nat, i ≤ n → x.c i = y.c i, fun _ _ _ => rfl,
    fun h i hi => (h i hi).symm, fun h k i hi => (h i hi).trans (k i hi)⟩
  map {n m} g x := ⟨fun i => x.c (g.f i), fun i hi =>
    chain_le x (g.mono i hi) (g.bound (i + 1) hi)⟩
  map_eqv g := fun {_ _} h i hi => h _ (g.bound i hi)
  map_resp {n m g g'} x e i hi := by
    show x.c (g.f i) = x.c (g'.f i)
    rw [e i hi]
  map_id _ _ _ _ := rfl
  map_comp _ _ _ _ _ := rfl

/-! ## inner horn Λ²₁ -/

theorem lt_two {i : Nat} (h : i < 2) : i = 0 ∨ i = 1 := by
  cases i with
  | zero => exact Or.inl rfl
  | succ k => cases k with
    | zero => exact Or.inr rfl
    | succ k => exact absurd (Nat.lt_of_succ_lt_succ (Nat.lt_of_succ_lt_succ h)) (Nat.not_lt_zero k)

/-- given 1-simplices a = (a₀ ≤ a₁), b = (b₀ ≤ b₁) with a₁ = b₀, a 2-simplex filling the horn -/
def fill {Q : Preorder'} (a b : Chain Q 1) (e : a.c 1 = b.c 0) : Chain Q 2 :=
  ⟨fun i => match i with
    | 0 => a.c 0
    | 1 => a.c 1
    | _ + 2 => b.c 1,
   fun i hi => (lt_two hi).elim (fun h0 => by
      cases h0
      exact a.mono 0 (Nat.lt_succ_self 0))
    (fun h1 => by
      cases h1
      show Q.le (a.c 1) (b.c 1)
      rw [e]
      exact b.mono 0 (Nat.lt_succ_self 0))⟩

theorem fill_d2 {Q : Preorder'} (a b : Chain Q 1) (e : a.c 1 = b.c 0) :
    (fill a b e).c 0 = a.c 0 ∧ (fill a b e).c 1 = a.c 1 := ⟨rfl, rfl⟩

theorem fill_d0 {Q : Preorder'} (a b : Chain Q 1) (e : a.c 1 = b.c 0) :
    (fill a b e).c 1 = b.c 0 ∧ (fill a b e).c 2 = b.c 1 := ⟨e, rfl⟩

end Simp

end Found

#print axioms Found.Simp.Delta
#print axioms Found.Simp.chain_le
#print axioms Found.Simp.nerve
#print axioms Found.Simp.fill
#print axioms Found.Simp.fill_d2
#print axioms Found.Simp.fill_d0

#print axioms: 6 theorems, no axioms.

85.103 Kan extensions

For a monotone map and a frame-valued map, the pointwise join over the comma preorder is monotone and is the left Kan extension: it lies below a monotone \(h\) exactly when \(g\le h\circ f\). \(\mathrm {Lan}_f g\le h\iff g\le h\circ f\).

found/KanExt.lean

/-
  T149. found/KanExt — Kan extensions as a point, in the order-enriched
  case of the category parameter: for monotone f : P → Q and g : P → L into
  a frame L (T115, complete), the left Kan extension
      (Lan_f g)(q) = ⋁ { g p | f p ≤ q }
  satisfies the universal property  Lan_f g ≤ h  ⟺  g ≤ h ∘ f  (h monotone),
  and is itself monotone. The right Kan extension is dual (meets).
  (Set-valued Kan extensions as coends are the line to T95/T59 localization.)

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Locale

namespace Found

namespace Kan

universe u

variable (L : Loc.Frame.{u}) {P Q : Type u} (leP : P → P → Prop) (leQ : Q → Q → Prop)
  (transQ : ∀ {a b c}, leQ a b → leQ b c → leQ a c) (reflQ : ∀ a, leQ a a)

def lan (f : P → Q) (g : P → L.car) (q : Q) : L.car :=
  L.sup (fun x : {p : P // leQ (f p) q} => g x.val)

include transQ in
theorem lan_mono (f : P → Q) (g : P → L.car) {q q' : Q} (h : leQ q q') :
    L.le (lan L leQ f g q) (lan L leQ f g q') :=
  L.sup_least _ _ (fun x => L.sup_ub (fun x : {p : P // leQ (f p) q'} => g x.val) ⟨x.val, transQ x.property h⟩)

include reflQ in
/-- the universal property of the left Kan extension -/
theorem lan_universal (f : P → Q) (g : P → L.car) (h : Q → L.car)
    (hm : ∀ {q q'}, leQ q q' → L.le (h q) (h q')) :
    (∀ q, L.le (lan L leQ f g q) (h q)) ↔ (∀ p, L.le (g p) (h (f p))) :=
  ⟨fun k p => L.le_trans (L.sup_ub (fun x : {p' : P // leQ (f p') (f p)} => g x.val) ⟨p, reflQ (f p)⟩) (k (f p)),
   fun k _ => L.sup_least _ _ (fun x => L.le_trans (k x.val) (hm x.property))⟩

end Kan

end Found

#print axioms Found.Kan.lan_mono
#print axioms Found.Kan.lan_universal

#print axioms: 2 theorems, no axioms.

85.104 Homotopy categories

On objects the homotopy category is the core’s localization of the object setoid at weak equivalences, with its universal property; in the trivial model structure, objects identified there are isomorphic. \(\pi _0=\mathrm {Ob}[W^{-1}];\quad a\sim b\Rightarrow a\cong b\ (W=\mathrm {Iso})\).

found/Homotopy.lean

/-
  T135. found/Homotopy — homotopy theory as a point: the homotopy category
  is a localization; on objects it is the core's localization (T59, op 7)
  of the object setoid at "connected by a weak equivalence".
  * π₀ / Ho on objects: Loc(Ob, W) with the universal property (maps of
    objects inverting W factor uniquely).
  * For the trivial model structure (T133) W-related objects are
    isomorphic, so Ho = C on objects.
  The full Ho(C) on morphisms (zig-zags) and Quillen equivalences are the
  known continuation (cited).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.ModelCat
import found.Core

namespace Found

namespace Htpy

open Core

universe u v

variable {C : ECat.{u, v}} (M : Model.ModelStr C)

/-- objects as a discrete setoid -/
def obS (C : ECat.{u, v}) : Setd.{u} := ⟨C.Ob, Eq, fun _ => rfl, fun h => h.symm, fun h k => h.trans k⟩

def WRel (a b : C.Ob) : Prop := ∃ f : C.Hom a b, M.W f

/-- π₀ = objects localized at weak equivalences -/
def pi0 : Setd.{u} := loc (obS C) (WRel M)

theorem we_identified {a b : C.Ob} (f : C.Hom a b) (hf : M.W f) :
    (pi0 M).eqv ((locMap (obS C) (WRel M)).fn a) ((locMap (obS C) (WRel M)).fn b) :=
  loc_inverts (X := obS C) (WRel M) ⟨f, hf⟩

/-- universal property: an invariant of objects that is constant along weak
  equivalences factors through π₀ -/
def factor {Y : Setd.{u}} (F : SHom (obS C) Y) (hF : ∀ {a b}, WRel M a b → Y.eqv (F.fn a) (F.fn b)) :
    SHom (pi0 M) Y := locLift (X := obS C) (WRel M) F hF

theorem factor_comm {Y : Setd.{u}} (F : SHom (obS C) Y) (hF : ∀ {a b}, WRel M a b → Y.eqv (F.fn a) (F.fn b)) :
    SetdCat.heq (SetdCat.comp (locMap (obS C) (WRel M)) (factor M F hF)) F :=
  locLift_comm (X := obS C) (WRel M) F hF

/-- in the trivial model structure, π₀-identified objects are isomorphic -/
theorem trivial_iso {a b : (obS C).car} (h : Gen (obS C) (WRel (Model.trivialModel C)) a b) :
    ∃ f : C.Hom a b, Model.IsIso f := by
  induction h with
  | base e => cases e; exact ⟨C.id _, Model.iso_id _⟩
  | rel r => exact r
  | symm _ ih => exact match ih with
    | ⟨f, ⟨g, h1, h2⟩⟩ => ⟨g, ⟨f, h2, h1⟩⟩
  | trans _ _ ih₁ ih₂ => exact match ih₁, ih₂ with
    | ⟨f, hf⟩, ⟨g, hg⟩ => ⟨C.comp f g, Model.iso_comp hf hg⟩

end Htpy

end Found

#print axioms Found.Htpy.we_identified
#print axioms Found.Htpy.factor_comm
#print axioms Found.Htpy.trivial_iso

#print axioms: 3 theorems, no axioms.

85.105 Geometric logic

Interpretations of geometric formulas, built from truth, finite conjunction and arbitrary disjunction, are preserved by frame homomorphisms, the inverse images of geometric morphisms. \(h\llbracket \varphi \rrbracket _L=\llbracket \varphi \rrbracket _M\ (\le \text { both ways})\).

found/GeometricLogic.lean

/-
  T194. found/GeometricLogic — geometric logic as a point: geometric
  (propositional) formulas use ⊤, ∧ and arbitrary disjunctions ⋁ (no →, ∀);
  their interpretation in a frame (T115) is preserved by frame
  homomorphisms (inverse images of geometric morphisms of locales/toposes).
  Classifying toposes (every geometric theory has one) are the known
  continuation (cited).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Locale

namespace Found

namespace Geo

universe u

inductive GF : Type (u + 1) where
  | atom : Nat → GF
  | top : GF
  | and : GF → GF → GF
  | sup : {I : Type u} → (I → GF) → GF

def interp (L : Loc.Frame.{u}) (v : Nat → L.car) : GF.{u} → L.car
  | .atom n => v n
  | .top => L.top
  | .and a b => L.meet (interp L v a) (interp L v b)
  | .sup f => L.sup (fun i => interp L v (f i))

structure FrameHom (L M : Loc.Frame.{u}) where
  h : L.car → M.car
  mono : ∀ {a b}, L.le a b → M.le (h a) (h b)
  top : M.le M.top (h L.top)
  meet : ∀ a b, M.le (M.meet (h a) (h b)) (h (L.meet a b))
  sup : ∀ {I : Type u} (f : I → L.car), M.le (h (L.sup f)) (M.sup (fun i => h (f i)))

/-- geometric formulas are preserved by frame homomorphisms (both inequalities) -/
theorem preserve (L M : Loc.Frame.{u}) (φ : FrameHom L M) (v : Nat → L.car) :
    (g : GF.{u}) → M.le (φ.h (interp L v g)) (interp M (fun n => φ.h (v n)) g) ∧
      M.le (interp M (fun n => φ.h (v n)) g) (φ.h (interp L v g))
  | .atom _ => ⟨M.le_refl _, M.le_refl _⟩
  | .top => ⟨M.le_top _, φ.top⟩
  | .and a b =>
    ⟨M.meet_univ (M.le_trans (φ.mono (L.meet_l _ _)) (preserve L M φ v a).1)
                 (M.le_trans (φ.mono (L.meet_r _ _)) (preserve L M φ v b).1),
     M.le_trans (M.meet_univ (M.le_trans (M.meet_l _ _) (preserve L M φ v a).2)
                             (M.le_trans (M.meet_r _ _) (preserve L M φ v b).2)) (φ.meet _ _)⟩
  | .sup f =>
    ⟨M.le_trans (φ.sup _) (M.sup_least _ _ (fun i =>
        M.le_trans (preserve L M φ v (f i)).1 (M.sup_ub (fun j => interp M (fun n => φ.h (v n)) (f j)) i))),
     M.sup_least _ _ (fun i => M.le_trans (preserve L M φ v (f i)).2
        (φ.mono (L.sup_ub (fun j => interp L v (f j)) i)))⟩

end Geo

end Found

#print axioms Found.Geo.preserve

#print axioms: 1 theorems, no axioms.

85.106 (\(\infty \),1)-categories as quasi-categories

The inner horn condition in dimension two is a predicate on any simplicial set, and nerves of preorders satisfy it, with the filler built from the two given edges. \(\forall a,b\in X_1,\ t(a)=s(b)\Rightarrow \exists \sigma \in X_2,\ d_2\sigma =a,\ d_0\sigma =b\).

found/InfCat.lean

/-
  T153. found/InfCat — (∞,1)-categories as a point: quasi-categories, i.e.
  simplicial sets (T134) with inner horn fillers; stated here in dimension 2
  for any simplicial set X (the parameter):
    for 1-simplices a, b with  target(a) ≈ source(b)  there is σ ∈ X₂ with
    d₂σ ≈ a and d₀σ ≈ b.
  * Nerves of preorders are quasi-categories in dimension 2 (T134's fill).
  Higher inner horns, ∞-toposes and (∞,n)-categories are the known
  continuation (cited; T196).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Simplicial

namespace Found

namespace InfCat

open Simp

def v0 : DHom 0 1 := ⟨fun _ => 0, fun _ h => absurd h (Nat.not_lt_zero _), fun _ _ => Nat.zero_le _⟩
def v1 : DHom 0 1 := ⟨fun _ => 1, fun _ h => absurd h (Nat.not_lt_zero _), fun _ _ => Nat.le_refl _⟩
def d2 : DHom 1 2 := ⟨fun i => i, fun _ _ => Nat.le_succ _, fun _ h => Nat.le_trans h (Nat.le_succ _)⟩
def d0 : DHom 1 2 := ⟨fun i => i + 1, fun _ _ => Nat.le_succ _, fun _ h => Nat.succ_le_succ h⟩

/-- inner horn Λ²₁ filling for a simplicial set -/
def n0 : Delta.Ob := (0 : Nat)
def n1 : Delta.Ob := (1 : Nat)
def n2 : Delta.Ob := (2 : Nat)

def Inner2 (X : Psh.{0, 0, 0} Delta) : Prop :=
  ∀ a b : (X.obj n1).car, (X.obj n0).eqv (X.map (a := n0) (b := n1) v1 a) (X.map (a := n0) (b := n1) v0 b) →
    ∃ σ : (X.obj n2).car, (X.obj n1).eqv (X.map (a := n1) (b := n2) d2 σ) a ∧
      (X.obj n1).eqv (X.map (a := n1) (b := n2) d0 σ) b

theorem le_one {i : Nat} (h : i ≤ 1) : i = 0 ∨ i = 1 := by
  cases i with
  | zero => exact Or.inl rfl
  | succ k => cases k with
    | zero => exact Or.inr rfl
    | succ k => exact absurd (Nat.le_of_succ_le_succ h) (Nat.not_succ_le_zero k)

/-- nerves of preorders are quasi-categories (dimension 2) -/
theorem nerve_inner2 (Q : Preorder') : Inner2 (nerve Q) := by
  intro a b e
  have e' : a.c 1 = b.c 0 := e 0 (Nat.le_refl 0)
  refine ⟨fill a b e', fun i hi => ?_, fun i hi => ?_⟩
  · rcases le_one hi with h | h <;> (cases h; rfl)
  · rcases le_one hi with h | h <;> cases h
    · exact e'
    · rfl

end InfCat

end Found

#print axioms Found.InfCat.nerve_inner2

#print axioms: 1 theorems, no axioms.

85.107 Ultraproducts and reduced products

For a filter on an index type, the product with \(a\sim b\iff \{i\mid a_i=b_i\}\in F\) is a setoid without quotient, pointwise operations respect it, and Łoś’s theorem holds for equations and conjunctions. \(\prod M_i/F\models t=s\iff \{i\mid M_i\models t=s\}\in F\).

found/Ultraproduct.lean

/-
  T190. found/Ultraproduct — reduced products and ultraproducts as a point:
  a filter F on an index type I (a parameter; an ultrafilter is the
  condition "for every A, A ∈ F or Aᶜ ∈ F"), structures Mᵢ, and the reduced
  product as a setoid (no quotient): a ~ b ⟺ {i | aᵢ = bᵢ} ∈ F.
  * ~ is an equivalence (filter laws); pointwise operations respect ~.
  * Łoś for equations and conjunctions (Horn part), constructively;
    the full Łoś theorem needs the ultrafilter condition (and choice for
    existentials), giving nonstandard models (T165) — cited for ∃.
  Morley categoricity and Lindström's theorem are cited lines.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Core

namespace Found

namespace Ultra

universe u v

structure Filter (I : Type u) where
  mem : (I → Prop) → Prop
  univ : mem (fun _ => True)
  up : ∀ {A B : I → Prop}, (∀ i, A i → B i) → mem A → mem B
  inter : ∀ {A B : I → Prop}, mem A → mem B → mem (fun i => A i ∧ B i)

variable {I : Type u} (F : Filter I) (M : I → Type v)

def Prod' : Type (max u v) := (i : I) → M i

def sim (a b : Prod' M) : Prop := F.mem (fun i => a i = b i)

def reduced : Setd.{max u v} where
  car := Prod' M
  eqv := sim F M
  refl _ := F.up (fun _ _ => rfl) F.univ
  symm h := F.up (fun _ e => e.symm) h
  trans h k := F.up (fun _ e => e.1.trans e.2) (F.inter h k)

/-- a pointwise binary operation respects ~ -/
theorem op_resp (op : ∀ i, M i → M i → M i) {a a' b b' : Prod' M}
    (ha : sim F M a a') (hb : sim F M b b') :
    sim F M (fun i => op i (a i) (b i)) (fun i => op i (a' i) (b' i)) :=
  F.up (fun i e => show op i (a i) (b i) = op i (a' i) (b' i) by rw [e.1, e.2]) (F.inter ha hb)

/-- Łoś for equations: the product satisfies t = s iff the set of factors does is in F -/
theorem los_eq (a b : Prod' M) : (reduced F M).eqv a b ↔ F.mem (fun i => a i = b i) := Iff.rfl

/-- Łoś for conjunction -/
theorem los_and (P Q : I → Prop) :
    F.mem (fun i => P i ∧ Q i) ↔ F.mem P ∧ F.mem Q :=
  ⟨fun h => ⟨F.up (fun _ x => x.1) h, F.up (fun _ x => x.2) h⟩, fun h => F.inter h.1 h.2⟩

end Ultra

end Found

#print axioms Found.Ultra.reduced
#print axioms Found.Ultra.op_resp
#print axioms Found.Ultra.los_eq
#print axioms Found.Ultra.los_and

#print axioms: 4 theorems, no axioms.

85.108 Type theory variants

Session-type duality exchanges sending with receiving and choice with offer, is an involution and preserves size, mirroring linear negation; linear and modal type theories are the closed and modal coordinates. \(\overline {\overline {s}}=s\).

found/TypeVariants.lean

/-
  T195. found/TypeVariants — type-theory variants as points on existing
  coordinates:
  * Session types: protocols with send/receive/choice/offer/end; duality is
    an involution and swaps the roles — the line to linear logic's negation
    (T68: session types = propositions of linear logic, Caires–Pfenning).
  * Linear type theory: the residuated/closed coordinate (T68, T150).
  * Modal / cohesive type theory: modalities as (co)monads on the type
    coordinate — □ as an idempotent comonad is S4 (T67) (cited for cohesion).
  * Parametricity: relational interpretation (cited).

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Session

inductive S where
  | stop : S
  | send : Nat → S → S      -- !T.s  (message type index)
  | recv : Nat → S → S      -- ?T.s
  | choose : S → S → S      -- ⊕
  | offer : S → S → S       -- &

def dual : S → S
  | .stop => .stop
  | .send t s => .recv t (dual s)
  | .recv t s => .send t (dual s)
  | .choose a b => .offer (dual a) (dual b)
  | .offer a b => .choose (dual a) (dual b)

theorem dual_dual : (s : S) → dual (dual s) = s
  | .stop => rfl
  | .send t s => congrArg (S.send t) (dual_dual s)
  | .recv t s => congrArg (S.recv t) (dual_dual s)
  | .choose a b => by show S.choose (dual (dual a)) (dual (dual b)) = _; rw [dual_dual a, dual_dual b]
  | .offer a b => by show S.offer (dual (dual a)) (dual (dual b)) = _; rw [dual_dual a, dual_dual b]

/-- the "linear negation" reading: ⊕ ↔ &, ! ↔ ? (sizes agree) -/
def size : S → Nat
  | .stop => 0
  | .send _ s => size s + 1
  | .recv _ s => size s + 1
  | .choose a b => size a + size b + 1
  | .offer a b => size a + size b + 1

theorem size_dual : (s : S) → size (dual s) = size s
  | .stop => rfl
  | .send _ s => congrArg (· + 1) (size_dual s)
  | .recv _ s => congrArg (· + 1) (size_dual s)
  | .choose a b => by show size (dual a) + size (dual b) + 1 = _; rw [size_dual a, size_dual b]; rfl
  | .offer a b => by show size (dual a) + size (dual b) + 1 = _; rw [size_dual a, size_dual b]; rfl

end Session

end Found

#print axioms Found.Session.dual_dual
#print axioms Found.Session.size_dual

#print axioms: 2 theorems, no axioms.

85.109 Ackermann set theory

Every class of sets of the lower universe level becomes a set one level up, obtained by separation inside the universe \(U\); its members are exactly the lifts of the class’s members. \(x\in \{\varphi \}_1\iff \exists a\,(x\approx \mathrm {lift}\,a\wedge \varphi a)\).

found/Ackermann.lean

/-
  T167. found/Ackermann — Ackermann's set theory as a point: classes of the
  sets of one universe level become sets one level up (the reflection-style
  principle of Ackermann, realized by the universe U of T104).
  * For every class φ of V₀-sets (no respect needed: membership is via ≈ to a lift), the set
    {x ∈ U | x ≈ lift a for some a with φ a} ∈ V₁ has exactly the lifted
    members of φ (separation in V₁, T88; lift, T104).
  Ackermann's theory is conservative over ZF (Lévy/Reinhardt, cited line).

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: universe hierarchy, impredicative Prop (separation).
-/
import found.Grothendieck

namespace Found

namespace Ack

open WF

def classSet (φ : V.{0} → Prop) : V.{1} :=
  IZF.sep Groth.U (fun x => ∃ a : V.{0}, Eq' x (Groth.lift a) ∧ φ a)

theorem classSet_spec (φ : V.{0} → Prop) (x : V.{1}) :
    Mem x (classSet φ) ↔ ∃ a : V.{0}, Eq' x (Groth.lift a) ∧ φ a :=
  ⟨fun m => ((IZF.sep_spec _ _ (fun _ _ e ⟨a, ea, pa⟩ => ⟨a, eq_trans _ _ _ (eq_symm _ _ e) ea, pa⟩) x).mp m).2,
   fun h => (IZF.sep_spec _ _ (fun _ _ e ⟨a, ea, pa⟩ => ⟨a, eq_trans _ _ _ (eq_symm _ _ e) ea, pa⟩) x).mpr
     ⟨match h with | ⟨a, ea, _⟩ => ⟨a, ea⟩, h⟩⟩

/-- in particular, a class's lifted members are exactly the lifts of its members -/
theorem lift_mem (φ : V.{0} → Prop) (a : V.{0}) (h : φ a) :
    Mem (Groth.lift a) (classSet φ) := (classSet_spec φ _).mpr ⟨a, eq_refl _, h⟩

end Ack

end Found

#print axioms Found.Ack.classSet_spec
#print axioms Found.Ack.lift_mem

#print axioms: 2 theorems, no axioms.

85.110 Descriptive complexity

For 2-colourability, the existential second-order guess is a colouring and the first-order part a Boolean check over the edge list, which is correct: it succeeds exactly for proper colourings. \(\mathrm {check}(c,E)=1\iff \forall (u,v)\in E,\ c(u)\ne c(v)\).

found/Fagin.lean

/-
  T185. found/Fagin — descriptive complexity as a point (Fagin: NP =
  existential second-order logic on finite structures), certificate side:
  * An ESO property: "there is a colouring c with no monochromatic edge"
    (2-colourability) — the second-order ∃ guesses c, the first-order part
    is a check over the finite edge list.
  * The check is a Boolean function and is correct: check c E = true ⟺ c
    is proper on E — the polynomial-time verifier of the NP side.
  The converse (every NP property is ESO) is cited.

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Fagin

def neq : Bool → Bool → Bool
  | true, true => false
  | true, false => true
  | false, true => true
  | false, false => false

theorem neq_true : (a b : Bool) → (neq a b = true ↔ a ≠ b)
  | true, true => ⟨fun h => Bool.noConfusion h, fun h => (h rfl).elim⟩
  | true, false => ⟨fun _ e => Bool.noConfusion e, fun _ => rfl⟩
  | false, true => ⟨fun _ e => Bool.noConfusion e, fun _ => rfl⟩
  | false, false => ⟨fun h => Bool.noConfusion h, fun h => (h rfl).elim⟩

def check (c : Nat → Bool) : List (Nat × Nat) → Bool
  | [] => true
  | (u, v) :: E => neq (c u) (c v) && check c E

def Proper (c : Nat → Bool) (E : List (Nat × Nat)) : Prop := ∀ e, e ∈ E → c e.1 ≠ c e.2

theorem check_correct (c : Nat → Bool) : (E : List (Nat × Nat)) → (check c E = true ↔ Proper c E)
  | [] => ⟨(fun _ _ m => nomatch m), (fun _ => rfl)⟩
  | (u, v) :: E => by
    show (neq (c u) (c v) && check c E) = true ↔ _
    cases h1 : neq (c u) (c v) with
    | false =>
      exact ⟨fun h => Bool.noConfusion h, fun hp => by
        have := (neq_true _ _).mpr (hp (u, v) (.head _))
        rw [h1] at this
        exact Bool.noConfusion this⟩
    | true =>
      cases h2 : check c E with
      | false =>
        exact ⟨fun h => Bool.noConfusion h, fun hp => by
          have := (check_correct c E).mpr (fun e m => hp e (.tail _ m))
          rw [h2] at this
          exact Bool.noConfusion this⟩
      | true =>
        refine ⟨fun _ e m => ?_, fun _ => rfl⟩
        cases m with
        | head => exact (neq_true _ _).mp h1
        | tail _ m' => exact (check_correct c E).mp h2 e m'

/-- the ESO property: some colouring is proper -/
def TwoColourable (E : List (Nat × Nat)) : Prop := ∃ c : Nat → Bool, check c E = true

theorem eso_iff (E : List (Nat × Nat)) : TwoColourable E ↔ ∃ c, Proper c E :=
  ⟨fun ⟨c, h⟩ => ⟨c, (check_correct c E).mp h⟩, fun ⟨c, h⟩ => ⟨c, (check_correct c E).mpr h⟩⟩

end Fagin

end Found

#print axioms Found.Fagin.neq_true
#print axioms Found.Fagin.check_correct
#print axioms Found.Fagin.eso_iff

#print axioms: 3 theorems, no axioms.

85.111 Quantum circuits

On computational-basis states CNOT and Toffoli are involutions and three alternating CNOTs make SWAP; as integer matrices the unnormalized Hadamard squares to \(2I\) and the Pauli matrices anticommute. \(\mathrm {CNOT}_{12}\mathrm {CNOT}_{21}\mathrm {CNOT}_{12}=\mathrm {SWAP};\quad XZ=-ZX\).

found/QuantumCirc.lean

/-
  T184. found/QuantumCirc — quantum circuits as a point (known range):
  * Computational-basis (reversible) gates on bit tuples: NOT, CNOT, Toffoli;
    CNOT is an involution, and CNOT₁₂ ∘ CNOT₂₁ ∘ CNOT₁₂ = SWAP.
  * Single-qubit gates as 2×2 integer matrices (unnormalized):
    H² = 2·I, X² = I, Z² = I, XZ = −ZX (the Pauli anticommutation).
  ZX-calculus rewriting is the diagrammatic line (cited); amplitudes over ℂ
  need the analysis point (T118).

  Lean 4 core only, concrete computations by rfl, no axioms.
-/

namespace Found

namespace QC

def cnot12 : Bool × Bool → Bool × Bool
  | (a, b) => (a, xor a b)

def cnot21 : Bool × Bool → Bool × Bool
  | (a, b) => (xor a b, b)

def swap : Bool × Bool → Bool × Bool
  | (a, b) => (b, a)

theorem cnot_involution (x : Bool × Bool) : cnot12 (cnot12 x) = x := by
  cases x with
  | mk a b => cases a <;> cases b <;> rfl

theorem three_cnots (x : Bool × Bool) : cnot12 (cnot21 (cnot12 x)) = swap x := by
  cases x with
  | mk a b => cases a <;> cases b <;> rfl

def toffoli : Bool × Bool × Bool → Bool × Bool × Bool
  | (a, b, c) => (a, b, xor (a && b) c)

theorem toffoli_involution (x : Bool × Bool × Bool) : toffoli (toffoli x) = x := by
  cases x with
  | mk a bc => cases bc with
    | mk b c => cases a <;> cases b <;> cases c <;> rfl

structure M2 where
  a : Int
  b : Int
  c : Int
  d : Int

def mul (x y : M2) : M2 :=
  ⟨x.a * y.a + x.b * y.c, x.a * y.b + x.b * y.d, x.c * y.a + x.d * y.c, x.c * y.b + x.d * y.d⟩

def H : M2 := ⟨1, 1, 1, -1⟩
def X : M2 := ⟨0, 1, 1, 0⟩
def Z : M2 := ⟨1, 0, 0, -1⟩

theorem H_sq : mul H H = ⟨2, 0, 0, 2⟩ := rfl
theorem X_sq : mul X X = ⟨1, 0, 0, 1⟩ := rfl
theorem Z_sq : mul Z Z = ⟨1, 0, 0, 1⟩ := rfl
theorem XZ_anti : mul X Z = ⟨0, -1, 1, 0⟩ ∧ mul Z X = ⟨0, 1, -1, 0⟩ := ⟨rfl, rfl⟩
theorem HXH : mul (mul H X) H = ⟨2, 0, 0, -2⟩ := rfl

end QC

end Found

#print axioms Found.QC.cnot_involution
#print axioms Found.QC.three_cnots
#print axioms Found.QC.toffoli_involution
#print axioms Found.QC.H_sq
#print axioms Found.QC.XZ_anti
#print axioms Found.QC.HXH

#print axioms: 6 theorems, no axioms.

85.112 Alternative set theory

In the tree universe with full separation every subclass of a set is a set, so Vopěnka’s condition that some semiset is not a set is incompatible with separation. \(\neg \exists A\,(A\subseteq a\wedge A\ \text {not a set})\) under separation.

found/AST.lean

/-
  T166. found/AST — Vopěnka's alternative set theory as a point: classes,
  sets, and semisets (subclasses of sets); AST's characteristic condition is
  that some semiset is not a set (e.g. the class of "small" naturals).
  * In the V point with full separation (T88, T91) every semiset is a set:
    AST's condition contradicts separation — the line AST ⟂ ZF-style
    separation; AST lives where separation is restricted (to set
    formulas), like NF/GPK (T106, T164).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.NBG

namespace Found

namespace AST

open WF

/-- a semiset: a respecting class contained in some set -/
def Semiset (A : NBG.Cls.{0}) : Prop := ∃ a : V.{0}, ∀ x, A.p x → Mem x a

def IsSet (A : NBG.Cls.{0}) : Prop := ∃ s : V.{0}, ∀ x, Mem x s ↔ A.p x

/-- AST's condition: a proper semiset -/
def ProperSemiset : Prop := ∃ A : NBG.Cls.{0}, Semiset A ∧ ¬ IsSet A

/-- with full separation (V, T91) every semiset is a set -/
theorem semiset_is_set (A : NBG.Cls.{0}) (h : Semiset A) : IsSet A :=
  match h with
  | ⟨a, ha⟩ => NBG.subclass_set A a ha

theorem ast_contradicts_separation : ¬ ProperSemiset :=
  fun ⟨A, hs, hn⟩ => hn (semiset_is_set A hs)

end AST

end Found

#print axioms Found.AST.semiset_is_set
#print axioms Found.AST.ast_contradicts_separation

#print axioms: 2 theorems, no axioms.

85.113 Condensed sets

For any type \(X\), the presheaf \(S\mapsto (S\to X)\) sends disjoint unions to products and the empty set to a point, as setoid isomorphisms with pointwise equality: the finite part of the condensed sheaf condition. \(X^{S\sqcup T}\cong X^S\times X^T,\quad X^{\varnothing }\cong 1\).

found/Condensed.lean

/-
  T202. found/Condensed — condensed (and pyknotic) sets as a point, at the
  level reachable without topology: a condensed set is a presheaf on
  profinite sets sending finite disjoint unions to products (plus a descent
  condition for surjections, cited).
  * For any type X, S ↦ (S → X) sends S ⊕ T to the product: the setoid
    isomorphism (S ⊕ T → X) ≅ (S → X) × (T → X), pointwise (no funext),
    and the empty union to the point.
  Profinite sets, the descent condition and the comparison with
  topological spaces are cited.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Core

namespace Found

namespace Cond2

open Core

def funS (S X : Type) : Setd.{0} := ⟨S → X, fun f g => ∀ s, f s = g s, fun _ _ => rfl,
  fun h s => (h s).symm, fun h k s => (h s).trans (k s)⟩

def split {S T X : Type} : SHom (funS (S ⊕ T) X) (prodS (funS S X) (funS T X)) :=
  ⟨fun f => (fun s => f (.inl s), fun t => f (.inr t)), fun h => ⟨fun _ => h _, fun _ => h _⟩⟩

def join {S T X : Type} : SHom (prodS (funS S X) (funS T X)) (funS (S ⊕ T) X) :=
  ⟨fun p u => match u with | .inl s => p.1 s | .inr t => p.2 t,
   fun h u => match u with | .inl s => h.1 s | .inr t => h.2 t⟩

theorem sum_to_product (S T X : Type) : Iso' (funS (S ⊕ T) X) (prodS (funS S X) (funS T X)) :=
  ⟨split, join, fun _ u => match u with | .inl _ => rfl | .inr _ => rfl,
   fun _ => ⟨fun _ => rfl, fun _ => rfl⟩⟩

theorem empty_to_point (X : Type) : Iso' (funS Empty X) unitS :=
  ⟨⟨fun _ => PUnit.unit, fun _ => trivial⟩, ⟨(fun _ (e : Empty) => nomatch e), (fun _ (e : Empty) => nomatch e)⟩,
   (fun _ (e : Empty) => nomatch e), (fun _ => trivial)⟩

end Cond2

end Found

#print axioms Found.Cond2.sum_to_product
#print axioms Found.Cond2.empty_to_point

#print axioms: 2 theorems, no axioms.

85.114 Martin’s axiom (countable case)

Given countably many dense sets with explicit extension maps, the recursively built descending sequence generates a filter, upward closed and directed, that meets every one of them. \(\forall n\,\exists q\in G\cap D_n,\quad G\ \text {a filter}\).

found/MartinAxiom.lean

/-
  T189. found/MartinAxiom — Martin's axiom as a point: the
  Rasiowa–Sikorski lemma (its countable, provable case) on a poset of
  conditions (the forcing coordinate, T108):
  * given dense sets Dₙ with explicit extension maps eₙ (eₙ p ≤ p,
    eₙ p ∈ Dₙ), the recursive sequence pₙ₊₁ = eₙ pₙ is descending and meets
    every Dₙ; its upward closure is a filter meeting all Dₙ (generic for the
    family).
  MA_κ (κ < 𝔠 dense sets, ccc posets) is the condition beyond the countable
  case (cited); V = L and GCH are T169.

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace MA

universe u

variable {P : Type u} (le : P → P → Prop) (refl : ∀ p, le p p)
  (trans : ∀ {a b c}, le a b → le b c → le a c)

def seq (e : Nat → P → P) (p0 : P) : Nat → P
  | 0 => p0
  | n + 1 => e n (seq e p0 n)

theorem descending (e : Nat → P → P) (he : ∀ n p, le (e n p) p) (p0 : P) :
    ∀ n, le (seq e p0 (n + 1)) (seq e p0 n) := fun n => he n _

include refl trans in
theorem desc_le (e : Nat → P → P) (he : ∀ n p, le (e n p) p) (p0 : P) :
    ∀ n k, le (seq e p0 (n + k)) (seq e p0 n)
  | _, 0 => refl _
  | n, k + 1 => trans (he _ _) (desc_le e he p0 n k)

/-- the generic filter: conditions above some element of the sequence -/
def G (e : Nat → P → P) (p0 : P) (q : P) : Prop := ∃ n, le (seq e p0 n) q

include refl in
theorem meets (D : Nat → P → Prop) (e : Nat → P → P) (hD : ∀ n p, D n (e n p)) (p0 : P) (n : Nat) :
    ∃ q, D n q ∧ G le e p0 q := ⟨seq e p0 (n + 1), hD n _, n + 1, refl _⟩

include refl trans in
/-- G is a filter: upward closed and any two members have a common lower member in G -/
theorem filter_directed (e : Nat → P → P) (he : ∀ n p, le (e n p) p) (p0 : P) {q r : P}
    (hq : G le e p0 q) (hr : G le e p0 r) : ∃ s, G le e p0 s ∧ le s q ∧ le s r :=
  match hq, hr with
  | ⟨n, hn⟩, ⟨m, hm⟩ => ⟨seq e p0 (n + m), ⟨n + m, refl _⟩,
      trans (desc_le le refl trans e he p0 n m) hn,
      trans (by rw [Nat.add_comm]; exact desc_le le refl trans e he p0 m n) hm⟩

include trans in
theorem filter_up (e : Nat → P → P) (p0 : P) {q r : P} (hq : G le e p0 q) (h : le q r) : G le e p0 r :=
  match hq with
  | ⟨n, hn⟩ => ⟨n, trans hn h⟩

end MA

end Found

#print axioms Found.MA.desc_le
#print axioms Found.MA.meets
#print axioms Found.MA.filter_directed
#print axioms Found.MA.filter_up

#print axioms: 4 theorems, no axioms.

85.115 Predicativism

Extensions of formulas quantifying only over numbers are closed under the connectives and number quantifiers, and the impredicative definition of the natural numbers as the intersection of all inductive sets agrees with the predicative one by finitely many successors. \((\forall X\,(X0\wedge \forall k(Xk\to X(k+1))\to Xn))\iff \exists k\,(S^k0=n)\).

found/Predicative.lean

/-
  T199. found/Predicative — predicativism (Weyl, Feferman) as a point: the
  comprehension coordinate restricted to formulas quantifying only over
  numbers (arithmetical, ACA₀-style), with impredicative definitions
  replaced by inductive generation.
  * Arithmetical formulas over decidable atoms; their extensions are closed
    under ∧, ∨, ¬ and number quantifiers (structural).
  * Weyl's example: the impredicative definition of ℕ ("in every set
    containing 0 and closed under successor", quantifying over all sets) is
    equivalent to the predicative one ("reached by finitely many
    successors"): the impredicative ∀X can be eliminated here.
  Feferman's predicative ordinal Γ₀ is the ordinal-analysis line (T124, cited).

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: imp_nat is stated with impredicative Prop (used only by one instantiation).
-/

namespace Found

namespace Pred

inductive AF where
  | atom : (Nat → Nat → Bool) → AF        -- decidable relation of (bound var, parameter)
  | neg : AF → AF
  | and : AF → AF → AF
  | or : AF → AF → AF
  | ex : AF → AF                          -- ∃k, with k becoming the new parameter
  | all : AF → AF

def sat : AF → Nat → Nat → Prop
  | .atom r, x, p => r x p = true
  | .neg a, x, p => ¬ sat a x p
  | .and a b, x, p => sat a x p ∧ sat b x p
  | .or a b, x, p => sat a x p ∨ sat b x p
  | .ex a, x, _ => ∃ k, sat a x k
  | .all a, x, _ => ∀ k, sat a x k

/-- the extension of a predicative formula: a set of numbers -/
def ext (a : AF) (p : Nat) : Nat → Prop := fun x => sat a x p

theorem ext_and (a b : AF) (p x : Nat) : ext (.and a b) p x ↔ ext a p x ∧ ext b p x := Iff.rfl
theorem ext_neg (a : AF) (p x : Nat) : ext (.neg a) p x ↔ ¬ ext a p x := Iff.rfl
theorem ext_ex (a : AF) (p x : Nat) : ext (.ex a) p x ↔ ∃ k, ext a k x := Iff.rfl

/-! Weyl: impredicative ℕ vs predicative ℕ -/

def imp_nat (n : Nat) : Prop := ∀ X : Nat → Prop, X 0 → (∀ k, X k → X (k + 1)) → X n

def iter : Nat → Nat
  | 0 => 0
  | k + 1 => iter k + 1

def pred_nat (n : Nat) : Prop := ∃ k, iter k = n

theorem iter_id : (k : Nat) → iter k = k
  | 0 => rfl
  | k + 1 => congrArg (· + 1) (iter_id k)

theorem imp_to_pred (n : Nat) (h : imp_nat n) : pred_nat n :=
  h pred_nat ⟨0, rfl⟩ (fun _ ⟨j, e⟩ => ⟨j + 1, congrArg (· + 1) e⟩)

theorem pred_to_imp (n : Nat) (h : pred_nat n) : imp_nat n :=
  match h with
  | ⟨k, e⟩ => fun X h0 hs => e ▸ go X h0 hs k
where
  go (X : Nat → Prop) (h0 : X 0) (hs : ∀ k, X k → X (k + 1)) : (k : Nat) → X (iter k)
    | 0 => h0
    | k + 1 => hs _ (go X h0 hs k)

theorem weyl (n : Nat) : imp_nat n ↔ pred_nat n := ⟨imp_to_pred n, pred_to_imp n⟩

theorem all_pred (n : Nat) : pred_nat n := ⟨n, iter_id n⟩

end Pred

end Found

#print axioms Found.Pred.ext_and
#print axioms Found.Pred.ext_neg
#print axioms Found.Pred.ext_ex
#print axioms Found.Pred.weyl
#print axioms Found.Pred.all_pred

#print axioms: 5 theorems, no axioms.

85.116 Proof nets

In one-sided multiplicative linear logic, linear negation is an involution and every derivable sequent has exactly twice as many atoms as tensors plus one, the counting shadow of the acyclic-connected switching criterion. \(\vdash \Gamma \ \Rightarrow \ \#\mathrm {at}(\Gamma )=2(\#\otimes (\Gamma )+1)\).

found/ProofNets.lean

/-
  T179. found/ProofNets — proof nets as a point (multiplicative linear
  logic, MLL, the linear coordinate T68): formulas, involutive linear
  negation, one-sided sequent derivations (ax, ⊗, ⅋, exchange).
  * The proof-net count invariant (Euler characteristic of a correct net):
    for every derivable ⊢ Γ,  #atoms(Γ) = 2·(#⊗(Γ) + 1), i.e. a net with
    k axiom links has exactly k − 1 tensors — the numerical shadow of the
    Danos–Regnier criterion (switching graphs are trees).
  Full sequentialization, deep inference and the geometry of interaction
  are cited.

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace PN

inductive F where
  | pos : Nat → F
  | neg : Nat → F
  | tensor : F → F → F
  | par : F → F → F

def dual : F → F
  | .pos n => .neg n
  | .neg n => .pos n
  | .tensor a b => .par (dual a) (dual b)
  | .par a b => .tensor (dual a) (dual b)

theorem dual_dual : (a : F) → dual (dual a) = a
  | .pos _ => rfl
  | .neg _ => rfl
  | .tensor a b => by show F.tensor (dual (dual a)) (dual (dual b)) = _; rw [dual_dual a, dual_dual b]
  | .par a b => by show F.par (dual (dual a)) (dual (dual b)) = _; rw [dual_dual a, dual_dual b]

def atc : F → Nat
  | .pos _ => 1
  | .neg _ => 1
  | .tensor a b => atc a + atc b
  | .par a b => atc a + atc b

def tc : F → Nat
  | .pos _ => 0
  | .neg _ => 0
  | .tensor a b => tc a + tc b + 1
  | .par a b => tc a + tc b

def sumL (m : F → Nat) : List F → Nat
  | [] => 0
  | a :: l => m a + sumL m l

theorem sumL_app (m : F → Nat) : (l k : List F) → sumL m (l ++ k) = sumL m l + sumL m k
  | [], k => (Nat.zero_add _).symm
  | a :: l, k => by
    show m a + sumL m (l ++ k) = m a + sumL m l + sumL m k
    rw [sumL_app m l k, Nat.add_assoc]

inductive D : List F → Type where
  | ax (n : Nat) : D [.pos n, .neg n]
  | tensor {Γ Δ : List F} {a b : F} : D (Γ ++ [a]) → D (Δ ++ [b]) → D (Γ ++ Δ ++ [.tensor a b])
  | par {Γ : List F} {a b : F} : D (Γ ++ [a, b]) → D (Γ ++ [.par a b])
  | exch {Γ Δ : List F} {a b : F} : D (Γ ++ [a, b] ++ Δ) → D (Γ ++ [b, a] ++ Δ)

theorem dbl (X : Nat) : (Y : Nat) → X + X + 1 + 1 + (Y + Y + 1 + 1) = X + Y + 1 + (X + Y + 1) + 1 + 1
  | 0 => by
    show X + X + 1 + 1 + 1 + 1 = X + 1 + X + 1 + 1 + 1
    rw [Nat.add_right_comm X 1 X]
  | Y + 1 => by
    show X + X + 1 + 1 + (Y + 1 + Y + 1 + 1 + 1) = X + Y + 1 + 1 + (X + Y + 1) + 1 + 1 + 1
    rw [Nat.add_right_comm Y 1 Y, Nat.add_right_comm (X + Y + 1) 1 (X + Y + 1)]
    show X + X + 1 + 1 + (Y + Y + 1 + 1) + 1 + 1 = X + Y + 1 + (X + Y + 1) + 1 + 1 + 1 + 1
    rw [dbl X Y]

theorem ten_arith (g d A B tg td TA TB : Nat)
    (h1 : g + A = tg + TA + (tg + TA) + 1 + 1) (h2 : d + B = td + TB + (td + TB) + 1 + 1) :
    g + d + (A + B) = tg + td + (TA + TB + 1) + (tg + td + (TA + TB + 1)) + 1 + 1 := by
  rw [Nat.add_add_add_comm g d A B, h1, h2]
  show _ = tg + td + (TA + TB) + 1 + (tg + td + (TA + TB) + 1) + 1 + 1
  rw [Nat.add_add_add_comm tg td TA TB]
  exact dbl _ _

theorem sumL_swap (m : F → Nat) (Γ Δ : List F) (a b : F) :
    sumL m (Γ ++ [a, b] ++ Δ) = sumL m (Γ ++ [b, a] ++ Δ) := by
  rw [sumL_app, sumL_app, sumL_app, sumL_app]
  show sumL m Γ + (m a + (m b + 0)) + sumL m Δ = sumL m Γ + (m b + (m a + 0)) + sumL m Δ
  rw [Nat.add_zero, Nat.add_zero, Nat.add_comm (m a)]

/-- Euler-characteristic invariant of MLL proofs: atoms = 2·(tensors + 1) -/
theorem euler {Γ : List F} (d : D Γ) : sumL atc Γ = sumL tc Γ + sumL tc Γ + 1 + 1 := by
  induction d with
  | ax _ => rfl
  | @tensor Γ Δ a b _ _ ih1 ih2 =>
    rw [sumL_app, sumL_app] at ih1 ih2
    rw [sumL_app, sumL_app, sumL_app, sumL_app]
    show sumL atc Γ + sumL atc Δ + (atc a + atc b + 0) =
      sumL tc Γ + sumL tc Δ + (tc a + tc b + 1 + 0) + (sumL tc Γ + sumL tc Δ + (tc a + tc b + 1 + 0)) + 1 + 1
    have h1 : sumL atc Γ + (atc a + 0) = _ := ih1
    have h2 : sumL atc Δ + (atc b + 0) = _ := ih2
    rw [Nat.add_zero] at h1 h2 ⊢
    rw [Nat.add_zero]
    exact ten_arith _ _ _ _ _ _ _ _ h1 h2
  | @par Γ a b _ ih =>
    rw [sumL_app, sumL_app] at ih
    rw [sumL_app, sumL_app]
    show sumL atc Γ + (atc a + atc b + 0) = sumL tc Γ + (tc a + tc b + 0) + (sumL tc Γ + (tc a + tc b + 0)) + 1 + 1
    have h : sumL atc Γ + (atc a + (atc b + 0)) = sumL tc Γ + (tc a + (tc b + 0)) + (sumL tc Γ + (tc a + (tc b + 0))) + 1 + 1 := ih
    rw [Nat.add_zero] at h ⊢
    exact h
  | @exch Γ Δ a b _ ih =>
    rw [sumL_swap atc Γ Δ b a, sumL_swap tc Γ Δ b a]
    exact ih

end PN

end Found

#print axioms Found.PN.dual_dual
#print axioms Found.PN.dbl
#print axioms Found.PN.ten_arith
#print axioms Found.PN.sumL_swap
#print axioms Found.PN.euler

#print axioms: 5 theorems, no axioms.

85.117 (\(\infty \),n)-categories

Iterated identity cells of any type form a globular set with inverse cells, an \((\infty ,0)\)-category; in the CIC point any two cells with the same boundary are equal, so types are 0-truncated there. \(s\circ s=s\circ t,\ t\circ s=t\circ t;\quad \partial c=\partial d\Rightarrow c=d\ (\mathrm {CIC})\).

found/InfN.lean

/-
  T196. found/InfN — (∞,n)-categories as a point, at the definition level:
  globular sets (cells of every dimension with source/target satisfying the
  globular identities) are the shape parameter; (∞,n) means cells above
  dimension n are invertible.
  * Every type A gives a globular set by iterated identity types
    (cells: x, then (x, y, x = y), …): the ∞-groupoid of a type, an
    (∞,0)-category; the globular identities hold.
  * In the CIC point all higher cells collapse: any two cells with the same
    boundary are equal (proof irrelevance) — CIC types are 0-truncated; the
    non-truncated version is Cubical Agda's (work/agda/Univalence.agda).
  Complicial sets, Θₙ-spaces and comparison theorems are cited.

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: proof irrelevance (collapse).
-/

namespace Found

namespace InfN

universe u

structure Glob where
  C : Nat → Type u
  s : (k : Nat) → C (k + 1) → C k
  t : (k : Nat) → C (k + 1) → C k
  glob_s : ∀ k (x : C (k + 2)), s k (s (k + 1) x) = s k (t (k + 1) x)
  glob_t : ∀ k (x : C (k + 2)), t k (s (k + 1) x) = t k (t (k + 1) x)

/-- iterated identity cells of a type -/
def Cell (A : Type u) : Nat → Type u
  | 0 => A
  | k + 1 => (x : Cell A k) × (y : Cell A k) × PLift (x = y)

def src (A : Type u) (k : Nat) (c : Cell A (k + 1)) : Cell A k := c.1
def tgt (A : Type u) (k : Nat) (c : Cell A (k + 1)) : Cell A k := c.2.1

theorem bnd_eq (A : Type u) (k : Nat) (c : Cell A (k + 1)) : src A k c = tgt A k c := c.2.2.down

/-- the ∞-groupoid of a type -/
def ofType (A : Type u) : Glob.{u} where
  C := Cell A
  s := src A
  t := tgt A
  glob_s k x := congrArg (src A k) (bnd_eq A (k + 1) x)
  glob_t k x := congrArg (tgt A k) (bnd_eq A (k + 1) x)

/-- every cell has an inverse cell (groupoid: (∞,0)) -/
def inv (A : Type u) (k : Nat) (c : Cell A (k + 1)) : Cell A (k + 1) :=
  ⟨c.2.1, c.1, ⟨c.2.2.down.symm⟩⟩

theorem inv_bnd (A : Type u) (k : Nat) (c : Cell A (k + 1)) :
    src A k (inv A k c) = tgt A k c ∧ tgt A k (inv A k c) = src A k c := ⟨rfl, rfl⟩

/-- CIC collapse: cells with the same boundary are equal -/
theorem collapse (A : Type u) (k : Nat) (c d : Cell A (k + 1))
    (hs : src A k c = src A k d) (ht : tgt A k c = tgt A k d) : c = d :=
  match c, d with
  | ⟨x, y, ⟨_⟩⟩, ⟨x', y', ⟨_⟩⟩ => by
    cases hs
    cases ht
    rfl

end InfN

end Found

#print axioms Found.InfN.ofType
#print axioms Found.InfN.inv_bnd
#print axioms Found.InfN.collapse

#print axioms: 3 theorems, no axioms.

85.118 The Shulman path

The four proved stages of the arrow from set theory with universes to homotopy type theory are packaged as one theorem: universe closure, Glivenko’s double-negation translation, a model structure on setoids, and interval paths; the final step to every \(\infty \)-topos is cited. \(U\ \text {closed}\ \wedge \ (\vdash _c\varphi \iff \vdash _i\neg \neg \varphi )\wedge \exists M\ \wedge \ \mathrm {refl}\ \text {paths}\).

found/ShulmanPath.lean

/-
  T136. found/ShulmanPath — one arrow of the map, as a composite of proved
  stages (each stage is an existing point; only the last step is cited):
    ZFC + universes (T104: U closed under pairing, union, power)
    → classical logic via double negation (T66: Glivenko)
    → model categories (T133: every E-category, e.g. setoids, carries the
      trivial model structure; Ho = C on objects, T135)
    → HoTT model with an interval (T127/OrtonPitts: paths over an interval
      value, e.g. the two-point interval)
    → Shulman 2019 (every ∞-topos models HoTT with univalent universes): cited.
  The theorem below packages the four proved stages into one statement.

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: universe hierarchy, impredicative Prop (the T104 stage).
-/
import found.Grothendieck
import found.DNTrans
import found.Homotopy
import found.OrtonPitts

namespace Found

namespace Shulman

open WF

theorem path :
    -- stage 1: universe closure in V
    (∀ x y : V.{1}, Mem x Groth.U → Mem y Groth.U → Mem (IZF.pair x y) Groth.U) ∧
    -- stage 2: classical provability = intuitionistic provability of ¬¬
    (∀ φ : Prp.Form, Prp.CD (fun _ => False) φ ↔ Prp.PD true (fun _ => False) (Prp.N φ)) ∧
    -- stage 3: model structure on setoids, weak equivalences = isomorphisms
    (∃ M : Model.ModelStr SetdCat.{0}, ∀ {a b : SetdCat.{0}.Ob} (f : SetdCat.Hom a b), M.W f ↔ Model.IsIso f) ∧
    -- stage 4: interval paths exist and are reflexive (HoTT side, an interval value)
    (∀ (A : Type) (a : A), (OP.refl' OP.two a).p OP.two.i0 = a) :=
  ⟨Groth.U_pair, Prp.glivenko0, ⟨Model.trivialModel _, fun _ => Iff.rfl⟩, fun _ _ => rfl⟩

end Shulman

end Found

#print axioms Found.Shulman.path

#print axioms: 1 theorems, no axioms.

85.119 Local universes

Representing a type in context as a map into a universe makes substitution precomposition, so the identity and composition laws, comprehension with projection and pairing, and substitution into pairs all hold definitionally. \(A[\mathrm {id}]=A,\ A[\sigma ][\tau ]=A[\sigma \tau ],\ q[\langle \sigma ,a\rangle ]=a\).

found/LocalUniverse.lean

/-
  T155. found/LocalUniverse — local universes (Lumsdaine–Warren) as a
  point: the coherence problem of type-theoretic models is solved by
  representing a type in context Γ as a map Γ → U into a universe
  (U, El) — a value of the universe coordinate — so substitution is
  precomposition and is strictly functorial.
  * types Γ ⊢ A := Γ → U; terms := sections of El ∘ A; substitution by
    precomposition; strict laws A[id] = A, A[σ][τ] = A[σ∘τ] (rfl).
  * comprehension Γ.A := Σ γ, El (A γ) with projection and pairing; the
    substitution of a pair is the pair of substitutions (rfl).
  Type-theoretic model toposes (Shulman) are cited.

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace LU

universe u v

structure Univ where
  U : Type u
  El : U → Type u

variable (W : Univ.{u})

def Ty (Γ : Type u) : Type u := Γ → W.U
def Tm (Γ : Type u) (A : Ty W Γ) : Type u := (γ : Γ) → W.El (A γ)

def subTy {Δ Γ : Type u} (A : Ty W Γ) (σ : Δ → Γ) : Ty W Δ := fun δ => A (σ δ)
def subTm {Δ Γ : Type u} {A : Ty W Γ} (a : Tm W Γ A) (σ : Δ → Γ) : Tm W Δ (subTy W A σ) := fun δ => a (σ δ)

theorem sub_id {Γ : Type u} (A : Ty W Γ) : subTy W A (fun γ => γ) = A := rfl
theorem sub_comp {Θ Δ Γ : Type u} (A : Ty W Γ) (σ : Δ → Γ) (τ : Θ → Δ) :
    subTy W (subTy W A σ) τ = subTy W A (fun θ => σ (τ θ)) := rfl
theorem subTm_comp {Θ Δ Γ : Type u} {A : Ty W Γ} (a : Tm W Γ A) (σ : Δ → Γ) (τ : Θ → Δ) :
    subTm W (subTm W a σ) τ = subTm W a (fun θ => σ (τ θ)) := rfl

def ext (Γ : Type u) (A : Ty W Γ) : Type u := (γ : Γ) × W.El (A γ)
def p {Γ : Type u} {A : Ty W Γ} : ext W Γ A → Γ := fun x => x.1
def q {Γ : Type u} {A : Ty W Γ} : Tm W (ext W Γ A) (subTy W A (p W)) := fun x => x.2
def pair {Δ Γ : Type u} {A : Ty W Γ} (σ : Δ → Γ) (a : Tm W Δ (subTy W A σ)) : Δ → ext W Γ A :=
  fun δ => ⟨σ δ, a δ⟩

theorem p_pair {Δ Γ : Type u} {A : Ty W Γ} (σ : Δ → Γ) (a : Tm W Δ (subTy W A σ)) :
    (fun δ => p W (pair W σ a δ)) = σ := rfl
theorem q_pair {Δ Γ : Type u} {A : Ty W Γ} (σ : Δ → Γ) (a : Tm W Δ (subTy W A σ)) :
    subTm W (q W) (pair W σ a) = a := rfl
theorem pair_sub {Θ Δ Γ : Type u} {A : Ty W Γ} (σ : Δ → Γ) (a : Tm W Δ (subTy W A σ)) (τ : Θ → Δ) :
    (fun θ => pair W σ a (τ θ)) = pair W (fun θ => σ (τ θ)) (subTm W a τ) := rfl

end LU

end Found

#print axioms Found.LU.sub_id
#print axioms Found.LU.sub_comp
#print axioms Found.LU.subTm_comp
#print axioms Found.LU.p_pair
#print axioms Found.LU.q_pair
#print axioms Found.LU.pair_sub

#print axioms: 6 theorems, no axioms.

85.120 Presentable categories and localization

In a power set every subset is the directed union of its finite subsets, and a closure operator is a reflective localization: its value is local and lies below a local object exactly when the original does. \(Lx\le y\iff x\le y\ \ (y\ \text {local})\).

found/Presentable.lean

/-
  T154. found/Presentable — locally presentable categories and Bousfield
  localization as a point, in the order-enriched case of the category
  parameter:
  * Presentability: in the power set of a type, every subset is the
    (directed) union of its finite subsets (lists) — the compact objects
    generate under filtered colimits (ℵ₀-presentable / algebraic lattice).
  * Bousfield (reflective) localization: a closure operator L
    (monotone, inflationary, idempotent); local objects are the fixed
    points, and L x is the reflection: L x ≤ y ⟺ x ≤ y for local y.
    Left exactness corresponds to L preserving meets (nuclei, T110).
  Combinatorial model categories and Dugger/Smith presentation theorems
  are cited.

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Pres

universe u

/-! ## presentability: unions of finite subsets -/

def finSub {X : Type u} (A : X → Prop) (l : List X) : Prop := ∀ x, x ∈ l → A x

theorem union_of_finite {X : Type u} (A : X → Prop) (x : X) :
    A x ↔ ∃ l : List X, finSub A l ∧ x ∈ l :=
  ⟨fun h => ⟨[x], ⟨(fun y (m : y ∈ [x]) => by
      cases m with
      | head => exact h
      | tail _ m' => exact nomatch m'), List.Mem.head _⟩⟩,
   fun ⟨_, hl, m⟩ => hl x m⟩

theorem mem_app_inv {X : Type u} {x : X} : (l k : List X) → x ∈ l ++ k → x ∈ l ∨ x ∈ k
  | [], _, m => Or.inr m
  | _ :: l, k, m => by
    cases m with
    | head => exact Or.inl (.head _)
    | tail _ m' => exact (mem_app_inv l k m').elim (fun h => Or.inl (.tail _ h)) Or.inr

theorem mem_app_l {X : Type u} {x : X} : (l k : List X) → x ∈ l → x ∈ l ++ k
  | _ :: _, _, .head _ => .head _
  | _ :: l, k, .tail _ m => .tail _ (mem_app_l l k m)

theorem mem_app_r {X : Type u} {x : X} : (l k : List X) → x ∈ k → x ∈ l ++ k
  | [], _, m => m
  | _ :: l, k, m => .tail _ (mem_app_r l k m)

/-- the system of finite subsets is directed -/
theorem directed {X : Type u} (A : X → Prop) (l k : List X) (hl : finSub A l) (hk : finSub A k) :
    finSub A (l ++ k) ∧ (∀ x, x ∈ l → x ∈ l ++ k) ∧ (∀ x, x ∈ k → x ∈ l ++ k) :=
  ⟨fun x m => (mem_app_inv l k m).elim (hl x) (hk x),
   fun _ m => mem_app_l l k m, fun _ m => mem_app_r l k m⟩

/-! ## Bousfield localization as a reflection -/

structure Closure (P : Type u) (le : P → P → Prop) where
  L : P → P
  mono : ∀ {a b}, le a b → le (L a) (L b)
  infl : ∀ a, le a (L a)
  idem : ∀ a, le (L (L a)) (L a)

variable {P : Type u} {le : P → P → Prop} (trans : ∀ {a b c}, le a b → le b c → le a c)

def Local (C : Closure P le) (y : P) : Prop := le (C.L y) y

include trans in
theorem reflection (C : Closure P le) (x y : P) (hy : Local C y) : le (C.L x) y ↔ le x y :=
  ⟨fun h => trans (C.infl x) h, fun h => trans (C.mono h) hy⟩

theorem L_local (C : Closure P le) (x : P) : Local C (C.L x) := C.idem x

end Pres

end Found

#print axioms Found.Pres.union_of_finite
#print axioms Found.Pres.mem_app_inv
#print axioms Found.Pres.directed
#print axioms Found.Pres.reflection
#print axioms Found.Pres.L_local

#print axioms: 5 theorems, no axioms.

85.121 V = L

For the quantifier-free definable power set with parameters, every member of \(\mathrm {Def}(x)\) is a subset of \(x\), and a transitive \(x\) is contained in \(\mathrm {Def}(x)\), so the constructible hierarchy increases. \(x\ \text {transitive}\Rightarrow x\subseteq \mathrm {Def}(x)\subseteq \mathcal P(x)\).

found/VeqL.lean

/-
  T169. found/VeqL — V = L as a point: the constructible hierarchy
  L₀ = ∅, L_{α+1} = Def(L_α), and V = L as a condition on the set
  coordinate (with GCH, ◊ consequences, cited).
  Here: the definable-power-set operator Def on Aczel's V (T109), for the
  quantifier-free fragment with parameters from x (the Gödel-operation
  core):
  * every member of Def(x) is a subset of x (Def(x) ⊆ 𝒫(x));
  * if x is transitive then x ⊆ Def(x) (each y ∈ x is {z ∈ x | z ∈ y}),
    so the L-hierarchy is increasing on transitive stages.
  The full first-order Def, absoluteness of L and V = L ⇒ GCH are cited.

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: impredicative Prop (separation).
-/
import found.IZF

namespace Found

namespace VL

open WF

/-- quantifier-free formulas in the bound variable z and parameters pₙ -/
inductive QF where
  | memP : Nat → QF          -- z ∈ pₙ
  | eqP : Nat → QF           -- z ≈ pₙ
  | neg : QF → QF
  | and : QF → QF → QF

def ev (ρ : Nat → V.{0}) : QF → V.{0} → Prop
  | .memP n, z => Mem z (ρ n)
  | .eqP n, z => Eq' z (ρ n)
  | .neg a, z => ¬ ev ρ a z
  | .and a b, z => ev ρ a z ∧ ev ρ b z

theorem ev_resp (ρ : Nat → V.{0}) : (a : QF) → IZF.Resp (ev ρ a)
  | .memP _ => fun _ _ e h => mem_resp_left e h
  | .eqP _ => fun _ _ e h => eq_trans _ _ _ (eq_symm _ _ e) h
  | .neg a => fun x y e h h' => h (ev_resp ρ a y x (eq_symm _ _ e) h')
  | .and a b => fun x y e h => ⟨ev_resp ρ a x y e h.1, ev_resp ρ b x y e h.2⟩

/-- definable subsets of x with parameters from x -/
def Def (x : V.{0}) : V.{0} :=
  .sup (QF × (Nat → x.I)) (fun p => IZF.sep x (ev (fun n => x.f (p.2 n)) p.1))

theorem def_sub (x w : V.{0}) (hw : Mem w (Def x)) : ∀ z, Mem z w → Mem z x :=
  match hw with
  | ⟨⟨φ, _⟩, e⟩ => fun z m =>
    ((IZF.sep_spec x _ (ev_resp _ φ) z).mp (mem_resp_right m e)).1

def Transitive (x : V.{0}) : Prop := ∀ y z, Mem z y → Mem y x → Mem z x

theorem sub_def (x : V.{0}) (ht : Transitive x) (y : V.{0}) (hy : Mem y x) : Mem y (Def x) :=
  match x, hy with
  | .sup I f, ⟨i, ei⟩ => ⟨⟨.memP 0, fun _ => i⟩, extensionality _ _ (fun z =>
      ⟨fun m => (IZF.sep_spec (.sup I f) _ (ev_resp _ (.memP 0)) z).mpr
          ⟨ht y z m ⟨i, ei⟩, mem_resp_right m ei⟩,
       fun m => mem_resp_right ((IZF.sep_spec (.sup I f) _ (ev_resp _ (.memP 0)) z).mp m).2 (eq_symm _ _ ei)⟩)⟩

end VL

end Found

#print axioms Found.VL.ev_resp
#print axioms Found.VL.def_sub
#print axioms Found.VL.sub_def

#print axioms: 3 theorems, no axioms.

85.122 Typed calculi (PCF)

PCF with naturals, if-zero and a fixed-point operator is given an environment semantics with fuel and a type checker; the factorial written with the fixed point evaluates to 120 at 5 and checks at type nat to nat. \(\mathrm {eval}(\mathrm {fact}\ 5)=120,\quad \vdash \mathrm {fact}:\mathbb N\to \mathbb N\).

found/TypedCalculi.lean

/-
  T144. found/TypedCalculi — typed calculi as points on the λ coordinate:
  * PCF: simply typed λ with naturals, if-zero and a fixed-point operator;
    environment semantics with fuel (no substitution), a type checker, and
    computations: the factorial written with fix evaluates to 120, and the
    term checks at type nat.
  * Fω and λΠ (LF) are the higher-kind / dependent corners of the λ-cube
    (T181); their typing is the PTS line (cited here, PTS in T181).

  Lean 4 core only, concrete computations by rfl, no axioms.
-/

namespace Found

namespace PCF

inductive Ty where
  | nat : Ty
  | arr : Ty → Ty → Ty

inductive Tm where
  | var : Nat → Tm
  | lit : Nat → Tm
  | succ : Tm → Tm
  | pred : Tm → Tm
  | mul : Tm → Tm → Tm
  | ifz : Tm → Tm → Tm → Tm
  | lam : Ty → Tm → Tm
  | app : Tm → Tm → Tm
  | fix : Ty → Ty → Tm → Tm    -- fix f : τ → σ. λ x : τ. body   (x = var 0, f = var 1)

inductive Val where
  | num : Nat → Val
  | clo : List Val → Tm → Val
  | fixc : List Val → Tm → Val

def look : List Val → Nat → Option Val
  | [], _ => none
  | v :: _, 0 => some v
  | _ :: l, n + 1 => look l n

def predN : Nat → Nat
  | 0 => 0
  | n + 1 => n

def asNum : Option Val → Option Nat
  | none => none
  | some (.num n) => some n
  | some (.clo _ _) => none
  | some (.fixc _ _) => none

def mapNum (f : Nat → Nat) : Option Nat → Option Val
  | none => none
  | some n => some (.num (f n))

def mul2 : Option Nat → Option Nat → Option Val
  | none, _ => none
  | some _, none => none
  | some a, some b => some (.num (a * b))

def eval : Nat → List Val → Tm → Option Val
  | 0, _, _ => none
  | _ + 1, ρ, .var n => look ρ n
  | _ + 1, _, .lit n => some (.num n)
  | k + 1, ρ, .succ t => mapNum (· + 1) (asNum (eval k ρ t))
  | k + 1, ρ, .pred t => mapNum predN (asNum (eval k ρ t))
  | k + 1, ρ, .mul s t => mul2 (asNum (eval k ρ s)) (asNum (eval k ρ t))
  | k + 1, ρ, .ifz c a b => branch (asNum (eval k ρ c)) (eval k ρ a) (eval k ρ b)
  | _ + 1, ρ, .lam _ b => some (.clo ρ b)
  | k + 1, ρ, .app s t => apply (eval k ρ s) (eval k ρ t) (fun ρ' b => eval k ρ' b)
  | _ + 1, ρ, .fix _ _ b => some (.fixc ρ b)
where
  branch : Option Nat → Option Val → Option Val → Option Val
    | none, _, _ => none
    | some 0, a, _ => a
    | some (_ + 1), _, b => b
  apply : Option Val → Option Val → (List Val → Tm → Option Val) → Option Val
    | none, _, _ => none
    | some (.num _), _, _ => none
    | some (.clo _ _), none, _ => none
    | some (.clo ρ' b), some v, e => e (v :: ρ') b
    | some (.fixc _ _), none, _ => none
    | some (.fixc ρ' b), some v, e => e (v :: .fixc ρ' b :: ρ') b

/-- fact = fix f. λ n. ifz n 1 (n * f (pred n)) -/
def fact : Tm :=
  .fix .nat .nat (.ifz (.var 0) (.lit 1) (.mul (.var 0) (.app (.var 1) (.pred (.var 0)))))

theorem fact5 : asNum (eval 40 [] (.app fact (.lit 5))) = some 120 := rfl
theorem fact0 : asNum (eval 10 [] (.app fact (.lit 0))) = some 1 := rfl

/-! a type checker -/

def tyEq : Ty → Ty → Bool
  | .nat, .nat => true
  | .nat, .arr _ _ => false
  | .arr _ _, .nat => false
  | .arr a b, .arr c d => tyEq a c && tyEq b d

def lookT : List Ty → Nat → Option Ty
  | [], _ => none
  | v :: _, 0 => some v
  | _ :: l, n + 1 => lookT l n

def isNat : Option Ty → Bool
  | none => false
  | some .nat => true
  | some (.arr _ _) => false

def guard' (b : Bool) (t : Option Ty) : Option Ty := match b with
  | true => t
  | false => none

def appT : Option Ty → Option Ty → Option Ty
  | none, _ => none
  | some .nat, _ => none
  | some (.arr _ _), none => none
  | some (.arr τ σ), some τ' => guard' (tyEq τ τ') (some σ)

def sameT : Option Ty → Option Ty → Option Ty
  | none, _ => none
  | some _, none => none
  | some τ, some σ => guard' (tyEq τ σ) (some τ)

def lamT (τ : Ty) : Option Ty → Option Ty
  | none => none
  | some σ => some (.arr τ σ)

def check : List Ty → Tm → Option Ty
  | Γ, .var n => lookT Γ n
  | _, .lit _ => some .nat
  | Γ, .succ t => guard' (isNat (check Γ t)) (some .nat)
  | Γ, .pred t => guard' (isNat (check Γ t)) (some .nat)
  | Γ, .mul s t => guard' (isNat (check Γ s) && isNat (check Γ t)) (some .nat)
  | Γ, .ifz c a b => guard' (isNat (check Γ c)) (sameT (check Γ a) (check Γ b))
  | Γ, .lam τ b => lamT τ (check (τ :: Γ) b)
  | Γ, .app s t => appT (check Γ s) (check Γ t)
  | Γ, .fix τ σ b => lamT τ (sameT (check (τ :: .arr τ σ :: Γ) b) (some σ))

theorem fact_type : check [] fact = some (.arr .nat .nat) := rfl
theorem fact5_type : check [] (.app fact (.lit 5)) = some .nat := rfl

end PCF

end Found

#print axioms Found.PCF.fact5
#print axioms Found.PCF.fact0
#print axioms Found.PCF.fact_type
#print axioms Found.PCF.fact5_type

#print axioms: 4 theorems, no axioms.

85.123 Pure type systems

Typing in a pure type system is defined over an arbitrary specification with substitution and conversion as parameters; derivations transfer along specification inclusion, so the λ-cube’s edges are embeddings from λ→ up to the calculus of constructions. \(P\subseteq Q\ \Rightarrow \ (\Gamma \vdash _P a:A\Rightarrow \Gamma \vdash _Q a:A)\).

found/PTS.lean

/-
  T181. found/PTS — pure type systems as a point: the specification
  (sorts S, axioms A ⊆ S×S, rules R ⊆ S×S×S) is the parameter; the λ-cube
  is the family of specifications over sorts {*, □} with axiom * : □ and
  rules (*,*) plus any subset of {(□,*), (*,□), (□,□)}:
    λ→, λ2 (System F), λP (LF), λω, λP2, λPω, λω (Fω), λC (CoC).
  * PTS typing over an arbitrary specification (de Bruijn terms; substitution
    and conversion are parameters too, so nothing depends on a particular
    calculus).
  * Cube edges = specification inclusion, and derivability is monotone along
    inclusion: every judgment of λ→ holds in λ2, …, all in λC.
  Strong normalization of λC (and Gödel's T, T182/HAomega) are cited / T79.

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace PTS

inductive Tm (S : Type) where
  | sort : S → Tm S
  | var : Nat → Tm S
  | pi : Tm S → Tm S → Tm S
  | lam : Tm S → Tm S → Tm S
  | app : Tm S → Tm S → Tm S

structure Spec (S : Type) where
  ax : S → S → Prop
  rule : S → S → S → Prop

/-- the operations a calculus supplies: lifting/substitution and conversion -/
structure Ops (S : Type) where
  lookup : List (Tm S) → Nat → Option (Tm S)
  inst : Tm S → Tm S → Tm S          -- B[a/0]
  conv : Tm S → Tm S → Prop

inductive Der {S : Type} (P : Spec S) (O : Ops S) : List (Tm S) → Tm S → Tm S → Prop where
  | ax {Γ s t} : P.ax s t → Der P O Γ (.sort s) (.sort t)
  | var {Γ n A} : O.lookup Γ n = some A → Der P O Γ (.var n) A
  | pi {Γ A B s₁ s₂ s₃} : P.rule s₁ s₂ s₃ → Der P O Γ A (.sort s₁) → Der P O (A :: Γ) B (.sort s₂) →
      Der P O Γ (.pi A B) (.sort s₃)
  | lam {Γ A b B s} : Der P O (A :: Γ) b B → Der P O Γ (.pi A B) (.sort s) →
      Der P O Γ (.lam A b) (.pi A B)
  | app {Γ f a A B} : Der P O Γ f (.pi A B) → Der P O Γ a A → Der P O Γ (.app f a) (O.inst B a)
  | conv {Γ a A B s} : Der P O Γ a A → O.conv A B → Der P O Γ B (.sort s) → Der P O Γ a B

def Sub {S : Type} (P Q : Spec S) : Prop :=
  (∀ s t, P.ax s t → Q.ax s t) ∧ (∀ a b c, P.rule a b c → Q.rule a b c)

/-- derivability is monotone along specification inclusion -/
theorem mono {S : Type} {P Q : Spec S} (O : Ops S) (h : Sub P Q) {Γ a A} (d : Der P O Γ a A) :
    Der Q O Γ a A := by
  induction d with
  | ax hx => exact .ax (h.1 _ _ hx)
  | var e => exact .var e
  | pi r _ _ ih1 ih2 => exact .pi (h.2 _ _ _ r) ih1 ih2
  | lam _ _ ih1 ih2 => exact .lam ih1 ih2
  | app _ _ ih1 ih2 => exact .app ih1 ih2
  | conv _ c _ ih1 ih2 => exact .conv ih1 c ih2

/-! ## the λ-cube -/

inductive Srt where
  | star : Srt
  | box : Srt

/-- a cube vertex: which of (□,*), (*,□), (□,□) are allowed -/
structure Vertex where
  poly : Bool     -- (□,*)  terms depending on types (λ2)
  dep : Bool      -- (*,□)  types depending on terms (λP)
  ops : Bool      -- (□,□)  types depending on types (λω)

def allowed (v : Vertex) : Srt → Srt → Bool
  | .star, .star => true
  | .box, .star => v.poly
  | .star, .box => v.dep
  | .box, .box => v.ops

def cube (v : Vertex) : Spec Srt where
  ax s t := s = .star ∧ t = .box
  rule a b c := allowed v a b = true ∧ c = b

def le (v w : Vertex) : Prop :=
  (v.poly = true → w.poly = true) ∧ (v.dep = true → w.dep = true) ∧ (v.ops = true → w.ops = true)

theorem cube_sub (v w : Vertex) (h : le v w) : Sub (cube v) (cube w) :=
  ⟨fun _ _ x => x, fun a b c ⟨hr, e⟩ => ⟨by
    cases a <;> cases b
    · exact hr
    · exact h.2.1 hr
    · exact h.1 hr
    · exact h.2.2 hr, e⟩⟩

def lamArrow : Vertex := ⟨false, false, false⟩
def lamC : Vertex := ⟨true, true, true⟩

theorem bottom_le (v : Vertex) : le lamArrow v :=
  ⟨fun h => Bool.noConfusion h, fun h => Bool.noConfusion h, fun h => Bool.noConfusion h⟩

theorem le_top (v : Vertex) : le v lamC := ⟨fun _ => rfl, fun _ => rfl, fun _ => rfl⟩

/-- every judgment of any cube system holds in the calculus of constructions -/
theorem into_CoC (O : Ops Srt) (v : Vertex) {Γ a A} (d : Der (cube v) O Γ a A) : Der (cube lamC) O Γ a A :=
  mono O (cube_sub v lamC (le_top v)) d

/-- and λ→ embeds into every vertex -/
theorem from_arrow (O : Ops Srt) (v : Vertex) {Γ a A} (d : Der (cube lamArrow) O Γ a A) : Der (cube v) O Γ a A :=
  mono O (cube_sub lamArrow v (bottom_le v)) d

end PTS

end Found

#print axioms Found.PTS.mono
#print axioms Found.PTS.cube_sub
#print axioms Found.PTS.into_CoC
#print axioms Found.PTS.from_arrow

#print axioms: 4 theorems, no axioms.

85.124 Simply typed \(\lambda \)-calculus: normalization

Normalization by evaluation for intrinsically typed simply typed terms is total by construction, and a Tait-style logical predicate shows reflection gives good values and reification gives normal forms, so every closed term normalizes to a \(\beta \)-normal form. \(\vdash t:A\ \Rightarrow \ \mathrm {nf}(t)\in \mathrm {Nf}\).

found/STLC_F.lean

/-
  T79. found/STLC_F — normalization for the simply typed λ-calculus as a
  point (the λ coordinate with a type parameter):
  * intrinsically typed terms over contexts (List Ty), a semantic domain by
    structural recursion on types (Sem ι = neutral-code generators,
    Sem (A→B) = Sem A → Sem B), evaluation, and reify/reflect with de Bruijn
    levels: normalization by evaluation, total by construction.
  * Tait-style logical predicate (Good): reflect sends neutrals to Good
    values, reify sends Good values to β-normal forms; every closed term's
    output is in normal form (IsNf).
  Strong normalization by Tait reducibility and System F (Girard's
  candidates, impredicative) are cited — OPEN_LEMMAS T79a.

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace NbE

inductive Ty where
  | base : Ty
  | arr : Ty → Ty → Ty

inductive Var : List Ty → Ty → Type where
  | zero {Γ A} : Var (A :: Γ) A
  | succ {Γ A B} : Var Γ A → Var (B :: Γ) A

inductive Tm : List Ty → Ty → Type where
  | var {Γ A} : Var Γ A → Tm Γ A
  | lam {Γ A B} : Tm (A :: Γ) B → Tm Γ (.arr A B)
  | app {Γ A B} : Tm Γ (.arr A B) → Tm Γ A → Tm Γ B

inductive Raw where
  | var : Nat → Raw
  | lam : Raw → Raw
  | app : Raw → Raw → Raw

mutual
  inductive IsNf : Raw → Prop where
    | lam {b} : IsNf b → IsNf (.lam b)
    | ne {t} : IsNe t → IsNf t
  inductive IsNe : Raw → Prop where
    | var (n) : IsNe (.var n)
    | app {f a} : IsNe f → IsNf a → IsNe (.app f a)
end

def Sem : Ty → Type
  | .base => Nat → Raw
  | .arr A B => Sem A → Sem B

/-- reflect (neutral generator → value) and reify (value → normal code), at depth -/
def rr : (A : Ty) → ((Nat → Raw) → Sem A) × (Sem A → Nat → Raw)
  | .base => (fun ne => ne, fun f n => f n)
  | .arr A B => (fun ne a => (rr B).1 (fun n => .app (ne n) ((rr A).2 a n)),
                 fun f n => .lam ((rr B).2 (f ((rr A).1 (fun m => .var (m - n - 1)))) (n + 1)))

def Good : (A : Ty) → Sem A → Prop
  | .base, f => ∀ n, IsNe (f n)
  | .arr A B, g => ∀ a, Good A a → Good B (g a)

theorem rr_good : (A : Ty) →
    (∀ ne : Nat → Raw, (∀ n, IsNe (ne n)) → Good A ((rr A).1 ne)) ∧
    (∀ a : Sem A, Good A a → ∀ n, IsNf ((rr A).2 a n))
  | .base => ⟨fun _ h => h, fun _ h n => .ne (h n)⟩
  | .arr A B =>
    ⟨fun _ h a ga => (rr_good B).1 _ (fun n => .app (h n) ((rr_good A).2 a ga n)),
     fun _ gf n => .lam ((rr_good B).2 _ (gf _ ((rr_good A).1 _ (fun _ => .var _))) (n + 1))⟩

inductive Env : List Ty → Type where
  | nil : Env []
  | cons {Γ A} : Sem A → Env Γ → Env (A :: Γ)

def lookup : {Γ : List Ty} → {A : Ty} → Var Γ A → Env Γ → Sem A
  | _, _, .zero, .cons a _ => a
  | _, _, .succ x, .cons _ ρ => lookup x ρ

def eval : {Γ : List Ty} → {A : Ty} → Tm Γ A → Env Γ → Sem A
  | _, _, .var x, ρ => lookup x ρ
  | _, _, .lam b, ρ => fun a => eval b (.cons a ρ)
  | _, _, .app f a, ρ => eval f ρ (eval a ρ)

def GoodEnv : {Γ : List Ty} → Env Γ → Prop
  | _, .nil => True
  | _, .cons (A := A) a ρ => Good A a ∧ GoodEnv ρ

theorem lookup_good : {Γ : List Ty} → {A : Ty} → (x : Var Γ A) → (ρ : Env Γ) → GoodEnv ρ → Good A (lookup x ρ)
  | _, _, .zero, .cons _ _, h => h.1
  | _, _, .succ x, .cons _ ρ, h => lookup_good x ρ h.2

theorem eval_good : {Γ : List Ty} → {A : Ty} → (t : Tm Γ A) → (ρ : Env Γ) → GoodEnv ρ → Good A (eval t ρ)
  | _, _, .var x, ρ, h => lookup_good x ρ h
  | _, _, .lam b, ρ, h => fun a ga => eval_good b (.cons a ρ) ⟨ga, h⟩
  | _, _, .app f a, ρ, h => eval_good f ρ h _ (eval_good a ρ h)

def nf {A : Ty} (t : Tm [] A) : Raw := (rr A).2 (eval t .nil) 0

/-- every closed simply typed term normalizes to a β-normal form -/
theorem nf_normal {A : Ty} (t : Tm [] A) : IsNf (nf t) :=
  (rr_good A).2 _ (eval_good t .nil trivial) 0

/-- example: (λx.x) (λy.y) at ι→ι normalizes to λ 0 -/
def idI : Tm [] (.arr .base .base) := .lam (.var .zero)
theorem ex_nf : nf (.app (.lam (B := .arr .base .base) (.var .zero)) idI) = .lam (.var 0) := rfl

end NbE

end Found

#print axioms Found.NbE.rr_good
#print axioms Found.NbE.eval_good
#print axioms Found.NbE.nf_normal
#print axioms Found.NbE.ex_nf

#print axioms: 4 theorems, no axioms.

85.125 Gödel’s incompleteness (linked)

The user’s existing formalization proves Löb’s theorem and Gödel’s first and second incompleteness theorems for any proof system with the derivability conditions and a diagonal sentence; the bridge places its Löb principle beside the Löb validity of transitive, conversely well-founded frames. \(\vdash \Box b\to b\Rightarrow \ \vdash b;\quad \nvdash \bot \Rightarrow \ \nvdash \neg \Box \bot \).

found/GoedelBridge.lean

/-
  T85. found/GoedelBridge — Gödel's incompleteness theorems, linked from the
  user's existing formalization (found/NoSelfVerify.lean, a copy of
  ~/Downloads/NoSelfVerify.lean; the original is untouched): Löb, Gödel I
  and II for any proof system with K, S, the derivability conditions and a
  diagonal sentence, plus the type-level diagonal results.
  Bridge (short): the same Löb principle appears on both sides of the
  provability-logic line —
    syntax  (NoSelfVerify.loeb: ⊢ □b → b  ⟹  ⊢ b)
    frames  (T137 GL: transitive + conversely well-founded ⟹ Löb valid),
  and Gödel II is Löb at b = ⊥.
  found/NoSelfVerify.lean is the axiom-free version of the user's file (same
  statements; Classical.em in cantor_inj replaced by the constructive
  diagonal, simp by Bool case splits); the verbatim copy is kept, unbuilt, in
  work/imported/NoSelfVerify.lean.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.NoSelfVerify
import found.GL

namespace Found

namespace GoedelBridge

theorem loeb_both :
    (∀ (T : NoSelfVerify.ProvSys) (b : T.S), T.Pr (T.imp (T.box b) b) → T.Pr b) ∧
    (∀ {W : Type} (R : W → W → Prop), Modal.Trans R → Modal.CWF R → Modal.LobValid R) :=
  ⟨NoSelfVerify.loeb, fun R ht hw => Modal.lob_of_frame R ht hw⟩

/-- Gödel II as Löb at ⊥ -/
theorem goedel2_from_loeb (T : NoSelfVerify.ProvSys) (hc : ¬ T.Pr T.bot) :
    ¬ T.Pr (T.imp (T.box T.bot) T.bot) :=
  fun h => hc (NoSelfVerify.loeb T T.bot h)

end GoedelBridge

end Found

#print axioms NoSelfVerify.loeb
#print axioms NoSelfVerify.goedel1
#print axioms NoSelfVerify.goedel2
#print axioms NoSelfVerify.model_consistent
#print axioms NoSelfVerify.model_no_self_verify
#print axioms NoSelfVerify.no_truth_inside
#print axioms NoSelfVerify.tower_never_closes
#print axioms NoSelfVerify.cantor_inj
#print axioms NoSelfVerify.lean_types_not_inside_lean
#print axioms NoSelfVerify.no_code_of_all_types
#print axioms NoSelfVerify.no_self_checker
#print axioms NoSelfVerify.not_every_map_coded
#print axioms Found.GoedelBridge.loeb_both
#print axioms Found.GoedelBridge.goedel2_from_loeb

#print axioms: 9 theorems, no axioms.

85.126 First-order completeness, compactness, Löwenheim–Skolem

Intuitionistic first-order derivability coincides with validity in all Heyting-valued structures whose quantifiers are existing infima and suprema; validity in the one Lindenbaum structure on \(\mathbb N\) already suffices, and a consequence of an infinite theory of sentences follows from finitely many of its members. \(\Gamma \vdash \varphi \iff \Gamma \models \varphi ;\quad T\models \varphi \Rightarrow \exists \Gamma \subseteq _{\mathrm {fin}}T,\ \Gamma \vdash \varphi \).

found/FOCompact.lean

/-
  T208 (L2) slices L2b, L2c. found/FOCompact —
  * Löwenheim–Skolem (Heyting-valued form): validity in all safe structures
    equals validity in the single Lindenbaum structure, whose domain is ℕ.
  * Compactness / strong completeness for a theory T of sentences (possibly
    infinite): if every safe structure in which c lies below the values of
    all of T also has c below φ's value, then φ is derivable from finitely
    many members of T.  Built from the T-relative Lindenbaum structure
    (a ≤ b iff some finite part Γ of T gives a, Γ ⊢ b).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.FOCompleteness

namespace Found

namespace FO

/-! ## Löwenheim–Skolem -/

def ValidIn (M : Str) (Γ : List Fm) (φ : Fm) : Prop :=
  ∀ (v : Nat → M.D) (c : M.H.car), (∀ γ x, γ ∈ Γ → Val M γ v x → M.H.le c x) → ∀ y, Val M φ v y → M.H.le c y

theorem complete_LS {Γ : List Fm} {φ : Fm} (h : ValidIn LS Γ φ) : Pf Γ φ := by
  have key : Pf [bigConj Γ] (ren (fun n => n) φ) :=
    h (fun n => n) (bigConj Γ) (fun γ x m hx =>
      cut (big_mem Γ m) (by
        have e := val_le (M := LS) γ (val_lind γ (fun n => n)) hx
        rw [ren_id] at e
        exact e)) _ (val_lind φ (fun n => n))
  rw [ren_id] at key
  exact cut (big_intro Γ) key

/-- a consequence valid in the countable (domain ℕ) Lindenbaum structure is valid everywhere -/
theorem lowenheim_skolem (Γ : List Fm) (φ : Fm) : ValidIn LS Γ φ ↔ Valid Γ φ :=
  ⟨fun h => soundness (complete_LS h), fun h => h LS lind_safe⟩

/-! ## T-relative Lindenbaum structure -/

def Ctx (T : Fm → Prop) (Γ : List Fm) : Prop := ∀ γ, γ ∈ Γ → T γ

theorem mem_app_inv' {a : Fm} : (l k : List Fm) → a ∈ l ++ k → a ∈ l ∨ a ∈ k
  | [], _, m => Or.inr m
  | _ :: l, k, m => by
    cases m with
    | head => exact Or.inl (.head _)
    | tail _ m' => exact (mem_app_inv' l k m').elim (fun h => Or.inl (.tail _ h)) Or.inr

theorem mem_app_l' {a : Fm} : (l k : List Fm) → a ∈ l → a ∈ l ++ k
  | _ :: _, _, .head _ => .head _
  | _ :: l, k, .tail _ m => .tail _ (mem_app_l' l k m)

theorem mem_app_r' {a : Fm} : (l k : List Fm) → a ∈ k → a ∈ l ++ k
  | [], _, m => m
  | _ :: l, k, m => .tail _ (mem_app_r' l k m)

theorem ctx_app {T : Fm → Prop} {Γ Δ : List Fm} (h1 : Ctx T Γ) (h2 : Ctx T Δ) : Ctx T (Γ ++ Δ) :=
  fun γ m => (mem_app_inv' Γ Δ m).elim (h1 γ) (h2 γ)

theorem sub_l (a : Fm) (Γ Δ : List Fm) : Sub (a :: Γ) (a :: (Γ ++ Δ)) := fun b m => by
  cases m with
  | head => exact .head _
  | tail _ m' => exact .tail _ (mem_app_l' Γ Δ m')

theorem sub_r (a : Fm) (Γ Δ : List Fm) : Sub (a :: Δ) (a :: (Γ ++ Δ)) := fun b m => by
  cases m with
  | head => exact .head _
  | tail _ m' => exact .tail _ (mem_app_r' Γ Δ m')

theorem cutC {Γ : List Fm} {a b c : Fm} (h1 : Pf (a :: Γ) b) (h2 : Pf (b :: Γ) c) : Pf (a :: Γ) c :=
  .impE (weaken (Pf.impI h2) (fun _ m => .tail _ m)) h1

theorem ctx_nil (T : Fm → Prop) : Ctx T [] := fun _ m => nomatch m

def LT (T : Fm → Prop) : HA.{0} where
  car := Fm
  le a b := ∃ Γ, Ctx T Γ ∧ Pf (a :: Γ) b
  le_refl _ := ⟨[], ctx_nil T, .hyp (.head _)⟩
  le_trans := fun ⟨Γ, hΓ, h1⟩ ⟨Δ, hΔ, h2⟩ =>
    ⟨Γ ++ Δ, ctx_app hΓ hΔ, cutC (weaken h1 (sub_l _ Γ Δ)) (weaken h2 (sub_r _ Γ Δ))⟩
  top := .imp .bot .bot
  bot := .bot
  meet := .conj
  join := .disj
  imp := .imp
  le_top _ := ⟨[], ctx_nil T, .impI (.hyp (.head _))⟩
  bot_le _ := ⟨[], ctx_nil T, .botE (.hyp (.head _))⟩
  meet_l _ _ := ⟨[], ctx_nil T, .conjL (.hyp (.head _))⟩
  meet_r _ _ := ⟨[], ctx_nil T, .conjR (.hyp (.head _))⟩
  meet_univ := fun ⟨Γ, hΓ, h1⟩ ⟨Δ, hΔ, h2⟩ =>
    ⟨Γ ++ Δ, ctx_app hΓ hΔ, .conjI (weaken h1 (sub_l _ Γ Δ)) (weaken h2 (sub_r _ Γ Δ))⟩
  join_l _ _ := ⟨[], ctx_nil T, .disjL (.hyp (.head _))⟩
  join_r _ _ := ⟨[], ctx_nil T, .disjR (.hyp (.head _))⟩
  join_univ := fun ⟨Γ, hΓ, h1⟩ ⟨Δ, hΔ, h2⟩ =>
    ⟨Γ ++ Δ, ctx_app hΓ hΔ, .disjE (.hyp (.head _))
      (weaken h1 (fun b m => by
        cases m with
        | head => exact .head _
        | tail _ m' => exact .tail _ (.tail _ (mem_app_l' Γ Δ m'))))
      (weaken h2 (fun b m => by
        cases m with
        | head => exact .head _
        | tail _ m' => exact .tail _ (.tail _ (mem_app_r' Γ Δ m'))))⟩
  imp_adj := ⟨fun ⟨Γ, hΓ, h⟩ => ⟨Γ, hΓ, .impI (.impE (weaken (Pf.impI h) (fun _ m => .tail _ (.tail _ m)))
      (.conjI (.hyp (.tail _ (.head _))) (.hyp (.head _))))⟩,
    fun ⟨Γ, hΓ, h⟩ => ⟨Γ, hΓ, .impE (cutC (.conjL (.hyp (.head _))) (weaken h (fun b m => by
        cases m with
        | head => exact .head _
        | tail _ m' => exact .tail _ m'))) (.conjR (.hyp (.head _)))⟩⟩

/-! ## sentences, quantifier lemmas relative to T -/

def Sent (T : Fm → Prop) : Prop := ∀ γ, T γ → bound γ = 0

theorem ren_closed (ρ : Nat → Nat) (γ : Fm) (h : bound γ = 0) : ren ρ γ = γ :=
  (ren_bound γ (σ := fun n => n) (fun n hn => absurd (h ▸ hn) (Nat.not_lt_zero n))).trans (ren_id γ)

theorem mapF_closed {T : Fm → Prop} (hT : Sent T) (ρ : Nat → Nat) : (Γ : List Fm) → Ctx T Γ → mapF ρ Γ = Γ
  | [], _ => rfl
  | γ :: Γ, h => by
    show ren ρ γ :: mapF ρ Γ = γ :: Γ
    rw [ren_closed ρ γ (hT γ (h γ (.head _))), mapF_closed hT ρ Γ (fun g m => h g (.tail _ m))]

theorem all_inf_T {T : Fm → Prop} (hT : Sent T) (ψ a : Fm)
    (h : ∀ y, ∃ Γ, Ctx T Γ ∧ Pf (ψ :: Γ) (inst y a)) : ∃ Γ, Ctx T Γ ∧ Pf (ψ :: Γ) (.all a) :=
  match h (bound ψ + bound a) with
  | ⟨Γ, hΓ, d⟩ => by
    have hN := pf_ren d (sig (bound ψ + bound a))
    rw [sig_inst _ a (Nat.le_succ_of_le (Nat.le_add_left _ _))] at hN
    have e : mapF (sig (bound ψ + bound a)) (ψ :: Γ) = sh (ψ :: Γ) := by
      show ren (sig (bound ψ + bound a)) ψ :: mapF (sig (bound ψ + bound a)) Γ = shift ψ :: mapF Nat.succ Γ
      rw [sig_shift _ ψ (Nat.le_add_right _ _), mapF_closed hT _ Γ hΓ, mapF_closed hT _ Γ hΓ]
    rw [e] at hN
    exact ⟨Γ, hΓ, .allI hN⟩

theorem ex_sup_T {T : Fm → Prop} (hT : Sent T) (ψ a : Fm)
    (h : ∀ y, ∃ Γ, Ctx T Γ ∧ Pf (inst y a :: Γ) ψ) : ∃ Γ, Ctx T Γ ∧ Pf (.ex a :: Γ) ψ :=
  match h (bound ψ + bound a) with
  | ⟨Γ, hΓ, d⟩ => by
    have hN := pf_ren d (sig (bound ψ + bound a))
    have e : mapF (sig (bound ψ + bound a)) (inst (bound ψ + bound a) a :: Γ) = a :: Γ := by
      show ren (sig (bound ψ + bound a)) (inst (bound ψ + bound a) a) :: mapF (sig (bound ψ + bound a)) Γ = a :: Γ
      rw [sig_inst _ a (Nat.le_succ_of_le (Nat.le_add_left _ _)), mapF_closed hT _ Γ hΓ]
    rw [e, sig_shift _ ψ (Nat.le_add_right _ _)] at hN
    have e2 : sh (Fm.ex a :: Γ) = shift (.ex a) :: Γ := by
      show shift (.ex a) :: mapF Nat.succ Γ = _
      rw [mapF_closed hT _ Γ hΓ]
    refine ⟨Γ, hΓ, .exE (.hyp (.head _)) ?_⟩
    rw [e2]
    exact weaken hN (fun b m => by
      cases m with
      | head => exact .head _
      | tail _ m' => exact .tail _ (.tail _ m'))

def LST (T : Fm → Prop) : Str := ⟨LT T, Nat, fun r l => .atom r l⟩

theorem val_lindT {T : Fm → Prop} (hT : Sent T) : (φ : Fm) → (v : Nat → Nat) → Val (LST T) φ v (ren v φ)
  | .atom r l, v => by
    show Val (LST T) (.atom r l) v (Fm.atom r (mapL v l))
    rw [← mapD_mapL']
    exact .atom
  | .bot, _ => .bot
  | .conj a b, v => .conj (val_lindT hT a v) (val_lindT hT b v)
  | .disj a b, v => .disj (val_lindT hT a v) (val_lindT hT b v)
  | .imp a b, v => .imp (val_lindT hT a v) (val_lindT hT b v)
  | .all a, v => .all (fun d => ren (ext v d) a) (fun d => val_lindT hT a (ext v d))
      (fun (d : Nat) => ⟨[], ctx_nil T, by
        show Pf [Fm.all (ren (up v) a)] (ren (ext (D := Nat) v d) a)
        rw [inst_ext]
        exact .allE d (.hyp (.head _))⟩)
      (fun c hc => all_inf_T hT c (ren (up v) a) (fun (y : Nat) =>
        match hc y with
        | ⟨Γ, hΓ, h⟩ => ⟨Γ, hΓ, by
          have h' : Pf (c :: Γ) (ren (ext (D := Nat) v y) a) := h
          rw [inst_ext] at h'
          exact h'⟩))
  | .ex a, v => .ex (fun d => ren (ext v d) a) (fun d => val_lindT hT a (ext v d))
      (fun (d : Nat) => ⟨[], ctx_nil T, by
        show Pf [ren (ext (D := Nat) v d) a] (Fm.ex (ren (up v) a))
        rw [inst_ext]
        exact .exI d (.hyp (.head _))⟩)
      (fun c hc => ex_sup_T hT c (ren (up v) a) (fun (y : Nat) =>
        match hc y with
        | ⟨Γ, hΓ, h⟩ => ⟨Γ, hΓ, by
          have h' : Pf (ren (ext (D := Nat) v y) a :: Γ) c := h
          rw [inst_ext] at h'
          exact h'⟩))

theorem lindT_safe {T : Fm → Prop} (hT : Sent T) : Safe (LST T) := fun φ v => ⟨ren v φ, val_lindT hT φ v⟩

/-- semantic consequence from a (possibly infinite) theory -/
def TValid (T : Fm → Prop) (φ : Fm) : Prop :=
  ∀ M : Str, Safe M → ∀ (v : Nat → M.D) (c : M.H.car),
    (∀ γ x, T γ → Val M γ v x → M.H.le c x) → ∀ y, Val M φ v y → M.H.le c y

/-- compactness (strong completeness): a semantic consequence of a theory of
  sentences follows from finitely many of its members -/
theorem compactness {T : Fm → Prop} (hT : Sent T) {φ : Fm} (h : TValid T φ) :
    ∃ Γ, Ctx T Γ ∧ Pf Γ φ := by
  have key := h (LST T) (lindT_safe hT) (fun n => n) (.imp .bot .bot) (fun γ x hγ hx =>
    match val_le (M := LST T) γ (val_lindT hT γ (fun n => n)) hx with
    | ⟨Γ', hΓ', d⟩ => ⟨γ :: Γ', fun g m => by
        cases m with
        | head => exact hγ
        | tail _ m' => exact hΓ' g m', by
        rw [ren_id] at d
        exact weaken d (fun b m => by
          cases m with
          | head => exact .tail _ (.head _)
          | tail _ m' => exact .tail _ (.tail _ m'))⟩) _ (val_lindT hT φ (fun n => n))
  match key with
  | ⟨Γ, hΓ, d⟩ => exact ⟨Γ, hΓ, .impE (.impI (by rw [ren_id] at d; exact d)) (.impI (.hyp (.head _)))⟩

/-- and conversely (soundness for theories) -/
theorem compactness_converse {T : Fm → Prop} {φ : Fm} (h : ∃ Γ, Ctx T Γ ∧ Pf Γ φ) : TValid T φ :=
  fun M hM v c hc y hy => match h with
  | ⟨_, hΓ, d⟩ => sound d M hM v c (fun γ x m hx => hc γ x (hΓ γ m) hx) y hy

end FO

end Found

#print axioms Found.FO.lowenheim_skolem
#print axioms Found.FO.LT
#print axioms Found.FO.all_inf_T
#print axioms Found.FO.ex_sup_T
#print axioms Found.FO.val_lindT
#print axioms Found.FO.compactness
#print axioms Found.FO.compactness_converse

#print axioms: 7 theorems, no axioms.

85.127 Homotopy type theory: lines

Interval paths coincide with equality exactly when every map out of the interval agrees on its endpoints; equality always yields a path; and univalence, which holds in the Cubical Agda point, fails at the CIC point because proof irrelevance leaves only one proof of \(\mathrm {Bool}=\mathrm {Bool}\). \((\forall f\colon I\to A,\ f0=f1)\iff (\mathrm {Path}\subseteq {=});\quad \neg \,\mathrm {UA}_{\mathrm {CIC}}\).

found/HoTTLines.lean

/-
  T127. found/HoTTLines — cubical type theory / HoTT as a value of the
  interval coordinate (E, I, Φ) (T127, OrtonPitts: Cubical Agda's I is such
  a value), and its lines to the other points:
  * paths ↔ equality: interval paths in A coincide with Lean equality exactly
    when every map I → A is constant on the endpoints (connectedness of I
    relative to A); equality always gives a path (the A = A chain, T60);
    the two-point interval is not connected (OrtonPitts.two_not_connected),
    so there paths are strictly coarser.
  * setoids / h-sets: at the CIC point every type is an h-set (InfN.collapse,
    T196); the setoid model (T87) lives there.
  * univalence: holds at the Cubical Agda point (work/agda/Univalence.agda:
    ua, uaβ, checked by agda --safe) and FAILS at the CIC point: with proof
    irrelevance, idtoeqv cannot hit the swap of Bool (not_univalent).
  Shulman 2019 (every ∞-topos models HoTT) is the cited instance with a
  Grothendieck E and classical metatheory.

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: proof irrelevance (not_univalent: any e : Bool = Bool equals rfl).
-/
import found.OrtonPitts

namespace Found

namespace HoTTL

open OP

theorem path_eq_iff_connected (J : Interval) (A : Type) :
    (∀ f : J.I → A, f J.i0 = f J.i1) ↔ (∀ a b : A, Path J A a b → a = b) :=
  ⟨fun h _ _ q => q.src.symm.trans ((h q.p).trans q.tgt),
   fun h f => h _ _ ⟨f, rfl, rfl⟩⟩

def eq_to_path (J : Interval) {A : Type} {a b : A} (e : a = b) : Path J A a b := ofEq J e

structure Equiv' (A B : Type) where
  to : A → B
  inv : B → A
  li : ∀ a, inv (to a) = a
  ri : ∀ b, to (inv b) = b

def idtoeqv {A B : Type} (e : A = B) : Equiv' A B := by
  cases e
  exact ⟨fun a => a, fun a => a, fun _ => rfl, fun _ => rfl⟩

def notB : Bool → Bool
  | true => false
  | false => true

theorem notB_notB : (b : Bool) → notB (notB b) = b
  | true => rfl
  | false => rfl

def swapEqv : Equiv' Bool Bool := ⟨notB, notB, notB_notB, notB_notB⟩

/-- univalence (surjectivity of idtoeqv at Bool) fails in CIC -/
theorem not_univalent : ¬ ∃ e : Bool = Bool, idtoeqv e = swapEqv := fun ⟨e, h⟩ => by
  have e1 : e = rfl := rfl
  rw [e1] at h
  have : (idtoeqv (rfl : Bool = Bool)).to true = swapEqv.to true := congrArg (fun q => q.to true) h
  exact Bool.noConfusion this

end HoTTL

end Found

#print axioms Found.HoTTL.path_eq_iff_connected
#print axioms Found.HoTTL.not_univalent

#print axioms: 2 theorems, no axioms.

85.128 ETCS and Mac Lane set theory

The element functor from Aczel’s universe to setoids preserves power sets, products and function sets, and conversely the core’s W-type of well-founded trees, with membership and operations transported, satisfies pairing, union, power set, infinity and \(\Delta _0\)-separation. \(\mathrm {El}(\mathcal P a)\cong \Omega ^{\mathrm {El}\,a},\ \mathrm {El}(a\times b)\cong \mathrm {El}\,a\times \mathrm {El}\,b,\ \mathrm {El}(b^a)\cong \mathrm {El}\,b^{\mathrm {El}\,a};\ VW\models \mathrm {MacLane}\).

found/ETCSZF3.lean

/-
  T209 slice L3c. found/ETCSZF3 — the converse line, topos → Mac Lane:
  inside the core (T59), the W-type of the universe coordinate
  VW = W(Type, ULift) (operation 5, induction) carries membership and
  bisimilarity transported along fromW : VW → V, and with the operations
  transported along toW it satisfies the Mac Lane axioms (pairing, union,
  power, infinity, Δ₀-separation) — built only from the core's operations
  plus the setoid topos' power objects.  Together with L3a/L3b
  (El : V → setoids preserves power, products, exponentials) this gives
  both directions at the instance level.

  Lean 4 core only, hand-written proofs, no axioms.
  CIC dependence: impredicative Prop (power, Δ₀-separation).
-/
import found.CoreBridges
import found.MacLane

namespace Found

namespace ETCSZF3

open WF CoreBridges

def memW (x y : VW) : Prop := Mem (fromW x) (fromW y)
def eqW (x y : VW) : Prop := Eq' (fromW x) (fromW y)

def pairW (a b : VW) : VW := toW (IZF.pair (fromW a) (fromW b))
def unionW (a : VW) : VW := toW (IZF.union (fromW a))
def powerW (a : VW) : VW := toW (IZF.power (fromW a))
def emptyW : VW := toW IZF.empty
def omegaW : VW := toW IZF.omega
def succW (a : VW) : VW := toW (IZF.succ (fromW a))
def sepW (a : VW) (φ : KP.D0) (ρ : Nat → VW) : VW :=
  toW (IZF.sep (fromW a) (fun y => KP.sat φ (KP.cons y (fun n => fromW (ρ n)))))

theorem memW_toW (x : VW) (P : V) : memW x (toW P) ↔ Mem (fromW x) P :=
  ⟨fun m => mem_resp_right m (from_to P), fun m => mem_resp_right m (eq_symm _ _ (from_to P))⟩

theorem maclaneW (a b x : VW) (φ : KP.D0) (ρ : Nat → VW) :
    (memW x (pairW a b) ↔ eqW x a ∨ eqW x b) ∧
    (memW x (unionW a) ↔ ∃ y : V, Mem y (fromW a) ∧ Mem (fromW x) y) ∧
    (memW x (powerW a) ↔ ∀ z : V, Mem z (fromW x) → Mem z (fromW a)) ∧
    (memW emptyW omegaW ∧ ∀ y : VW, memW y omegaW → memW (succW y) omegaW) ∧
    (memW x (sepW a φ ρ) ↔ memW x a ∧ KP.sat φ (KP.cons (fromW x) (fun n => fromW (ρ n)))) :=
  ⟨(memW_toW _ _).trans (IZF.pair_spec _ _ _),
   (memW_toW _ _).trans (IZF.union_spec _ _),
   (memW_toW _ _).trans (IZF.power_spec _ _),
   ⟨(memW_toW _ _).mpr (mem_resp_left (eq_symm _ _ (from_to _)) IZF.infinity.{0,0}.1),
    fun _ m => (memW_toW _ _).mpr (mem_resp_left (eq_symm _ _ (from_to _))
      (IZF.infinity.{0,0}.2 _ ((memW_toW _ _).mp m)))⟩,
   (memW_toW _ _).trans (KP.d0_separation φ _ _ _)⟩

end ETCSZF3

end Found

#print axioms Found.ETCSZF3.memW_toW
#print axioms Found.ETCSZF3.maclaneW

#print axioms: 2 theorems, no axioms.

85.129 Nominal sets and the Schanuel topos

The support presheaf of a nominal set satisfies the gluing condition of the atomic topology, the colimit setoid of any presheaf with a local permutation action is a nominal set, and with chosen supports gluing the support presheaf gives back the nominal set, compatibly with the action. \(X_S\cap X_T=X_{S\cap T};\quad \operatorname {colim}_S X_S\cong X\).

found/Schanuel3.lean

/-
  T210 slice L4c. found/Schanuel3 — the converse line, sheaves → nominal
  sets: a functor on finite atom sets with extensions along inclusions and
  a permutation action that is local (depends only on π restricted to S)
  is glued, as a colimit setoid (no quotient), into a nominal set; and for
  a nominal set with chosen supports the presheaf S ↦ X_S glues back to the
  original set (setoid iso, compatible with the action).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Schanuel
import found.Core

namespace Found

namespace Nom

theorem sub_refl (S : List Nat) : Sub' S S := fun _ m => m
theorem sub_trans {S T U : List Nat} (h1 : Sub' S T) (h2 : Sub' T U) : Sub' S U := fun a m => h2 a (h1 a m)

theorem mem_image_inv (π : Perm) {a : Nat} : (S : List Nat) → a ∈ image π S → ∃ b, b ∈ S ∧ a = π.f b
  | [], m => nomatch m
  | b :: S, m => by
    cases m with
    | head => exact ⟨b, .head _, rfl⟩
    | tail _ m' => exact match mem_image_inv π S m' with | ⟨c, hc, e⟩ => ⟨c, .tail _ hc, e⟩

theorem image_mono (π : Perm) {S T : List Nat} (h : Sub' S T) : Sub' (image π S) (image π T) := fun _ m =>
  match mem_image_inv π S m with
  | ⟨b, hb, e⟩ => e ▸ mem_image π T (h b hb)

theorem image_fixed {π : Perm} {S : List Nat} (hf : Fixes π S) : Sub' (image π S) S := fun _ m =>
  match mem_image_inv π S m with
  | ⟨b, hb, e⟩ => by rw [e, hf b hb]; exact hb

/-- a presheaf on finite atom sets with a local permutation action -/
structure Fam where
  F : List Nat → Type
  ext : {S T : List Nat} → Sub' S T → F S → F T
  ext_id : ∀ {S} (h : Sub' S S) x, ext h x = x
  ext_comp : ∀ {S T U} (h1 : Sub' S T) (h2 : Sub' T U) x, ext h2 (ext h1 x) = ext (sub_trans h1 h2) x
  act : (π : Perm) → (S : List Nat) → F S → F (image π S)
  act_ext : ∀ π {S T} (h : Sub' S T) x, act π T (ext h x) = ext (image_mono π h) (act π S x)
  loc : ∀ π S x (hf : Fixes π S), ext (image_fixed hf) (act π S x) = x

/-- gluing: the colimit setoid Σ S, F S -/
def glue (A : Fam) : Setd.{0} where
  car := (S : List Nat) × A.F S
  eqv p q := ∃ U, ∃ (h1 : Sub' p.1 U) (h2 : Sub' q.1 U), A.ext h1 p.2 = A.ext h2 q.2
  refl p := ⟨p.1, sub_refl _, sub_refl _, rfl⟩
  symm := fun ⟨U, h1, h2, e⟩ => ⟨U, h2, h1, e.symm⟩
  trans := fun {p q r} ⟨U, h1, h2, e⟩ ⟨U', k1, k2, e'⟩ => by
    refine ⟨U ++ U', sub_trans h1 (fun a m => Prp.mem_app_l m), sub_trans k2 (fun a m => Prp.mem_app_r U m), ?_⟩
    have l1 : Sub' U (U ++ U') := fun a m => Prp.mem_app_l m
    have l2 : Sub' U' (U ++ U') := fun a m => Prp.mem_app_r U m
    calc A.ext _ p.2 = A.ext l1 (A.ext h1 p.2) := (A.ext_comp h1 l1 p.2).symm
      _ = A.ext l1 (A.ext h2 q.2) := by rw [e]
      _ = A.ext (sub_trans h2 l1) q.2 := A.ext_comp h2 l1 q.2
      _ = A.ext (sub_trans k1 l2) q.2 := rfl
      _ = A.ext l2 (A.ext k1 q.2) := (A.ext_comp k1 l2 q.2).symm
      _ = A.ext l2 (A.ext k2 r.2) := by rw [e']
      _ = A.ext _ r.2 := A.ext_comp k2 l2 r.2

def gact (A : Fam) (π : Perm) (p : (glue A).car) : (glue A).car := ⟨image π p.1, A.act π p.1 p.2⟩

/-- the action respects gluing -/
theorem gact_resp (A : Fam) (π : Perm) {p q : (glue A).car} (h : (glue A).eqv p q) :
    (glue A).eqv (gact A π p) (gact A π q) :=
  match h with
  | ⟨U, h1, h2, e⟩ => ⟨image π U, image_mono π h1, image_mono π h2, by
      show A.ext _ (A.act π p.1 p.2) = A.ext _ (A.act π q.1 q.2)
      rw [← A.act_ext π h1, ← A.act_ext π h2, e]⟩

/-- every glued element is supported by its stage: the colimit is nominal -/
theorem glue_nominal (A : Fam) (p : (glue A).car) (π : Perm) (hf : Fixes π p.1) :
    (glue A).eqv (gact A π p) p :=
  ⟨p.1, image_fixed hf, sub_refl _, by
    show A.ext _ (A.act π p.1 p.2) = A.ext _ p.2
    rw [A.loc π p.1 p.2 hf, A.ext_id]⟩

/-! ## round trip: nominal set → presheaf S ↦ X_S → glue ≅ the set -/

theorem subtype_eq {α : Type} {P : α → Prop} {a b : {x : α // P x}} (h : a.val = b.val) : a = b := by
  cases a with
  | mk v hv => cases b with
    | mk w hw =>
      cases h
      rfl

def ofNSet (N : NSet) (hc : ActComp N) : Fam where
  F S := {x : N.X // XS N S x}
  ext h x := ⟨x.val, XS_mono N h x.val x.property⟩
  ext_id _ _ := rfl
  ext_comp _ _ _ := rfl
  act π S x := ⟨N.act π x.val, equivariant N hc π S x.val x.property⟩
  act_ext := fun _ {_ _} _ _ => rfl

  loc π _ x hf := subtype_eq (x.property π hf)

def discS (X : Type) : Setd.{0} := ⟨X, Eq, fun _ => rfl, fun h => h.symm, fun h k => h.trans k⟩

/-- the round trip: with chosen supports, gluing X_S gives back X (as setoids),
  and the identification commutes with the action -/
theorem roundtrip (N : NSet) (hc : ActComp N) (supp : ∀ x : N.X, {S : List Nat // XS N S x}) :
    Core.Iso' (glue (ofNSet N hc)) (discS N.X) ∧
      ∀ π (p : (glue (ofNSet N hc)).car), (gact (ofNSet N hc) π p).2.val = N.act π p.2.val :=
  ⟨⟨⟨fun p => p.2.val, fun {p q} h => match h with
      | ⟨_, _, _, e⟩ => congrArg Subtype.val e⟩,
    ⟨fun x => ⟨(supp x).val, ⟨x, (supp x).property⟩⟩, fun {x y} e => by cases e; exact (glue _).refl _⟩,
    fun p => ⟨(supp p.2.val).val ++ p.1, fun _ m => Prp.mem_app_l m, fun _ m => Prp.mem_app_r _ m,
      subtype_eq rfl⟩,
    fun _ => rfl⟩,
   fun _ _ => rfl⟩

end Nom

end Found

#print axioms Found.Nom.glue
#print axioms Found.Nom.gact_resp
#print axioms Found.Nom.glue_nominal
#print axioms Found.Nom.roundtrip

#print axioms: 4 theorems, no axioms.

85.130 Lines: the whole table

Every proved point’s general theorems are re-exported in one Lean file generated from the chain table, and the section opens with the status of every point as recorded. \(197\ \text {re-exported theorems, no axioms}\).

found/Lines.lean

/-
  T126. found/Lines — every proved point's general theorems re-exported in one file
  (generated by work/found/gen_lines.py from CHAIN.md; do not edit by hand).
  Lean 4 core only, no axioms.
-/
import found.AD
import found.AST
import found.Ack2
import found.AckD
import found.Ackermann
import found.AlgebraicLogic
import found.Automata
import found.Beth
import found.Bishop
import found.Brouwer
import found.CIC
import found.ChurchTuring2
import found.ChurchTuring3
import found.Coalgebra
import found.Compactness
import found.Completeness
import found.Condensed
import found.Conditional
import found.Core
import found.CwF
import found.DRSound
import found.DaCosta
import found.Dependence
import found.Description
import found.Dialectica
import found.Domain
import found.ETCC
import found.ETCS
import found.ETCSZF
import found.ETCSZF2
import found.ETCSZF3
import found.EffectiveK1
import found.Epsilon
import found.FOClassicalT
import found.FOCompact
import found.FOCompleteness
import found.Fagin
import found.Fibration
import found.Finitism
import found.FixpointLogic
import found.Frege
import found.GPK
import found.Game
import found.GeometricLogic
import found.GoedelBridge
import found.Grothendieck
import found.HAomega
import found.HOIL
import found.HOL
import found.Higher2
import found.Hilbert
import found.HoTTLines
import found.Homotopy
import found.IST
import found.InfN
import found.Institutions
import found.Justification
import found.KP
import found.KanExt
import found.Krivine
import found.LargeCardinals
import found.LocalUniverse
import found.MLTTVariants
import found.MacLane
import found.ManySorted
import found.Markov
import found.MartinAxiom
import found.Mereology
import found.MetaFrameworks
import found.ModalMu
import found.NFAlt
import found.NFAssemble
import found.NFCountStep
import found.NFLabel
import found.NFReduce
import found.NFStruct
import found.NFSupp
import found.Nominal
import found.NonMono
import found.OTT
import found.Ordinal
import found.PAEmbed
import found.PAHA
import found.PTS
import found.Plural
import found.Predicative
import found.Presburger
import found.Presentable
import found.ProbLogic
import found.Process
import found.ProofNets
import found.Quantum
import found.QuantumCirc
import found.Ramified
import found.Recursive
import found.RegToMu
import found.Register
import found.SDG
import found.SEAR
import found.SK
import found.STLC_F
import found.Schanuel
import found.Schanuel2
import found.Schanuel3
import found.SecondOrder
import found.SecondOrder2
import found.ShulmanCor
import found.ShulmanPath
import found.StrDiag1
import found.StrDiag2
import found.Truth
import found.TwoLevel
import found.TypeVariants
import found.TypedCalculi
import found.Ultraproduct
import found.UniversalLogic
import found.VeqL
import found.Zinf

namespace Found.Lines

/-- T107: Found.ETCS.well_pointed -/
theorem line_T107_0 : type_of% @Found.ETCS.well_pointed := @Found.ETCS.well_pointed
#print axioms line_T107_0
/-- T90: Found.KP.sat_resp -/
theorem line_T90_0 : type_of% @Found.KP.sat_resp := @Found.KP.sat_resp
#print axioms line_T90_0
/-- T91: Found.FOCT.completenessT -/
theorem line_T91_0 : type_of% @Found.FOCT.completenessT := @Found.FOCT.completenessT
#print axioms line_T91_0
/-- T119: Found.SDG.kl_not_all_zero -/
theorem line_T119_0 : type_of% @Found.SDG.kl_not_all_zero := @Found.SDG.kl_not_all_zero
#print axioms line_T119_0
/-- T119: Found.SDG.nn_zero -/
theorem line_T119_1 : type_of% @Found.SDG.nn_zero := @Found.SDG.nn_zero
#print axioms line_T119_1
/-- T111: Found.Quantum.toHA_boolean -/
theorem line_T111_0 : type_of% @Found.Quantum.toHA_boolean := @Found.Quantum.toHA_boolean
#print axioms line_T111_0
/-- T59: Found.Core.copair_uniq -/
theorem line_T59_0 : type_of% @Found.Core.copair_uniq := @Found.Core.copair_uniq
#print axioms line_T59_0
/-- T59: Found.Core.chiU_spec -/
theorem line_T59_1 : type_of% @Found.Core.chiU_spec := @Found.Core.chiU_spec
#print axioms line_T59_1
/-- T59: Found.Core.qlift_uniq -/
theorem line_T59_2 : type_of% @Found.Core.qlift_uniq := @Found.Core.qlift_uniq
#print axioms line_T59_2
/-- T59: Found.Core.fold_uniq -/
theorem line_T59_3 : type_of% @Found.Core.fold_uniq := @Found.Core.fold_uniq
#print axioms line_T59_3
/-- T59: Found.Core.unfold_uniq -/
theorem line_T59_4 : type_of% @Found.Core.unfold_uniq := @Found.Core.unfold_uniq
#print axioms line_T59_4
/-- T59: Found.Core.locLift_uniq -/
theorem line_T59_5 : type_of% @Found.Core.locLift_uniq := @Found.Core.locLift_uniq
#print axioms line_T59_5
/-- T143: Found.Prp.deduction -/
theorem line_T143_0 : type_of% @Found.Prp.deduction := @Found.Prp.deduction
#print axioms line_T143_0
/-- T116: Found.Dom.fix_le -/
theorem line_T116_0 : type_of% @Found.Dom.fix_le := @Found.Dom.fix_le
#print axioms line_T116_0
/-- T116: Found.Dom.le_fix -/
theorem line_T116_1 : type_of% @Found.Dom.le_fix := @Found.Dom.le_fix
#print axioms line_T116_1
/-- T116: Found.Dom.fix_least -/
theorem line_T116_2 : type_of% @Found.Dom.fix_least := @Found.Dom.fix_least
#print axioms line_T116_2
/-- T156: Found.Coalg.comp_hom -/
theorem line_T156_0 : type_of% @Found.Coalg.comp_hom := @Found.Coalg.comp_hom
#print axioms line_T156_0
/-- T156: Found.Coalg.final_iso -/
theorem line_T156_1 : type_of% @Found.Coalg.final_iso := @Found.Coalg.final_iso
#print axioms line_T156_1
/-- T156: Found.Coalg.lambek -/
theorem line_T156_2 : type_of% @Found.Coalg.lambek := @Found.Coalg.lambek
#print axioms line_T156_2
/-- T139: Found.DaCosta.lem -/
theorem line_T139_0 : type_of% @Found.DaCosta.lem := @Found.DaCosta.lem
#print axioms line_T139_0
/-- T104: Found.Groth.lift_eq -/
theorem line_T104_0 : type_of% @Found.Groth.lift_eq := @Found.Groth.lift_eq
#print axioms line_T104_0
/-- T104: Found.Groth.mem_lift -/
theorem line_T104_1 : type_of% @Found.Groth.mem_lift := @Found.Groth.mem_lift
#print axioms line_T104_1
/-- T171: Found.Mu.ef_eq_reach -/
theorem line_T171_0 : type_of% @Found.Mu.ef_eq_reach := @Found.Mu.ef_eq_reach
#print axioms line_T171_0
/-- T177: Found.LFP.tc_lfp -/
theorem line_T177_0 : type_of% @Found.LFP.tc_lfp := @Found.LFP.tc_lfp
#print axioms line_T177_0
/-- T176: Found.DL.tr_correct -/
theorem line_T176_0 : type_of% @Found.DL.tr_correct := @Found.DL.tr_correct
#print axioms line_T176_0
/-- T176: Found.DL.subsumption_iff -/
theorem line_T176_1 : type_of% @Found.DL.subsumption_iff := @Found.DL.subsumption_iff
#print axioms line_T176_1
/-- T172: Found.Cond.identity -/
theorem line_T172_0 : type_of% @Found.Cond.identity := @Found.Cond.identity
#print axioms line_T172_0
/-- T172: Found.Cond.no_strengthening -/
theorem line_T172_1 : type_of% @Found.Cond.no_strengthening := @Found.Cond.no_strengthening
#print axioms line_T172_1
/-- T173: Found.NonMono.refl -/
theorem line_T173_0 : type_of% @Found.NonMono.refl := @Found.NonMono.refl
#print axioms line_T173_0
/-- T173: Found.NonMono.and_rule -/
theorem line_T173_1 : type_of% @Found.NonMono.and_rule := @Found.NonMono.and_rule
#print axioms line_T173_1
/-- T173: Found.NonMono.not_monotone -/
theorem line_T173_2 : type_of% @Found.NonMono.not_monotone := @Found.NonMono.not_monotone
#print axioms line_T173_2
/-- T175: Found.Team.dep_down -/
theorem line_T175_0 : type_of% @Found.Team.dep_down := @Found.Team.dep_down
#print axioms line_T175_0
/-- T175: Found.Team.tensor_down -/
theorem line_T175_1 : type_of% @Found.Team.tensor_down := @Found.Team.tensor_down
#print axioms line_T175_1
/-- T175: Found.Team.not_flat -/
theorem line_T175_2 : type_of% @Found.Team.not_flat := @Found.Team.not_flat
#print axioms line_T175_2
/-- T178: Found.Just.application -/
theorem line_T178_0 : type_of% @Found.Just.application := @Found.Just.application
#print axioms line_T178_0
/-- T178: Found.Just.reflection -/
theorem line_T178_1 : type_of% @Found.Just.reflection := @Found.Just.reflection
#print axioms line_T178_1
/-- T178: Found.Just.forget -/
theorem line_T178_2 : type_of% @Found.Just.forget := @Found.Just.forget
#print axioms line_T178_2
/-- T182: Found.Auto.run_spec -/
theorem line_T182_0 : type_of% @Found.Auto.run_spec := @Found.Auto.run_spec
#print axioms line_T182_0
/-- T182: Found.Auto.subset_construction -/
theorem line_T182_1 : type_of% @Found.Auto.subset_construction := @Found.Auto.subset_construction
#print axioms line_T182_1
/-- T183: Found.Proc.bis_trans -/
theorem line_T183_0 : type_of% @Found.Proc.bis_trans := @Found.Proc.bis_trans
#print axioms line_T183_0
/-- T183: Found.Proc.hm_invariance -/
theorem line_T183_1 : type_of% @Found.Proc.hm_invariance := @Found.Proc.hm_invariance
#print axioms line_T183_1
/-- T198: Found.Markov.lem_mp -/
theorem line_T198_0 : type_of% @Found.Markov.lem_mp := @Found.Markov.lem_mp
#print axioms line_T198_0
/-- T198: Found.Markov.mp_not_all -/
theorem line_T198_1 : type_of% @Found.Markov.mp_not_all := @Found.Markov.mp_not_all
#print axioms line_T198_1
/-- T201: Found.Mereo.strong_supp -/
theorem line_T201_0 : type_of% @Found.Mereo.strong_supp := @Found.Mereo.strong_supp
#print axioms line_T201_0
/-- T201: Found.Mereo.fusion_least -/
theorem line_T201_1 : type_of% @Found.Mereo.fusion_least := @Found.Mereo.fusion_least
#print axioms line_T201_1
/-- T191: Found.Prp.interp_LT -/
theorem line_T191_0 : type_of% @Found.Prp.interp_LT := @Found.Prp.interp_LT
#print axioms line_T191_0
/-- T191: Found.Prp.completeness -/
theorem line_T191_1 : type_of% @Found.Prp.completeness := @Found.Prp.completeness
#print axioms line_T191_1
/-- T191: Found.Prp.heyting_iff -/
theorem line_T191_2 : type_of% @Found.Prp.heyting_iff := @Found.Prp.heyting_iff
#print axioms line_T191_2
/-- T192: Found.Truth.lawvere -/
theorem line_T192_0 : type_of% @Found.Truth.lawvere := @Found.Truth.lawvere
#print axioms line_T192_0
/-- T192: Found.Truth.cantor -/
theorem line_T192_1 : type_of% @Found.Truth.cantor := @Found.Truth.cantor
#print axioms line_T192_1
/-- T192: Found.Truth.undefinable -/
theorem line_T192_2 : type_of% @Found.Truth.undefinable := @Found.Truth.undefinable
#print axioms line_T192_2
/-- T142: Found.SO.henkin_to_standard -/
theorem line_T142_0 : type_of% @Found.SO.henkin_to_standard := @Found.SO.henkin_to_standard
#print axioms line_T142_0
/-- T170: Found.MS.relativize -/
theorem line_T170_0 : type_of% @Found.MS.relativize := @Found.MS.relativize
#print axioms line_T170_0
/-- T170: Found.MS.ofD2_all -/
theorem line_T170_1 : type_of% @Found.MS.ofD2_all := @Found.MS.ofD2_all
#print axioms line_T170_1
/-- T146: Found.Zermelo.zermelo_sep -/
theorem line_T146_0 : type_of% @Found.Zermelo.zermelo_sep := @Found.Zermelo.zermelo_sep
#print axioms line_T146_0
/-- T162: Found.Zermelo.tg -/
theorem line_T162_0 : type_of% @Found.Zermelo.tg := @Found.Zermelo.tg
#print axioms line_T162_0
/-- T81: Found.Rec.add_correct -/
theorem line_T81_0 : type_of% @Found.Rec.add_correct := @Found.Rec.add_correct
#print axioms line_T81_0
/-- T81: Found.Rec.mu_det -/
theorem line_T81_1 : type_of% @Found.Rec.mu_det := @Found.Rec.mu_det
#print axioms line_T81_1
/-- T145: Found.Reg.add_runs -/
theorem line_T145_0 : type_of% @Found.Reg.add_runs := @Found.Reg.add_runs
#print axioms line_T145_0
/-- T186: Found.Weak.d0_decidable -/
theorem line_T186_0 : type_of% @Found.Weak.d0_decidable := @Found.Weak.d0_decidable
#print axioms line_T186_0
/-- T186: Found.Weak.bounded_all -/
theorem line_T186_1 : type_of% @Found.Weak.bounded_all := @Found.Weak.bounded_all
#print axioms line_T186_1
/-- T93: Found.Prp.classical_iff -/
theorem line_T93_0 : type_of% @Found.Prp.classical_iff := @Found.Prp.classical_iff
#print axioms line_T93_0
/-- T94: Found.Prp.finite_hyps -/
theorem line_T94_0 : type_of% @Found.Prp.finite_hyps := @Found.Prp.finite_hyps
#print axioms line_T94_0
/-- T94: Found.Prp.strong_completeness -/
theorem line_T94_1 : type_of% @Found.Prp.strong_completeness := @Found.Prp.strong_completeness
#print axioms line_T94_1
/-- T94: Found.Prp.compactness -/
theorem line_T94_2 : type_of% @Found.Prp.compactness := @Found.Prp.compactness
#print axioms line_T94_2
/-- T83: Found.PA.nat_PA -/
theorem line_T83_0 : type_of% @Found.PA.nat_PA := @Found.PA.nat_PA
#print axioms line_T83_0
/-- T83: Found.PA.one_not_Q -/
theorem line_T83_1 : type_of% @Found.PA.one_not_Q := @Found.PA.one_not_Q
#print axioms line_T83_1
/-- T83: Found.PA.reach -/
theorem line_T83_2 : type_of% @Found.PA.reach := @Found.PA.reach
#print axioms line_T83_2
/-- T84: Found.RM.comp_mono -/
theorem line_T84_0 : type_of% @Found.RM.comp_mono := @Found.RM.comp_mono
#print axioms line_T84_0
/-- T84: Found.RM.chain -/
theorem line_T84_1 : type_of% @Found.RM.chain := @Found.RM.chain
#print axioms line_T84_1
/-- T84: Found.RM.full_model -/
theorem line_T84_2 : type_of% @Found.RM.full_model := @Found.RM.full_model
#print axioms line_T84_2
/-- T151: Found.Hyper.ex_mono -/
theorem line_T151_0 : type_of% @Found.Hyper.ex_mono := @Found.Hyper.ex_mono
#print axioms line_T151_0
/-- T151: Found.Hyper.all_mono -/
theorem line_T151_1 : type_of% @Found.Hyper.all_mono := @Found.Hyper.all_mono
#print axioms line_T151_1
/-- T110: Found.Nom.atoms_nominal -/
theorem line_T110_0 : type_of% @Found.Nom.atoms_nominal := @Found.Nom.atoms_nominal
#print axioms line_T110_0
/-- T110: Found.Nom.prod_nominal -/
theorem line_T110_1 : type_of% @Found.Nom.prod_nominal := @Found.Nom.prod_nominal
#print axioms line_T110_1
/-- T197: Found.Brouwer.wcn_not_lem -/
theorem line_T197_0 : type_of% @Found.Brouwer.wcn_not_lem := @Found.Brouwer.wcn_not_lem
#print axioms line_T197_0
/-- T164: Found.GPK.univ -/
theorem line_T164_0 : type_of% @Found.GPK.univ := @Found.GPK.univ
#print axioms line_T164_0
/-- T164: Found.GPK.union -/
theorem line_T164_1 : type_of% @Found.GPK.union := @Found.GPK.union
#print axioms line_T164_1
/-- T164: Found.GPK.inter -/
theorem line_T164_2 : type_of% @Found.GPK.inter := @Found.GPK.inter
#print axioms line_T164_2
/-- T180: Found.Dial.hom_is_dialectica -/
theorem line_T180_0 : type_of% @Found.Dial.hom_is_dialectica := @Found.Dial.hom_is_dialectica
#print axioms line_T180_0
/-- T99: Found.CICPoint.impProp_holds -/
theorem line_T99_0 : type_of% @Found.CICPoint.impProp_holds := @Found.CICPoint.impProp_holds
#print axioms line_T99_0
/-- T99: Found.CICPoint.proof_irrel -/
theorem line_T99_1 : type_of% @Found.CICPoint.proof_irrel := @Found.CICPoint.proof_irrel
#print axioms line_T99_1
/-- T99: Found.CICPoint.uip -/
theorem line_T99_2 : type_of% @Found.CICPoint.uip := @Found.CICPoint.uip
#print axioms line_T99_2
/-- T200: Found.Rec.mul_correct -/
theorem line_T200_0 : type_of% @Found.Rec.mul_correct := @Found.Rec.mul_correct
#print axioms line_T200_0
/-- T122: Found.TwoL.innerConstToOuter -/
theorem line_T122_0 : type_of% @Found.TwoL.innerConstToOuter := @Found.TwoL.innerConstToOuter
#print axioms line_T122_0
/-- T121: Found.OTT.funext_obs -/
theorem line_T121_0 : type_of% @Found.OTT.funext_obs := @Found.OTT.funext_obs
#print axioms line_T121_0
/-- T121: Found.OTT.pair_obs -/
theorem line_T121_2 : type_of% @Found.OTT.pair_obs := @Found.OTT.pair_obs
#print axioms line_T121_2
/-- T148: Found.Beth.beth_sound -/
theorem line_T148_0 : type_of% @Found.Beth.beth_sound := @Found.Beth.beth_sound
#print axioms line_T148_0
/-- T147: Found.SEAR.tab_spec -/
theorem line_T147_0 : type_of% @Found.SEAR.tab_spec := @Found.SEAR.tab_spec
#print axioms line_T147_0
/-- T147: Found.SEAR.jointly_monic -/
theorem line_T147_1 : type_of% @Found.SEAR.jointly_monic := @Found.SEAR.jointly_monic
#print axioms line_T147_1
/-- T206: Found.UL2.nd_tarskian -/
theorem line_T206_0 : type_of% @Found.UL2.nd_tarskian := @Found.UL2.nd_tarskian
#print axioms line_T206_0
/-- T206: Found.UL2.sem_tarskian -/
theorem line_T206_1 : type_of% @Found.UL2.sem_tarskian := @Found.UL2.sem_tarskian
#print axioms line_T206_1
/-- T206: Found.UL2.pref_not_monotone -/
theorem line_T206_2 : type_of% @Found.UL2.pref_not_monotone := @Found.UL2.pref_not_monotone
#print axioms line_T206_2
/-- T157: Found.Inst.condition -/
theorem line_T157_0 : type_of% @Found.Inst.condition := @Found.Inst.condition
#print axioms line_T157_0
/-- T80: Found.UL.K_beta -/
theorem line_T80_0 : type_of% @Found.UL.K_beta := @Found.UL.K_beta
#print axioms line_T80_0
/-- T80: Found.UL.S_beta -/
theorem line_T80_1 : type_of% @Found.UL.S_beta := @Found.UL.S_beta
#print axioms line_T80_1
/-- T80: Found.CL.simulate -/
theorem line_T80_2 : type_of% @Found.CL.simulate := @Found.CL.simulate
#print axioms line_T80_2
/-- T205: Found.HOL.fun_ext -/
theorem line_T205_0 : type_of% @Found.HOL.fun_ext := @Found.HOL.fun_ext
#print axioms line_T205_0
/-- T205: Found.HOL.bool_ext -/
theorem line_T205_1 : type_of% @Found.HOL.bool_ext := @Found.HOL.bool_ext
#print axioms line_T205_1
/-- T205: Found.HOL.classical_condition -/
theorem line_T205_2 : type_of% @Found.HOL.classical_condition := @Found.HOL.classical_condition
#print axioms line_T205_2
/-- T174: Found.Prob.incl_excl -/
theorem line_T174_0 : type_of% @Found.Prob.incl_excl := @Found.Prob.incl_excl
#print axioms line_T174_0
/-- T174: Found.Prob.complement -/
theorem line_T174_1 : type_of% @Found.Prob.complement := @Found.Prob.complement
#print axioms line_T174_1
/-- T174: Found.Prob.monotone -/
theorem line_T174_2 : type_of% @Found.Prob.monotone := @Found.Prob.monotone
#print axioms line_T174_2
/-- T193: Found.TwoCat.interchange -/
theorem line_T193_0 : type_of% @Found.TwoCat.interchange := @Found.TwoCat.interchange
#print axioms line_T193_0
/-- T193: Found.TwoCat.hcomp_nat -/
theorem line_T193_1 : type_of% @Found.TwoCat.hcomp_nat := @Found.TwoCat.hcomp_nat
#print axioms line_T193_1
/-- T193: Found.SD.sound -/
theorem line_T193_2 : type_of% @Found.SD.sound := @Found.SD.sound
#print axioms line_T193_2
/-- T193: Found.SD.term_read -/
theorem line_T193_3 : type_of% @Found.SD.term_read := @Found.SD.term_read
#print axioms line_T193_3
/-- T193: Found.SD.joyal_street -/
theorem line_T193_4 : type_of% @Found.SD.joyal_street := @Found.SD.joyal_street
#print axioms line_T193_4
/-- T187: Found.GodelT.rec_zero -/
theorem line_T187_0 : type_of% @Found.GodelT.rec_zero := @Found.GodelT.rec_zero
#print axioms line_T187_0
/-- T187: Found.GodelT.addT_correct -/
theorem line_T187_1 : type_of% @Found.GodelT.addT_correct := @Found.GodelT.addT_correct
#print axioms line_T187_1
/-- T152: Found.CwF.pi_beta -/
theorem line_T152_0 : type_of% @Found.CwF.pi_beta := @Found.CwF.pi_beta
#print axioms line_T152_0
/-- T152: Found.CwF.sig_eta -/
theorem line_T152_1 : type_of% @Found.CwF.sig_eta := @Found.CwF.sig_eta
#print axioms line_T152_1
/-- T152: Found.CwF.id_reflect -/
theorem line_T152_2 : type_of% @Found.CwF.id_reflect := @Found.CwF.id_reflect
#print axioms line_T152_2
/-- T152: Found.CwF.id_uip -/
theorem line_T152_3 : type_of% @Found.CwF.id_uip := @Found.CwF.id_uip
#print axioms line_T152_3
/-- T98: Found.CwF.pi_beta -/
theorem line_T98_0 : type_of% @Found.CwF.pi_beta := @Found.CwF.pi_beta
#print axioms line_T98_0
/-- T98: Found.CwF.sig_eta -/
theorem line_T98_1 : type_of% @Found.CwF.sig_eta := @Found.CwF.sig_eta
#print axioms line_T98_1
/-- T98: Found.CwF.id_reflect -/
theorem line_T98_2 : type_of% @Found.CwF.id_reflect := @Found.CwF.id_reflect
#print axioms line_T98_2
/-- T120: Found.MLTTV.not_uip -/
theorem line_T120_0 : type_of% @Found.MLTTV.not_uip := @Found.MLTTV.not_uip
#print axioms line_T120_0
/-- T120: Found.MLTTV.uip_extensional -/
theorem line_T120_1 : type_of% @Found.MLTTV.uip_extensional := @Found.MLTTV.uip_extensional
#print axioms line_T120_1
/-- T160: Found.Meta.lf_adequate -/
theorem line_T160_0 : type_of% @Found.Meta.lf_adequate := @Found.Meta.lf_adequate
#print axioms line_T160_0
/-- T158: Found.Meta.mmt_compose -/
theorem line_T158_0 : type_of% @Found.Meta.mmt_compose := @Found.Meta.mmt_compose
#print axioms line_T158_0
/-- T159: Found.Meta.dedukti_rule -/
theorem line_T159_0 : type_of% @Found.Meta.dedukti_rule := @Found.Meta.dedukti_rule
#print axioms line_T159_0
/-- T203: Found.Meta.metamath_subst -/
theorem line_T203_0 : type_of% @Found.Meta.metamath_subst := @Found.Meta.metamath_subst
#print axioms line_T203_0
/-- T204: Found.Meta.mizar -/
theorem line_T204_0 : type_of% @Found.Meta.mizar := @Found.Meta.mizar
#print axioms line_T204_0
/-- T168: Found.Det.determined -/
theorem line_T168_0 : type_of% @Found.Det.determined := @Found.Det.determined
#print axioms line_T168_0
/-- T168: Found.Det.not_both -/
theorem line_T168_1 : type_of% @Found.Det.not_both := @Found.Det.not_both
#print axioms line_T168_1
/-- T117: Found.GameSem.win_iff -/
theorem line_T117_0 : type_of% @Found.GameSem.win_iff := @Found.GameSem.win_iff
#print axioms line_T117_0
/-- T117: Found.GameSem.determined -/
theorem line_T117_1 : type_of% @Found.GameSem.determined := @Found.GameSem.determined
#print axioms line_T117_1
/-- T165: Found.IST.bound -/
theorem line_T165_0 : type_of% @Found.IST.bound := @Found.IST.bound
#print axioms line_T165_0
/-- T165: Found.IST.nonstandard -/
theorem line_T165_1 : type_of% @Found.IST.nonstandard := @Found.IST.nonstandard
#print axioms line_T165_1
/-- T188: Found.LC.liftU_eq -/
theorem line_T188_0 : type_of% @Found.LC.liftU_eq := @Found.LC.liftU_eq
#print axioms line_T188_0
/-- T188: Found.LC.in_U -/
theorem line_T188_1 : type_of% @Found.LC.in_U := @Found.LC.in_U
#print axioms line_T188_1
/-- T188: Found.LC.tower -/
theorem line_T188_2 : type_of% @Found.LC.tower := @Found.LC.tower
#print axioms line_T188_2
/-- T114: Found.HOIL.boolean_iff_lem -/
theorem line_T114_0 : type_of% @Found.HOIL.boolean_iff_lem := @Found.HOIL.boolean_iff_lem
#print axioms line_T114_0
/-- T114: Found.HOIL.nn_lem -/
theorem line_T114_1 : type_of% @Found.HOIL.nn_lem := @Found.HOIL.nn_lem
#print axioms line_T114_1
/-- T149: Found.Kan.lan_mono -/
theorem line_T149_0 : type_of% @Found.Kan.lan_mono := @Found.Kan.lan_mono
#print axioms line_T149_0
/-- T149: Found.Kan.lan_universal -/
theorem line_T149_1 : type_of% @Found.Kan.lan_universal := @Found.Kan.lan_universal
#print axioms line_T149_1
/-- T135: Found.Htpy.we_identified -/
theorem line_T135_0 : type_of% @Found.Htpy.we_identified := @Found.Htpy.we_identified
#print axioms line_T135_0
/-- T135: Found.Htpy.factor_comm -/
theorem line_T135_1 : type_of% @Found.Htpy.factor_comm := @Found.Htpy.factor_comm
#print axioms line_T135_1
/-- T135: Found.Htpy.trivial_iso -/
theorem line_T135_2 : type_of% @Found.Htpy.trivial_iso := @Found.Htpy.trivial_iso
#print axioms line_T135_2
/-- T194: Found.Geo.preserve -/
theorem line_T194_0 : type_of% @Found.Geo.preserve := @Found.Geo.preserve
#print axioms line_T194_0
/-- T190: Found.Ultra.op_resp -/
theorem line_T190_0 : type_of% @Found.Ultra.op_resp := @Found.Ultra.op_resp
#print axioms line_T190_0
/-- T190: Found.Ultra.los_eq -/
theorem line_T190_1 : type_of% @Found.Ultra.los_eq := @Found.Ultra.los_eq
#print axioms line_T190_1
/-- T190: Found.Ultra.los_and -/
theorem line_T190_2 : type_of% @Found.Ultra.los_and := @Found.Ultra.los_and
#print axioms line_T190_2
/-- T195: Found.Session.dual_dual -/
theorem line_T195_0 : type_of% @Found.Session.dual_dual := @Found.Session.dual_dual
#print axioms line_T195_0
/-- T195: Found.Session.size_dual -/
theorem line_T195_1 : type_of% @Found.Session.size_dual := @Found.Session.size_dual
#print axioms line_T195_1
/-- T167: Found.Ack.classSet_spec -/
theorem line_T167_0 : type_of% @Found.Ack.classSet_spec := @Found.Ack.classSet_spec
#print axioms line_T167_0
/-- T167: Found.Ack.lift_mem -/
theorem line_T167_1 : type_of% @Found.Ack.lift_mem := @Found.Ack.lift_mem
#print axioms line_T167_1
/-- T167: Found.AK.ack_meta -/
theorem line_T167_2 : type_of% @Found.AK.ack_meta := @Found.AK.ack_meta
#print axioms line_T167_2
/-- T167: Found.AKD.ack_zf -/
theorem line_T167_3 : type_of% @Found.AKD.ack_zf := @Found.AKD.ack_zf
#print axioms line_T167_3
/-- T185: Found.Fagin.check_correct -/
theorem line_T185_0 : type_of% @Found.Fagin.check_correct := @Found.Fagin.check_correct
#print axioms line_T185_0
/-- T185: Found.Fagin.eso_iff -/
theorem line_T185_1 : type_of% @Found.Fagin.eso_iff := @Found.Fagin.eso_iff
#print axioms line_T185_1
/-- T184: Found.QC.three_cnots -/
theorem line_T184_0 : type_of% @Found.QC.three_cnots := @Found.QC.three_cnots
#print axioms line_T184_0
/-- T184: Found.QC.H_sq -/
theorem line_T184_1 : type_of% @Found.QC.H_sq := @Found.QC.H_sq
#print axioms line_T184_1
/-- T184: Found.QC.XZ_anti -/
theorem line_T184_2 : type_of% @Found.QC.XZ_anti := @Found.QC.XZ_anti
#print axioms line_T184_2
/-- T166: Found.AST.semiset_is_set -/
theorem line_T166_0 : type_of% @Found.AST.semiset_is_set := @Found.AST.semiset_is_set
#print axioms line_T166_0
/-- T166: Found.AST.ast_contradicts_separation -/
theorem line_T166_1 : type_of% @Found.AST.ast_contradicts_separation := @Found.AST.ast_contradicts_separation
#print axioms line_T166_1
/-- T202: Found.Cond2.sum_to_product -/
theorem line_T202_0 : type_of% @Found.Cond2.sum_to_product := @Found.Cond2.sum_to_product
#print axioms line_T202_0
/-- T202: Found.Cond2.empty_to_point -/
theorem line_T202_1 : type_of% @Found.Cond2.empty_to_point := @Found.Cond2.empty_to_point
#print axioms line_T202_1
/-- T189: Found.MA.meets -/
theorem line_T189_0 : type_of% @Found.MA.meets := @Found.MA.meets
#print axioms line_T189_0
/-- T189: Found.MA.filter_directed -/
theorem line_T189_1 : type_of% @Found.MA.filter_directed := @Found.MA.filter_directed
#print axioms line_T189_1
/-- T189: Found.MA.filter_up -/
theorem line_T189_2 : type_of% @Found.MA.filter_up := @Found.MA.filter_up
#print axioms line_T189_2
/-- T199: Found.Pred.ext_and -/
theorem line_T199_0 : type_of% @Found.Pred.ext_and := @Found.Pred.ext_and
#print axioms line_T199_0
/-- T199: Found.Pred.ext_ex -/
theorem line_T199_1 : type_of% @Found.Pred.ext_ex := @Found.Pred.ext_ex
#print axioms line_T199_1
/-- T199: Found.Pred.weyl -/
theorem line_T199_2 : type_of% @Found.Pred.weyl := @Found.Pred.weyl
#print axioms line_T199_2
/-- T179: Found.PN.dual_dual -/
theorem line_T179_0 : type_of% @Found.PN.dual_dual := @Found.PN.dual_dual
#print axioms line_T179_0
/-- T179: Found.PN.euler -/
theorem line_T179_1 : type_of% @Found.PN.euler := @Found.PN.euler
#print axioms line_T179_1
/-- T179: Found.DR.dr_sound -/
theorem line_T179_2 : type_of% @Found.DR.dr_sound := @Found.DR.dr_sound
#print axioms line_T179_2
/-- T179: Found.DR.danos_regnier_sound -/
theorem line_T179_3 : type_of% @Found.DR.danos_regnier_sound := @Found.DR.danos_regnier_sound
#print axioms line_T179_3
/-- T196: Found.InfN.inv_bnd -/
theorem line_T196_0 : type_of% @Found.InfN.inv_bnd := @Found.InfN.inv_bnd
#print axioms line_T196_0
/-- T196: Found.InfN.collapse -/
theorem line_T196_1 : type_of% @Found.InfN.collapse := @Found.InfN.collapse
#print axioms line_T196_1
/-- T136: Found.Shulman.path -/
theorem line_T136_0 : type_of% @Found.Shulman.path := @Found.Shulman.path
#print axioms line_T136_0
/-- T136: Found.ShulmanCor.univalent -/
theorem line_T136_1 : type_of% @Found.ShulmanCor.univalent := @Found.ShulmanCor.univalent
#print axioms line_T136_1
/-- T136: Found.ShulmanCor.shulman -/
theorem line_T136_2 : type_of% @Found.ShulmanCor.shulman := @Found.ShulmanCor.shulman
#print axioms line_T136_2
/-- T155: Found.LU.sub_comp -/
theorem line_T155_0 : type_of% @Found.LU.sub_comp := @Found.LU.sub_comp
#print axioms line_T155_0
/-- T155: Found.LU.q_pair -/
theorem line_T155_1 : type_of% @Found.LU.q_pair := @Found.LU.q_pair
#print axioms line_T155_1
/-- T155: Found.LU.pair_sub -/
theorem line_T155_2 : type_of% @Found.LU.pair_sub := @Found.LU.pair_sub
#print axioms line_T155_2
/-- T154: Found.Pres.union_of_finite -/
theorem line_T154_0 : type_of% @Found.Pres.union_of_finite := @Found.Pres.union_of_finite
#print axioms line_T154_0
/-- T154: Found.Pres.directed -/
theorem line_T154_1 : type_of% @Found.Pres.directed := @Found.Pres.directed
#print axioms line_T154_1
/-- T154: Found.Pres.reflection -/
theorem line_T154_2 : type_of% @Found.Pres.reflection := @Found.Pres.reflection
#print axioms line_T154_2
/-- T169: Found.VL.ev_resp -/
theorem line_T169_0 : type_of% @Found.VL.ev_resp := @Found.VL.ev_resp
#print axioms line_T169_0
/-- T169: Found.VL.def_sub -/
theorem line_T169_1 : type_of% @Found.VL.def_sub := @Found.VL.def_sub
#print axioms line_T169_1
/-- T169: Found.VL.sub_def -/
theorem line_T169_2 : type_of% @Found.VL.sub_def := @Found.VL.sub_def
#print axioms line_T169_2
/-- T144: Found.PCF.fact5 -/
theorem line_T144_0 : type_of% @Found.PCF.fact5 := @Found.PCF.fact5
#print axioms line_T144_0
/-- T144: Found.PCF.fact_type -/
theorem line_T144_1 : type_of% @Found.PCF.fact_type := @Found.PCF.fact_type
#print axioms line_T144_1
/-- T181: Found.PTS.mono -/
theorem line_T181_0 : type_of% @Found.PTS.mono := @Found.PTS.mono
#print axioms line_T181_0
/-- T181: Found.PTS.cube_sub -/
theorem line_T181_1 : type_of% @Found.PTS.cube_sub := @Found.PTS.cube_sub
#print axioms line_T181_1
/-- T181: Found.PTS.into_CoC -/
theorem line_T181_2 : type_of% @Found.PTS.into_CoC := @Found.PTS.into_CoC
#print axioms line_T181_2
/-- T79: Found.NbE.rr_good -/
theorem line_T79_0 : type_of% @Found.NbE.rr_good := @Found.NbE.rr_good
#print axioms line_T79_0
/-- T79: Found.NbE.eval_good -/
theorem line_T79_1 : type_of% @Found.NbE.eval_good := @Found.NbE.eval_good
#print axioms line_T79_1
/-- T79: Found.NbE.nf_normal -/
theorem line_T79_2 : type_of% @Found.NbE.nf_normal := @Found.NbE.nf_normal
#print axioms line_T79_2
/-- T85: Found.GoedelBridge.loeb_both -/
theorem line_T85_0 : type_of% @Found.GoedelBridge.loeb_both := @Found.GoedelBridge.loeb_both
#print axioms line_T85_0
/-- T85: Found.GoedelBridge.goedel2_from_loeb -/
theorem line_T85_1 : type_of% @Found.GoedelBridge.goedel2_from_loeb := @Found.GoedelBridge.goedel2_from_loeb
#print axioms line_T85_1
/-- T208: Found.FO.complete_iff -/
theorem line_T208_0 : type_of% @Found.FO.complete_iff := @Found.FO.complete_iff
#print axioms line_T208_0
/-- T208: Found.FO.lowenheim_skolem -/
theorem line_T208_1 : type_of% @Found.FO.lowenheim_skolem := @Found.FO.lowenheim_skolem
#print axioms line_T208_1
/-- T208: Found.FO.compactness -/
theorem line_T208_2 : type_of% @Found.FO.compactness := @Found.FO.compactness
#print axioms line_T208_2
/-- T127: Found.HoTTL.path_eq_iff_connected -/
theorem line_T127_0 : type_of% @Found.HoTTL.path_eq_iff_connected := @Found.HoTTL.path_eq_iff_connected
#print axioms line_T127_0
/-- T127: Found.HoTTL.not_univalent -/
theorem line_T127_1 : type_of% @Found.HoTTL.not_univalent := @Found.HoTTL.not_univalent
#print axioms line_T127_1
/-- T209: Found.ETCSZF.power_iso -/
theorem line_T209_0 : type_of% @Found.ETCSZF.power_iso := @Found.ETCSZF.power_iso
#print axioms line_T209_0
/-- T209: Found.ETCSZF2.prod_iso -/
theorem line_T209_1 : type_of% @Found.ETCSZF2.prod_iso := @Found.ETCSZF2.prod_iso
#print axioms line_T209_1
/-- T209: Found.ETCSZF2.exp_iso -/
theorem line_T209_2 : type_of% @Found.ETCSZF2.exp_iso := @Found.ETCSZF2.exp_iso
#print axioms line_T209_2
/-- T209: Found.ETCSZF3.maclaneW -/
theorem line_T209_3 : type_of% @Found.ETCSZF3.maclaneW := @Found.ETCSZF3.maclaneW
#print axioms line_T209_3
/-- T210: Found.Nom.equivariant -/
theorem line_T210_0 : type_of% @Found.Nom.equivariant := @Found.Nom.equivariant
#print axioms line_T210_0
/-- T210: Found.Nom.swap_inter -/
theorem line_T210_1 : type_of% @Found.Nom.swap_inter := @Found.Nom.swap_inter
#print axioms line_T210_1
/-- T210: Found.Nom.glue_nominal -/
theorem line_T210_2 : type_of% @Found.Nom.glue_nominal := @Found.Nom.glue_nominal
#print axioms line_T210_2
/-- T210: Found.Nom.roundtrip -/
theorem line_T210_3 : type_of% @Found.Nom.roundtrip := @Found.Nom.roundtrip
#print axioms line_T210_3
/-- T118: Found.Bishop.four_upper -/
theorem line_T118_0 : type_of% @Found.Bishop.four_upper := @Found.Bishop.four_upper
#print axioms line_T118_0
/-- T118: Found.Bishop.arch -/
theorem line_T118_1 : type_of% @Found.Bishop.arch := @Found.Bishop.arch
#print axioms line_T118_1
/-- T118: Found.Bishop.eqv_trans -/
theorem line_T118_2 : type_of% @Found.Bishop.eqv_trans := @Found.Bishop.eqv_trans
#print axioms line_T118_2
/-- T118: Found.Bishop.neg_resp -/
theorem line_T118_3 : type_of% @Found.Bishop.neg_resp := @Found.Bishop.neg_resp
#print axioms line_T118_3
/-- T96b: Found.K1.dec_enc -/
theorem line_T96b_0 : type_of% @Found.K1.dec_enc := @Found.K1.dec_enc
#print axioms line_T96b_0
/-- T96b: Found.K1.ev_det -/
theorem line_T96b_1 : type_of% @Found.K1.ev_det := @Found.K1.ev_det
#print axioms line_T96b_1
/-- T96b: Found.K1.church_thesis -/
theorem line_T96b_2 : type_of% @Found.K1.church_thesis := @Found.K1.church_thesis
#print axioms line_T96b_2
/-- T96b: Found.K1.no_halting_realizer -/
theorem line_T96b_3 : type_of% @Found.K1.no_halting_realizer := @Found.K1.no_halting_realizer
#print axioms line_T96b_3
/-- T207: Found.CT.correct -/
theorem line_T207_0 : type_of% @Found.CT.correct := @Found.CT.correct
#print axioms line_T207_0
/-- T207: Found.CT3.cor -/
theorem line_T207_1 : type_of% @Found.CT3.cor := @Found.CT3.cor
#print axioms line_T207_1
/-- T207: Found.RM.reg_to_mu -/
theorem line_T207_2 : type_of% @Found.RM.reg_to_mu := @Found.RM.reg_to_mu
#print axioms line_T207_2
/-- T82: Found.CT3.cor -/
theorem line_T82_0 : type_of% @Found.CT3.cor := @Found.CT3.cor
#print axioms line_T82_0
/-- T82: Found.RM.reg_to_mu -/
theorem line_T82_1 : type_of% @Found.RM.reg_to_mu := @Found.RM.reg_to_mu
#print axioms line_T82_1
/-- T82: Found.K1.no_halting_realizer -/
theorem line_T82_2 : type_of% @Found.K1.no_halting_realizer := @Found.K1.no_halting_realizer
#print axioms line_T82_2
/-- T124: Found.Ord.nf_acc -/
theorem line_T124_0 : type_of% @Found.Ord.nf_acc := @Found.Ord.nf_acc
#print axioms line_T124_0
/-- T124: Found.Zinf.cut_elim -/
theorem line_T124_1 : type_of% @Found.Zinf.cut_elim := @Found.Zinf.cut_elim
#print axioms line_T124_1
/-- T124: Found.PAE.embed -/
theorem line_T124_2 : type_of% @Found.PAE.embed := @Found.PAE.embed
#print axioms line_T124_2
/-- T124: Found.PAE.pa_consistent -/
theorem line_T124_3 : type_of% @Found.PAE.pa_consistent := @Found.PAE.pa_consistent
#print axioms line_T124_3
/-- T106: Found.NFS.allowable_mul -/
theorem line_T106_0 : type_of% @Found.NFS.allowable_mul := @Found.NFS.allowable_mul
#print axioms line_T106_0
/-- T106: Found.NFA.alt_equivariant -/
theorem line_T106_1 : type_of% @Found.NFA.alt_equivariant := @Found.NFA.alt_equivariant
#print axioms line_T106_1
/-- T106: Found.NFU.supp_act -/
theorem line_T106_2 : type_of% @Found.NFU.supp_act := @Found.NFU.supp_act
#print axioms line_T106_2
/-- T106: Found.NFR.fmap_inj -/
theorem line_T106_3 : type_of% @Found.NFR.fmap_inj := @Found.NFR.fmap_inj
#print axioms line_T106_3
/-- T106: Found.NFAs.assemble -/
theorem line_T106_4 : type_of% @Found.NFAs.assemble := @Found.NFAs.assemble
#print axioms line_T106_4
/-- T106: Found.NFCS.bound_of_small -/
theorem line_T106_5 : type_of% @Found.NFCS.bound_of_small := @Found.NFCS.bound_of_small
#print axioms line_T106_5
/-- T106: Found.NFLb.orbitSmall_of_labels -/
theorem line_T106_6 : type_of% @Found.NFLb.orbitSmall_of_labels := @Found.NFLb.orbitSmall_of_labels
#print axioms line_T106_6
/-- T211: Found.Frege.russell -/
theorem line_T211_0 : type_of% @Found.Frege.russell := @Found.Frege.russell
#print axioms line_T211_0
/-- T211: Found.Frege.cantor -/
theorem line_T211_1 : type_of% @Found.Frege.cantor := @Found.Frege.cantor
#print axioms line_T211_1
/-- T211: Found.Frege.zero_not_succ -/
theorem line_T211_2 : type_of% @Found.Frege.zero_not_succ := @Found.Frege.zero_not_succ
#print axioms line_T211_2
/-- T211: Found.Frege.nat_ind -/
theorem line_T211_3 : type_of% @Found.Frege.nat_ind := @Found.Frege.nat_ind
#print axioms line_T211_3
/-- T212: Found.Ramified.collapse_all -/
theorem line_T212_0 : type_of% @Found.Ramified.collapse_all := @Found.Ramified.collapse_all
#print axioms line_T212_0
/-- T212: Found.Ramified.collapse_ex -/
theorem line_T212_1 : type_of% @Found.Ramified.collapse_ex := @Found.Ramified.collapse_ex
#print axioms line_T212_1
/-- T212: Found.Ramified.bool_not_reducible -/
theorem line_T212_2 : type_of% @Found.Ramified.bool_not_reducible := @Found.Ramified.bool_not_reducible
#print axioms line_T212_2
/-- T213: Found.ETCC.toArr_ofArr -/
theorem line_T213_0 : type_of% @Found.ETCC.toArr_ofArr := @Found.ETCC.toArr_ofArr
#print axioms line_T213_0
/-- T213: Found.ETCC.ofArr_obj -/
theorem line_T213_1 : type_of% @Found.ETCC.ofArr_obj := @Found.ETCC.ofArr_obj
#print axioms line_T213_1
/-- T213: Found.ETCC.discF_obj -/
theorem line_T213_2 : type_of% @Found.ETCC.discF_obj := @Found.ETCC.discF_obj
#print axioms line_T213_2
/-- T214: Found.Epsilon.ex_iff -/
theorem line_T214_0 : type_of% @Found.Epsilon.ex_iff := @Found.Epsilon.ex_iff
#print axioms line_T214_0
/-- T214: Found.Epsilon.all_iff -/
theorem line_T214_1 : type_of% @Found.Epsilon.all_iff := @Found.Epsilon.all_iff
#print axioms line_T214_1
/-- T214: Found.Epsilon.choice -/
theorem line_T214_2 : type_of% @Found.Epsilon.choice := @Found.Epsilon.choice
#print axioms line_T214_2
/-- T214: Found.Epsilon.diaconescu -/
theorem line_T214_3 : type_of% @Found.Epsilon.diaconescu := @Found.Epsilon.diaconescu
#print axioms line_T214_3
/-- T215: Found.Plural.compr -/
theorem line_T215_0 : type_of% @Found.Plural.compr := @Found.Plural.compr
#print axioms line_T215_0
/-- T215: Found.Plural.boolos_ex -/
theorem line_T215_1 : type_of% @Found.Plural.boolos_ex := @Found.Plural.boolos_ex
#print axioms line_T215_1
/-- T215: Found.Plural.boolos_all -/
theorem line_T215_2 : type_of% @Found.Plural.boolos_all := @Found.Plural.boolos_all
#print axioms line_T215_2
/-- T215: Found.Plural.oneOf_iff_part -/
theorem line_T215_3 : type_of% @Found.Plural.oneOf_iff_part := @Found.Plural.oneOf_iff_part
#print axioms line_T215_3
/-- T216: Found.Krivine.mp -/
theorem line_T216_0 : type_of% @Found.Krivine.mp := @Found.Krivine.mp
#print axioms line_T216_0
/-- T216: Found.Krivine.k_real -/
theorem line_T216_1 : type_of% @Found.Krivine.k_real := @Found.Krivine.k_real
#print axioms line_T216_1
/-- T216: Found.Krivine.peirce -/
theorem line_T216_2 : type_of% @Found.Krivine.peirce := @Found.Krivine.peirce
#print axioms line_T216_2
/-- T216: Found.Krivine.empty_arr -/
theorem line_T216_3 : type_of% @Found.Krivine.empty_arr := @Found.Krivine.empty_arr
#print axioms line_T216_3

end Found.Lines

-- not resolved to a theorem in the listed files (definitions or prose): T62:Adj, T63:CCC, T63:H, T64:H, T65:H, T65:PD, T66:H, T66:PD, T67:R, T68:M, T68:H, T70:H, T71:H, T71:M, T71:PD, T72:R, T73:H, T76:PD, T77:PD, T108:H, T108:R, T108:PD, T96:H, T95:H, T86:NNO, T107:T86, T107:NNO, T107:T66, T107:T87, T88:T109, T89:T109, T89:T87, T90:T88, T90:T109, T91:T88, T91:T109, T91:NBGc.nbg_conservative, T91  -- (+960 chars; full line in the Zenodo source)

#print axioms: 197 theorems, no axioms.

85.131 Bishop’s constructive reals

Regular sequences of integers read over the denominators \(n+1\) form a setoid under \(|x_n-y_n|\le 2/n\), transitivity coming from a four-term estimate valid for every \(m\) and an Archimedean step; negation and the integers respect it. \(|x_n-z_n|(m{+}1)\le 2(m{+}1)+6(n{+}1)\ \forall m\ \Rightarrow \ |x_n-z_n|\le 2\).

found/Bishop.lean

/-
  T118. found/Bishop — Bishop's constructive reals as a point: the setoid
  coordinate applied to regular sequences.
  * x is a sequence of integers p n read as p n / (n+1), regular:
      |p m (n+1) − p n (m+1)| ≤ (m+1) + (n+1)   (Bishop: |x_m − x_n| ≤ 1/m + 1/n);
  * x ≈ y  :⟺  ∀ n, |p n − q n| ≤ 2   (|x_n − y_n| ≤ 2/n);
  * ≈ is an equivalence (transitivity by Bishop's argument: for every m,
    |x_n − z_n|·(m+1) ≤ 2(m+1) + 6(n+1), then an Archimedean step);
  * negation and the integers embed, respecting ≈.
  Order is ∃k, b = a + k (no core Int order lemmas: they use propext);
  ring identities by lib_int (lib_shared). Arithmetic of sums/products and
  the approximate intermediate value theorem are the continuation (cited).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import lib.IntRing

namespace Found

namespace Bishop

def LE' (a b : Int) : Prop := ∃ k : Nat, b = a + Int.ofNat k

theorem le_refl' (a : Int) : LE' a a := ⟨0, by show a = a + 0; lib_int⟩

theorem le_trans' {a b c : Int} (h1 : LE' a b) (h2 : LE' b c) : LE' a c :=
  match h1, h2 with
  | ⟨k, e1⟩, ⟨l, e2⟩ => ⟨k + l, by
      rw [e2, e1]
      show a + Int.ofNat k + Int.ofNat l = a + (Int.ofNat k + Int.ofNat l)
      lib_int⟩

theorem le_add' {a b c d : Int} (h1 : LE' a b) (h2 : LE' c d) : LE' (a + c) (b + d) :=
  match h1, h2 with
  | ⟨k, e1⟩, ⟨l, e2⟩ => ⟨k + l, by
      rw [e1, e2]
      show a + Int.ofNat k + (c + Int.ofNat l) = a + c + (Int.ofNat k + Int.ofNat l)
      lib_int⟩

theorem le_mulN {a b : Int} (m : Nat) (h : LE' a b) : LE' (a * Int.ofNat m) (b * Int.ofNat m) :=
  match h with
  | ⟨k, e⟩ => ⟨k * m, by
      rw [e]
      show (a + Int.ofNat k) * Int.ofNat m = a * Int.ofNat m + Int.ofNat k * Int.ofNat m
      lib_int⟩

theorem le_neg' {a b : Int} (h : LE' a b) : LE' (-b) (-a) :=
  match h with
  | ⟨k, e⟩ => ⟨k, by rw [e]; lib_int⟩

theorem le_eq {a b c : Int} (e : a = b) (h : LE' b c) : LE' a c := e ▸ h
theorem le_eq' {a b c : Int} (h : LE' a b) (e : b = c) : LE' a c := e ▸ h

/-- |a| ≤ c -/
def Bnd (a c : Int) : Prop := LE' (-c) a ∧ LE' a c

theorem bnd_neg {a c : Int} (h : Bnd a c) : Bnd (-a) c :=
  ⟨le_neg' h.2, le_eq' (le_neg' h.1) (by lib_int)⟩

theorem bnd_eq {a b c : Int} (e : a = b) (h : Bnd b c) : Bnd a c := e ▸ h

def N (n : Nat) : Int := Int.ofNat (n + 1)

structure Real where
  p : Nat → Int
  reg : ∀ m n, Bnd (p m * N n - p n * N m) (N m + N n)

def Eqv (x y : Real) : Prop := ∀ n, Bnd (x.p n - y.p n) 2

theorem eqv_refl (x : Real) : Eqv x x := fun n =>
  ⟨⟨2, by show x.p n - x.p n = -2 + 2; lib_int⟩, ⟨2, by show (2 : Int) = x.p n - x.p n + 2; lib_int⟩⟩

theorem eqv_symm {x y : Real} (h : Eqv x y) : Eqv y x := fun n =>
  match bnd_neg (h n) with
  | ⟨h1, h2⟩ => ⟨le_eq' h1 (by lib_int), le_eq (by lib_int) h2⟩

/-- the four-term estimate: (x_n − z_n)(m+1) ≤ 2(m+1) + 6(n+1) -/
theorem four_upper {x y z : Real} (h1 : Eqv x y) (h2 : Eqv y z) (n m : Nat) :
    LE' ((x.p n - z.p n) * N m) (2 * N m + 6 * N n) := by
  have a1 : LE' (-(x.p m * N n - x.p n * N m)) (N m + N n) := le_neg' (x.reg m n).1 |> fun h => le_eq' h (by lib_int)
  have a2 : LE' ((x.p m - y.p m) * N n) (2 * N n) := le_mulN (n + 1) (h1 m).2
  have a3 : LE' ((y.p m - z.p m) * N n) (2 * N n) := le_mulN (n + 1) (h2 m).2
  have a4 : LE' (z.p m * N n - z.p n * N m) (N m + N n) := (z.reg m n).2
  have s := le_add' (le_add' (le_add' a1 a2) a3) a4
  exact le_eq (by lib_int) (le_eq' s (by lib_int))

/-- Archimedean step: if d(m+1) ≤ 2(m+1) + c for all m then d ≤ 2 -/
theorem arch (d : Int) (c : Nat) (h : ∀ m : Nat, LE' (d * N m) (2 * N m + Int.ofNat c)) : LE' d 2 := by
  have hd : d = 2 + (d - 2) := by lib_int
  generalize he : d - 2 = e at hd
  cases e with
  | ofNat k =>
    cases k with
    | zero => exact ⟨0, by rw [hd]; show (2 : Int) = 2 + 0 + 0; lib_int⟩
    | succ k =>
      exfalso
      match h c with
      | ⟨j, ej⟩ =>
        have e2 : Int.ofNat (2 * (c + 1) + c) = Int.ofNat (2 * (c + 1) + (k + 1) * (c + 1) + j) := by
          show 2 * N c + Int.ofNat c = _
          rw [ej, hd]
          show (2 + Int.ofNat (k + 1)) * N c + Int.ofNat j = Int.ofNat (2 * (c + 1) + (k + 1) * (c + 1) + j)
          show (2 + Int.ofNat (k + 1)) * Int.ofNat (c + 1) + Int.ofNat j =
            2 * Int.ofNat (c + 1) + Int.ofNat (k + 1) * Int.ofNat (c + 1) + Int.ofNat j
          lib_int
        have e3 := Int.ofNat.inj e2
        have l1 : c + 1 ≤ (k + 1) * (c + 1) := Nat.le_mul_of_pos_left _ (Nat.succ_pos k)
        have l2 : 2 * (c + 1) + (c + 1) ≤ 2 * (c + 1) + (k + 1) * (c + 1) + j :=
          Nat.le_trans (Nat.add_le_add_left l1 _) (Nat.le_add_right _ _)
        rw [← e3] at l2
        exact Nat.lt_irrefl _ (Nat.lt_of_lt_of_le (Nat.add_lt_add_left (Nat.lt_succ_self c) _) l2)
  | negSucc k =>
    exact ⟨k + 1, by
      rw [hd]
      show (2 : Int) = 2 + Int.negSucc k + Int.ofNat (k + 1)
      show (2 : Int) = 2 + -Int.ofNat (k + 1) + Int.ofNat (k + 1)
      lib_int⟩

theorem eqv_trans {x y z : Real} (h1 : Eqv x y) (h2 : Eqv y z) : Eqv x z := fun n =>
  ⟨le_eq' (le_neg' (arch (-(x.p n - z.p n)) (6 * (n + 1)) (fun m =>
      le_eq (by lib_int) (le_eq' (four_upper (eqv_symm h2) (eqv_symm h1) n m) (by show _ = _ + Int.ofNat (6 * (n + 1)); show 2 * N m + 6 * Int.ofNat (n + 1) = 2 * N m + Int.ofNat 6 * Int.ofNat (n + 1); rfl))))) (by lib_int),
   arch (x.p n - z.p n) (6 * (n + 1)) (fun m => le_eq' (four_upper h1 h2 n m) rfl)⟩

/-! ## negation and the integers -/

def neg (x : Real) : Real :=
  ⟨fun n => -(x.p n), fun m n => match bnd_neg (x.reg m n) with
    | ⟨h1, h2⟩ => ⟨le_eq' h1 (by lib_int), le_eq (by lib_int) h2⟩⟩

theorem neg_resp {x y : Real} (h : Eqv x y) : Eqv (neg x) (neg y) := fun n =>
  match bnd_neg (h n) with
  | ⟨h1, h2⟩ => ⟨le_eq' h1 (by show -(x.p n - y.p n) = -(x.p n) - -(y.p n); lib_int),
                 le_eq (by show -(x.p n) - -(y.p n) = -(x.p n - y.p n); lib_int) h2⟩

theorem neg_neg (x : Real) : Eqv (neg (neg x)) x := fun n =>
  bnd_eq (by show -(-(x.p n)) - x.p n = x.p n - x.p n; lib_int) (eqv_refl x n)

def ofInt (k : Int) : Real :=
  ⟨fun n => k * N n, fun m n => by
    have e : k * N m * N n - k * N n * N m = 0 := by lib_int
    rw [e]
    exact ⟨⟨m + 1 + (n + 1), by show (0 : Int) = -(N m + N n) + (N m + N n); lib_int⟩,
           ⟨m + 1 + (n + 1), by show N m + N n = 0 + (N m + N n); lib_int⟩⟩⟩

theorem ofInt_neg (k : Int) : Eqv (neg (ofInt k)) (ofInt (-k)) := fun n =>
  bnd_eq (by show -(k * N n) - -k * N n = 0 - 0; lib_int)
    (⟨⟨2, by show (0 : Int) - 0 = -2 + 2; lib_int⟩, ⟨2, by show (2 : Int) = 0 - 0 + 2; lib_int⟩⟩ :
      Bnd (0 - 0) 2)

end Bishop

end Found

#print axioms Found.Bishop.four_upper
#print axioms Found.Bishop.arch
#print axioms Found.Bishop.eqv_trans
#print axioms Found.Bishop.neg_resp
#print axioms Found.Bishop.neg_neg
#print axioms Found.Bishop.ofInt
#print axioms Found.Bishop.ofInt_neg

#print axioms: 7 theorems, no axioms.

85.132 Realizability over Kleene’s first algebra

With μ-recursive programs as realizers, programs are numbered with a decoder, evaluation is deterministic, Church’s thesis is realized, and by the diagonal program \(\mu t.\,d(n)\) no program realizes \(\forall n\,(H n\vee \neg H n)\) for halting. \(\neg \exists d\ \forall n\ (d(n){=}1\wedge H n)\vee (d(n){=}0\wedge \neg H n)\).

found/EffectiveK1.lean

/-
  T96b. found/EffectiveK1 — realizability over Kleene's first algebra
  (codes = μ-recursive programs MR of T207 with their relational semantics
  Ev), the effective-topos point:
  * a numbering of programs: enc : MR → ℕ with a decoder (dec_enc), built
    on the pairing ⟨a,b⟩ = 2^a(2b+1) with hand-written parity/halving;
  * Ev is deterministic;
  * Church's thesis is realized (a realizer of ∀n∃m φ is a program);
  * ∀n (H n ∨ ¬H n) has no realizer, for H n = "program n halts on n"
    (diagonal: the program μt.d(n) halts on n exactly when d says no).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.ChurchTuring3

namespace Found

namespace K1

open CT3 Rec

/-! ## pairing ⟨a,b⟩ = 2^a (2b+1) -/

def dbl (n : Nat) : Nat := n + n

def pr : Nat → Nat → Nat
  | 0, b => dbl b + 1
  | a + 1, b => dbl (pr a b)

/-- parity: n = 2q + r -/
def par : Nat → Bool × Nat
  | 0 => (false, 0)
  | 1 => (true, 0)
  | n + 2 => ((par n).1, (par n).2 + 1)

theorem par_dbl : (n : Nat) → par (dbl n) = (false, n)
  | 0 => rfl
  | n + 1 => by
    show par (n + 1 + (n + 1)) = _
    have e : n + 1 + (n + 1) = (n + n) + 2 := by
      rw [Nat.add_succ, Nat.succ_add]
    rw [e]
    show ((par (dbl n)).1, (par (dbl n)).2 + 1) = _
    rw [par_dbl n]

theorem par_dbl1 : (n : Nat) → par (dbl n + 1) = (true, n)
  | 0 => rfl
  | n + 1 => by
    have e : dbl (n + 1) + 1 = (dbl n + 1) + 2 := by
      show n + 1 + (n + 1) + 1 = n + n + 1 + 2
      rw [Nat.add_succ (n + 1) n, Nat.succ_add n n]
    rw [e]
    show ((par (dbl n + 1)).1, (par (dbl n + 1)).2 + 1) = _
    rw [par_dbl1 n]

def unp : Nat → Nat → Nat × Nat
  | 0, _ => (0, 0)
  | f + 1, w => match par w with
    | (true, q) => (0, q)
    | (false, q) => ((unp f q).1 + 1, (unp f q).2)

theorem unp_pr : (a b f : Nat) → a < f → unp f (pr a b) = (a, b)
  | 0, b, f + 1, _ => by
    show (match par (dbl b + 1) with
      | (true, q) => (0, q)
      | (false, q) => ((unp f q).1 + 1, (unp f q).2)) = _
    rw [par_dbl1]
  | a + 1, b, f + 1, h => by
    show (match par (dbl (pr a b)) with
      | (true, q) => (0, q)
      | (false, q) => ((unp f q).1 + 1, (unp f q).2)) = _
    rw [par_dbl]
    show ((unp f (pr a b)).1 + 1, (unp f (pr a b)).2) = _
    rw [unp_pr a b f (Nat.lt_of_succ_lt_succ h)]
  | _, _, 0, h => absurd h (Nat.not_lt_zero _)

theorem pr_ge : (a b : Nat) → a + b < pr a b
  | 0, b => by
    show 0 + b < b + b + 1
    rw [Nat.zero_add]
    exact Nat.lt_succ_of_le (Nat.le_add_left b b)
  | a + 1, b => by
    show a + 1 + b < pr a b + pr a b
    have h := pr_ge a b
    have h1 : a + 1 + b ≤ pr a b := by
      rw [Nat.add_right_comm]
      exact h
    exact Nat.lt_of_le_of_lt h1 (Nat.lt_add_of_pos_right (Nat.lt_of_le_of_lt (Nat.zero_le _) h))

def unpS (w : Nat) : Nat × Nat := unp w w

theorem unpS_pr (a b : Nat) : unpS (pr a b) = (a, b) :=
  unp_pr a b _ (Nat.lt_of_le_of_lt (Nat.le_add_right a b) (pr_ge a b))

/-! ## numbering of programs -/

mutual
def enc : MR → Nat
  | .zero => pr 0 0
  | .succ => pr 1 0
  | .proj i => pr 2 i
  | .comp f gs => pr 3 (pr (enc f) (encL gs))
  | .prec f g => pr 4 (pr (enc f) (enc g))
  | .mu f => pr 5 (enc f)
def encL : List MR → Nat
  | [] => 0
  | g :: gs => pr (enc g) (encL gs) + 1
end

mutual
def dec : Nat → Nat → MR
  | 0, _ => .zero
  | f + 1, n => match (unpS n).1 with
    | 0 => .zero
    | 1 => .succ
    | 2 => .proj (unpS n).2
    | 3 => .comp (dec f (unpS (unpS n).2).1) (decL f (unpS (unpS n).2).2)
    | 4 => .prec (dec f (unpS (unpS n).2).1) (dec f (unpS (unpS n).2).2)
    | 5 => .mu (dec f (unpS n).2)
    | _ + 6 => .zero
def decL : Nat → Nat → List MR
  | 0, _ => []
  | _ + 1, 0 => []
  | f + 1, n + 1 => dec f (unpS n).1 :: decL f (unpS n).2
end

theorem lt_pr_l (a b : Nat) : a < pr a b := Nat.lt_of_le_of_lt (Nat.le_add_right a b) (pr_ge a b)
theorem lt_pr_r (a b : Nat) : b < pr a b := Nat.lt_of_le_of_lt (Nat.le_add_left b a) (pr_ge a b)

mutual
theorem dec_enc : (g : MR) → (f : Nat) → enc g < f → dec f (enc g) = g
  | .zero, f + 1, _ => by unfold enc dec; rw [unpS_pr]
  | .succ, f + 1, _ => by unfold enc dec; rw [unpS_pr]
  | .proj i, f + 1, _ => by unfold enc dec; rw [unpS_pr]
  | .comp g gs, f + 1, h => by
    unfold enc dec
    rw [unpS_pr]
    show MR.comp (dec f (unpS (pr (enc g) (encL gs))).1) (decL f (unpS (pr (enc g) (encL gs))).2) = _
    rw [unpS_pr]
    have h1 : pr (enc g) (encL gs) < f + 1 := Nat.lt_trans (lt_pr_r 3 _) h
    rw [dec_enc g f (Nat.lt_of_lt_of_le (lt_pr_l _ _) (Nat.le_of_lt_succ h1)),
        decL_encL gs f (Nat.lt_of_lt_of_le (lt_pr_r _ _) (Nat.le_of_lt_succ h1))]
  | .prec g k, f + 1, h => by
    unfold enc dec
    rw [unpS_pr]
    show MR.prec (dec f (unpS (pr (enc g) (enc k))).1) (dec f (unpS (pr (enc g) (enc k))).2) = _
    rw [unpS_pr]
    have h1 : pr (enc g) (enc k) < f + 1 := Nat.lt_trans (lt_pr_r 4 _) h
    rw [dec_enc g f (Nat.lt_of_lt_of_le (lt_pr_l _ _) (Nat.le_of_lt_succ h1)),
        dec_enc k f (Nat.lt_of_lt_of_le (lt_pr_r _ _) (Nat.le_of_lt_succ h1))]
  | .mu g, f + 1, h => by
    unfold enc dec
    rw [unpS_pr]
    show MR.mu (dec f (enc g)) = _
    rw [dec_enc g f (Nat.lt_of_lt_of_le (lt_pr_r 5 _) (Nat.le_of_lt_succ h))]
  | _, 0, h => absurd h (Nat.not_lt_zero _)
theorem decL_encL : (gs : List MR) → (f : Nat) → encL gs < f → decL f (encL gs) = gs
  | [], f + 1, _ => rfl
  | g :: gs, f + 1, h => by
    show dec f (unpS (pr (enc g) (encL gs))).1 :: decL f (unpS (pr (enc g) (encL gs))).2 = _
    rw [unpS_pr]
    have h1 : pr (enc g) (encL gs) < f := Nat.lt_of_succ_lt_succ h
    rw [dec_enc g f (Nat.lt_trans (lt_pr_l _ _) h1), decL_encL gs f (Nat.lt_trans (lt_pr_r _ _) h1)]
  | _, 0, h => absurd h (Nat.not_lt_zero _)
end

/-- the program numbered n -/
def prog (n : Nat) : MR := dec (n + 1) n

theorem prog_enc (g : MR) : prog (enc g) = g := dec_enc g _ (Nat.lt_succ_self _)

/-! ## determinism -/

def hdN : List Nat → Nat
  | [] => 0
  | a :: _ => a

def tlN : List Nat → List Nat
  | [] => []
  | _ :: l => l

def isNilB : List Nat → Bool
  | [] => true
  | _ :: _ => false

def getF : MR → MR
  | .zero => .zero
  | .succ => .zero
  | .proj _ => .zero
  | .comp f _ => f
  | .prec f _ => f
  | .mu f => f

def getG : MR → MR
  | .zero => .zero
  | .succ => .zero
  | .proj _ => .zero
  | .comp _ _ => .zero
  | .prec _ g => g
  | .mu _ => .zero

def getGs : MR → List MR
  | .zero => []
  | .succ => []
  | .proj _ => []
  | .comp _ gs => gs
  | .prec _ _ => []
  | .mu _ => []

def tag : MR → Nat
  | .zero => 0
  | .succ => 1
  | .proj _ => 2
  | .comp _ _ => 3
  | .prec _ _ => 4
  | .mu _ => 5

def hdM : List MR → MR
  | [] => .zero
  | g :: _ => g

def tlM : List MR → List MR
  | [] => []
  | _ :: l => l

def isNilM : List MR → Bool
  | [] => true
  | _ :: _ => false

/-! Inversion lemmas with variable indices: `cases` on a derivation whose index is a
  constructor application unifies through injEq lemmas (propext), so every inversion
  goes through equations and projection functions instead. -/

theorem beq_refl' : (n : Nat) → Nat.beq n n = true
  | 0 => rfl
  | n + 1 => beq_refl' n

theorem tag_ne' {m m' : MR} (e : m = m') (h : Nat.beq (tag m) (tag m') = false) : False :=
  Bool.noConfusion (h.symm.trans ((congrArg (fun x => Nat.beq (tag x) (tag m')) e).trans (beq_refl' (tag m'))))

theorem inv_zero {h a v} (d : Ev h a v) (eh : h = .zero) : v = 0 := by
  cases d with
  | zero => rfl
  | succ => exact (tag_ne' eh rfl).elim
  | proj => exact (tag_ne' eh rfl).elim
  | comp => exact (tag_ne' eh rfl).elim
  | precNil => exact (tag_ne' eh rfl).elim
  | prec0 => exact (tag_ne' eh rfl).elim
  | precS => exact (tag_ne' eh rfl).elim
  | mu => exact (tag_ne' eh rfl).elim

theorem inv_succ {h a v} (d : Ev h a v) (eh : h = .succ) : v = nth a 0 + 1 := by
  cases d with
  | succ => rfl
  | zero => exact (tag_ne' eh rfl).elim
  | proj => exact (tag_ne' eh rfl).elim
  | comp => exact (tag_ne' eh rfl).elim
  | precNil => exact (tag_ne' eh rfl).elim
  | prec0 => exact (tag_ne' eh rfl).elim
  | precS => exact (tag_ne' eh rfl).elim
  | mu => exact (tag_ne' eh rfl).elim

def projIdx : MR → Nat
  | .zero => 0
  | .succ => 0
  | .proj i => i
  | .comp _ _ => 0
  | .prec _ _ => 0
  | .mu _ => 0

theorem inv_proj {h a v i} (d : Ev h a v) (eh : h = .proj i) : v = nth a i := by
  cases d with
  | proj j => exact congrArg (nth a) (congrArg projIdx eh)
  | zero => exact (tag_ne' eh rfl).elim
  | succ => exact (tag_ne' eh rfl).elim
  | comp => exact (tag_ne' eh rfl).elim
  | precNil => exact (tag_ne' eh rfl).elim
  | prec0 => exact (tag_ne' eh rfl).elim
  | precS => exact (tag_ne' eh rfl).elim
  | mu => exact (tag_ne' eh rfl).elim

theorem inv_comp {h a v f gs} (d : Ev h a v) (eh : h = .comp f gs) : ∃ bs, EvL gs a bs ∧ Ev f bs v := by
  cases d with
  | @comp f' gs' _ bs _ l e =>
    have hf : f' = f := congrArg getF eh
    have hg : gs' = gs := congrArg getGs eh
    subst hf hg
    exact ⟨bs, l, e⟩
  | zero => exact (tag_ne' eh rfl).elim
  | succ => exact (tag_ne' eh rfl).elim
  | proj => exact (tag_ne' eh rfl).elim
  | precNil => exact (tag_ne' eh rfl).elim
  | prec0 => exact (tag_ne' eh rfl).elim
  | precS => exact (tag_ne' eh rfl).elim
  | mu => exact (tag_ne' eh rfl).elim

theorem inv_mu {h a v f} (d : Ev h a v) (eh : h = .mu f) : MuS f a 0 v := by
  cases d with
  | @mu f' _ _ m =>
    have hf : f' = f := congrArg getF eh
    subst hf
    exact m
  | zero => exact (tag_ne' eh rfl).elim
  | succ => exact (tag_ne' eh rfl).elim
  | proj => exact (tag_ne' eh rfl).elim
  | comp => exact (tag_ne' eh rfl).elim
  | precNil => exact (tag_ne' eh rfl).elim
  | prec0 => exact (tag_ne' eh rfl).elim
  | precS => exact (tag_ne' eh rfl).elim

/-- prec-shaped derivations: the three cases, by the shape of the arguments -/
theorem inv_prec {h a v f g} (d : Ev h a v) (eh : h = .prec f g) :
    (a = [] ∧ Ev f [] v) ∨ (∃ rest, a = 0 :: rest ∧ Ev f rest v) ∨
    (∃ k rest v0, a = (k + 1) :: rest ∧ Ev (.prec f g) (k :: rest) v0 ∧ Ev g (k :: v0 :: rest) v) := by
  cases d with
  | @precNil f' g' _ e =>
    have hf : f' = f := congrArg getF eh
    subst hf
    exact Or.inl ⟨rfl, e⟩
  | @prec0 f' g' rest _ e =>
    have hf : f' = f := congrArg getF eh
    subst hf
    exact Or.inr (Or.inl ⟨rest, rfl, e⟩)
  | @precS f' g' k rest v0 _ p e =>
    have hf : f' = f := congrArg getF eh
    have hg : g' = g := congrArg getG eh
    subst hf hg
    exact Or.inr (Or.inr ⟨k, rest, v0, rfl, p, e⟩)
  | zero => exact (tag_ne' eh rfl).elim
  | succ => exact (tag_ne' eh rfl).elim
  | proj => exact (tag_ne' eh rfl).elim
  | comp => exact (tag_ne' eh rfl).elim
  | mu => exact (tag_ne' eh rfl).elim

theorem invL {gs a bs} (d : EvL gs a bs) :
    (gs = [] ∧ bs = []) ∨ (∃ b bs', bs = b :: bs' ∧ Ev (hdM gs) a b ∧ EvL (tlM gs) a bs') := by
  cases d with
  | nil => exact Or.inl ⟨rfl, rfl⟩
  | @cons g gs' _ b bs' e l => exact Or.inr ⟨b, bs', rfl, e, l⟩

mutual
theorem ev_det : {h : MR} → {a : List Nat} → {v v' : Nat} → Ev h a v → Ev h a v' → v = v'
  | _, _, _, _, .zero _, d => (inv_zero d rfl).symm
  | _, _, _, _, .succ _, d => (inv_succ d rfl).symm
  | _, _, _, _, .proj _ _, d => (inv_proj d rfl).symm
  | _, _, _, _, .comp l1 e1, d => match inv_comp d rfl with
    | ⟨_, l2, e2⟩ => by
      have hb := evL_det l1 l2
      subst hb
      exact ev_det e1 e2
  | _, _, _, _, .precNil e1, d => match inv_prec d rfl with
    | Or.inl ⟨_, e2⟩ => ev_det e1 e2
    | Or.inr (Or.inl ⟨_, ea, _⟩) => Bool.noConfusion (congrArg isNilB ea)
    | Or.inr (Or.inr ⟨_, _, _, ea, _, _⟩) => Bool.noConfusion (congrArg isNilB ea)
  | _, _, _, _, .prec0 (rest := rest) e1, d => match inv_prec d rfl with
    | Or.inl ⟨ea, _⟩ => Bool.noConfusion (congrArg isNilB ea)
    | Or.inr (Or.inl ⟨rest', ea, e2⟩) => by
      have hr : rest = rest' := congrArg tlN ea
      subst hr
      exact ev_det e1 e2
    | Or.inr (Or.inr ⟨_, _, _, ea, _, _⟩) => Nat.noConfusion (congrArg hdN ea)
  | _, _, _, _, .precS (k := k) (rest := rest) p1 e1, d => match inv_prec d rfl with
    | Or.inl ⟨ea, _⟩ => Bool.noConfusion (congrArg isNilB ea)
    | Or.inr (Or.inl ⟨_, ea, _⟩) => Nat.noConfusion (congrArg hdN ea)
    | Or.inr (Or.inr ⟨k', rest', _, ea, p2, e2⟩) => by
      have hk : k = k' := Nat.succ.inj (congrArg hdN ea)
      have hr : rest = rest' := congrArg tlN ea
      subst hk hr
      have hv := ev_det p1 p2
      subst hv
      exact ev_det e1 e2
  | _, _, _, _, .mu m1, d => muS_det m1 (inv_mu d rfl)
theorem evL_det : {gs : List MR} → {a bs bs' : List Nat} → EvL gs a bs → EvL gs a bs' → bs = bs'
  | _, _, _, _, .nil _, d => match invL d with
    | Or.inl ⟨_, e⟩ => e.symm
    | Or.inr ⟨_, _, _, _, _⟩ => by
      cases d with
      | nil => rfl
  | _, _, _, _, .cons e1 l1, d => match invL d with
    | Or.inl ⟨eg, _⟩ => Bool.noConfusion (congrArg isNilM eg)
    | Or.inr ⟨_, _, eb, e2, l2⟩ => by
      rw [eb, ev_det e1 e2, evL_det l1 l2]
theorem muS_det : {f : MR} → {a : List Nat} → {j n n' : Nat} → MuS f a j n → MuS f a j n' → n = n'
  | _, _, _, _, _, .stop e1, d => by
    cases d with
    | stop _ => rfl
    | next e2 _ => exact Nat.noConfusion (ev_det e1 e2)
  | _, _, _, _, _, .next e1 m1, d => by
    cases d with
    | stop e2 => exact Nat.noConfusion (ev_det e1 e2)
    | next _ m2 => exact muS_det m1 m2
end

/-! ## realizability: Church's thesis, and the failure of decidability of halting -/

/-- e realizes ∀n ∃m φ n m -/
def RealizesAE (e : MR) (φ : Nat → Nat → Prop) : Prop := ∀ n, ∃ m, Ev e [n] m ∧ φ n m

/-- Church's thesis: a realized ∀∃ statement has a program computing its witnesses -/
theorem church_thesis (φ : Nat → Nat → Prop) (e : MR) (h : RealizesAE e φ) :
    ∃ g : MR, ∀ n, ∃ m, Ev g [n] m ∧ φ n m := ⟨e, h⟩

/-- e realizes ∀n (P n ∨ ¬P n): it answers 1 for P and 0 for ¬P -/
def RealizesDec (e : MR) (P : Nat → Prop) : Prop :=
  ∀ n, (Ev e [n] 1 ∧ P n) ∨ (Ev e [n] 0 ∧ ¬ P n)

def Halts (n : Nat) : Prop := ∃ v, Ev (prog n) [n] v

/-- the diagonal program for a candidate decider d: μt. d(n) -/
def diag (d : MR) : MR := .mu (.comp d [.proj 1])

theorem diag_halts (d : MR) (n : Nat) (h : Ev d [n] 0) : Ev (diag d) [n] 0 :=
  .mu (.stop (.comp (.cons (.proj 1 [0, n]) (.nil _)) h))

theorem diag_mu (d : MR) (n : Nat) (h : Ev d [n] 1) : (f : MR) → (a : List Nat) → (j w : Nat) →
    MuS f a j w → f = .comp d [.proj 1] → a = [n] → False
  | _, _, _, _, .stop e, hf, ha => by
    subst hf ha
    match inv_comp e rfl with
    | ⟨bs, l, e'⟩ => match invL l with
      | Or.inl ⟨eg, _⟩ => exact Bool.noConfusion (congrArg isNilM eg)
      | Or.inr ⟨b, bs', eb, ep, l'⟩ =>
        have eb' : bs' = [] := evL_det l' (EvL.nil _)
        have hb : b = n := inv_proj ep rfl
        have e'' : Ev d [n] 0 := by rw [eb, eb', hb] at e'; exact e'
        exact Nat.noConfusion (ev_det h e'')
  | _, _, _, _, .next _ ms, hf, ha => diag_mu d n h _ _ _ _ ms hf ha

theorem diag_diverges (d : MR) (n : Nat) (h : Ev d [n] 1) : ∀ v, ¬ Ev (diag d) [n] v := by
  intro v hv
  cases hv with
  | mu m =>
    exact diag_mu d n h _ _ _ _ m rfl rfl

/-- ∀n (Halts n ∨ ¬Halts n) has no realizer -/
theorem no_halting_realizer : ¬ ∃ d : MR, RealizesDec d Halts := fun ⟨d, hd⟩ => by
  have hp : prog (enc (diag d)) = diag d := prog_enc (diag d)
  cases hd (enc (diag d)) with
  | inl h =>
    match h.2 with
    | ⟨v, hv⟩ =>
      rw [hp] at hv
      exact diag_diverges d _ h.1 v hv
  | inr h =>
    exact h.2 ⟨0, by rw [hp]; exact diag_halts d _ h.1⟩

end K1

end Found

#print axioms Found.K1.unpS_pr
#print axioms Found.K1.pr_ge
#print axioms Found.K1.dec_enc
#print axioms Found.K1.prog_enc
#print axioms Found.K1.ev_det
#print axioms Found.K1.church_thesis
#print axioms Found.K1.diag_diverges
#print axioms Found.K1.no_halting_realizer

#print axioms: 8 theorems, no axioms.

85.133 The Church–Turing line

Every primitive recursive and every μ-recursive function is λ-definable on Church numerals, and conversely every two-counter machine is simulated by a μ-recursive program that returns its output at the first halting time, through Cantor pairing and a μ-search for the halting time. \(\mathrm {Ev}(h,\vec a,n)\Rightarrow \ulcorner h\urcorner \,\vec a\to _\beta ^* \underline n;\quad M\downarrow _t\Rightarrow \mathrm {Ev}(F_M,[x,y],r_0(t_{\min }))\).

found/RegToMu.lean

/-
  T207 (L1, Church–Turing line), part 4. found/RegToMu — register machines
  compute μ-recursive functions.
  Part A: primitive recursive terms (T81) embed into μ-recursive programs with
  the same values (emb_ev); a small library of primitive recursive functions
  with their values: constants, predecessor, truncated subtraction, case
  distinction, addition, triangular numbers, and Cantor pairing with its
  inverse.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.ChurchTuring3

namespace Found

namespace RM

open Rec CT3

mutual
def emb : PR → MR
  | .zero => .zero
  | .succ => .succ
  | .proj i => .proj i
  | .comp f gs => .comp (emb f) (embL gs)
  | .prec f g => .prec (emb f) (emb g)
def embL : List PR → List MR
  | [] => []
  | g :: gs => emb g :: embL gs
end

theorem prec_ev (f g : PR) (hf : ∀ a, Ev (emb f) a (eval f a)) (hg : ∀ a, Ev (emb g) a (eval g a))
    (rest : List Nat) : ∀ k, Ev (.prec (emb f) (emb g)) (k :: rest) (precIter (eval f) (eval g) k rest)
  | 0 => .prec0 (hf rest)
  | k + 1 => .precS (prec_ev f g hf hg rest k) (hg _)

mutual
theorem emb_ev : (f : PR) → (a : List Nat) → Ev (emb f) a (eval f a)
  | .zero, a => .zero a
  | .succ, a => .succ a
  | .proj i, a => .proj i a
  | .comp f gs, a => .comp (embL_ev gs a) (emb_ev f _)
  | .prec f _, [] => .precNil (emb_ev f [])
  | .prec f g, k :: rest => prec_ev f g (emb_ev f) (emb_ev g) rest k
theorem embL_ev : (gs : List PR) → (a : List Nat) → EvL (embL gs) a (evalList gs a)
  | [], a => .nil a
  | g :: gs, a => .cons (emb_ev g a) (embL_ev gs a)
end

/-! ## a library of primitive recursive functions -/

def cst : Nat → PR
  | 0 => .zero
  | c + 1 => .comp .succ [cst c]

theorem cst_eval (a : List Nat) : (c : Nat) → eval (cst c) a = c
  | 0 => rfl
  | c + 1 => congrArg (· + 1) (cst_eval a c)

/-- predecessor, at [n] -/
def predP : PR := .prec .zero (.proj 0)

theorem predP_eval : (n : Nat) → eval predP [n] = n - 1
  | 0 => rfl
  | _ + 1 => rfl

/-- truncated subtraction, at [y, x]: x - y -/
def subRev : PR := .prec (.proj 0) (.comp predP [.proj 1])

theorem subRev_eval (x : Nat) : (y : Nat) → eval subRev [y, x] = x - y
  | 0 => rfl
  | y + 1 => by
    show eval predP [precIter (eval (.proj 0)) (eval (.comp predP [.proj 1])) y [x]] = x - (y + 1)
    show eval predP [eval subRev [y, x]] = _
    rw [subRev_eval x y, predP_eval]
    rfl

/-- x - y, at [x, y] -/
def subP : PR := .comp subRev [.proj 1, .proj 0]

theorem subP_eval (x y : Nat) : eval subP [x, y] = x - y := subRev_eval x y

/-- case distinction, at [c, a, b]: a if c = 0, else b -/
def condP : PR := .prec (.proj 0) (.proj 3)

theorem condP_zero (a b : Nat) : eval condP [0, a, b] = a := rfl
theorem condP_succ (k a b : Nat) : eval condP [k + 1, a, b] = b := rfl

/-- addition, at [x, y] (T81) -/
theorem addP_eval (x y : Nat) : eval addPR [x, y] = x + y := add_correct y x

/-- triangular numbers, at [s]: T(0) = 0, T(s+1) = T(s) + s + 1 -/
def tri : Nat → Nat
  | 0 => 0
  | s + 1 => tri s + (s + 1)

def triP : PR := .prec .zero (.comp addPR [.proj 1, .comp .succ [.proj 0]])

theorem triP_eval : (s : Nat) → eval triP [s] = tri s
  | 0 => rfl
  | s + 1 => by
    show eval addPR [eval triP [s], s + 1] = tri s + (s + 1)
    rw [addP_eval, triP_eval s]

/-! ## Cantor pairing ⟨a, b⟩ = T(a+b) + b and its inverse -/

def leb (x y : Nat) : Nat := match x - y with
  | 0 => 1
  | _ + 1 => 0

/-- 1 if x ≤ y, else 0; at [x, y] -/
def leP : PR := .comp condP [subP, cst 1, cst 0]

theorem leP_eval (x y : Nat) : eval leP [x, y] = leb x y := by
  show eval condP [eval subP [x, y], eval (cst 1) [x, y], eval (cst 0) [x, y]] = leb x y
  rw [subP_eval, cst_eval, cst_eval]
  unfold leb
  cases x - y with
  | zero => rfl
  | succ _ => rfl

theorem sub_ne_zero : (x y : Nat) → y < x → x - y ≠ 0
  | 0, _, h => absurd h (Nat.not_lt_zero _)
  | x + 1, 0, _ => fun e => Nat.noConfusion e
  | x + 1, y + 1, h => by
    rw [Nat.succ_sub_succ]
    exact sub_ne_zero x y (Nat.lt_of_succ_lt_succ h)

theorem leb_lt {x y : Nat} (h : y < x) : leb x y = 0 := by
  unfold leb
  have := sub_ne_zero x y h
  cases e : x - y with
  | zero => exact absurd e this
  | succ _ => rfl

theorem leb_self (x : Nat) : leb x x = 1 := by
  unfold leb
  rw [Nat.sub_self]

def sfun : Nat → Nat
  | 0 => 0
  | z + 1 => sfun z + leb (tri (sfun z + 1)) (z + 1)

theorem tri_succ (s : Nat) : tri (s + 1) = tri s + (s + 1) := rfl

theorem sfun_inv : (z : Nat) → tri (sfun z) ≤ z ∧ z < tri (sfun z + 1)
  | 0 => ⟨Nat.le_refl 0, Nat.lt_succ_self 0⟩
  | z + 1 => by
    have ih := sfun_inv z
    show tri (sfun z + leb (tri (sfun z + 1)) (z + 1)) ≤ z + 1 ∧
      z + 1 < tri (sfun z + leb (tri (sfun z + 1)) (z + 1) + 1)
    cases Nat.lt_or_ge (z + 1) (tri (sfun z + 1)) with
    | inl hlt =>
      rw [leb_lt hlt]
      exact ⟨Nat.le_succ_of_le ih.1, hlt⟩
    | inr hge =>
      have heq : tri (sfun z + 1) = z + 1 := Nat.le_antisymm hge (Nat.succ_le_of_lt ih.2)
      rw [heq, leb_self]
      refine ⟨Nat.le_of_eq heq, ?_⟩
      rw [tri_succ, heq]
      exact Nat.lt_add_of_pos_right (Nat.succ_pos _)

theorem tri_mono : {a b : Nat} → a ≤ b → tri a ≤ tri b
  | _, _, .refl => Nat.le_refl _
  | _, _, .step h => Nat.le_trans (tri_mono h) (Nat.le_add_right _ _)

theorem tri_unique {s s' z : Nat} (h : tri s ≤ z ∧ z < tri (s + 1)) (h' : tri s' ≤ z ∧ z < tri (s' + 1)) :
    s = s' := by
  cases Nat.lt_or_ge s s' with
  | inl hl => exact absurd (Nat.lt_of_lt_of_le h.2 (Nat.le_trans (tri_mono hl) h'.1)) (Nat.lt_irrefl _)
  | inr hg =>
    cases Nat.lt_or_ge s' s with
    | inl hl => exact absurd (Nat.lt_of_lt_of_le h'.2 (Nat.le_trans (tri_mono hl) h.1)) (Nat.lt_irrefl _)
    | inr hg' => exact Nat.le_antisymm hg' hg

def pair (a b : Nat) : Nat := tri (a + b) + b

theorem sfun_pair (a b : Nat) : sfun (pair a b) = a + b :=
  tri_unique (sfun_inv _) ⟨Nat.le_add_right _ _, by
    show tri (a + b) + b < tri (a + b) + (a + b + 1)
    exact Nat.add_lt_add_left (Nat.lt_succ_of_le (Nat.le_add_left b a)) _⟩

theorem add_sub_left' : (x y : Nat) → (x + y) - x = y
  | 0, y => by rw [Nat.zero_add]; rfl
  | x + 1, y => by rw [Nat.succ_add, Nat.succ_sub_succ]; exact add_sub_left' x y

theorem add_sub_right' (a : Nat) : (b : Nat) → (a + b) - b = a
  | 0 => rfl
  | b + 1 => by rw [Nat.add_succ, Nat.succ_sub_succ]; exact add_sub_right' a b

def sndU (z : Nat) : Nat := z - tri (sfun z)
def fstU (z : Nat) : Nat := sfun z - sndU z

theorem sndU_pair (a b : Nat) : sndU (pair a b) = b := by
  unfold sndU
  rw [sfun_pair]
  exact add_sub_left' _ _

theorem fstU_pair (a b : Nat) : fstU (pair a b) = a := by
  unfold fstU
  rw [sndU_pair, sfun_pair]
  exact add_sub_right' a b

/-! primitive recursive versions -/

def sP : PR := .prec .zero (.comp addPR [.proj 1, .comp leP [.comp triP [.comp .succ [.proj 1]], .comp .succ [.proj 0]]])

theorem sP_eval : (z : Nat) → eval sP [z] = sfun z
  | 0 => rfl
  | z + 1 => by
    show eval addPR [eval sP [z], eval leP [eval triP [eval sP [z] + 1], z + 1]] = _
    rw [sP_eval z, triP_eval, leP_eval, addP_eval]
    rfl

def sndP : PR := .comp subP [.proj 0, .comp triP [sP]]
def fstP : PR := .comp subP [sP, sndP]
def pairP : PR := .comp addPR [.comp triP [addPR], .proj 1]

theorem sndP_eval (z : Nat) : eval sndP [z] = sndU z := by
  show eval subP [z, eval triP [eval sP [z]]] = _
  rw [sP_eval, triP_eval, subP_eval]
  rfl

theorem fstP_eval (z : Nat) : eval fstP [z] = fstU z := by
  show eval subP [eval sP [z], eval sndP [z]] = _
  rw [sP_eval, sndP_eval, subP_eval]
  rfl

theorem pairP_eval (a b : Nat) : eval pairP [a, b] = pair a b := by
  show eval addPR [eval triP [eval addPR [a, b]], b] = _
  rw [addP_eval, triP_eval, addP_eval]
  rfl

/-! ## Part B: two-counter machines and their μ-recursive simulation -/

inductive Ins where
  | inc0 : Nat → Ins
  | inc1 : Nat → Ins
  | dec0 : Nat → Nat → Ins      -- if r0 = 0 goto a else (r0 -= 1, goto b)
  | dec1 : Nat → Nat → Ins
  | halt : Ins

structure Cf where
  pc : Nat
  r0 : Nat
  r1 : Nat

def fetch : List Ins → Nat → Ins
  | [], _ => .halt
  | i :: _, 0 => i
  | _ :: is, k + 1 => fetch is k

def exec : Ins → Cf → Cf
  | .inc0 g, c => ⟨g, c.r0 + 1, c.r1⟩
  | .inc1 g, c => ⟨g, c.r0, c.r1 + 1⟩
  | .dec0 a b, c => match c.r0 with
    | 0 => ⟨a, 0, c.r1⟩
    | k + 1 => ⟨b, k, c.r1⟩
  | .dec1 a b, c => match c.r1 with
    | 0 => ⟨a, c.r0, 0⟩
    | k + 1 => ⟨b, c.r0, k⟩
  | .halt, c => c

def step (prog : List Ins) (c : Cf) : Cf := exec (fetch prog c.pc) c

def run (prog : List Ins) (c : Cf) : Nat → Cf
  | 0 => c
  | t + 1 => step prog (run prog c t)

def haltNum : Ins → Nat
  | .halt => 0
  | .inc0 _ => 1
  | .inc1 _ => 1
  | .dec0 _ _ => 1
  | .dec1 _ _ => 1

def code (c : Cf) : Nat := pair c.pc (pair c.r0 c.r1)

def r0P : PR := .comp fstP [sndP]
def r1P : PR := .comp sndP [sndP]

theorem fst_code (c : Cf) : eval fstP [code c] = c.pc := by rw [fstP_eval]; exact fstU_pair _ _
theorem r0_code (c : Cf) : eval r0P [code c] = c.r0 := by
  show eval fstP [eval sndP [code c]] = _
  rw [sndP_eval]; unfold code; rw [sndU_pair, fstP_eval, fstU_pair]
theorem r1_code (c : Cf) : eval r1P [code c] = c.r1 := by
  show eval sndP [eval sndP [code c]] = _
  rw [sndP_eval, sndP_eval]; unfold code; rw [sndU_pair, sndU_pair]

def codeP (pcT r0T r1T : PR) : PR := .comp pairP [pcT, .comp pairP [r0T, r1T]]

theorem codeP_eval (pcT r0T r1T : PR) (a : List Nat) :
    eval (codeP pcT r0T r1T) a = code ⟨eval pcT a, eval r0T a, eval r1T a⟩ := by
  show eval pairP [eval pcT a, eval pairP [eval r0T a, eval r1T a]] = _
  rw [pairP_eval, pairP_eval]
  rfl

def effect : Ins → PR
  | .inc0 g => codeP (cst g) (.comp .succ [r0P]) r1P
  | .inc1 g => codeP (cst g) r0P (.comp .succ [r1P])
  | .dec0 a b => .comp condP [r0P, codeP (cst a) r0P r1P, codeP (cst b) (.comp predP [r0P]) r1P]
  | .dec1 a b => .comp condP [r1P, codeP (cst a) r0P r1P, codeP (cst b) r0P (.comp predP [r1P])]
  | .halt => .proj 0

theorem effect_eval (i : Ins) (c : Cf) : eval (effect i) [code c] = code (exec i c) := by
  cases i with
  | inc0 g =>
    show eval (codeP (cst g) (.comp .succ [r0P]) r1P) [code c] = _
    rw [codeP_eval, cst_eval]
    show code ⟨g, eval r0P [code c] + 1, eval r1P [code c]⟩ = _
    rw [r0_code, r1_code]; rfl
  | inc1 g =>
    show eval (codeP (cst g) r0P (.comp .succ [r1P])) [code c] = _
    rw [codeP_eval, cst_eval]
    show code ⟨g, eval r0P [code c], eval r1P [code c] + 1⟩ = _
    rw [r0_code, r1_code]; rfl
  | dec0 a b =>
    show eval condP [eval r0P [code c], eval (codeP (cst a) r0P r1P) [code c],
      eval (codeP (cst b) (.comp predP [r0P]) r1P) [code c]] = _
    rw [codeP_eval, codeP_eval, cst_eval, cst_eval]
    show eval condP [eval r0P [code c], code ⟨a, eval r0P [code c], eval r1P [code c]⟩,
      code ⟨b, eval predP [eval r0P [code c]], eval r1P [code c]⟩] = _
    rw [r0_code, r1_code, predP_eval]
    cases c with
    | mk pc r0 r1 => cases r0 with
      | zero => rfl
      | succ k => rfl
  | dec1 a b =>
    show eval condP [eval r1P [code c], eval (codeP (cst a) r0P r1P) [code c],
      eval (codeP (cst b) r0P (.comp predP [r1P])) [code c]] = _
    rw [codeP_eval, codeP_eval, cst_eval, cst_eval]
    show eval condP [eval r1P [code c], code ⟨a, eval r0P [code c], eval r1P [code c]⟩,
      code ⟨b, eval r0P [code c], eval predP [eval r1P [code c]]⟩] = _
    rw [r0_code, r1_code, predP_eval]
    cases c with
    | mk pc r0 r1 => cases r1 with
      | zero => rfl
      | succ k => rfl
  | halt => rfl

/-- dispatch on the program counter -/
def table : List Ins → PR → PR
  | [], _ => .proj 0
  | i :: is, pcT => .comp condP [pcT, effect i, table is (.comp predP [pcT])]

theorem table_eval (c : Cf) : (is : List Ins) → (pcT : PR) → (n : Nat) → eval pcT [code c] = n →
    eval (table is pcT) [code c] = code (exec (fetch is n) c)
  | [], _, _, _ => rfl
  | i :: is, pcT, n, h => by
    show eval condP [eval pcT [code c], eval (effect i) [code c], eval (table is (.comp predP [pcT])) [code c]] = _
    rw [h]
    cases n with
    | zero => rw [effect_eval]; rfl
    | succ k =>
      have hk : eval (.comp predP [pcT]) [code c] = k := by
        show eval predP [eval pcT [code c]] = k
        rw [h, predP_eval]; rfl
      rw [table_eval c is _ k hk]
      rfl

def stepP (prog : List Ins) : PR := table prog fstP

theorem stepP_eval (prog : List Ins) (c : Cf) : eval (stepP prog) [code c] = code (step prog c) :=
  table_eval c prog fstP c.pc (fst_code c)

def htable : List Ins → PR → PR
  | [], _ => cst 0
  | i :: is, pcT => .comp condP [pcT, cst (haltNum i), htable is (.comp predP [pcT])]

theorem htable_eval (c : Cf) : (is : List Ins) → (pcT : PR) → (n : Nat) → eval pcT [code c] = n →
    eval (htable is pcT) [code c] = haltNum (fetch is n)
  | [], _, _, _ => rfl
  | i :: is, pcT, n, h => by
    show eval condP [eval pcT [code c], eval (cst (haltNum i)) [code c], eval (htable is (.comp predP [pcT])) [code c]] = _
    rw [h, cst_eval]
    cases n with
    | zero => rfl
    | succ k =>
      have hk : eval (.comp predP [pcT]) [code c] = k := by
        show eval predP [eval pcT [code c]] = k
        rw [h, predP_eval]; rfl
      rw [htable_eval c is _ k hk]
      rfl

def haltP (prog : List Ins) : PR := htable prog fstP

theorem haltP_eval (prog : List Ins) (c : Cf) : eval (haltP prog) [code c] = haltNum (fetch prog c.pc) :=
  htable_eval c prog fstP c.pc (fst_code c)

/-- run, at [t, x, y], from the start configuration ⟨0, x, y⟩ -/
def runP (prog : List Ins) : PR :=
  .prec (codeP (cst 0) (.proj 0) (.proj 1)) (.comp (stepP prog) [.proj 1])

theorem runP_eval (prog : List Ins) (x y : Nat) : (t : Nat) →
    eval (runP prog) [t, x, y] = code (run prog ⟨0, x, y⟩ t)
  | 0 => by
    show eval (codeP (cst 0) (.proj 0) (.proj 1)) [x, y] = _
    rw [codeP_eval, cst_eval]; rfl
  | t + 1 => by
    show eval (stepP prog) [eval (runP prog) [t, x, y]] = _
    rw [runP_eval prog x y t, stepP_eval]
    rfl

/-! ## Part C: the halting time by μ, and the main theorem -/

def hv (prog : List Ins) (x y t : Nat) : Nat := haltNum (fetch prog (run prog ⟨0, x, y⟩ t).pc)

def fM (prog : List Ins) : MR := .comp (emb (haltP prog)) [emb (runP prog)]

theorem ev_f (prog : List Ins) (x y t : Nat) : Ev (fM prog) (t :: [x, y]) (hv prog x y t) := by
  have e : eval (haltP prog) [eval (runP prog) [t, x, y]] = hv prog x y t := by
    rw [runP_eval, haltP_eval]; rfl
  rw [← e]
  exact .comp (.cons (emb_ev (runP prog) [t, x, y]) (.nil _)) (emb_ev (haltP prog) _)

def lsearch (prog : List Ins) (x y : Nat) (j : Nat) : Nat → Nat
  | 0 => j
  | k + 1 => match hv prog x y j with
    | 0 => j
    | _ + 1 => lsearch prog x y (j + 1) k

theorem search_spec (prog : List Ins) (x y : Nat) : (k j : Nat) → hv prog x y (j + k) = 0 →
    MuS (fM prog) [x, y] j (lsearch prog x y j k) ∧ hv prog x y (lsearch prog x y j k) = 0 ∧
      ∀ i, j ≤ i → i < lsearch prog x y j k → hv prog x y i ≠ 0
  | 0, j, h => by
    have h0 : hv prog x y j = 0 := h
    have ef := ev_f prog x y j
    rw [h0] at ef
    exact ⟨.stop ef, h0, fun i hi hl => absurd (Nat.lt_of_le_of_lt hi hl) (Nat.lt_irrefl _)⟩
  | k + 1, j, h => by
    have ef := ev_f prog x y j
    cases hj : hv prog x y j with
    | zero =>
      rw [hj] at ef
      show MuS (fM prog) [x, y] j (match hv prog x y j with | 0 => j | _ + 1 => lsearch prog x y (j + 1) k) ∧
        hv prog x y (match hv prog x y j with | 0 => j | _ + 1 => lsearch prog x y (j + 1) k) = 0 ∧
        ∀ i, j ≤ i → i < (match hv prog x y j with | 0 => j | _ + 1 => lsearch prog x y (j + 1) k) → hv prog x y i ≠ 0
      rw [hj]
      exact ⟨.stop ef, hj, fun i hi hl => absurd (Nat.lt_of_le_of_lt hi hl) (Nat.lt_irrefl _)⟩
    | succ n =>
      rw [hj] at ef
      have h' : hv prog x y (j + 1 + k) = 0 := by rw [Nat.add_right_comm, Nat.add_assoc]; exact h
      have ih := search_spec prog x y k (j + 1) h'
      show MuS (fM prog) [x, y] j (match hv prog x y j with | 0 => j | _ + 1 => lsearch prog x y (j + 1) k) ∧
        hv prog x y (match hv prog x y j with | 0 => j | _ + 1 => lsearch prog x y (j + 1) k) = 0 ∧
        ∀ i, j ≤ i → i < (match hv prog x y j with | 0 => j | _ + 1 => lsearch prog x y (j + 1) k) → hv prog x y i ≠ 0
      rw [hj]
      refine ⟨.next ef ih.1, ih.2.1, fun i hi hl => ?_⟩
      cases Nat.lt_or_ge i (j + 1) with
      | inl hlt =>
        have hij : i = j := Nat.le_antisymm (Nat.le_of_lt_succ hlt) hi
        rw [hij, hj]
        exact fun e => Nat.noConfusion e
      | inr hge => exact ih.2.2 i hge hl

/-- the μ-recursive program computing a two-counter machine's output -/
def F (prog : List Ins) : MR :=
  .comp (emb r0P) [.comp (emb (runP prog)) [.mu (fM prog), .proj 0, .proj 1]]

/-- register machines → μ-recursive: if the machine halts from ⟨0, x, y⟩ at some
  time t0, then F prog evaluates on [x, y] to r0 at the first halting time -/
theorem reg_to_mu (prog : List Ins) (x y t0 : Nat) (h : hv prog x y t0 = 0) :
    Ev (F prog) [x, y] (run prog ⟨0, x, y⟩ (lsearch prog x y 0 t0)).r0 ∧
      hv prog x y (lsearch prog x y 0 t0) = 0 ∧ ∀ i, i < lsearch prog x y 0 t0 → hv prog x y i ≠ 0 := by
  have hs := search_spec prog x y t0 0 (by rw [Nat.zero_add]; exact h)
  refine ⟨?_, hs.2.1, fun i hl => hs.2.2 i (Nat.zero_le i) hl⟩
  generalize lsearch prog x y 0 t0 = m at hs
  have er : eval r0P [eval (runP prog) [m, x, y]] = (run prog ⟨0, x, y⟩ m).r0 := by
    rw [runP_eval, r0_code]
  rw [← er]
  exact .comp (.cons (.comp (.cons (.mu hs.1) (.cons (.proj 0 [x, y]) (.cons (.proj 1 [x, y]) (.nil _))))
    (emb_ev (runP prog) [m, x, y])) (.nil _)) (emb_ev r0P _)

end RM

end Found

#print axioms Found.RM.emb_ev
#print axioms Found.RM.subP_eval
#print axioms Found.RM.triP_eval
#print axioms Found.RM.fstU_pair
#print axioms Found.RM.sndU_pair
#print axioms Found.RM.fstP_eval
#print axioms Found.RM.pairP_eval
#print axioms Found.RM.effect_eval
#print axioms Found.RM.stepP_eval
#print axioms Found.RM.runP_eval
#print axioms Found.RM.search_spec
#print axioms Found.RM.reg_to_mu

#print axioms: 12 theorems, no axioms.

85.134 Ordinal analysis of Peano arithmetic

Cantor normal forms below \(\varepsilon _0\) are well-founded; Peano arithmetic embeds into infinitary arithmetic with heights \(\omega \cdot d\), cut elimination brings every derivation to cut-free height below \(\varepsilon _0\), and so \(0=1\) is not provable. \(\mathrm {PA}\vdash \Gamma \Rightarrow \ \vdash ^{\omega _r(\omega \cdot d)}_0\Gamma ;\quad \mathrm {PA}\nvdash 0=1\).

found/PAEmbed.lean

/-
  T124 (b), part 4. found/PAEmbed — embedding Peano arithmetic into Z∞
  (found/Zinf), hence PA is consistent, and every PA-provable sequent has
  cut-free Z∞-derivations of height below ε₀.
  Part A: substitution on terms and formulas, and transport of Z∞
  derivations along items related by a meaning-preserving substitution.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Zinf

namespace Found

namespace PAE

open _root_.Found.Ord _root_.Found.Zinf

def subT (σ : Nat → Tm) : Tm → Tm
  | .var i => σ i
  | .zero => .zero
  | .succ t => .succ (subT σ t)
  | .add s t => .add (subT σ s) (subT σ t)
  | .mul s t => .mul (subT σ s) (subT σ t)

def shiftT (t : Tm) : Tm := subT (fun v => .var (v + 1)) t

def upS (σ : Nat → Tm) : Nat → Tm
  | 0 => .var 0
  | v + 1 => shiftT (σ v)

def subF (σ : Nat → Tm) : Fm → Fm
  | .eq s t => .eq (subT σ s) (subT σ t)
  | .ne s t => .ne (subT σ s) (subT σ t)
  | .and a b => .and (subF σ a) (subF σ b)
  | .or a b => .or (subF σ a) (subF σ b)
  | .all a => .all (subF (upS σ) a)
  | .ex a => .ex (subF (upS σ) a)

theorem ev_subT (ρ' ρ : Nat → Nat) (σ : Nat → Tm) (h : ∀ v, ev ρ' (σ v) = ρ v) :
    (t : Tm) → ev ρ' (subT σ t) = ev ρ t
  | .var i => h i
  | .zero => rfl
  | .succ t => congrArg (· + 1) (ev_subT ρ' ρ σ h t)
  | .add s t => by show ev ρ' (subT σ s) + ev ρ' (subT σ t) = _; rw [ev_subT ρ' ρ σ h s, ev_subT ρ' ρ σ h t]; rfl
  | .mul s t => by show ev ρ' (subT σ s) * ev ρ' (subT σ t) = _; rw [ev_subT ρ' ρ σ h s, ev_subT ρ' ρ σ h t]; rfl

theorem ev_shift (n : Nat) (ρ : Nat → Nat) (t : Tm) : ev (cons n ρ) (shiftT t) = ev ρ t :=
  ev_subT (cons n ρ) ρ _ (fun _ => rfl) t

theorem ev_upS (ρ' ρ : Nat → Nat) (σ : Nat → Tm) (h : ∀ v, ev ρ' (σ v) = ρ v) (n : Nat) :
    ∀ v, ev (cons n ρ') (upS σ v) = cons n ρ v
  | 0 => rfl
  | v + 1 => (ev_shift n ρ' (σ v)).trans (h v)

theorem trueAt_sub (σ : Nat → Tm) : (A : Fm) → (ρ' ρ : Nat → Nat) → (∀ v, ev ρ' (σ v) = ρ v) →
    (TrueAt (subF σ A) ρ' ↔ TrueAt A ρ)
  | .eq s t, ρ', ρ, h => by
    show ev ρ' (subT σ s) = ev ρ' (subT σ t) ↔ ev ρ s = ev ρ t
    rw [ev_subT ρ' ρ σ h s, ev_subT ρ' ρ σ h t]
  | .ne s t, ρ', ρ, h => by
    show ev ρ' (subT σ s) ≠ ev ρ' (subT σ t) ↔ ev ρ s ≠ ev ρ t
    rw [ev_subT ρ' ρ σ h s, ev_subT ρ' ρ σ h t]
  | .and _ _, _, _, _ => Iff.rfl
  | .or _ _, _, _, _ => Iff.rfl
  | .all _, _, _, _ => Iff.rfl
  | .ex _, _, _, _ => Iff.rfl

theorem subT_var : (t : Tm) → subT Tm.var t = t
  | .var _ => rfl
  | .zero => rfl
  | .succ t => congrArg Tm.succ (subT_var t)
  | .add s t => by show Tm.add _ _ = _; rw [subT_var s, subT_var t]
  | .mul s t => by show Tm.mul _ _ = _; rw [subT_var s, subT_var t]

theorem subT_ext {σ τ : Nat → Tm} (h : ∀ v, σ v = τ v) : (t : Tm) → subT σ t = subT τ t
  | .var i => h i
  | .zero => rfl
  | .succ t => congrArg Tm.succ (subT_ext h t)
  | .add s t => by show Tm.add _ _ = _; rw [subT_ext h s, subT_ext h t]; rfl
  | .mul s t => by show Tm.mul _ _ = _; rw [subT_ext h s, subT_ext h t]; rfl

theorem upS_ext {σ τ : Nat → Tm} (h : ∀ v, σ v = τ v) : ∀ v, upS σ v = upS τ v
  | 0 => rfl
  | v + 1 => congrArg shiftT (h v)

theorem subF_ext : (A : Fm) → {σ τ : Nat → Tm} → (∀ v, σ v = τ v) → subF σ A = subF τ A
  | .eq s t, _, _, h => by show Fm.eq _ _ = _; rw [subT_ext h s, subT_ext h t]; rfl
  | .ne s t, _, _, h => by show Fm.ne _ _ = _; rw [subT_ext h s, subT_ext h t]; rfl
  | .and a b, _, _, h => by show Fm.and _ _ = _; rw [subF_ext a h, subF_ext b h]; rfl
  | .or a b, _, _, h => by show Fm.or _ _ = _; rw [subF_ext a h, subF_ext b h]; rfl
  | .all a, _, _, h => congrArg Fm.all (subF_ext a (upS_ext h))
  | .ex a, _, _, h => congrArg Fm.ex (subF_ext a (upS_ext h))

theorem upS_var : ∀ v, upS Tm.var v = Tm.var v
  | 0 => rfl
  | _ + 1 => rfl

theorem subF_var : (A : Fm) → subF Tm.var A = A
  | .eq s t => by show Fm.eq _ _ = _; rw [subT_var s, subT_var t]
  | .ne s t => by show Fm.ne _ _ = _; rw [subT_var s, subT_var t]
  | .and a b => by show Fm.and _ _ = _; rw [subF_var a, subF_var b]
  | .or a b => by show Fm.or _ _ = _; rw [subF_var a, subF_var b]
  | .all a => congrArg Fm.all ((subF_ext a upS_var).trans (subF_var a))
  | .ex a => congrArg Fm.ex ((subF_ext a upS_var).trans (subF_var a))

/-- two items have the same meaning: same shape, equivalent atoms -/
def Eqv : Fm → (Nat → Nat) → Fm → (Nat → Nat) → Prop
  | .eq s t, ρ, .eq s' t', ρ' => (ev ρ s = ev ρ t ↔ ev ρ' s' = ev ρ' t')
  | .eq _ _, _, .ne _ _, _ => False
  | .eq _ _, _, .and _ _, _ => False
  | .eq _ _, _, .or _ _, _ => False
  | .eq _ _, _, .all _, _ => False
  | .eq _ _, _, .ex _, _ => False
  | .ne _ _, _, .eq _ _, _ => False
  | .ne s t, ρ, .ne s' t', ρ' => (ev ρ s = ev ρ t ↔ ev ρ' s' = ev ρ' t')
  | .ne _ _, _, .and _ _, _ => False
  | .ne _ _, _, .or _ _, _ => False
  | .ne _ _, _, .all _, _ => False
  | .ne _ _, _, .ex _, _ => False
  | .and _ _, _, .eq _ _, _ => False
  | .and _ _, _, .ne _ _, _ => False
  | .and a b, ρ, .and a' b', ρ' => Eqv a ρ a' ρ' ∧ Eqv b ρ b' ρ'
  | .and _ _, _, .or _ _, _ => False
  | .and _ _, _, .all _, _ => False
  | .and _ _, _, .ex _, _ => False
  | .or _ _, _, .eq _ _, _ => False
  | .or _ _, _, .ne _ _, _ => False
  | .or _ _, _, .and _ _, _ => False
  | .or a b, ρ, .or a' b', ρ' => Eqv a ρ a' ρ' ∧ Eqv b ρ b' ρ'
  | .or _ _, _, .all _, _ => False
  | .or _ _, _, .ex _, _ => False
  | .all _, _, .eq _ _, _ => False
  | .all _, _, .ne _ _, _ => False
  | .all _, _, .and _ _, _ => False
  | .all _, _, .or _ _, _ => False
  | .all a, ρ, .all a', ρ' => ∀ n, Eqv a (cons n ρ) a' (cons n ρ')
  | .all _, _, .ex _, _ => False
  | .ex _, _, .eq _ _, _ => False
  | .ex _, _, .ne _ _, _ => False
  | .ex _, _, .and _ _, _ => False
  | .ex _, _, .or _ _, _ => False
  | .ex _, _, .all _, _ => False
  | .ex a, ρ, .ex a', ρ' => ∀ n, Eqv a (cons n ρ) a' (cons n ρ')

theorem eqv_refl : (A : Fm) → (ρ : Nat → Nat) → Eqv A ρ A ρ
  | .eq _ _, _ => Iff.rfl
  | .ne _ _, _ => Iff.rfl
  | .and a b, ρ => ⟨eqv_refl a ρ, eqv_refl b ρ⟩
  | .or a b, ρ => ⟨eqv_refl a ρ, eqv_refl b ρ⟩
  | .all a, ρ => fun n => eqv_refl a (cons n ρ)
  | .ex a, ρ => fun n => eqv_refl a (cons n ρ)

theorem eqv_symm : (A : Fm) → (ρ : Nat → Nat) → (A' : Fm) → (ρ' : Nat → Nat) → Eqv A ρ A' ρ' → Eqv A' ρ' A ρ
  | .eq _ _, _, .eq _ _, _, h => h.symm
  | .ne _ _, _, .ne _ _, _, h => h.symm
  | .and a b, ρ, .and a' b', ρ', h => ⟨eqv_symm a ρ a' ρ' h.1, eqv_symm b ρ b' ρ' h.2⟩
  | .or a b, ρ, .or a' b', ρ', h => ⟨eqv_symm a ρ a' ρ' h.1, eqv_symm b ρ b' ρ' h.2⟩
  | .all a, _, .all a', _, h => fun n => eqv_symm a _ a' _ (h n)
  | .ex a, _, .ex a', _, h => fun n => eqv_symm a _ a' _ (h n)
  | .eq _ _, _, .ne _ _, _, h => h.elim
  | .eq _ _, _, .and _ _, _, h => h.elim
  | .eq _ _, _, .or _ _, _, h => h.elim
  | .eq _ _, _, .all _, _, h => h.elim
  | .eq _ _, _, .ex _, _, h => h.elim
  | .ne _ _, _, .eq _ _, _, h => h.elim
  | .ne _ _, _, .and _ _, _, h => h.elim
  | .ne _ _, _, .or _ _, _, h => h.elim
  | .ne _ _, _, .all _, _, h => h.elim
  | .ne _ _, _, .ex _, _, h => h.elim
  | .and _ _, _, .eq _ _, _, h => h.elim
  | .and _ _, _, .ne _ _, _, h => h.elim
  | .and _ _, _, .or _ _, _, h => h.elim
  | .and _ _, _, .all _, _, h => h.elim
  | .and _ _, _, .ex _, _, h => h.elim
  | .or _ _, _, .eq _ _, _, h => h.elim
  | .or _ _, _, .ne _ _, _, h => h.elim
  | .or _ _, _, .and _ _, _, h => h.elim
  | .or _ _, _, .all _, _, h => h.elim
  | .or _ _, _, .ex _, _, h => h.elim
  | .all _, _, .eq _ _, _, h => h.elim
  | .all _, _, .ne _ _, _, h => h.elim
  | .all _, _, .and _ _, _, h => h.elim
  | .all _, _, .or _ _, _, h => h.elim
  | .all _, _, .ex _, _, h => h.elim
  | .ex _, _, .eq _ _, _, h => h.elim
  | .ex _, _, .ne _ _, _, h => h.elim
  | .ex _, _, .and _ _, _, h => h.elim
  | .ex _, _, .or _ _, _, h => h.elim
  | .ex _, _, .all _, _, h => h.elim

theorem eqv_sub (σ : Nat → Tm) : (A : Fm) → (ρ' ρ : Nat → Nat) → (∀ v, ev ρ' (σ v) = ρ v) →
    Eqv (subF σ A) ρ' A ρ
  | .eq s t, ρ', ρ, h => by
    show ev ρ' (subT σ s) = ev ρ' (subT σ t) ↔ ev ρ s = ev ρ t
    rw [ev_subT ρ' ρ σ h s, ev_subT ρ' ρ σ h t]
  | .ne s t, ρ', ρ, h => by
    show ev ρ' (subT σ s) = ev ρ' (subT σ t) ↔ ev ρ s = ev ρ t
    rw [ev_subT ρ' ρ σ h s, ev_subT ρ' ρ σ h t]
  | .and a b, ρ', ρ, h => ⟨eqv_sub σ a ρ' ρ h, eqv_sub σ b ρ' ρ h⟩
  | .or a b, ρ', ρ, h => ⟨eqv_sub σ a ρ' ρ h, eqv_sub σ b ρ' ρ h⟩
  | .all a, ρ', ρ, h => fun n => eqv_sub (upS σ) a (cons n ρ') (cons n ρ) (ev_upS ρ' ρ σ h n)
  | .ex a, ρ', ρ, h => fun n => eqv_sub (upS σ) a (cons n ρ') (cons n ρ) (ev_upS ρ' ρ σ h n)

theorem eqv_dual : (A : Fm) → (ρ : Nat → Nat) → (A' : Fm) → (ρ' : Nat → Nat) → Eqv A ρ A' ρ' →
    Eqv (dual A) ρ (dual A') ρ'
  | .eq _ _, _, .eq _ _, _, h => h
  | .ne _ _, _, .ne _ _, _, h => h
  | .and a b, ρ, .and a' b', ρ', h => ⟨eqv_dual a ρ a' ρ' h.1, eqv_dual b ρ b' ρ' h.2⟩
  | .or a b, ρ, .or a' b', ρ', h => ⟨eqv_dual a ρ a' ρ' h.1, eqv_dual b ρ b' ρ' h.2⟩
  | .all a, _, .all a', _, h => fun n => eqv_dual a _ a' _ (h n)
  | .ex a, _, .ex a', _, h => fun n => eqv_dual a _ a' _ (h n)
  | .eq _ _, _, .ne _ _, _, h => h.elim
  | .eq _ _, _, .and _ _, _, h => h.elim
  | .eq _ _, _, .or _ _, _, h => h.elim
  | .eq _ _, _, .all _, _, h => h.elim
  | .eq _ _, _, .ex _, _, h => h.elim
  | .ne _ _, _, .eq _ _, _, h => h.elim
  | .ne _ _, _, .and _ _, _, h => h.elim
  | .ne _ _, _, .or _ _, _, h => h.elim
  | .ne _ _, _, .all _, _, h => h.elim
  | .ne _ _, _, .ex _, _, h => h.elim
  | .and _ _, _, .eq _ _, _, h => h.elim
  | .and _ _, _, .ne _ _, _, h => h.elim
  | .and _ _, _, .or _ _, _, h => h.elim
  | .and _ _, _, .all _, _, h => h.elim
  | .and _ _, _, .ex _, _, h => h.elim
  | .or _ _, _, .eq _ _, _, h => h.elim
  | .or _ _, _, .ne _ _, _, h => h.elim
  | .or _ _, _, .and _ _, _, h => h.elim
  | .or _ _, _, .all _, _, h => h.elim
  | .or _ _, _, .ex _, _, h => h.elim
  | .all _, _, .eq _ _, _, h => h.elim
  | .all _, _, .ne _ _, _, h => h.elim
  | .all _, _, .and _ _, _, h => h.elim
  | .all _, _, .or _ _, _, h => h.elim
  | .all _, _, .ex _, _, h => h.elim
  | .ex _, _, .eq _ _, _, h => h.elim
  | .ex _, _, .ne _ _, _, h => h.elim
  | .ex _, _, .and _ _, _, h => h.elim
  | .ex _, _, .or _ _, _, h => h.elim
  | .ex _, _, .all _, _, h => h.elim

theorem eqv_true : (A : Fm) → (ρ : Nat → Nat) → (A' : Fm) → (ρ' : Nat → Nat) → Eqv A ρ A' ρ' →
    TrueAt A ρ → TrueAt A' ρ'
  | .eq _ _, _, .eq _ _, _, h, t => h.mp t
  | .ne _ _, _, .ne _ _, _, h, t => fun e => t (h.mpr e)
  | .and _ _, _, _, _, _, t => t.elim
  | .or _ _, _, _, _, _, t => t.elim
  | .all _, _, _, _, _, t => t.elim
  | .ex _, _, _, _, _, t => t.elim
  | .eq _ _, _, .ne _ _, _, h, _ => h.elim
  | .eq _ _, _, .and _ _, _, h, _ => h.elim
  | .eq _ _, _, .or _ _, _, h, _ => h.elim
  | .eq _ _, _, .all _, _, h, _ => h.elim
  | .eq _ _, _, .ex _, _, h, _ => h.elim
  | .ne _ _, _, .eq _ _, _, h, _ => h.elim
  | .ne _ _, _, .and _ _, _, h, _ => h.elim
  | .ne _ _, _, .or _ _, _, h, _ => h.elim
  | .ne _ _, _, .all _, _, h, _ => h.elim
  | .ne _ _, _, .ex _, _, h, _ => h.elim

def Covers (Γ Γ' : List Item) : Prop := ∀ x, x ∈ Γ → ∃ x', x' ∈ Γ' ∧ Eqv x.1 x.2 x'.1 x'.2

theorem covers_cons {Γ Γ' : List Item} (h : Covers Γ Γ') (x x' : Item) (he : Eqv x.1 x.2 x'.1 x'.2) :
    Covers (x :: Γ) (x' :: Γ') := fun y m =>
  (mem_cons' m).elim (fun e => ⟨x', .head _, by rw [e]; exact he⟩) (fun m' => match h y m' with
    | ⟨y', hy', hr'⟩ => ⟨y', .tail _ hy', hr'⟩)

theorem mem_of_eq {x : Item} {Γ : List Item} (A : Fm) (ρ : Nat → Nat) (hx : x ∈ Γ) (e : x.1 = A) (e2 : x.2 = ρ) :
    (A, ρ) ∈ Γ := by
  have : x = (A, ρ) := by
    cases x with
    | mk f g => cases e; cases e2; rfl
  rw [← this]; exact hx
theorem eqv_and_inv (A B : Fm) (ρ ρ' : Nat → Nat) : (F : Fm) → Eqv (.and A B) ρ F ρ' → ∃ A' B', F = .and A' B' ∧ Eqv A ρ A' ρ' ∧ Eqv B ρ B' ρ'
  | .eq _ _, h => h.elim
  | .ne _ _, h => h.elim
  | .and A' B', h => ⟨A', B', rfl, h.1, h.2⟩
  | .or _ _, h => h.elim
  | .all _, h => h.elim
  | .ex _, h => h.elim

theorem eqv_or_inv (A B : Fm) (ρ ρ' : Nat → Nat) : (F : Fm) → Eqv (.or A B) ρ F ρ' → ∃ A' B', F = .or A' B' ∧ Eqv A ρ A' ρ' ∧ Eqv B ρ B' ρ'
  | .eq _ _, h => h.elim
  | .ne _ _, h => h.elim
  | .and _ _, h => h.elim
  | .or A' B', h => ⟨A', B', rfl, h.1, h.2⟩
  | .all _, h => h.elim
  | .ex _, h => h.elim

theorem eqv_all_inv (A : Fm) (ρ ρ' : Nat → Nat) : (F : Fm) → Eqv (.all A) ρ F ρ' → ∃ A', F = .all A' ∧ ∀ n, Eqv A (cons n ρ) A' (cons n ρ')
  | .eq _ _, h => h.elim
  | .ne _ _, h => h.elim
  | .and _ _, h => h.elim
  | .or _ _, h => h.elim
  | .all A', h => ⟨A', rfl, h⟩
  | .ex _, h => h.elim

theorem eqv_ex_inv (A : Fm) (ρ ρ' : Nat → Nat) : (F : Fm) → Eqv (.ex A) ρ F ρ' → ∃ A', F = .ex A' ∧ ∀ n, Eqv A (cons n ρ) A' (cons n ρ')
  | .eq _ _, h => h.elim
  | .ne _ _, h => h.elim
  | .and _ _, h => h.elim
  | .or _ _, h => h.elim
  | .all _, h => h.elim
  | .ex A', h => ⟨A', rfl, h⟩

/-- transport of Z∞ derivations along items with the same meaning -/
theorem transport {α r Γ} (d : Der α r Γ) : ∀ Γ', Covers Γ Γ' → Der α r Γ' := by
  induction d with
  | ax A ρ m t =>
    intro Γ' h
    match h _ m with
    | ⟨x', hx', he⟩ => exact .ax x'.1 x'.2 hx' (eqv_true A ρ x'.1 x'.2 he t)
  | and A B ρ β γ m _ _ h1 h2 ih1 ih2 =>
    intro Γ' h
    match h _ m with
    | ⟨x', hx', he⟩ => match eqv_and_inv A B ρ x'.2 x'.1 he with
      | ⟨A', B', eF, eA, eB⟩ =>
        exact .and A' B' x'.2 β γ (mem_of_eq _ _ hx' eF rfl)
          (ih1 _ (covers_cons h _ (A', x'.2) eA)) (ih2 _ (covers_cons h _ (B', x'.2) eB)) h1 h2
  | orL A B ρ β m _ h1 ih =>
    intro Γ' h
    match h _ m with
    | ⟨x', hx', he⟩ => match eqv_or_inv A B ρ x'.2 x'.1 he with
      | ⟨A', B', eF, eA, _⟩ =>
        exact .orL A' B' x'.2 β (mem_of_eq _ _ hx' eF rfl) (ih _ (covers_cons h _ (A', x'.2) eA)) h1
  | orR A B ρ β m _ h1 ih =>
    intro Γ' h
    match h _ m with
    | ⟨x', hx', he⟩ => match eqv_or_inv A B ρ x'.2 x'.1 he with
      | ⟨A', B', eF, _, eB⟩ =>
        exact .orR A' B' x'.2 β (mem_of_eq _ _ hx' eF rfl) (ih _ (covers_cons h _ (B', x'.2) eB)) h1
  | all A ρ β m _ h1 ih =>
    intro Γ' h
    match h _ m with
    | ⟨x', hx', he⟩ => match eqv_all_inv A ρ x'.2 x'.1 he with
      | ⟨A', eF, eA⟩ =>
        exact .all A' x'.2 β (mem_of_eq _ _ hx' eF rfl)
          (fun n => ih n _ (covers_cons h _ (A', cons n x'.2) (eA n))) h1
  | ex A ρ n β m _ h1 ih =>
    intro Γ' h
    match h _ m with
    | ⟨x', hx', he⟩ => match eqv_ex_inv A ρ x'.2 x'.1 he with
      | ⟨A', eF, eA⟩ =>
        exact .ex A' x'.2 n β (mem_of_eq _ _ hx' eF rfl) (ih _ (covers_cons h _ (A', cons n x'.2) (eA n))) h1
  | cut C ρ β γ hr _ _ h1 h2 ih1 ih2 =>
    intro Γ' h
    exact .cut C ρ β γ hr (ih1 _ (covers_cons h _ _ (eqv_refl C ρ)))
      (ih2 _ (covers_cons h _ _ (eqv_refl (dual C) ρ))) h1 h2

/-! ## Part B: heights ω·d + n, rank monotonicity -/

def fin : Nat → ON
  | 0 => .zero
  | m + 1 => .oadd .zero m .zero

def one : ON := .oadd .zero 0 .zero

def om : Nat → Nat → ON
  | 0, n => fin n
  | d + 1, n => .oadd one d (fin n)

theorem fin_lt : {m n : Nat} → m < n → Lt (fin m) (fin n)
  | 0, 0, h => absurd h (Nat.lt_irrefl 0)
  | 0, _ + 1, _ => rfl
  | _ + 1, 0, h => absurd h (Nat.not_lt_zero _)
  | _ + 1, _ + 1, h => lt_of_coef (Nat.lt_of_succ_lt_succ h)

theorem om_lt_n {m n : Nat} (h : m < n) : (D : Nat) → Lt (om D m) (om D n)
  | 0 => fin_lt h
  | _ + 1 => lt_of_tail (fin_lt h)

theorem om_lt_succ : (d n : Nat) → Lt (om d n) (om (d + 1) 0)
  | 0, 0 => rfl
  | 0, _ + 1 => lt_of_exp (rfl : cmp ON.zero one = .lt)
  | _ + 1, _ => lt_of_coef (Nat.lt_succ_self _)

theorem om_lt_d {d : Nat} (n : Nat) : {D : Nat} → d < D → Lt (om d n) (om D 0)
  | 0, h => absurd h (Nat.not_lt_zero _)
  | D + 1, h => (Nat.lt_or_ge d D).elim (fun hl => lt_trans _ _ _ (om_lt_d n hl) (om_lt_succ D 0))
      (fun hg => by
        have e : d = D := Nat.le_antisymm (Nat.le_of_lt_succ h) hg
        rw [e]; exact om_lt_succ D n)

theorem raise_om {d D r Γ} (h : d ≤ D) (x : Der (om d 0) r Γ) : Der (om D 0) r Γ :=
  (Nat.lt_or_ge d D).elim (fun hl => raise x (om_lt_d 0 hl))
    (fun hg => by have e : d = D := Nat.le_antisymm h hg; rw [← e]; exact x)

theorem rank_mono {α r Γ} (d : Der α r Γ) : ∀ {r'}, r ≤ r' → Der α r' Γ := by
  induction d with
  | ax A ρ m t => exact fun _ => .ax A ρ m t
  | and A B ρ β γ m _ _ h1 h2 ih1 ih2 => exact fun h => .and A B ρ β γ m (ih1 h) (ih2 h) h1 h2
  | orL A B ρ β m _ h1 ih => exact fun h => .orL A B ρ β m (ih h) h1
  | orR A B ρ β m _ h1 ih => exact fun h => .orR A B ρ β m (ih h) h1
  | all A ρ β m _ h1 ih => exact fun h => .all A ρ β m (fun n => ih n h) h1
  | ex A ρ n β m _ h1 ih => exact fun h => .ex A ρ n β m (ih h) h1
  | cut C ρ β γ hr _ _ h1 h2 ih1 ih2 => exact fun h => .cut C ρ β γ (Nat.lt_of_lt_of_le hr h) (ih1 h) (ih2 h) h1 h2

/-! ## Part C: Peano arithmetic (Tait calculus) and its embedding -/

def shσ (v : Nat) : Tm := .var (v + 1)
def c0 (t : Tm) : Nat → Tm
  | 0 => t
  | v + 1 => .var v
def sσ : Nat → Tm
  | 0 => .succ (.var 0)
  | v + 1 => .var (v + 1)

def sh : List Fm → List Fm
  | [] => []
  | A :: Γ => subF shσ A :: sh Γ

def mapI (ρ : Nat → Nat) : List Fm → List Item
  | [] => []
  | A :: Γ => (A, ρ) :: mapI ρ Γ

theorem mem_mapI (ρ : Nat → Nat) {A : Fm} : (Γ : List Fm) → A ∈ Γ → (A, ρ) ∈ mapI ρ Γ
  | [], m => nomatch m
  | _ :: Γ, m => by
    cases m with
    | head => exact .head _
    | tail _ m' => exact .tail _ (mem_mapI ρ Γ m')

/-- Peano arithmetic: true literal sequents (the quantifier-free axioms), the
  logical rules, cut, and induction -/
inductive PD : List Fm → Prop where
  | ax {Γ} : (∀ ρ : Nat → Nat, ∃ A, A ∈ Γ ∧ TrueAt A ρ) → PD Γ
  | and {Γ A B} : .and A B ∈ Γ → PD (A :: Γ) → PD (B :: Γ) → PD Γ
  | orL {Γ A B} : .or A B ∈ Γ → PD (A :: Γ) → PD Γ
  | orR {Γ A B} : .or A B ∈ Γ → PD (B :: Γ) → PD Γ
  | all {Γ A} : .all A ∈ Γ → PD (A :: sh Γ) → PD Γ
  | ex {Γ A} (t : Tm) : .ex A ∈ Γ → PD (subF (c0 t) A :: Γ) → PD Γ
  | cut {Γ} (C : Fm) : PD (C :: Γ) → PD (dual C :: Γ) → PD Γ
  | ind {Γ A} : .all A ∈ Γ → PD (subF (c0 .zero) A :: Γ) → PD (subF sσ A :: dual A :: sh Γ) → PD Γ

theorem covers_sh (n : Nat) (ρ : Nat → Nat) : (Γ : List Fm) → Covers (mapI (cons n ρ) (sh Γ)) (mapI ρ Γ)
  | [] => fun _ m => nomatch m
  | A :: Γ => covers_cons (covers_sh n ρ Γ) _ (A, ρ) (eqv_sub shσ A (cons n ρ) ρ (fun _ => rfl))

theorem covers_id (Γ : List Item) : Covers Γ Γ := fun x m => ⟨x, m, eqv_refl x.1 x.2⟩

theorem covers_tail {Γ Γ' : List Item} (y : Item) (h : Covers Γ Γ') : Covers Γ (y :: Γ') := fun x m =>
  match h x m with
  | ⟨x', hx', he⟩ => ⟨x', .tail _ hx', he⟩

theorem eqv_inst (t : Tm) (A : Fm) (ρ : Nat → Nat) : Eqv (subF (c0 t) A) ρ A (cons (ev ρ t) ρ) :=
  eqv_sub (c0 t) A ρ (cons (ev ρ t) ρ) (fun v => match v with | 0 => rfl | _ + 1 => rfl)

theorem eqv_succ (A : Fm) (n : Nat) (ρ : Nat → Nat) : Eqv (subF sσ A) (cons n ρ) A (cons (n + 1) ρ) :=
  eqv_sub sσ A (cons n ρ) (cons (n + 1) ρ) (fun v => match v with | 0 => rfl | _ + 1 => rfl)

theorem max_le_l (a b : Nat) : a ≤ a + b := Nat.le_add_right a b
theorem max_le_r (a b : Nat) : b ≤ a + b := Nat.le_add_left b a

/-- the embedding: every PA-derivable sequent has, at every environment, a
  Z∞-derivation of height ω·d and cut rank r (uniformly) -/
theorem embed {Γ : List Fm} (p : PD Γ) : ∃ d r, ∀ ρ, Der (om d 0) r (mapI ρ Γ) := by
  induction p with
  | ax h => exact ⟨0, 0, fun ρ => match h ρ with | ⟨A, m, t⟩ => .ax A ρ (mem_mapI ρ _ m) t⟩
  | @and Γ A B m _ _ ih1 ih2 =>
    match ih1, ih2 with
    | ⟨d1, r1, D1⟩, ⟨d2, r2, D2⟩ =>
      exact ⟨Nat.add d1 d2 + 1, Nat.add r1 r2, fun ρ =>
        .and A B ρ _ _ (mem_mapI ρ _ m) (rank_mono (D1 ρ) (max_le_l _ _)) (rank_mono (D2 ρ) (max_le_r _ _))
          (om_lt_d 0 (Nat.lt_succ_of_le (max_le_l _ _))) (om_lt_d 0 (Nat.lt_succ_of_le (max_le_r _ _)))⟩
  | @orL Γ A B m _ ih =>
    match ih with
    | ⟨d1, r1, D1⟩ => exact ⟨d1 + 1, r1, fun ρ => .orL A B ρ _ (mem_mapI ρ _ m) (D1 ρ) (om_lt_succ d1 0)⟩
  | @orR Γ A B m _ ih =>
    match ih with
    | ⟨d1, r1, D1⟩ => exact ⟨d1 + 1, r1, fun ρ => .orR A B ρ _ (mem_mapI ρ _ m) (D1 ρ) (om_lt_succ d1 0)⟩
  | @all Γ A m _ ih =>
    match ih with
    | ⟨d1, r1, D1⟩ =>
      exact ⟨d1 + 1, r1, fun ρ => .all A ρ (fun _ => om d1 0) (mem_mapI ρ _ m)
        (fun n => transport (D1 (cons n ρ)) _ (covers_cons (covers_sh n ρ Γ) _ _ (eqv_refl A (cons n ρ))))
        (fun _ => om_lt_succ d1 0)⟩
  | @ex Γ A t m _ ih =>
    match ih with
    | ⟨d1, r1, D1⟩ =>
      exact ⟨d1 + 1, r1, fun ρ => .ex A ρ (ev ρ t) _ (mem_mapI ρ _ m)
        (transport (D1 ρ) _ (covers_cons (covers_id _) _ _ (eqv_inst t A ρ))) (om_lt_succ d1 0)⟩
  | @cut Γ C _ _ ih1 ih2 =>
    match ih1, ih2 with
    | ⟨d1, r1, D1⟩, ⟨d2, r2, D2⟩ =>
      exact ⟨Nat.add d1 d2 + 1, Nat.add (Nat.add r1 r2) (rk C + 1), fun ρ =>
        .cut C ρ _ _ (Nat.lt_of_lt_of_le (Nat.lt_succ_self _) (max_le_r _ _))
          (rank_mono (D1 ρ) (Nat.le_trans (max_le_l _ _) (max_le_l _ _)))
          (rank_mono (D2 ρ) (Nat.le_trans (max_le_r _ _) (max_le_l _ _)))
          (om_lt_d 0 (Nat.lt_succ_of_le (max_le_l _ _))) (om_lt_d 0 (Nat.lt_succ_of_le (max_le_r _ _)))⟩
  | @ind Γ A m _ _ ih0 ihs =>
    match ih0, ihs with
    | ⟨d0, r0, D0⟩, ⟨ds, rs, DS⟩ =>
      refine ⟨Nat.add d0 ds + 1, Nat.add (Nat.add r0 rs) (rk A + 1), fun ρ => ?_⟩
      have hR0 : r0 ≤ Nat.add (Nat.add r0 rs) (rk A + 1) := Nat.le_trans (max_le_l _ _) (max_le_l _ _)
      have hRs : rs ≤ Nat.add (Nat.add r0 rs) (rk A + 1) := Nat.le_trans (max_le_r _ _) (max_le_l _ _)
      have hRA : rk A < Nat.add (Nat.add r0 rs) (rk A + 1) := Nat.lt_of_lt_of_le (Nat.lt_succ_self _) (max_le_r _ _)
      -- the chain of cuts: A(n) at height ω·D + n
      have chain : ∀ n, Der (om (Nat.add d0 ds) n) (Nat.add (Nat.add r0 rs) (rk A + 1)) ((A, cons n ρ) :: mapI ρ Γ) := by
        intro n
        induction n with
        | zero =>
          exact raise_om (max_le_l _ _)
            (rank_mono (transport (D0 ρ) _ (covers_cons (covers_id _) _ _ (eqv_inst .zero A ρ))) hR0)
        | succ n ihn =>
          have left : Der (om (Nat.add d0 ds) n) _ ((A, cons n ρ) :: (A, cons (n + 1) ρ) :: mapI ρ Γ) :=
            weaken ihn (fun x mx => (mem_cons' mx).elim (fun e => e ▸ .head _) (fun mx' => .tail _ (.tail _ mx')))
          have right : Der (om ds 0) rs ((dual A, cons n ρ) :: (A, cons (n + 1) ρ) :: mapI ρ Γ) :=
            transport (DS (cons n ρ)) _ (fun x mx => (mem_cons' mx).elim
              (fun e => ⟨(A, cons (n + 1) ρ), .tail _ (.head _), by rw [e]; exact eqv_succ A n ρ⟩)
              (fun mx' => (mem_cons' mx').elim
                (fun e => ⟨(dual A, cons n ρ), .head _, by rw [e]; exact eqv_refl _ _⟩)
                (fun mx'' => match covers_sh n ρ Γ x mx'' with
                  | ⟨x', hx', he⟩ => ⟨x', .tail _ (.tail _ hx'), he⟩)))
          have hlt : Lt (om ds 0) (om (Nat.add d0 ds) (n + 1)) :=
            (Nat.lt_or_ge ds (Nat.add d0 ds)).elim
              (fun hl => lt_trans _ _ _ (om_lt_d 0 hl) (om_lt_n (Nat.succ_pos n) _))
              (fun hg => by
                have e : ds = Nat.add d0 ds := Nat.le_antisymm (max_le_r _ _) hg
                rw [← e]; exact om_lt_n (Nat.succ_pos n) ds)
          exact .cut A (cons n ρ) _ _ hRA left (rank_mono right hRs) (om_lt_n (Nat.lt_succ_self n) _) hlt
      exact .all A ρ (fun n => om (Nat.add d0 ds) n) (mem_mapI ρ _ m) chain (fun n => om_lt_succ _ n)

/-- Gentzen: Peano arithmetic is consistent -/
theorem pa_consistent : ¬ PD [.eq .zero (.succ .zero)] := fun p =>
  match embed p with
  | ⟨d, r, D⟩ => consistent (om d 0) r (fun _ => 0) (D (fun _ => 0))

/-- the ordinal bound: every PA-derivable sequent has cut-free Z∞-derivations
  whose heights are the notations tw r (ω·d), below ε₀ -/
theorem pa_cutfree {Γ : List Fm} (p : PD Γ) : ∃ d r, ∀ ρ, Der (tw r (om d 0)) 0 (mapI ρ Γ) :=
  match embed p with
  | ⟨d, r, D⟩ => ⟨d, r, fun ρ => cut_elim r (D ρ)⟩

theorem nf_om : (d n : Nat) → NF (om d n)
  | 0, 0 => trivial
  | 0, _ + 1 => ⟨trivial, trivial, trivial⟩
  | _ + 1, 0 => ⟨⟨trivial, trivial, trivial⟩, trivial, trivial⟩
  | _ + 1, _ + 1 => ⟨⟨trivial, trivial, trivial⟩, ⟨trivial, trivial, trivial⟩, (rfl : cmp ON.zero one = .lt)⟩

theorem nf_tw : (r : Nat) → (α : ON) → NF α → NF (tw r α)
  | 0, _, h => h
  | r + 1, α, h => nf_tw r (w α) ⟨h, trivial, trivial⟩

end PAE

end Found

#print axioms Found.PAE.transport
#print axioms Found.PAE.embed
#print axioms Found.PAE.pa_consistent
#print axioms Found.PAE.pa_cutfree
#print axioms Found.PAE.nf_tw

#print axioms: 5 theorems, no axioms.

85.135 Stone duality

Spec of a Boolean algebra is compact and Hausdorff, its clopens are exactly the basic sets, Stone spaces are recovered from their clopen algebras, and lattice maps give continuous maps (classical point).

\[ U \text { clopen in } \mathrm {Spec}\,B \Rightarrow \exists a,\ U = \{P \mid a \in P\} \]

found/StoneDual.lean

/-
  T191 line. found/StoneDual — Stone duality, algebra side, in the classical
  point.  For a Boolean algebra B, Spec B = prime filters with the basic
  opens rep a (found/Stone).
  * compactness: every cover of Spec B by basic opens has a finite subcover;
  * Hausdorff: distinct prime filters are separated by some rep a / rep ¬a;
  * B ≅ Clopen(Spec B): every clopen set is rep a for some a (and rep is
    injective up to ≤, Stone.rep_inj);
  * space side: a Stone space X, given by a Boolean algebra of clopens
    val : B → (X → Prop) (a lattice map that reflects ⊥), separating points
    and compact in the finite-intersection form, is homeomorphic on points
    to Spec B: x ↦ {a | x ∈ val a} is a prime filter, injective up to
    pointwise equality, and every prime filter arises;
  * functor: a lattice map f : B → B' gives Spec B' → Spec B (preimage),
    continuous: the preimage of rep a is rep (f a).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Stone

namespace Found

namespace StoneD

open CP PF Stone

variable (K : Classical') (H : HA.{0}) (hbool : ∀ a, H.le H.top (H.join a (HA.neg H a)))

abbrev Spec : Type := {P : H.car → Prop // PFilt H P}

theorem mL_mem (P : Spec H) : (l : List H.car) → (∀ x, x ∈ l → P.val x) → P.val (mL H l)
  | [], _ => P.property.top
  | x :: l, h => P.property.meet _ _ (h x (.head _)) (mL_mem P l (fun y m => h y (.tail _ m)))

theorem mL_mem' (P : Spec H) (l : List H.car) (h : ∀ x, x ∈ l → P.val x) : P.val (mL H l) :=
  mL_mem H P l h

/-- choose, for each element of a list of negations of covers, the cover -/
theorem pick (C : H.car → Prop) : (l : List H.car) → (∀ x, x ∈ l → ∃ c, C c ∧ x = HA.neg H c) →
    ∃ cs : List H.car, (∀ c, c ∈ cs → C c) ∧ ∀ x, x ∈ l → ∃ c, c ∈ cs ∧ x = HA.neg H c
  | [], _ => ⟨[], ⟨fun _ m => (by cases m), fun _ m => (by cases m)⟩⟩
  | x :: l, h => match h x (.head _), pick C l (fun y m => h y (.tail _ m)) with
    | ⟨c, hc, ex⟩, ⟨cs, hcs, hl⟩ => ⟨c :: cs, fun d m => by
        cases m with
        | head => exact hc
        | tail _ m => exact hcs d m,
      fun y m => by
        cases m with
        | head => exact ⟨c, .head _, ex⟩
        | tail _ m => match hl y m with
          | ⟨d, hd, ed⟩ => exact ⟨d, .tail _ hd, ed⟩⟩

include K hbool in
/-- compactness of Spec B -/
theorem compact (C : H.car → Prop) (cover : ∀ P : Spec H, ∃ c, C c ∧ rep H c P) :
    ∃ cs : List H.car, (∀ c, c ∈ cs → C c) ∧ ∀ P : Spec H, ∃ c, c ∈ cs ∧ rep H c P := by
  let N : H.car → Prop := fun x => ∃ c, C c ∧ x = HA.neg H c
  have hG : Gen H N H.bot := dne K _ (fun hB => by
    let P : H.car → Prop := F K H N H.bot
    have hP : PFilt H P := ⟨fun _ _ hle h => gen_up H h hle, fun _ _ h1 h2 => gen_meet H h1 h2, gen_top H _,
      fun hb => F_avoids K H _ _ hB hb, fun x y hj => F_prime K H _ _ hB x y hj⟩
    match cover ⟨P, hP⟩ with
    | ⟨c, hc, hr⟩ =>
      have hn : P (HA.neg H c) := gen_of H (Or.inl ⟨c, hc, rfl⟩)
      exact F_avoids K H _ _ hB (gen_up H (gen_meet H hr hn) (HA.meet_neg H c)))
  match hG with
  | ⟨l, hl, hle⟩ => match pick H C l hl with
    | ⟨cs, hcs, hx⟩ => exact ⟨cs, hcs, fun P => dne K _ (fun hn => by
        have all : ∀ x, x ∈ l → P.val x := fun x m => match hx x m with
          | ⟨c, mc, ex⟩ => ex ▸ (rep_neg H hbool c P).mpr (fun hr => hn ⟨c, mc, hr⟩)
        exact P.property.nobot (P.property.up _ _ hle (mL_mem H P l all)))⟩

include K hbool in
/-- Hausdorff: distinct prime filters are separated by a basic clopen -/
theorem separated (P Q : Spec H) (h : ¬ ∀ a, P.val a ↔ Q.val a) :
    ∃ a, rep H a P ∧ rep H (HA.neg H a) Q := by
  refine dne K _ (fun hn => h (fun a => ⟨fun hp => dne K _ (fun hq => hn ⟨a, hp, (rep_neg H hbool a Q).mpr hq⟩),
    fun hq => dne K _ (fun hp => hn ⟨HA.neg H a, (rep_neg H hbool a P).mpr hp, ?_⟩)⟩))
  exact (rep_neg H hbool _ Q).mpr (fun hnq => (rep_neg H hbool a Q).mp hnq hq)

def Open (U : Spec H → Prop) : Prop := ∀ P, U P → ∃ c, rep H c P ∧ ∀ Q, rep H c Q → U Q

/-- the join of the members of a list on the U side -/
def jU (U : Spec H → Prop) : List H.car → H.car
  | [] => H.bot
  | c :: cs => match CP.dec K (∀ Q, rep H c Q → U Q) with
    | true => H.join c (jU U cs)
    | false => jU U cs

theorem jU_sound (U : Spec H → Prop) (P : Spec H) : (cs : List H.car) → rep H (jU K H U cs) P → U P
  | [], h => (rep_bot H P h).elim
  | c :: cs, h => by
    unfold jU at h
    cases hd : CP.dec K (∀ Q, rep H c Q → U Q) with
    | true =>
      rw [hd] at h
      exact ((rep_join H _ _ P).mp h).elim (fun hc => (CP.dec_spec K _).mp hd P hc) (jU_sound U P cs)
    | false =>
      rw [hd] at h
      exact jU_sound U P cs h

theorem jU_complete (U : Spec H → Prop) (P : Spec H) (hP : U P) : (cs : List H.car) →
    (∀ c, c ∈ cs → (∀ Q, rep H c Q → U Q) ∨ (∀ Q, rep H c Q → ¬ U Q)) →
    (∃ c, c ∈ cs ∧ rep H c P) → rep H (jU K H U cs) P
  | [], _, ⟨_, m, _⟩ => nomatch m
  | c :: cs, hc, ⟨d, md, hd⟩ => by
    unfold jU
    cases hdc : CP.dec K (∀ Q, rep H c Q → U Q) with
    | true =>
      show rep H (H.join c (jU K H U cs)) P
      cases md with
      | head => exact (rep_join H _ _ P).mpr (Or.inl hd)
      | tail _ m => exact (rep_join H _ _ P).mpr (Or.inr (jU_complete U P hP cs (fun e me => hc e (.tail _ me)) ⟨d, m, hd⟩))
    | false =>
      show rep H (jU K H U cs) P
      cases md with
      | head =>
        exact ((hc c (.head _)).elim (fun hu => absurd ((CP.dec_spec K _).mpr hu) (fun e => Bool.noConfusion (e.symm.trans hdc)))
          (fun hnu => (hnu P hd hP).elim))
      | tail _ m => exact jU_complete U P hP cs (fun e me => hc e (.tail _ me)) ⟨d, m, hd⟩

include K hbool in
/-- every clopen subset of Spec B is a basic clopen rep a -/
theorem clopen_rep (U : Spec H → Prop) (ho : Open H U) (hc : Open H (fun P => ¬ U P)) :
    ∃ a, ∀ P, rep H a P ↔ U P := by
  let C : H.car → Prop := fun c => (∀ Q, rep H c Q → U Q) ∨ (∀ Q, rep H c Q → ¬ U Q)
  have cover : ∀ P : Spec H, ∃ c, C c ∧ rep H c P := fun P => (K.lem (U P)).elim
    (fun hu => match ho P hu with | ⟨c, hr, hs⟩ => ⟨c, Or.inl hs, hr⟩)
    (fun hu => match hc P hu with | ⟨c, hr, hs⟩ => ⟨c, Or.inr hs, hr⟩)
  match compact K H hbool C cover with
  | ⟨cs, hcs, hall⟩ => exact ⟨jU K H U cs, fun P => ⟨jU_sound K H U P cs,
      fun hP => jU_complete K H U P hP cs hcs (hall P)⟩⟩

/-! ## space side -/

structure StoneSp (X : Type) where
  val : H.car → X → Prop
  v_top : ∀ x, val H.top x
  v_bot : ∀ x, ¬ val H.bot x
  v_meet : ∀ a b x, val (H.meet a b) x ↔ val a x ∧ val b x
  v_join : ∀ a b x, val (H.join a b) x ↔ val a x ∨ val b x
  v_mono : ∀ a b x, H.le a b → val a x → val b x
  v_reflect : ∀ a, (∀ x, ¬ val a x) → H.le a H.bot
  separate : ∀ x y, (∀ a, val a x ↔ val a y) → x = y
  compact : ∀ P : H.car → Prop, (∀ l : List H.car, (∀ a, a ∈ l → P a) → ∃ x, val (mL H l) x) →
    ∃ x, ∀ a, P a → val a x

variable {H}

def pt {X : Type} (S : StoneSp H X) (x : X) : Spec H :=
  ⟨fun a => S.val a x, ⟨fun a b h hx => S.v_mono a b x h hx, fun a b ha hb => (S.v_meet a b x).mpr ⟨ha, hb⟩,
    S.v_top x, S.v_bot x, fun a b h => (S.v_join a b x).mp h⟩⟩

theorem pt_inj {X : Type} (S : StoneSp H X) (x y : X) (h : ∀ a, (pt S x).val a ↔ (pt S y).val a) : x = y :=
  S.separate x y h

theorem v_mL {X : Type} (S : StoneSp H X) (x : X) : (l : List H.car) → (∀ a, a ∈ l → S.val a x) → S.val (mL H l) x
  | [], _ => S.v_top x
  | a :: l, h => (S.v_meet _ _ x).mpr ⟨h a (.head _), v_mL S x l (fun b m => h b (.tail _ m))⟩

include K hbool in
/-- every prime filter is the filter of some point -/
theorem pt_surj {X : Type} (S : StoneSp H X) (P : Spec H) : ∃ x, ∀ a, (pt S x).val a ↔ P.val a := by
  have fip : ∀ l : List H.car, (∀ a, a ∈ l → P.val a) → ∃ x, S.val (mL H l) x := fun l hl =>
    dne K _ (fun hn => P.property.nobot (P.property.up _ _
      (S.v_reflect _ (fun x hx => hn ⟨x, hx⟩)) (mL_mem H P l hl)))
  match S.compact P.val fip with
  | ⟨x, hx⟩ => exact ⟨x, fun a => ⟨fun hv => dne K _ (fun hna => by
      have hneg : P.val (HA.neg H a) := (rep_neg H hbool a P).mpr hna
      have := (S.v_meet _ _ x).mpr ⟨hv, hx _ hneg⟩
      exact S.v_bot x (S.v_mono _ _ x (HA.meet_neg H a) this)), hx a⟩⟩

/-! ## morphisms -/

structure LatHom (H' : HA.{0}) where
  f : H.car → H'.car
  f_mono : ∀ a b, H.le a b → H'.le (f a) (f b)
  f_top : H'.le H'.top (f H.top)
  f_bot : H'.le (f H.bot) H'.bot
  f_meet : ∀ a b, H'.le (H'.meet (f a) (f b)) (f (H.meet a b))
  f_join : ∀ a b, H'.le (f (H.join a b)) (H'.join (f a) (f b))

def spec_map {H' : HA.{0}} (φ : LatHom (H := H) H') (P : Spec H') : Spec H :=
  ⟨fun a => P.val (φ.f a), ⟨fun a b h hp => P.property.up _ _ (φ.f_mono a b h) hp,
    fun a b ha hb => P.property.up _ _ (φ.f_meet a b) (P.property.meet _ _ ha hb),
    P.property.up _ _ φ.f_top P.property.top,
    fun hb => P.property.nobot (P.property.up _ _ φ.f_bot hb),
    fun a b h => P.property.prime _ _ (P.property.up _ _ (φ.f_join a b) h)⟩⟩

theorem spec_map_cont {H' : HA.{0}} (φ : LatHom (H := H) H') (a : H.car) (P : Spec H') :
    rep H a (spec_map φ P) ↔ rep H' (φ.f a) P := Iff.rfl

end StoneD

end Found

#print axioms Found.StoneD.compact
#print axioms Found.StoneD.separated
#print axioms Found.StoneD.jU_sound
#print axioms Found.StoneD.jU_complete
#print axioms Found.StoneD.clopen_rep
#print axioms Found.StoneD.pt_inj
#print axioms Found.StoneD.pt_surj
#print axioms Found.StoneD.spec_map
#print axioms Found.StoneD.spec_map_cont

#print axioms: 9 theorems, no axioms.

85.136 Enriched categories

Categories enriched in a monoidal preorder: truth values give preorders, \((\mathbb {N},+)\) gives Lawvere metric spaces, and change of base turns a metric into its specialization preorder.

\[ \mathbf {1} \le C(a,a),\quad C(a,b)\otimes C(b,c) \le C(a,c) \]

found/Enriched.lean

/-
  T193 line. found/Enriched — enriched categories as a point: a category
  enriched in a monoidal preorder V (Lawvere).  Hom objects live in V,
  identities are I ≤ C(a,a), composition is C(a,b) ⊗ C(b,c) ≤ C(a,c).
  * V = (Prop, ∧, True): V-categories are exactly preorders (both ways).
  * V = (ℕ, +, 0) ordered by ≥: V-categories are Lawvere (generalized)
    metric spaces: d(a,a) = 0 and the triangle inequality.
  * Change of base along a lax monoidal monotone map V → W; the map
    ℕ → Prop, d ↦ (d = 0), turns a metric space into its specialization
    preorder.
  * V-functors compose; non-expansive maps are the ℕ-functors.

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Enr

universe u v

structure MonPre where
  car : Type u
  le : car → car → Prop
  refl : ∀ a, le a a
  trans : ∀ {a b c}, le a b → le b c → le a c
  ten : car → car → car
  unit : car
  ten_mono : ∀ {a a' b b'}, le a a' → le b b' → le (ten a b) (ten a' b')

structure VCat (V : MonPre.{u}) where
  Ob : Type v
  hom : Ob → Ob → V.car
  id : ∀ a, V.le V.unit (hom a a)
  comp : ∀ a b c, V.le (V.ten (hom a b) (hom b c)) (hom a c)

structure VFun {V : MonPre.{u}} (C D : VCat.{u, v} V) where
  obj : C.Ob → D.Ob
  map : ∀ a b, V.le (C.hom a b) (D.hom (obj a) (obj b))

def VFun.id' {V : MonPre.{u}} (C : VCat.{u, v} V) : VFun C C := ⟨fun a => a, fun _ _ => V.refl _⟩

def VFun.comp' {V : MonPre.{u}} {C D E : VCat.{u, v} V} (F : VFun C D) (G : VFun D E) : VFun C E :=
  ⟨fun a => G.obj (F.obj a), fun a b => V.trans (F.map a b) (G.map _ _)⟩

/-! ## V = truth values -/

def PropV : MonPre.{0} where
  car := Prop
  le p q := p → q
  refl _ h := h
  trans h k x := k (h x)
  ten p q := p ∧ q
  unit := True
  ten_mono h k x := ⟨h x.1, k x.2⟩

structure Preord where
  P : Type
  le : P → P → Prop
  refl : ∀ a, le a a
  trans : ∀ {a b c}, le a b → le b c → le a c

def ofPreord (Q : Preord) : VCat.{0, 0} PropV where
  Ob := Q.P
  hom := Q.le
  id a _ := Q.refl a
  comp _ _ _ h := Q.trans h.1 h.2

def toPreord (C : VCat.{0, 0} PropV) : Preord where
  P := C.Ob
  le := C.hom
  refl a := C.id a trivial
  trans {a b c} h k := C.comp a b c ⟨h, k⟩

theorem round_le (Q : Preord) (a b : Q.P) : (toPreord (ofPreord Q)).le a b ↔ Q.le a b := Iff.rfl
theorem round_hom (C : VCat.{0, 0} PropV) (a b : C.Ob) : (ofPreord (toPreord C)).hom a b ↔ C.hom a b := Iff.rfl

/-- monotone maps are exactly the Prop-functors -/
def monoFun (Q R : Preord) (f : Q.P → R.P) (hf : ∀ a b, Q.le a b → R.le (f a) (f b)) :
    VFun (ofPreord Q) (ofPreord R) := ⟨f, hf⟩

/-! ## V = distances (Lawvere metric spaces) -/

def NatV : MonPre.{0} where
  car := Nat
  le x y := y ≤ x
  refl x := Nat.le_refl x
  trans h k := Nat.le_trans k h
  ten x y := x + y
  unit := 0
  ten_mono h k := Nat.add_le_add h k

structure LMetric where
  X : Type
  d : X → X → Nat
  zero : ∀ a, d a a = 0
  tri : ∀ a b c, d a c ≤ d a b + d b c

def ofMetric (M : LMetric) : VCat.{0, 0} NatV where
  Ob := M.X
  hom := M.d
  id a := by
    show M.d a a ≤ 0
    rw [M.zero a]
    exact Nat.le_refl 0
  comp a b c := M.tri a b c

def toMetric (C : VCat.{0, 0} NatV) : LMetric where
  X := C.Ob
  d := C.hom
  zero a := Nat.le_antisymm (C.id a) (Nat.zero_le _)
  tri a b c := C.comp a b c

/-- non-expansive maps are the ℕ-functors -/
def nonexp (M N : LMetric) (f : M.X → N.X) (hf : ∀ a b, N.d (f a) (f b) ≤ M.d a b) :
    VFun (ofMetric M) (ofMetric N) := ⟨f, hf⟩

/-! ## change of base -/

structure LaxMon (V W : MonPre.{u}) where
  f : V.car → W.car
  mono : ∀ {a b}, V.le a b → W.le (f a) (f b)
  unit : W.le W.unit (f V.unit)
  ten : ∀ a b, W.le (W.ten (f a) (f b)) (f (V.ten a b))

def base {V W : MonPre.{u}} (φ : LaxMon V W) (C : VCat.{u, v} V) : VCat.{u, v} W where
  Ob := C.Ob
  hom a b := φ.f (C.hom a b)
  id a := W.trans φ.unit (φ.mono (C.id a))
  comp a b c := W.trans (φ.ten _ _) (φ.mono (C.comp a b c))

theorem le_zero {x : Nat} (h : x ≤ 0) : x = 0 := Nat.le_antisymm h (Nat.zero_le x)

def zf (d : Nat) : Prop := d = 0

theorem zf_mono {a b : Nat} (h : b ≤ a) (ha : zf a) : zf b := le_zero (show b ≤ 0 from ha ▸ h)

theorem zf_ten (a b : Nat) (h : zf a ∧ zf b) : zf (a + b) := by
  show a + b = 0
  rw [h.1, h.2]

/-- d ↦ (d = 0): distance zero is a lax monoidal map ℕ → Prop -/
def isZero : LaxMon NatV PropV where
  f := zf
  mono h ha := zf_mono h ha
  unit _ := rfl
  ten a b h := zf_ten a b h

/-- the specialization preorder of a metric space -/
theorem spec_preorder (M : LMetric) (a b : M.X) :
    (base isZero (ofMetric M)).hom a b ↔ M.d a b = 0 := Iff.rfl

end Enr

end Found

#print axioms Found.Enr.VFun.comp'
#print axioms Found.Enr.ofPreord
#print axioms Found.Enr.toPreord
#print axioms Found.Enr.round_le
#print axioms Found.Enr.round_hom
#print axioms Found.Enr.ofMetric
#print axioms Found.Enr.toMetric
#print axioms Found.Enr.nonexp
#print axioms Found.Enr.base
#print axioms Found.Enr.isZero
#print axioms Found.Enr.spec_preorder

#print axioms: 11 theorems, no axioms.

85.137 Operads

Planar operads in the partial-composition presentation; the endomorphism operad of a type satisfies the unit, sequential and parallel associativity laws, and algebras are law-preserving maps into it.

\[ (F \circ _i G) \circ _{i+j} H \approx F \circ _i (G \circ _j H) \]

found/Operad.lean

/-
  T193 line. found/Operad — (planar) operads as a point, in the
  partial-composition presentation: operations with arities, a unit of
  arity 1, and F ∘ᵢ G of arity |F| + |G| - 1, subject to the unit laws and
  the sequential and parallel associativity laws.
  * The endomorphism operad End X (operations = functions on lists of
    inputs, F ∘ᵢ G plugs G into the i-th input) satisfies all the laws,
    up to agreement on inputs of the right length.
  * An algebra of an operad on X is a law-preserving map into End X.
  Own list toolkit (append, take, drop, length) proved by structural
  recursion, since the core list lemmas use propext.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import lib.Semi

namespace Found

namespace Opd

variable {X : Type}

def app : List X → List X → List X
  | [], l => l
  | a :: k, l => a :: app k l

def len : List X → Nat
  | [] => 0
  | _ :: l => len l + 1

def tk : Nat → List X → List X
  | 0, [] => []
  | 0, _ :: _ => []
  | _ + 1, [] => []
  | n + 1, a :: l => a :: tk n l

def dr : Nat → List X → List X
  | 0, [] => []
  | 0, a :: l => a :: l
  | _ + 1, [] => []
  | n + 1, _ :: l => dr n l

theorem app_nil : (l : List X) → app l [] = l
  | [] => rfl
  | a :: l => congrArg (a :: ·) (app_nil l)

theorem app_assoc : (a b c : List X) → app (app a b) c = app a (app b c)
  | [], _, _ => rfl
  | x :: a, b, c => congrArg (x :: ·) (app_assoc a b c)

theorem tk_zero : (l : List X) → tk 0 l = []
  | [] => rfl
  | _ :: _ => rfl

theorem dr_zero : (l : List X) → dr 0 l = l
  | [] => rfl
  | _ :: _ => rfl

theorem tk_nil : (n : Nat) → tk n ([] : List X) = []
  | 0 => rfl
  | _ + 1 => rfl

theorem dr_nil : (n : Nat) → dr n ([] : List X) = []
  | 0 => rfl
  | _ + 1 => rfl

theorem tk_app : (a r : List X) → (k : Nat) → tk (len a + k) (app a r) = app a (tk k r)
  | [], r, k => by
    show tk (0 + k) r = tk k r
    rw [Nat.zero_add]
  | x :: a, r, k => by
    show tk (len a + 1 + k) (x :: app a r) = x :: app a (tk k r)
    rw [Nat.succ_add]
    exact congrArg (x :: ·) (tk_app a r k)

theorem dr_app : (a r : List X) → (k : Nat) → dr (len a + k) (app a r) = dr k r
  | [], r, k => by
    show dr (0 + k) r = dr k r
    rw [Nat.zero_add]
  | x :: a, r, k => by
    show dr (len a + 1 + k) (x :: app a r) = dr k r
    rw [Nat.succ_add]
    exact dr_app a r k

theorem tk_app0 (a r : List X) : tk (len a) (app a r) = a := by
  have := tk_app a r 0
  rw [Nat.add_zero, tk_zero, app_nil] at this
  exact this

theorem dr_app0 (a r : List X) : dr (len a) (app a r) = r := by
  have := dr_app a r 0
  rw [Nat.add_zero, dr_zero] at this
  exact this

theorem tk_add : (i j : Nat) → (l : List X) → tk (i + j) l = app (tk i l) (tk j (dr i l))
  | 0, j, l => by rw [Nat.zero_add, tk_zero, dr_zero]; rfl
  | i + 1, j, [] => by rw [Nat.succ_add, tk_nil, tk_nil, dr_nil, tk_nil]; rfl
  | i + 1, j, a :: l => by
    rw [Nat.succ_add]
    exact congrArg (a :: ·) (tk_add i j l)

theorem dr_add : (i j : Nat) → (l : List X) → dr (i + j) l = dr j (dr i l)
  | 0, j, l => by rw [Nat.zero_add, dr_zero]
  | i + 1, j, [] => by rw [Nat.succ_add, dr_nil, dr_nil, dr_nil]
  | i + 1, j, _ :: l => by
    rw [Nat.succ_add]
    exact dr_add i j l

theorem len_tk : (i : Nat) → (l : List X) → i ≤ len l → len (tk i l) = i
  | 0, [], _ => rfl
  | 0, _ :: _, _ => rfl
  | _ + 1, [], h => absurd h (Nat.not_succ_le_zero _)
  | i + 1, _ :: l, h => congrArg (· + 1) (len_tk i l (Nat.le_of_succ_le_succ h))

theorem len_dr : (i m : Nat) → (l : List X) → len l = i + m → len (dr i l) = m
  | 0, m, [], h => h.trans (Nat.zero_add m)
  | 0, m, _ :: _, h => h.trans (Nat.zero_add m)
  | i + 1, m, [], h => Nat.noConfusion ((Nat.succ_add i m).symm.trans h.symm)
  | i + 1, m, _ :: l, h => len_dr i m l (Nat.succ.inj (h.trans (Nat.succ_add i m)))

theorem tk_len : (l : List X) → tk (len l) l = l
  | [] => rfl
  | a :: l => congrArg (a :: ·) (tk_len l)

theorem tk_tk : (i k : Nat) → (l : List X) → tk i (tk (i + k) l) = tk i l
  | 0, _, l => by rw [tk_zero, tk_zero]
  | i + 1, k, [] => by rw [tk_nil, tk_nil]
  | i + 1, k, a :: l => by
    rw [Nat.succ_add]
    exact congrArg (a :: ·) (tk_tk i k l)

theorem dr_tk : (i k : Nat) → (l : List X) → dr i (tk (i + k) l) = tk k (dr i l)
  | 0, k, l => by rw [Nat.zero_add, dr_zero, dr_zero]
  | i + 1, k, [] => by rw [tk_nil, dr_nil, tk_nil]
  | i + 1, k, _ :: l => by
    rw [Nat.succ_add]
    exact dr_tk i k l

def hd (x0 : X) : List X → X
  | [] => x0
  | a :: _ => a

theorem split (x0 : X) : (i : Nat) → (xs : List X) → i < len xs →
    app (tk i xs) (hd x0 (tk 1 (dr i xs)) :: dr (i + 1) xs) = xs
  | 0, [], h => absurd h (Nat.not_lt_zero 0)
  | 0, a :: l, _ => by
    show a :: dr 0 l = a :: l
    rw [dr_zero]
  | _ + 1, [], h => absurd h (Nat.not_lt_zero _)
  | i + 1, a :: l, h => congrArg (a :: ·) (split x0 i l (Nat.lt_of_succ_lt_succ h))

/-! ## the endomorphism operad -/

structure Op (X : Type) where
  n : Nat
  f : List X → X

def comp (F G : Op X) (i : Nat) : Op X :=
  ⟨Nat.pred (G.n + F.n), fun xs => F.f (app (tk i xs) (G.f (tk G.n (dr i xs)) :: dr (i + G.n) xs))⟩

def unit (x0 : X) : Op X := ⟨1, hd x0⟩

def Eqv (F G : Op X) : Prop := F.n = G.n ∧ ∀ xs, len xs = F.n → F.f xs = G.f xs

theorem eqv_refl (F : Op X) : Eqv F F := ⟨rfl, fun _ _ => rfl⟩
theorem eqv_symm {F G : Op X} (h : Eqv F G) : Eqv G F := ⟨h.1.symm, fun xs hx => (h.2 xs (hx.trans h.1.symm)).symm⟩
theorem eqv_trans {F G H : Op X} (h : Eqv F G) (k : Eqv G H) : Eqv F H :=
  ⟨h.1.trans k.1, fun xs hx => (h.2 xs hx).trans (k.2 xs (hx.trans h.1))⟩

theorem unit_left (x0 : X) (G : Op X) : Eqv (comp (unit x0) G 0) G :=
  ⟨rfl, fun xs hx => by
    show hd x0 (app (tk 0 xs) (G.f (tk G.n (dr 0 xs)) :: dr (0 + G.n) xs)) = G.f xs
    have hx' : len xs = G.n := hx
    rw [tk_zero, dr_zero, ← hx', tk_len]
    rfl⟩

theorem pred_one_add (n : Nat) : Nat.pred (1 + n) = n := by
  rw [Nat.add_comm]
  rfl

theorem unit_right (x0 : X) (F : Op X) (i : Nat) (hi : i < F.n) : Eqv (comp F (unit x0) i) F :=
  ⟨pred_one_add F.n, fun xs hx => by
    have hx' : len xs = F.n := hx.trans (pred_one_add F.n)
    show F.f (app (tk i xs) (hd x0 (tk 1 (dr i xs)) :: dr (i + 1) xs)) = F.f xs
    rw [split x0 i xs (hx' ▸ hi)]⟩

theorem tk_app' (a r : List X) (k m : Nat) (h : len a = k) : tk (k + m) (app a r) = app a (tk m r) :=
  h ▸ tk_app a r m
theorem dr_app' (a r : List X) (k m : Nat) (h : len a = k) : dr (k + m) (app a r) = dr m r :=
  h ▸ dr_app a r m
theorem tk_app0' (a r : List X) (k : Nat) (h : len a = k) : tk k (app a r) = a := h ▸ tk_app0 a r
theorem dr_app0' (a r : List X) (k : Nat) (h : len a = k) : dr k (app a r) = r := h ▸ dr_app0 a r

theorem le_ex : {a b : Nat} → a ≤ b → ∃ r, b = a + r
  | _, _, .refl => ⟨0, rfl⟩
  | _, _, .step h => match le_ex h with
    | ⟨r, e⟩ => ⟨r + 1, by rw [e]; rfl⟩

/-- sequential associativity: (F ∘ᵢ G) ∘ᵢ₊ⱼ H ≈ F ∘ᵢ (G ∘ⱼ H) -/
theorem seq_assoc (F G H : Op X) (i j : Nat) (hi : i < F.n) (hj : j < G.n) :
    Eqv (comp (comp F G i) H (i + j)) (comp F (comp G H j) i) := by
  cases F with
  | mk fn ff => cases G with
    | mk gn gf => cases H with
      | mk hn hf =>
        cases fn with
        | zero => exact absurd hi (Nat.not_lt_zero _)
        | succ p => cases gn with
          | zero => exact absurd hj (Nat.not_lt_zero _)
          | succ q =>
            obtain ⟨s, hs⟩ := le_ex (Nat.le_of_lt_succ hi)
            obtain ⟨r, hr⟩ := le_ex (Nat.le_of_lt_succ hj)
            subst hs hr
            refine ⟨?_, fun xs hx => ?_⟩
            · show Nat.pred (hn + Nat.pred (j + r + 1 + (i + s + 1))) = Nat.pred (Nat.pred (hn + (j + r + 1)) + (i + s + 1))
              have e : j + r + 1 + (i + s + 1) = (j + r + 1 + (i + s)) + 1 := rfl
              rw [e]
              show Nat.pred (hn + (j + r + 1 + (i + s))) = hn + (j + r) + (i + s)
              have e2 : hn + (j + r + 1 + (i + s)) = (hn + (j + r) + (i + s)) + 1 := by lib_nat
              rw [e2]
              rfl
            · have e2 : hn + (j + r + 1 + (i + s)) = (hn + (j + r) + (i + s)) + 1 := by lib_nat
              have hx1 : len xs = Nat.pred (hn + (j + r + 1 + (i + s))) := hx
              rw [e2] at hx1
              have hx1' : len xs = hn + (j + r) + (i + s) := hx1
              have hx2 : len xs = i + (s + (hn + (j + r))) := hx1'.trans (by lib_nat)
              have lA : len (tk i xs) = i := len_tk i xs (hx2 ▸ Nat.le_add_right _ _)
              have lD : len (dr i xs) = s + (hn + (j + r)) := len_dr i _ xs hx2
              have lB : len (tk j (dr i xs)) = j :=
                len_tk j _ (by rw [lD, show s + (hn + (j + r)) = j + (s + hn + r) by lib_nat]; exact Nat.le_add_right _ _)
              -- left side
              have hy : app (tk (i + j) xs) (hf (tk hn (dr (i + j) xs)) :: dr (i + j + hn) xs)
                  = app (tk i xs) (app (tk j (dr i xs)) (hf (tk hn (dr (i + j) xs)) :: dr (i + j + hn) xs)) := by
                rw [tk_add, app_assoc]
              show ff (app (tk i _) (gf (tk (j + r + 1) (dr i _)) :: dr (i + (j + r + 1)) _)) = ff (app (tk i xs)
                (gf (app (tk j (tk (hn + (j + r)) (dr i xs))) (hf (tk hn (dr j (tk (hn + (j + r)) (dr i xs))))
                  :: dr (j + hn) (tk (hn + (j + r)) (dr i xs)))) :: dr (i + (hn + (j + r))) xs))
              rw [hy, tk_app0' _ _ i lA, dr_add i (j + r + 1), dr_app0' _ _ i lA]
              have L3 := tk_app' (tk j (dr i xs)) (hf (tk hn (dr (i + j) xs)) :: dr (i + j + hn) xs) j (r + 1) lB
              have L4 := dr_app' (tk j (dr i xs)) (hf (tk hn (dr (i + j) xs)) :: dr (i + j + hn) xs) j (r + 1) lB
              have eA : j + r + 1 = j + (r + 1) := rfl
              rw [eA, L3, L4]
              -- right side
              have z1 : hn + (j + r) = j + (r + hn) := by lib_nat
              have z2 : hn + (j + r) = (j + hn) + r := by lib_nat
              have R1 : tk j (tk (hn + (j + r)) (dr i xs)) = tk j (dr i xs) := by rw [z1, tk_tk]
              have R2 : tk hn (dr j (tk (hn + (j + r)) (dr i xs))) = tk hn (dr (i + j) xs) := by
                rw [z1, dr_tk, Nat.add_comm r hn, tk_tk, dr_add]
              have R3 : dr (j + hn) (tk (hn + (j + r)) (dr i xs)) = tk r (dr (i + j + hn) xs) := by
                rw [z2, dr_tk, ← dr_add, Nat.add_assoc]
              have R4 : dr (i + (hn + (j + r))) xs = dr r (dr (i + j + hn) xs) := by
                rw [← dr_add, show i + (hn + (j + r)) = i + j + hn + r by lib_nat]
              rw [R1, R2, R3, R4]
              rfl

/-- parallel associativity: (F ∘ₖ H) ∘ᵢ G ≈ (F ∘ᵢ G) ∘ₖ' H for i < k, k' = k + |G| - 1 -/
theorem par_assoc (F G H : Op X) (i c : Nat) (hk : i + (c + 1) < F.n) :
    Eqv (comp (comp F H (i + (c + 1))) G i) (comp (comp F G i) H (i + (G.n + c))) := by
  cases F with
  | mk fn ff => cases G with
    | mk gn gf => cases H with
      | mk hn hf =>
        cases fn with
        | zero => exact absurd hk (Nat.not_lt_zero _)
        | succ p =>
          obtain ⟨s, hs⟩ := le_ex (Nat.le_of_lt_succ hk)
          subst hs
          have aL : gn + (hn + (i + (c + 1) + s)) = (gn + hn + i + c + s) + 1 := by lib_nat
          have aR : hn + (gn + (i + (c + 1) + s)) = (gn + hn + i + c + s) + 1 := by lib_nat
          refine ⟨?_, fun xs hx => ?_⟩
          · show Nat.pred (gn + (hn + (i + (c + 1) + s))) = Nat.pred (hn + (gn + (i + (c + 1) + s)))
            rw [aL, aR]
          · have hx1 : len xs = Nat.pred (gn + (hn + (i + (c + 1) + s))) := hx
            rw [aL] at hx1
            have hx1' : len xs = gn + hn + i + c + s := hx1
            have hx2 : len xs = i + (gn + (c + hn + s)) := hx1'.trans (by lib_nat)
            have lA : len (tk i xs) = i := len_tk i xs (hx2 ▸ Nat.le_add_right _ _)
            have lD : len (dr i xs) = gn + (c + hn + s) := len_dr i _ xs hx2
            have l1 : len (tk gn (dr i xs)) = gn := len_tk gn _ (lD ▸ Nat.le_add_right _ _)
            show ff (app (tk (i + (c + 1)) (app (tk i xs) (gf (tk gn (dr i xs)) :: dr (i + gn) xs)))
                (hf (tk hn (dr (i + (c + 1)) (app (tk i xs) (gf (tk gn (dr i xs)) :: dr (i + gn) xs))))
                  :: dr (i + (c + 1) + hn) (app (tk i xs) (gf (tk gn (dr i xs)) :: dr (i + gn) xs))))
              = ff (app (tk i (app (tk (i + (gn + c)) xs) (hf (tk hn (dr (i + (gn + c)) xs)) :: dr (i + (gn + c) + hn) xs)))
                (gf (tk gn (dr i (app (tk (i + (gn + c)) xs) (hf (tk hn (dr (i + (gn + c)) xs)) :: dr (i + (gn + c) + hn) xs))))
                  :: dr (i + gn) (app (tk (i + (gn + c)) xs) (hf (tk hn (dr (i + (gn + c)) xs)) :: dr (i + (gn + c) + hn) xs))))
            -- left side
            have eL : i + (c + 1) + hn = i + ((c + hn) + 1) := by lib_nat
            rw [tk_app' _ _ i (c + 1) lA, dr_app' _ _ i (c + 1) lA, eL, dr_app' _ _ i _ lA]
            -- right side
            have hZ : app (tk (i + (gn + c)) xs) (hf (tk hn (dr (i + (gn + c)) xs)) :: dr (i + (gn + c) + hn) xs)
                = app (tk i xs) (app (tk gn (dr i xs)) (app (tk c (dr gn (dr i xs)))
                    (hf (tk hn (dr (i + (gn + c)) xs)) :: dr (i + (gn + c) + hn) xs))) := by
              rw [tk_add i (gn + c) xs, tk_add gn c (dr i xs), app_assoc, app_assoc]
            have D : ∀ l, dr (i + gn) (app (tk i xs) l) = dr gn l := fun l => by rw [dr_add, dr_app0' _ _ i lA]
            have E2 : dr (i + (gn + c)) xs = dr c (dr gn (dr i xs)) := by rw [dr_add i, dr_add gn]
            have E3 : dr (i + (gn + c) + hn) xs = dr (c + hn) (dr gn (dr i xs)) := by
              rw [show i + (gn + c) + hn = i + (gn + (c + hn)) by lib_nat, dr_add i, dr_add gn]
            rw [hZ, tk_app0' _ _ i lA, D, dr_app0' _ _ i lA, tk_app0' _ _ gn l1, dr_app0' _ _ gn l1, E2, E3, dr_add i gn xs, app_assoc]
            rfl

theorem len_app : (a b : List X) → len (app a b) = len a + len b
  | [], b => (Nat.zero_add _).symm
  | _ :: a, b => by
    show len (app a b) + 1 = len a + 1 + len b
    rw [len_app a b, Nat.succ_add]

theorem len_tk_eq (n : Nat) (l : List X) (h : len l = n) : len (tk n l) = n := len_tk n l (h ▸ Nat.le_refl _)

/-- composition respects agreement -/
theorem comp_resp {F F' G G' : Op X} (i : Nat) (hi : i < F.n) (hF : Eqv F F') (hG : Eqv G G') :
    Eqv (comp F G i) (comp F' G' i) := by
  cases F with
  | mk fn ff => cases F' with
    | mk fn' ff' => cases G with
      | mk gn gf => cases G' with
        | mk gn' gf' =>
          have e1 : fn = fn' := hF.1
          have e2 : gn = gn' := hG.1
          subst e1 e2
          cases fn with
          | zero => exact absurd hi (Nat.not_lt_zero _)
          | succ p =>
            obtain ⟨s, hs⟩ := le_ex (Nat.le_of_lt_succ hi)
            subst hs
            refine ⟨rfl, fun xs hx => ?_⟩
            have hx1 : len xs = gn + (i + s) := hx
            have hx2 : len xs = i + (gn + s) := hx1.trans (by lib_nat)
            have lA : len (tk i xs) = i := len_tk i xs (hx2 ▸ Nat.le_add_right _ _)
            have lD : len (dr i xs) = gn + s := len_dr i _ xs hx2
            have lG : len (tk gn (dr i xs)) = gn := len_tk gn _ (lD ▸ Nat.le_add_right _ _)
            have lR : len (dr (i + gn) xs) = s := len_dr (i + gn) s xs (hx2.trans (Nat.add_assoc _ _ _).symm)
            show ff (app (tk i xs) (gf (tk gn (dr i xs)) :: dr (i + gn) xs))
              = ff' (app (tk i xs) (gf' (tk gn (dr i xs)) :: dr (i + gn) xs))
            have hg : gf (tk gn (dr i xs)) = gf' (tk gn (dr i xs)) := hG.2 _ lG
            rw [hg]
            refine hF.2 _ ?_
            show len (app (tk i xs) (gf' (tk gn (dr i xs)) :: dr (i + gn) xs)) = i + s + 1
            rw [len_app, lA]
            show i + (len (dr (i + gn) xs) + 1) = i + s + 1
            rw [lR]
            rfl

/-! ## operads and algebras -/

/-- a (planar) operad in the partial-composition presentation -/
structure Operad where
  Op : Type
  ar : Op → Nat
  e : Op
  comp : Op → Op → Nat → Op
  eqv : Op → Op → Prop
  refl : ∀ F, eqv F F
  symm : ∀ {F G}, eqv F G → eqv G F
  trans : ∀ {F G H}, eqv F G → eqv G H → eqv F H
  ar_e : ar e = 1
  ar_comp : ∀ F G i, i < ar F → ar (comp F G i) = Nat.pred (ar G + ar F)
  resp : ∀ {F F' G G'} i, i < ar F → eqv F F' → eqv G G' → eqv (comp F G i) (comp F' G' i)
  unit_l : ∀ G, eqv (comp e G 0) G
  unit_r : ∀ F i, i < ar F → eqv (comp F e i) F
  seq : ∀ F G H i j, i < ar F → j < ar G → eqv (comp (comp F G i) H (i + j)) (comp F (comp G H j) i)
  par : ∀ F G H i c, i + (c + 1) < ar F →
    eqv (comp (comp F H (i + (c + 1))) G i) (comp (comp F G i) H (i + (ar G + c)))

/-- the endomorphism operad of X (x0 only fills the unused default of the unit) -/
def End (x0 : X) : Operad where
  Op := Op X
  ar F := F.n
  e := unit x0
  comp := comp
  eqv := Eqv
  refl := eqv_refl
  symm := eqv_symm
  trans := eqv_trans
  ar_e := rfl
  ar_comp _ _ _ _ := rfl
  resp i hi hF hG := comp_resp i hi hF hG
  unit_l := unit_left x0
  unit_r := unit_right x0
  seq := seq_assoc
  par := par_assoc

/-- an algebra of an operad on X: a law-preserving map into End X -/
structure Alg (O : Operad) (X : Type) (x0 : X) where
  act : O.Op → Op X
  ar : ∀ F, (act F).n = O.ar F
  resp : ∀ {F G}, O.eqv F G → Eqv (act F) (act G)
  unit : Eqv (act O.e) (Opd.unit x0)
  comp : ∀ F G i, i < O.ar F → Eqv (act (O.comp F G i)) (Opd.comp (act F) (act G) i)

/-- End X is an algebra over itself (on X) -/
def tautological (x0 : X) : Alg (End x0) X x0 where
  act F := F
  ar _ := rfl
  resp h := h
  unit := eqv_refl _
  comp _ _ _ _ := eqv_refl _

end Opd

end Found

#print axioms Found.Opd.split
#print axioms Found.Opd.unit_left
#print axioms Found.Opd.unit_right
#print axioms Found.Opd.seq_assoc
#print axioms Found.Opd.par_assoc
#print axioms Found.Opd.comp_resp
#print axioms Found.Opd.End
#print axioms Found.Opd.tautological

#print axioms: 8 theorems, no axioms.

85.138 Double categories

Double categories with horizontal and vertical pasting and the interchange law; the commutative squares of any category form one.

\[ f ; v \approx u ; g \ \text {and}\ f' ; w \approx v ; g' \Rightarrow (f;f') ; w \approx u ; (g;g') \]

found/DoubleCat.lean

/-
  T193 line. found/DoubleCat — double categories as a point: objects,
  horizontal and vertical arrows (two category structures on the same
  objects) and squares with horizontal and vertical pasting, unital and
  satisfying the interchange law, up to a square equivalence.
  * Sq(C): every E-category C gives the double category of commutative
    squares (Ehresmann's quintets of a 1-category), whose horizontal and
    vertical arrows are both arrows of C; pasting is the commutativity of
    the composite rectangle, proved by rewriting along associativity.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Base

namespace Found

namespace Dbl

universe u v w

structure DoubleCat where
  Ob : Type u
  H : Ob → Ob → Type v
  V : Ob → Ob → Type v
  hc : {a b c : Ob} → H a b → H b c → H a c
  vc : {a b c : Ob} → V a b → V b c → V a c
  hid : (a : Ob) → H a a
  vid : (a : Ob) → V a a
  /-- squares with top f, bottom g, left u, right v -/
  Sq : {a b c d : Ob} → H a b → H c d → V a c → V b d → Type w
  sqeq : {a b c d : Ob} → {f : H a b} → {g : H c d} → {u : V a c} → {v : V b d} →
    Sq f g u v → Sq f g u v → Prop
  hpaste : {a b c d e f' : Ob} → {f : H a b} → {f₂ : H b e} → {g : H c d} → {g₂ : H d f'} →
    {u : V a c} → {v : V b d} → {w' : V e f'} →
    Sq f g u v → Sq f₂ g₂ v w' → Sq (hc f f₂) (hc g g₂) u w'
  vpaste : {a b c d c' d' : Ob} → {f : H a b} → {g : H c d} → {k : H c' d'} →
    {u : V a c} → {v : V b d} → {u₂ : V c c'} → {v₂ : V d d'} →
    Sq f g u v → Sq g k u₂ v₂ → Sq f k (vc u u₂) (vc v v₂)
  interchange : ∀ {a b e c d f' c' d' e' : Ob}
    {f : H a b} {f₂ : H b e} {g : H c d} {g₂ : H d f'} {k : H c' d'} {k₂ : H d' e'}
    {u : V a c} {v : V b d} {w' : V e f'} {u₂ : V c c'} {v₂ : V d d'} {w₂ : V f' e'}
    (α : Sq f g u v) (β : Sq f₂ g₂ v w') (γ : Sq g k u₂ v₂) (δ : Sq g₂ k₂ v₂ w₂),
    sqeq (vpaste (hpaste α β) (hpaste γ δ)) (hpaste (vpaste α γ) (vpaste β δ))

variable (C : ECat.{u, v})

/-- a commutative square f ; v ≈ u ; g -/
structure CSq {a b c d : C.Ob} (f : C.Hom a b) (g : C.Hom c d) (u : C.Hom a c) (v : C.Hom b d) : Type where
  comm : C.heq (C.comp f v) (C.comp u g)

theorem h_comm {a b c d e f' : C.Ob} {f : C.Hom a b} {f₂ : C.Hom b e} {g : C.Hom c d} {g₂ : C.Hom d f'}
    {u : C.Hom a c} {v : C.Hom b d} {w : C.Hom e f'}
    (α : C.heq (C.comp f v) (C.comp u g)) (β : C.heq (C.comp f₂ w) (C.comp v g₂)) :
    C.heq (C.comp (C.comp f f₂) w) (C.comp u (C.comp g g₂)) :=
  C.htrans (C.assoc f f₂ w)
    (C.htrans (C.comp_resp (C.hrefl f) β)
      (C.htrans (C.hsymm (C.assoc f v g₂))
        (C.htrans (C.comp_resp α (C.hrefl g₂)) (C.assoc u g g₂))))

theorem v_comm {a b c d c' d' : C.Ob} {f : C.Hom a b} {g : C.Hom c d} {k : C.Hom c' d'}
    {u : C.Hom a c} {v : C.Hom b d} {u₂ : C.Hom c c'} {v₂ : C.Hom d d'}
    (α : C.heq (C.comp f v) (C.comp u g)) (γ : C.heq (C.comp g v₂) (C.comp u₂ k)) :
    C.heq (C.comp f (C.comp v v₂)) (C.comp (C.comp u u₂) k) :=
  C.htrans (C.hsymm (C.assoc f v v₂))
    (C.htrans (C.comp_resp α (C.hrefl v₂))
      (C.htrans (C.assoc u g v₂)
        (C.htrans (C.comp_resp (C.hrefl u) γ) (C.hsymm (C.assoc u u₂ k)))))

/-- the double category of commutative squares of C -/
def Sq' : DoubleCat.{u, v, 0} where
  Ob := C.Ob
  H := C.Hom
  V := C.Hom
  hc := C.comp
  vc := C.comp
  hid := C.id
  vid := C.id
  Sq f g u v := CSq C f g u v
  sqeq _ _ := True
  hpaste α β := ⟨h_comm C α.comm β.comm⟩
  vpaste α γ := ⟨v_comm C α.comm γ.comm⟩
  interchange _ _ _ _ := trivial

/-- identity squares: the horizontal identity square on a vertical arrow -/
def hidSq {a c : C.Ob} (u : C.Hom a c) : CSq C (C.id a) (C.id c) u u :=
  ⟨C.htrans (C.id_comp u) (C.hsymm (C.comp_id u))⟩

def vidSq {a b : C.Ob} (f : C.Hom a b) : CSq C f f (C.id a) (C.id b) :=
  ⟨C.htrans (C.comp_id f) (C.hsymm (C.id_comp f))⟩

end Dbl

end Found

#print axioms Found.Dbl.h_comm
#print axioms Found.Dbl.v_comm
#print axioms Found.Dbl.Sq'
#print axioms Found.Dbl.hidSq
#print axioms Found.Dbl.vidSq

#print axioms: 5 theorems, no axioms.

85.139 New Foundations (NF): the tangled-type construction in the classical point

NF is Quine’s set theory with stratified comprehension; this construction follows its consistency proof (Holmes–Wilshaw, con-nf) at the classical point. Atoms, litters, near-litters, paths, allowable permutations, codes, alternative extensions, supports and t-sets over a parameter value (\(\kappa =\omega _1\), \(\mu =\beth _{\omega _1}\)); the recursion step reduces to the orbit count, with freedom of action proved.

\[ \mathrm {Allowable}(\pi )\wedge \mathrm {Allowable}(\rho )\Rightarrow \mathrm {Allowable}(\pi \rho ),\qquad A_\gamma (\pi \cdot c)=\pi \cdot A_\gamma (c). \]

found/NFStruct.lean

/-
  T106 (b), slice N4b. found/NFStruct — paths, structural permutations,
  allowable permutations and supports of the tangled-type construction
  (con-nf), over a parameter value P (found/NFParamsO), in the classical point:
  * paths from a type level α down to the base, descending along ltΛ;
  * structural permutations at α: a base permutation for every path, with
    the group laws pointwise, and derivatives along β < α;
  * small sets: closed under injections, images by base permutations,
    and symmetric differences compose (near-litter transitivity);
  * allowable permutations at α, given lower tangle data at every β < α
    (tangles, an action, and an f-map `fuzz` into litters): the derivatives
    are allowable and the f-maps are respected up to small differences;
    allowable permutations contain 1 and are closed under products and
    inverses;
  * supports: a small set of addresses (path, atom) whose pointwise fixer
    fixes the object; the image of a support under π supports π • x.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.NFBase

namespace Found

namespace NFS

open CP WO Card NFP NFPO NFB

variable (K : Classical') (P : ParamsO)

/-! ## paths and structural permutations -/

inductive Path (P : ParamsO) : P.Λ → Type where
  | bot (α : P.Λ) : Path P α
  | cons {α : P.Λ} (β : P.Λ) (h : P.ltΛ β α) (p : Path P β) : Path P α

def StrPerm (α : P.Λ) : Type := Path P α → BPerm P

def SOne (α : P.Λ) : StrPerm P α := fun _ => BPerm.one P
def SMul {α : P.Λ} (π ρ : StrPerm P α) : StrPerm P α := fun A => BPerm.mul P (π A) (ρ A)
def SInv {α : P.Λ} (π : StrPerm P α) : StrPerm P α := fun A => BPerm.inv P (π A)

/-- pointwise equality of structural permutations -/
def SEq {α : P.Λ} (π ρ : StrPerm P α) : Prop := ∀ A a, (π A).f a = (ρ A).f a

theorem smul_assoc {α : P.Λ} (π ρ σ : StrPerm P α) : SEq P (SMul P (SMul P π ρ) σ) (SMul P π (SMul P ρ σ)) :=
  fun _ _ => rfl
theorem sone_mul {α : P.Λ} (π : StrPerm P α) : SEq P (SMul P (SOne P α) π) π := fun _ _ => rfl
theorem smul_one {α : P.Λ} (π : StrPerm P α) : SEq P (SMul P π (SOne P α)) π := fun _ _ => rfl
theorem smul_inv {α : P.Λ} (π : StrPerm P α) : SEq P (SMul P π (SInv P π)) (SOne P α) := fun A a => (π A).gf a
theorem sinv_mul {α : P.Λ} (π : StrPerm P α) : SEq P (SMul P (SInv P π) π) (SOne P α) := fun A a => (π A).fg a

/-- the derivative along β < α -/
def deriv {α β : P.Λ} (π : StrPerm P α) (h : P.ltΛ β α) : StrPerm P β := fun A => π (.cons β h A)

theorem deriv_one {α β : P.Λ} (h : P.ltΛ β α) : deriv P (SOne P α) h = SOne P β := rfl
theorem deriv_mul {α β : P.Λ} (π ρ : StrPerm P α) (h : P.ltΛ β α) :
    deriv P (SMul P π ρ) h = SMul P (deriv P π h) (deriv P ρ h) := rfl
theorem deriv_inv {α β : P.Λ} (π : StrPerm P α) (h : P.ltΛ β α) :
    deriv P (SInv P π) h = SInv P (deriv P π h) := rfl

/-! ## small sets -/

theorem small_of_inj {A B : Type} (f : A → B) (hf : Inj f) (hB : Small P B) : Small P A :=
  match hB.1 with
  | ⟨g, hg⟩ => ⟨⟨fun a => g (f a), fun _ _ e => hf _ _ (hg _ _ e)⟩,
      fun ⟨k, hk⟩ => hB.2 ⟨fun x => f (k x), fun _ _ e => hk _ _ (hf _ _ e)⟩⟩

theorem symm_small (S T : Atom P → Prop) (h : Small P (SymDiff P S T)) : Small P (SymDiff P T S) :=
  small_of_inj P (fun x => ⟨x.val, x.property.elim Or.inr Or.inl⟩) (fun x y e => Subtype.ext (by have e' := congrArg Subtype.val e; exact e')) h

theorem congr_small (S S' T : Atom P → Prop) (e : ∀ a, S a ↔ S' a) (h : Small P (SymDiff P S T)) :
    Small P (SymDiff P S' T) :=
  small_of_inj P (fun x => ⟨x.val, x.property.elim (fun h => Or.inl ⟨(e _).2 h.1, h.2⟩)
      (fun h => Or.inr ⟨h.1, fun h' => h.2 ((e _).1 h')⟩)⟩)
    (fun x y e => Subtype.ext (by have e' := congrArg Subtype.val e; exact e')) h

/-- the atom underlying an element of a sum of two symmetric differences -/
def proj {S T U V : Atom P → Prop} : SymDiff P S T ⊕ SymDiff P U V → Atom P
  | .inl x => x.val
  | .inr x => x.val

include K in
/-- near-litter transitivity: S Δ U ⊆ (S Δ T) ∪ (T Δ U) -/
theorem trans_small (S T U : Atom P → Prop) (h1 : Small P (SymDiff P S T)) (h2 : Small P (SymDiff P T U)) :
    Small P (SymDiff P S U) := by
  have ex : ∀ x : SymDiff P S U, ∃ s : SymDiff P S T ⊕ SymDiff P T U, proj P s = x.val := fun x =>
    (K.lem (T x.val)).elim
      (fun ht => x.property.elim (fun h => ⟨.inr ⟨x.val, Or.inl ⟨ht, h.2⟩⟩, rfl⟩)
        (fun h => ⟨.inl ⟨x.val, Or.inr ⟨ht, h.2⟩⟩, rfl⟩))
      (fun hn => x.property.elim (fun h => ⟨.inl ⟨x.val, Or.inl ⟨h.1, hn⟩⟩, rfl⟩)
        (fun h => ⟨.inr ⟨x.val, Or.inr ⟨h.1, hn⟩⟩, rfl⟩))
  have hs := small_sum K P _ _ h1 h2
  exact small_of_inj P (fun x => K.ch (fun s => proj P s = x.val) (ex x)) (fun x y e => by
    have hx := K.ch_spec (fun s => proj P s = x.val) (ex x)
    have hy := K.ch_spec (fun s => proj P s = y.val) (ex y)
    have e' : K.ch (fun s => proj P s = x.val) (ex x) = K.ch (fun s => proj P s = y.val) (ex y) := e
    rw [e'] at hx
    exact Subtype.ext (hx.symm.trans hy)) hs

/-- images under a base permutation preserve small symmetric differences -/
theorem img_small (π : BPerm P) (S T : Atom P → Prop) (h : Small P (SymDiff P S T)) :
    Small P (SymDiff P (img P π.g S) (img P π.g T)) :=
  small_of_inj P (fun x => ⟨π.g x.val, x.property⟩) (fun x y e => Subtype.ext (by
    have e' : π.g x.val = π.g y.val := congrArg Subtype.val e
    have := congrArg π.f e'
    rw [π.fg, π.fg] at this
    exact this)) h

theorem img_img (π : BPerm P) (S : Atom P → Prop) (a : Atom P) : img P π.f (img P π.g S) a ↔ S a := by
  show S (π.g (π.f a)) ↔ S a
  rw [π.gf]

/-! ## lower tangle data and allowable permutations -/

/-- a set S of atoms is near the litter i -/
def NearTo (S : Atom P → Prop) (i : P.μ) : Prop := Small P (SymDiff P S (litter P i))

/-- tangle data at a lower level β: tangles with an equivalence (their equality), allowable
  permutations acting on them (laws for allowable permutations, up to the equivalence), f-map -/
structure Lower (β : P.Λ) where
  T : Type
  eqv : T → T → Prop
  eqv_refl : ∀ t, eqv t t
  eqv_symm : ∀ {t t'}, eqv t t' → eqv t' t
  eqv_trans : ∀ {t t' t''}, eqv t t' → eqv t' t'' → eqv t t''
  act : StrPerm P β → T → T
  Allow : StrPerm P β → Prop
  allow_one : Allow (SOne P β)
  allow_mul : ∀ π ρ, Allow π → Allow ρ → Allow (SMul P π ρ)
  allow_inv : ∀ π, Allow π → Allow (SInv P π)
  allow_ext : ∀ π ρ, SEq P π ρ → Allow π → Allow ρ
  act_resp : ∀ π, Allow π → ∀ {t t'}, eqv t t' → eqv (act π t) (act π t')
  act_ext : ∀ π ρ, Allow π → Allow ρ → SEq P π ρ → ∀ t, eqv (act π t) (act ρ t)
  act_one : ∀ t, eqv (act (SOne P β) t) t
  act_mul : ∀ π ρ, Allow π → Allow ρ → ∀ t, eqv (act (SMul P π ρ) t) (act ρ (act π t))
  fuzz : T → P.μ
  fuzz_resp : ∀ {t t'}, eqv t t' → fuzz t = fuzz t'

variable {P}

/-- the base permutation acting on the litters at level γ < α -/
def atLit {α γ : P.Λ} (π : StrPerm P α) (h : P.ltΛ γ α) : BPerm P := π (.cons γ h (.bot γ))

/-- allowable permutations at α, given lower data L at every β < α -/
def Allowable {α : P.Λ} (L : ∀ β, P.ltΛ β α → Lower P β) (π : StrPerm P α) : Prop :=
  (∀ β h, (L β h).Allow (deriv P π h)) ∧
  (∀ β hβ γ (hγ : P.ltΛ γ α), β ≠ γ → ∀ t : (L β hβ).T,
    NearTo P (img P (atLit π hγ).g (litter P ((L β hβ).fuzz t))) ((L β hβ).fuzz ((L β hβ).act (deriv P π hβ) t)))

include K in
theorem allowable_one {α : P.Λ} (L : ∀ β, P.ltΛ β α → Lower P β) : Allowable L (SOne P α) :=
  ⟨fun β h => (L β h).allow_one, fun β hβ γ hγ _ t => by
    show Small P (SymDiff P (litter P ((L β hβ).fuzz t)) (litter P ((L β hβ).fuzz ((L β hβ).act (SOne P β) t))))
    rw [(L β hβ).fuzz_resp ((L β hβ).act_one t)]
    exact small_empty K P _ (symm_self_empty P _)⟩

include K in
theorem allowable_mul {α : P.Λ} (L : ∀ β, P.ltΛ β α → Lower P β) (π ρ : StrPerm P α)
    (hπ : Allowable L π) (hρ : Allowable L ρ) : Allowable L (SMul P π ρ) :=
  ⟨fun β h => (L β h).allow_mul _ _ (hπ.1 β h) (hρ.1 β h), fun β hβ γ hγ ne t => by
    let Lb := L β hβ
    have e1 := img_small P (atLit ρ hγ) _ _ (hπ.2 β hβ γ hγ ne t)
    have e2 := hρ.2 β hβ γ hγ ne (Lb.act (deriv P π hβ) t)
    have e3 := trans_small K P _ _ _ e1 e2
    show Small P (SymDiff P (img P (atLit ρ hγ).g (img P (atLit π hγ).g (litter P (Lb.fuzz t))))
      (litter P (Lb.fuzz (Lb.act (SMul P (deriv P π hβ) (deriv P ρ hβ)) t))))
    rw [Lb.fuzz_resp (Lb.act_mul _ _ (hπ.1 β hβ) (hρ.1 β hβ) t)]
    exact e3⟩

theorem allowable_inv {α : P.Λ} (L : ∀ β, P.ltΛ β α → Lower P β) (π : StrPerm P α)
    (hπ : Allowable L π) : Allowable L (SInv P π) :=
  ⟨fun β h => (L β h).allow_inv _ (hπ.1 β h), fun β hβ γ hγ ne t => by
    let Lb := L β hβ
    let s := Lb.act (SInv P (deriv P π hβ)) t
    have back : Lb.fuzz (Lb.act (deriv P π hβ) s) = Lb.fuzz t := by
      have hd := hπ.1 β hβ
      have hi := Lb.allow_inv _ hd
      exact Lb.fuzz_resp (Lb.eqv_trans (Lb.eqv_symm (Lb.act_mul _ _ hi hd t))
        (Lb.eqv_trans (Lb.act_ext _ (SOne P β) (Lb.allow_mul _ _ hi hd) Lb.allow_one (sinv_mul P _) t) (Lb.act_one t)))
    have e1 := hπ.2 β hβ γ hγ ne s
    rw [back] at e1
    have e2 := img_small P (BPerm.inv P (atLit π hγ)) _ _ e1
    have e3 := congr_small P _ _ _ (img_img P (atLit π hγ) (litter P (Lb.fuzz s))) e2
    exact symm_small P _ _ e3⟩

/-! ## supports -/

abbrev Addr (α : P.Λ) : Type := Path P α × Atom P

def actA {α : P.Λ} (π : StrPerm P α) (s : Addr α) : Addr α := (s.1, (π s.1).f s.2)

/-- a type with an action of structural permutations at α -/
structure Act (α : P.Λ) where
  X : Type
  act : StrPerm P α → X → X
  act_ext : ∀ π ρ, SEq P π ρ → ∀ x, act π x = act ρ x
  act_mul : ∀ π ρ x, act (SMul P π ρ) x = act ρ (act π x)

def Supports {α : P.Λ} (M : Act α) (S : Addr α → Prop) (x : M.X) : Prop :=
  Small P {s // S s} ∧ ∀ π, (∀ s, S s → actA π s = s) → M.act π x = x

/-- the image of a set of addresses under π -/
def imgA {α : P.Λ} (π : StrPerm P α) (S : Addr α → Prop) : Addr α → Prop := fun s => S (actA (SInv P π) s)

theorem actA_inv {α : P.Λ} (π : StrPerm P α) (s : Addr α) : actA (SInv P π) (actA π s) = s := by
  show (s.1, (π s.1).g ((π s.1).f s.2)) = s
  rw [(π s.1).gf]

theorem actA_inv' {α : P.Λ} (π : StrPerm P α) (s : Addr α) : actA π (actA (SInv P π) s) = s := by
  show (s.1, (π s.1).f ((π s.1).g s.2)) = s
  rw [(π s.1).fg]

theorem actA_mul {α : P.Λ} (π ρ : StrPerm P α) (s : Addr α) : actA (SMul P π ρ) s = actA ρ (actA π s) := rfl

/-- if S supports x then π S supports π • x -/
theorem supports_act {α : P.Λ} (M : Act α) (S : Addr α → Prop) (x : M.X) (h : Supports M S x)
    (π : StrPerm P α) : Supports M (imgA π S) (M.act π x) := by
  refine ⟨small_of_inj P (fun s => ⟨actA (SInv P π) s.val, s.property⟩) (fun s t e => Subtype.ext (by
    have e' : actA (SInv P π) s.val = actA (SInv P π) t.val := congrArg Subtype.val e
    have := congrArg (actA π) e'
    rw [actA_inv', actA_inv'] at this
    exact this)) h.1, fun ρ hρ => ?_⟩
  let σ := SMul P (SMul P π ρ) (SInv P π)
  have fix : ∀ s, S s → actA σ s = s := fun s hs => by
    have hs' : imgA π S (actA π s) := by
      show S (actA (SInv P π) (actA π s))
      rw [actA_inv]
      exact hs
    show actA (SInv P π) (actA ρ (actA π s)) = s
    rw [hρ _ hs', actA_inv]
  have hσ := h.2 σ fix
  have e : SEq P (SMul P σ π) (SMul P π ρ) := fun A a => by
    show (π A).f ((π A).g ((ρ A).f ((π A).f a))) = (ρ A).f ((π A).f a)
    rw [(π A).fg]
  rw [← M.act_mul, ← M.act_ext _ _ e, M.act_mul, hσ]

end NFS

end Found

#print axioms Found.NFS.smul_assoc
#print axioms Found.NFS.smul_inv
#print axioms Found.NFS.sinv_mul
#print axioms Found.NFS.deriv_mul
#print axioms Found.NFS.deriv_inv
#print axioms Found.NFS.small_of_inj
#print axioms Found.NFS.symm_small
#print axioms Found.NFS.congr_small
#print axioms Found.NFS.trans_small
#print axioms Found.NFS.img_small
#print axioms Found.NFS.img_img
#print axioms Found.NFS.allowable_one
#print axioms Found.NFS.allowable_mul
#print axioms Found.NFS.allowable_inv
#print axioms Found.NFS.actA_inv
#print axioms Found.NFS.supports_act

#print axioms: 16 theorems, no axioms.

85.140 NBG and ZF, NBG and ZFC

Definable classes over a model of ZF form a model of NBG, and the sets of a model of NBG form a model of ZF; with completeness for infinite theories, both prove the same set-theoretic sentences, also with choice.

\[ \mathrm {NBG} \vdash \varphi ^{M} \Leftrightarrow \mathrm {ZF} \vdash \varphi ,\qquad \mathrm {NBG}+\mathrm {AC} \vdash \varphi ^{M} \Leftrightarrow \mathrm {ZFC} \vdash \varphi \]

found/NbgZ7.lean

/-
  T91, NBG over ZF, part 7. found/NbgZ7 — the easy direction and the
  equivalences:
  * the sets of any model of NBG(B) form a model of ZF(B) (B containing
    pairing): extensionality from class extensionality, the base axioms by
    relativisation, foundation from comprehension and class foundation,
    replacement from comprehension (the class of pairs ⟨w, z⟩ with w ∈ x and
    θ(w, z)), Kuratowski pairs and class replacement;
  * hence every ZF(B) theorem relativised to sets is an NBG(B) theorem
    (B containing pairing and infinity, φ a sentence);
  * NBG ↔ ZF and NBG ↔ ZFC: for every sentence φ of the language of set
    theory, NBG ⊢ φ^M iff ZF ⊢ φ (and with choice in the base).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.NbgZ6

namespace Found

namespace NBGc

open FO FOCT

/-! ## the replacement and foundation schemes, read semantically -/

section E

variable {E : Type} (R : Nat → List E → Prop)

theorem replZ_intro (θ : Fm) (pF : Nat → E)
    (H : ∀ x, (∀ w, mem R w x → ∀ z z', Sat R θ (ext (ext pF z) w) → Sat R θ (ext (ext pF z') w) → Ceq R z z') →
      ∃ y, ∀ z, mem R z y ↔ ∃ w, mem R w x ∧ Sat R θ (ext (ext pF z) w)) :
    Sat R (replZ θ) pF := fun x hpre =>
  have eA : ∀ w z z', Sat R (ren (r3 2 1) θ) (ext (ext (ext (ext pF x) w) z) z') ↔ Sat R θ (ext (ext pF z) w) :=
    fun _ _ _ => (sat_ren R θ _ _).trans (sat_ext R θ (fun n => match n with
      | 0 => rfl
      | 1 => rfl
      | _ + 2 => rfl))
  have eB : ∀ w z z', Sat R (ren (r3 2 0) θ) (ext (ext (ext (ext pF x) w) z) z') ↔ Sat R θ (ext (ext pF z') w) :=
    fun _ _ _ => (sat_ren R θ _ _).trans (sat_ext R θ (fun n => match n with
      | 0 => rfl
      | 1 => rfl
      | _ + 2 => rfl))
  have eC : ∀ y z w, Sat R (ren (r3 0 1) θ) (ext (ext (ext (ext pF x) y) z) w) ↔ Sat R θ (ext (ext pF z) w) :=
    fun _ _ _ => (sat_ren R θ _ _).trans (sat_ext R θ (fun n => match n with
      | 0 => rfl
      | 1 => rfl
      | _ + 2 => rfl))
  match H x (fun w hw z z' h1 h2 => c2 R (hpre w hw z z' ⟨(eA w z z').2 h1, (eB w z z').2 h2⟩)) with
  | ⟨y, hy⟩ => ⟨y, fun z =>
    ⟨fun hz => match (hy z).1 hz with
      | ⟨w, h1, h2⟩ => ⟨w, h1, (eC y z w).2 h2⟩,
     fun ⟨w, h1, h2⟩ => (hy z).2 ⟨w, h1, (eC y z w).1 h2⟩⟩⟩

theorem foundZ_intro (θ : Fm) (pF : Nat → E)
    (H : (∃ x, Sat R θ (ext pF x)) → ∃ x, Sat R θ (ext pF x) ∧ ∀ y, mem R y x → ¬ Sat R θ (ext pF y)) :
    Sat R (foundZ θ) pF := fun hx =>
  have e : ∀ x y, Sat R (ren (up Nat.succ) θ) (ext (ext pF x) y) ↔ Sat R θ (ext pF y) := fun _ _ =>
    (sat_ren R θ _ _).trans (sat_ext R θ (fun n => match n with
      | 0 => rfl
      | _ + 1 => rfl))
  match H hx with
  | ⟨x, h1, h2⟩ => ⟨x, h1, fun y hy ht => h2 y hy ((e x y).1 ht)⟩

end E

/-- the class of pairs: ψ(p) = ∃w (w ∈ x ∧ ∃z (p = ⟨w, z⟩ ∧ θ(w, z))), variable 1 = x -/
def psiZ (θ : Fm) : Fm := .ex (.conj (m 0 2) (.ex (.conj (ren (opσ 2 1 0) OPz) (ren (r3 1 0) θ))))

theorem l0_psiZ {θ : Fm} (h : L0 θ) : L0 (psiZ θ) :=
  ⟨l0_m 0 2, l0_ren _ OPz l0_OPz, l0_ren _ θ h⟩

section D

variable {D : Type} (R : Nat → List D → Prop) {B : Fm → Prop}

theorem psiZ_sat (θ : Fm) (v : Nat → St R) (x p : St R) :
    Sat (Rs R) (psiZ θ) (ext (ext v x) p) ↔
      ∃ a, mem (Rs R) a x ∧ ∃ z, OPs (Rs R) p a z ∧ Sat (Rs R) θ (ext (ext v z) a) :=
  have e1 : ∀ a z, Sat (Rs R) (ren (opσ 2 1 0) OPz) (ext (ext (ext (ext v x) p) a) z) ↔ OPs (Rs R) p a z :=
    fun _ _ => (sat_ren (Rs R) OPz _ _).trans (sat_ext (Rs R) OPz (fun n => match n with
      | 0 => rfl
      | 1 => rfl
      | 2 => rfl
      | _ + 3 => rfl))
  have e2 : ∀ a z, Sat (Rs R) (ren (r3 1 0) θ) (ext (ext (ext (ext v x) p) a) z) ↔
      Sat (Rs R) θ (ext (ext v z) a) :=
    fun _ _ => (sat_ren (Rs R) θ _ _).trans (sat_ext (Rs R) θ (fun n => match n with
      | 0 => rfl
      | 1 => rfl
      | _ + 2 => rfl))
  ⟨fun ⟨a, ha, z, h1, h2⟩ => ⟨a, ha, z, (e1 a z).1 h1, (e2 a z).1 h2⟩,
   fun ⟨a, ha, z, h1, h2⟩ => ⟨a, ha, z, (e1 a z).2 h1, (e2 a z).2 h2⟩⟩

/-- comprehension in an arbitrary structure -/
theorem comp_gen (p : PF) (w : Nat → D) (h : Sat R (compAx p) w) :
    ∃ Y, ∀ X, R 1 [X] → (R 0 [X, Y] ↔ Sat R (emb p) (ext w X)) :=
  match h with
  | ⟨Y, hY⟩ => ⟨Y, fun X hX =>
    have e : Sat R (ren σc (emb p)) (ext (ext w Y) X) ↔ Sat R (emb p) (ext w X) :=
      (sat_ren R (emb p) σc _).trans (sat_ext R (emb p) (fun n => match n with
        | 0 => rfl
        | _ + 1 => rfl))
    ⟨fun h1 => e.1 ((hY X hX).1 h1), fun h2 => (hY X hX).2 (e.2 h2)⟩⟩

/-- comprehension for an L0 formula, read on the sets -/
theorem comp_set (hN : ModT (NBG B) R) (θ : Fm) (hl : L0 θ) (v : Nat → St R) :
    ∃ Y, ∀ s : St R, R 0 [s.1, Y] ↔ Sat (Rs R) θ (ext v s) :=
  match comp_gen R (pf θ) (fun n => (v n).1) (hN _ (.inr (.inr (.inr (.inl ⟨pf θ, rfl⟩)))) _) with
  | ⟨Y, hY⟩ => ⟨Y, fun s => (hY s.1 s.2).trans
      (rel_back R θ hl (ext (fun n => (v n).1) s.1) (ext v s) (ext_val R (fun _ => rfl) s))⟩

theorem setM (hN : ModT (NBG B) R) (w : Nat → D) {X Y : D} (h : R 0 [X, Y]) : R 1 [X] :=
  ((hN setAx (.inr (.inl rfl)) w) X).2 ⟨Y, h⟩

theorem extD_sets (hN : ModT (NBG B) R) (w : Nat → D) : ExtD (Rs R) := fun x y z hc hm =>
  (hN extAx (.inl rfl) w) x.1 y.1
    (fun U => ⟨fun h => (hc ⟨U, setM R hN w h⟩).1 h, fun h => (hc ⟨U, setM R hN w h⟩).2 h⟩) z.1 hm

/-- the sets of a model of NBG(B) form a model of ZF(B) -/
theorem sets_ZF (hB : Base B) (hpB : B pairAx) (hN : ModT (NBG B) R) : ModT (ZF B) (Rs R) := fun φ hφ v =>
  have w : Nat → D := fun n => (v n).1
  have hE : ExtD (Rs R) := extD_sets R hN w
  have hbase : ∀ β, B β → ∀ v' : Nat → St R, Sat (Rs R) β v' := fun β hb v' =>
    (rel_back R β (hB β hb).1 (fun n => (v' n).1) v' (fun _ => rfl)).1
      (hN _ (.inr (.inr (.inl ⟨β, hb, rfl⟩))) _)
  have hP : Pairing (Rs R) := pairing_of (Rs R) (hbase pairAx hpB v)
  match hφ with
  | .inl e => by
    rw [e]
    exact fun x y hc z hm => hE x y z (c2 (Rs R) hc) hm
  | .inr (.inl hb) => hbase φ hb v
  | .inr (.inr (.inl ⟨θ, hl, e⟩)) => by
    rw [e]
    exact replZ_intro (Rs R) θ v (fun x pre =>
      -- the class F of pairs ⟨a, z⟩ with a ∈ x and θ(a, z)
      match comp_set R hN (psiZ θ) (l0_psiZ hl) (ext v x) with
      | ⟨F, hF⟩ =>
        have inF : ∀ p : St R, R 0 [p.1, F] ↔
            ∃ a, mem (Rs R) a x ∧ ∃ z, OPs (Rs R) p a z ∧ Sat (Rs R) θ (ext (ext v z) a) :=
          fun p => (hF p).trans (psiZ_sat R θ v x p)
        have thC : ∀ a a' z z', Ceq (Rs R) a a' → Ceq (Rs R) z z' → Sat (Rs R) θ (ext (ext v z) a) →
            Sat (Rs R) θ (ext (ext v z') a') := fun a a' z z' ha hz ht =>
          sat_ceq (Rs R) hE θ hl (v := ext (ext v z) a) (w := ext (ext v z') a') (fun n => match n with
            | 0 => ha
            | 1 => hz
            | _ + 2 => ceq_refl (Rs R) _) ht
        have opD : ∀ (P W Z : St R), Sat R (relE OPz) (tri P.1 W.1 Z.1) ↔ OPs (Rs R) P W Z := fun P W Z =>
          rel_back R OPz l0_OPz (tri P.1 W.1 Z.1) (tri P W Z) (fun n => match n with
            | 0 => rfl
            | 1 => rfl
            | 2 => rfl
            | _ + 3 => rfl)
        have hRep := hN creplAx (.inr (.inr (.inr (.inr (.inl rfl))))) w F
          (fun W hW Z hZ Z' hZ' hc U hU =>
            match (PIN_gen R _ 2 1 3).1 hc.1, (PIN_gen R _ 2 0 3).1 hc.2 with
            | ⟨P, hP1, ho, hm⟩, ⟨P', hP1', ho', hm'⟩ =>
              match (inF ⟨P, hP1⟩).1 hm, (inF ⟨P', hP1'⟩).1 hm' with
              | ⟨a1, ha1, z1, hp1, ht1⟩, ⟨a2, _, z2, hp2, ht2⟩ =>
                have i1 := op_inj (Rs R) hP ((opD ⟨P, hP1⟩ ⟨W, hW⟩ ⟨Z, hZ⟩).1 ho) hp1
                have i2 := op_inj (Rs R) hP ((opD ⟨P', hP1'⟩ ⟨W, hW⟩ ⟨Z', hZ'⟩).1 ho') hp2
                have a21 : Ceq (Rs R) a2 a1 := ceq_trans (Rs R) (ceq_symm (Rs R) i2.1) i1.1
                have zz := pre a1 ha1 z1 z2 ht1 (thC a2 a1 z2 z2 a21 (ceq_refl (Rs R) z2) ht2)
                have c : Ceq (Rs R) ⟨Z, hZ⟩ ⟨Z', hZ'⟩ :=
                  ceq_trans (Rs R) i1.2 (ceq_trans (Rs R) zz (ceq_symm (Rs R) i2.2))
                ⟨(c ⟨U, hU⟩).1, (c ⟨U, hU⟩).2⟩)
          x.1 x.2
        match hRep with
        | ⟨Y, hY, hYi⟩ => ⟨⟨Y, hY⟩, fun z =>
          ⟨fun hz => match (hYi z.1 z.2).1 hz with
            | ⟨W, hW, hWx, hpi⟩ => match (PIN_gen R _ 0 1 4).1 hpi with
              | ⟨P, hP1, ho, hm⟩ => match (inF ⟨P, hP1⟩).1 hm with
                | ⟨a1, ha1, z1, hp1, ht1⟩ =>
                  have i1 := op_inj (Rs R) hP ((opD ⟨P, hP1⟩ ⟨W, hW⟩ z).1 ho) hp1
                  ⟨a1, ha1, thC a1 a1 z1 z (ceq_refl (Rs R) a1) (ceq_symm (Rs R) i1.2) ht1⟩,
           fun ⟨a, ha, ht⟩ => match op_ex (Rs R) hP a z with
            | ⟨p, hp⟩ => (hYi z.1 z.2).2 ⟨a.1, a.2, ha,
                (PIN_gen R _ 0 1 4).2 ⟨p.1, p.2, (opD p a z).2 hp, (inF p).2 ⟨a, ha, z, hp, ht⟩⟩⟩⟩⟩)
  | .inr (.inr (.inr ⟨θ, hl, e⟩)) => by
    rw [e]
    exact foundZ_intro (Rs R) θ v (fun ⟨x, hx⟩ =>
      match comp_set R hN θ hl v with
      | ⟨Y, hY⟩ =>
        match hN cfoundAx (.inr (.inr (.inr (.inr (.inr rfl))))) w Y ⟨x.1, x.2, (hY x).2 hx⟩ with
        | ⟨X0, h1, h2, h3⟩ => ⟨⟨X0, h1⟩, (hY ⟨X0, h1⟩).1 h2, fun y hy ht => h3 y.1 y.2 hy ((hY y).2 ht)⟩)

/-- there is a set (from infinity) -/
theorem set_ex (hiB : B infAx) (hN : ModT (NBG B) R) (w : Nat → D) : Nonempty (St R) :=
  match hN _ (.inr (.inr (.inl ⟨infAx, hiB, rfl⟩))) w with
  | ⟨X, hX, _⟩ => ⟨⟨X, hX⟩⟩

end D

/-- the easy direction: ZF(B) theorems, relativised, are NBG(B) theorems -/
theorem zf_to_nbg (K : CP.Classical') {B : Fm → Prop} (hB : Base B) (hpB : B pairAx) (hiB : B infAx)
    {φ : Fm} (hl : L0 φ) (hf : FV 0 φ) (h : PC (ZF B) [] φ) : PC (NBG B) [] (relE φ) :=
  completenessT (NBG B) K (fun _ R w hN _ =>
    match set_ex R hiB hN w with
    | ⟨s0⟩ =>
      have hs := soundnessT (ZF B) K h (St R) (Rs R) (fun _ => s0) (sets_ZF R hB hpB hN) (fun _ m => nomatch m)
      have hr := (rel_back R φ hl (fun _ => s0.1) (fun _ => s0) (fun _ => rfl)).2 hs
      (sat_agree R (relE φ) 0 (fv_rel φ 0 hf) (v := w) (w := fun _ => s0.1)
        (fun n hn => absurd hn (Nat.not_lt_zero n))).2 hr)

/-- NBG ↔ ZF on sentences of set theory -/
theorem nbg_iff_zf (K : CP.Classical') {φ : Fm} (hl : L0 φ) (hf : FV 0 φ) :
    PC (NBG B0) [] (relE φ) ↔ PC (ZF B0) [] φ :=
  ⟨nbg_zf K hl, zf_to_nbg K base_B0 (.inl rfl) (.inr (.inr (.inr rfl))) hl hf⟩

/-- NBG with choice ↔ ZFC on sentences of set theory -/
theorem nbg_iff_zfc (K : CP.Classical') {φ : Fm} (hl : L0 φ) (hf : FV 0 φ) :
    PC (NBG B1) [] (relE φ) ↔ PC (ZF B1) [] φ :=
  ⟨nbg_zfc K hl, zf_to_nbg K base_B1 (.inl (.inl rfl)) (.inl (.inr (.inr (.inr rfl)))) hl hf⟩

end NBGc

end Found

#print axioms Found.NBGc.replZ_intro
#print axioms Found.NBGc.foundZ_intro
#print axioms Found.NBGc.psiZ_sat
#print axioms Found.NBGc.comp_gen
#print axioms Found.NBGc.comp_set
#print axioms Found.NBGc.extD_sets
#print axioms Found.NBGc.sets_ZF
#print axioms Found.NBGc.set_ex
#print axioms Found.NBGc.zf_to_nbg
#print axioms Found.NBGc.nbg_iff_zf
#print axioms Found.NBGc.nbg_iff_zfc

#print axioms: 11 theorems, no axioms.

85.141 String diagrams: the combinatorial Joyal–Street theorem

Layered string diagrams modulo interchange moves of side-by-side boxes are the free strict monoidal category: two terms of the same type are equal iff their diagrams are related by interchange moves.

\[ t \approx u \iff \mathrm {diag}(t) \sim \mathrm {diag}(u) \]

found/StrDiag2.lean

/-
  T193, string diagrams, part 2. found/StrDiag2 — the combinatorial
  Joyal–Street theorem, completeness half and the equivalence:
  * reading a diagram back as a term (each layer = id ⊗ box ⊗ id, layers
    composed); every term is equal to the reading of its diagram;
  * an interchange move does not change the reading (up to ≈), and keeps
    the typing;
  * theorem (joyal_street): two terms of the same type are equal in the
    free strict monoidal category iff their string diagrams are related by
    interchange moves — string diagrams modulo deformation (in its
    combinatorial form) are the free strict monoidal category.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.StrDiag1

namespace Found

namespace SD

variable {S : Sig}

def wh (l : Ly S) : Tm S := .tens (.tens (.id l.L) (.gen l.g)) (.id l.R)

def read (A : Ob) : List (Ly S) → Tm S
  | [] => .id A
  | l :: D => .comp (wh l) (read (l.L ++ S.cod l.g ++ l.R) D)

theorem ty_wh (L R : Ob) (g : S.G) : Ty (wh ⟨L, g, R⟩) (L ++ S.dom g ++ R) (L ++ S.cod g ++ R) :=
  .tens (.tens (.id L) (.gen g)) (.id R)

theorem read_ty : {D : List (Ly S)} → {A B : Ob} → DTy D A B → Ty (read A D) A B
  | _, _, _, .nil A => .id A
  | _, _, _, @DTy.cons _ L R g _ _ _ e h => by
    subst e
    exact .comp (ty_wh L R g) (read_ty h)

theorem E_trans {t u v : Tm S} (h1 : Eqv t u) (h2 : Eqv u v) : Eqv t v := .trans h1 h2

/-! ## reading and the operations on diagrams -/

theorem read_app : {D : List (Ly S)} → {A B : Ob} → DTy D A B → {E : List (Ly S)} → {C : Ob} → DTy E B C →
    Eqv (read A (D ++ E)) (.comp (read A D) (read B E))
  | _, _, _, .nil _, _, _, hE => .symm (.idL (read_ty hE))
  | _, _, _, @DTy.cons _ L R g _ _ _ _ h, _, _, hE =>
    E_trans (.compC (.refl _) (read_app h hE)) (.symm (.assoc _ _ _))

theorem read_wR (C : Ob) : {D : List (Ly S)} → {A B : Ob} → DTy D A B →
    Eqv (read (A ++ C) (wR C D)) (.tens (read A D) (.id C))
  | _, _, _, .nil A => .symm (.tid A C)
  | _, _, _, @DTy.cons _ L R g D _ _ e h => by
    subst e
    have ih := read_wR C h
    rw [app_assoc (L ++ S.cod g) R C] at ih
    show Eqv (.comp (wh ⟨L, g, R ++ C⟩) (read (L ++ S.cod g ++ (R ++ C)) (wR C D))) _
    have hw : Eqv (wh (⟨L, g, R ++ C⟩ : Ly S)) (.tens (wh ⟨L, g, R⟩) (.id C)) :=
      E_trans (.tensC (.refl _) (.symm (.tid R C))) (.symm (.tassoc _ _ _))
    exact E_trans (.compC hw ih) (E_trans (.inter (ty_wh L R g) (read_ty h) (.id C) (.id C))
      (.tensC (.refl _) (.idL (.id C))))

theorem read_wL (C : Ob) : {D : List (Ly S)} → {A B : Ob} → DTy D A B →
    Eqv (read (C ++ A) (wL C D)) (.tens (.id C) (read A D))
  | _, _, _, .nil A => .symm (.tid C A)
  | _, _, _, @DTy.cons _ L R g D _ _ e h => by
    subst e
    have ih := read_wL C h
    rw [eqL C L (S.cod g) R] at ih
    show Eqv (.comp (wh ⟨C ++ L, g, R⟩) (read ((C ++ L) ++ S.cod g ++ R) (wL C D))) _
    have hw : Eqv (wh (⟨C ++ L, g, R⟩ : Ly S)) (.tens (.id C) (wh ⟨L, g, R⟩)) :=
      E_trans (.tensC (.tensC (.symm (.tid C L)) (.refl _)) (.refl _))
        (E_trans (.tensC (.tassoc _ _ _) (.refl _)) (.tassoc _ _ _))
    exact E_trans (.compC hw ih) (E_trans (.inter (.id C) (.id C) (ty_wh L R g) (read_ty h))
      (.tensC (.idL (.id C)) (.refl _)))

/-- every term equals the reading of its diagram -/
theorem term_read {t : Tm S} {A B : Ob} (h : Ty t A B) : Eqv t (read A (diag t)) := by
  induction h with
  | id A => exact .refl _
  | gen g =>
    show Eqv (.gen g) (.comp (wh ⟨[], g, []⟩) (.id ([] ++ S.cod g ++ [])))
    exact .symm (E_trans (.idR (ty_wh [] [] g)) (E_trans (.tunitR _) (.tunitL _)))
  | comp hf hg ih1 ih2 =>
    exact E_trans (.compC ih1 ih2) (.symm (read_app (diag_ty hf) (diag_ty hg)))
  | @tens f g A B C D hf hg ih1 ih2 =>
    show Eqv _ (read (A ++ C) (wR (dom g) (diag f) ++ wL (cod f) (diag g)))
    rw [(ty_dc hg).1, (ty_dc hf).2]
    have a1 := read_app (diag_ty.dty_wR C (diag_ty hf)) (diag_ty.dty_wL B (diag_ty hg))
    have a2 : Eqv (Tm.comp (read (A ++ C) (wR C (diag f))) (read (B ++ C) (wL B (diag g))))
        (.tens (read A (diag f)) (read C (diag g))) :=
      E_trans (.compC (read_wR C (diag_ty hf)) (read_wL B (diag_ty hg)))
        (E_trans (.inter (read_ty (diag_ty hf)) (.id B) (.id C) (read_ty (diag_ty hg)))
          (.tensC (.idR (read_ty (diag_ty hf))) (.idL (read_ty (diag_ty hg)))))
    exact E_trans (.tensC ih1 ih2) (.symm (E_trans a1 a2))

/-! ## interchange moves -/

theorem k1 (X d M e Y : Ob) : X ++ d ++ (M ++ e ++ Y) = X ++ d ++ M ++ e ++ Y := by
  rw [app_assoc M e Y, app_assoc (X ++ d ++ M) e Y, app_assoc (X ++ d) M, app_assoc X d]

/-- the interchange of two boxes side by side, on terms -/
theorem swap_eqv (X M Y : Ob) (g1 g2 : S.G) :
    Eqv (Tm.comp (wh ⟨X, g1, M ++ S.dom g2 ++ Y⟩) (wh ⟨X ++ S.cod g1 ++ M, g2, Y⟩))
      (.comp (wh ⟨X ++ S.dom g1 ++ M, g2, Y⟩) (wh ⟨X, g1, M ++ S.cod g2 ++ Y⟩)) :=
  let P : Tm S := .tens (.id X) (.gen g1)
  let Q : Tm S := .tens (.tens (.id M) (.gen g2)) (.id Y)
  have hP : Ty P (X ++ S.dom g1) (X ++ S.cod g1) := .tens (.id X) (.gen g1)
  have hQ : Ty Q (M ++ S.dom g2 ++ Y) (M ++ S.cod g2 ++ Y) := ty_wh M Y g2
  have side : ∀ Z : Ob, Eqv (wh (⟨Z ++ M, g2, Y⟩ : Ly S)) (.tens (.id Z) Q) := fun Z =>
    E_trans (.tensC (.tensC (.symm (.tid Z M)) (.refl _)) (.refl _))
      (E_trans (.tensC (.tassoc _ _ _) (.refl _)) (.tassoc _ _ _))
  have l1 : Eqv (Tm.comp (wh ⟨X, g1, M ++ S.dom g2 ++ Y⟩) (wh ⟨X ++ S.cod g1 ++ M, g2, Y⟩)) (.tens P Q) :=
    E_trans (.compC (.refl _) (side (X ++ S.cod g1)))
      (E_trans (.inter hP (.id _) (.id _) hQ) (.tensC (.idR hP) (.idL hQ)))
  have l2 : Eqv (Tm.comp (wh ⟨X ++ S.dom g1 ++ M, g2, Y⟩) (wh ⟨X, g1, M ++ S.cod g2 ++ Y⟩)) (.tens P Q) :=
    E_trans (.compC (side (X ++ S.dom g1)) (.refl _))
      (E_trans (.inter (.id _) hP hQ (.id _)) (.tensC (.idL hP) (.idR hQ)))
  E_trans l1 (.symm l2)

/-- an interchange move keeps the typing and the reading -/
theorem istep_read {D D' : List (Ly S)} (s : IStep D D') :
    ∀ {A B : Ob}, (DTy D A B ↔ DTy D' A B) ∧ (DTy D A B → Eqv (read A D) (read A D')) := by
  induction s with
  | @here X M Y R1 L2 L2' R1' g1 g2 Q e1 e2 e3 e4 =>
    subst e1; subst e2; subst e3; subst e4
    intro A B
    have mid : X ++ S.cod g1 ++ M ++ S.cod g2 ++ Y = X ++ S.cod g1 ++ (M ++ S.cod g2 ++ Y) :=
      (k1 X (S.cod g1) M (S.cod g2) Y).symm
    refine ⟨⟨fun h => ?_, fun h => ?_⟩, fun h => ?_⟩
    · match h with
      | .cons ea (.cons _ hq) =>
        exact .cons (ea.trans (k1 X _ M _ Y)) (.cons (k1 X (S.dom g1) M (S.cod g2) Y).symm (by rw [← mid]; exact hq))
    · match h with
      | .cons ea (.cons _ hq) =>
        refine .cons (ea.trans (k1 X _ M _ Y).symm) (.cons (k1 X (S.cod g1) M (S.dom g2) Y) ?_)
        rw [mid]
        exact hq
    · show Eqv (.comp (wh ⟨X, g1, M ++ S.dom g2 ++ Y⟩) (.comp (wh ⟨X ++ S.cod g1 ++ M, g2, Y⟩)
          (read (X ++ S.cod g1 ++ M ++ S.cod g2 ++ Y) Q)))
        (.comp (wh ⟨X ++ S.dom g1 ++ M, g2, Y⟩) (.comp (wh ⟨X, g1, M ++ S.cod g2 ++ Y⟩)
          (read (X ++ S.cod g1 ++ (M ++ S.cod g2 ++ Y)) Q)))
      rw [← mid]
      exact E_trans (.symm (.assoc _ _ _)) (E_trans (.compC (swap_eqv X M Y g1 g2) (.refl _)) (.assoc _ _ _))
  | cons l _ ih =>
    intro A B
    refine ⟨⟨fun h => ?_, fun h => ?_⟩, fun h => ?_⟩
    · match h with
      | .cons e hq => exact .cons e ((ih).1.1 hq)
    · match h with
      | .cons e hq => exact .cons e ((ih).1.2 hq)
    · match h with
      | .cons _ hq => exact .compC (.refl _) ((ih).2 hq)

theorem deq_read {D D' : List (Ly S)} (h : DEq D D') :
    ∀ {A B : Ob}, (DTy D A B ↔ DTy D' A B) ∧ (DTy D A B → Eqv (read A D) (read A D')) := by
  induction h with
  | refl => exact fun {_ _} => ⟨Iff.rfl, fun _ => .refl _⟩
  | step s => exact istep_read s
  | symm _ ih => exact fun {_ _} => ⟨ih.1.symm, fun h => .symm (ih.2 (ih.1.2 h))⟩
  | trans _ _ ih1 ih2 => exact fun {_ _} => ⟨ih1.1.trans ih2.1, fun h => E_trans (ih1.2 h) (ih2.2 (ih1.1.1 h))⟩

/-- the combinatorial Joyal–Street theorem: string diagrams modulo interchange
  are the free strict monoidal category -/
theorem joyal_street {t u : Tm S} {A B : Ob} (ht : Ty t A B) (hu : Ty u A B) :
    Eqv t u ↔ DEq (diag t) (diag u) :=
  ⟨sound, fun h => E_trans (term_read ht) (E_trans ((deq_read h).2 (diag_ty ht)) (.symm (term_read hu)))⟩

end SD

end Found

#print axioms Found.SD.read_ty
#print axioms Found.SD.read_app
#print axioms Found.SD.read_wR
#print axioms Found.SD.read_wL
#print axioms Found.SD.term_read
#print axioms Found.SD.k1
#print axioms Found.SD.swap_eqv
#print axioms Found.SD.istep_read
#print axioms Found.SD.deq_read
#print axioms Found.SD.joyal_street

#print axioms: 10 theorems, no axioms.

85.142 The realization theorem: S4 and the logic of proofs

Cut admissibility for a sequent calculus of S4, then realization of cut-free derivations in Artemov’s logic of proofs by lifting and substitution; with the forgetful projection, S4 is exactly the forgetful image of LP.

\[ \mathrm {S4} \vdash A \iff \exists P,\ \mathrm {LP} \vdash A^{P} \]

found/Realz3.lean

/-
  T178, realization, part 3. found/Realz3 — Artemov's realization theorem
  S4 → LP and the forgetful projection LP → S4:
  * the realization with parameter P: every negative □ becomes x:· (one
    variable x), every positive □ becomes P:· ;
  * a cut-free S4 sequent Γ ⇒ Δ is realized when LP derives ⊥ from the
    realized Γ and the negations of the realized Δ;
  * by induction on cut-free derivations, with a provisional variable u
    inside P: at each □R the premise is lifted to a u-free polynomial t, and
    u is replaced by t + u (substitution keeps all derivations), so the
    positive term keeps every lifted t as a summand;
  * realization theorem: every S4 theorem A has a realization A^r provable
    in LP; forgetful projection: every LP theorem forgets to an S4 theorem;
    hence S4 ⊢ A iff some realization of A is an LP theorem.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Realz2

namespace Found

namespace RZ

/-! ## the realization -/

mutual
def rp (P : JT) : MF → JF
  | .atom n => .atom n
  | .bot => .bot
  | .imp a b => .imp (rn P a) (rp P b)
  | .box a => .pf P (rp P a)
def rn (P : JT) : MF → JF
  | .atom n => .atom n
  | .bot => .bot
  | .imp a b => .imp (rp P a) (rn P b)
  | .box a => .pf (.var 0) (rn P a)
end

theorem sub_r (s P : JT) : (A : MF) → fsub s (rp P A) = rp (tsub s P) A ∧ fsub s (rn P A) = rn (tsub s P) A
  | .atom _ => ⟨rfl, rfl⟩
  | .bot => ⟨rfl, rfl⟩
  | .imp a b => by
    refine ⟨?_, ?_⟩
    · show JF.imp (fsub s (rn P a)) (fsub s (rp P b)) = JF.imp (rn (tsub s P) a) (rp (tsub s P) b)
      rw [(sub_r s P a).2, (sub_r s P b).1]
    · show JF.imp (fsub s (rp P a)) (fsub s (rn P b)) = JF.imp (rp (tsub s P) a) (rn (tsub s P) b)
      rw [(sub_r s P a).1, (sub_r s P b).2]
  | .box a => by
    refine ⟨?_, ?_⟩
    · show JF.pf (tsub s P) (fsub s (rp P a)) = JF.pf (tsub s P) (rp (tsub s P) a)
      rw [(sub_r s P a).1]
    · show JF.pf (.var 0) (fsub s (rn P a)) = JF.pf (.var 0) (rn (tsub s P) a)
      rw [(sub_r s P a).2]

def RN (P : JT) : List MF → List JF
  | [] => []
  | a :: l => rn P a :: RN P l

def NP (P : JT) : List MF → List JF
  | [] => []
  | a :: l => jneg (rp P a) :: NP P l

def japp : List JF → List JF → List JF
  | [], k => k
  | a :: l, k => a :: japp l k

/-- the hypotheses realizing a sequent -/
def hl (P : JT) (Γ Δ : List MF) : List JF := japp (RN P Γ) (NP P Δ)

theorem mem_japp_l {x : JF} : {l : List JF} → (k : List JF) → x ∈ l → x ∈ japp l k
  | _ :: _, _, .head _ => .head _
  | _ :: _, k, .tail _ m => .tail _ (mem_japp_l k m)

theorem mem_japp_r {x : JF} : (l : List JF) → {k : List JF} → x ∈ k → x ∈ japp l k
  | [], _, m => m
  | _ :: l, _, m => .tail _ (mem_japp_r l m)

theorem mem_japp_inv {x : JF} : (l : List JF) → {k : List JF} → x ∈ japp l k → x ∈ l ∨ x ∈ k
  | [], _, m => .inr m
  | _ :: l, _, m => by
    cases m with
    | head => exact .inl (.head _)
    | tail _ m' => exact (mem_japp_inv l m').elim (fun h => .inl (.tail _ h)) .inr

theorem mem_RN (P : JT) {a : MF} : {Γ : List MF} → a ∈ Γ → rn P a ∈ RN P Γ
  | _ :: _, .head _ => .head _
  | _ :: _, .tail _ m => .tail _ (mem_RN P m)

theorem mem_NP (P : JT) {a : MF} : {Δ : List MF} → a ∈ Δ → jneg (rp P a) ∈ NP P Δ
  | _ :: _, .head _ => .head _
  | _ :: _, .tail _ m => .tail _ (mem_NP P m)

theorem RN_inv (P : JT) {x : JF} : (Γ : List MF) → x ∈ RN P Γ → ∃ a, a ∈ Γ ∧ x = rn P a
  | [], m => nomatch m
  | b :: l, m => by
    cases m with
    | head => exact ⟨b, .head _, rfl⟩
    | tail _ m' => exact match RN_inv P l m' with | ⟨a, h, e⟩ => ⟨a, .tail _ h, e⟩

theorem mapF_japp (s : JT) : (l k : List JF) → mapF s (japp l k) = japp (mapF s l) (mapF s k)
  | [], _ => rfl
  | _ :: l, k => congrArg (List.cons _) (mapF_japp s l k)

theorem mapF_RN (s P : JT) : (Γ : List MF) → mapF s (RN P Γ) = RN (tsub s P) Γ
  | [] => rfl
  | a :: l => by
    show fsub s (rn P a) :: mapF s (RN P l) = rn (tsub s P) a :: RN (tsub s P) l
    rw [(sub_r s P a).2, mapF_RN s P l]

theorem mapF_NP (s P : JT) : (Δ : List MF) → mapF s (NP P Δ) = NP (tsub s P) Δ
  | [] => rfl
  | a :: l => by
    show JF.imp (fsub s (rp P a)) .bot :: mapF s (NP P l) = JF.imp (rp (tsub s P) a) .bot :: NP (tsub s P) l
    rw [(sub_r s P a).1, mapF_NP s P l]

theorem mapF_hl (s P : JT) (Γ Δ : List MF) : mapF s (hl P Γ Δ) = hl (tsub s P) Γ Δ := by
  unfold hl
  rw [mapF_japp, mapF_RN, mapF_NP]

theorem hl_sub {P : JT} {Γ Γ' Δ Δ' : List MF} (s1 : Sub Γ Γ') (s2 : Sub Δ Δ') : JSub (hl P Γ Δ) (hl P Γ' Δ') :=
  fun x m => (mem_japp_inv _ m).elim
    (fun h => match RN_inv P _ h with
      | ⟨a, ha, e⟩ => e ▸ mem_japp_l _ (mem_RN P (s1 _ ha)))
    (fun h => mem_japp_r _ (nps _ h s2))
where
  nps {x : JF} : (Δ0 : List MF) → x ∈ NP P Δ0 → Sub Δ0 Δ' → x ∈ NP P Δ'
    | [], m, _ => nomatch m
    | _ :: l, m, s => by
      cases m with
      | head => exact mem_NP P (s _ (.head _))
      | tail _ m' => exact nps l m' (fun y my => s y (.tail _ my))

def U : JT := .var 1

theorem tsub_U (t : JT) : tsub t U = t := rfl

theorem tsub_by_U : (t : JT) → tsub U t = t
  | .var 1 => rfl
  | .var 0 => rfl
  | .var (_ + 2) => rfl
  | .cst _ => rfl
  | .app a b => by show JT.app _ _ = _; rw [tsub_by_U a, tsub_by_U b]
  | .sum a b => by show JT.sum _ _ = _; rw [tsub_by_U a, tsub_by_U b]
  | .bang a => by show JT.bang _ = _; rw [tsub_by_U a]

/-- realized by the positive term P' -/
def Rz (P' : JT) (Γ Δ : List MF) : Prop := Der (hl P' Γ Δ) .bot

theorem rz_sub (s : JT) {P' : JT} {Γ Δ : List MF} (h : Rz P' Γ Δ) : Rz (tsub s P') Γ Δ := by
  have := der_sub s h
  rw [mapF_hl] at this
  exact this

theorem xhyp_bx (P : JT) (Γ : List MF) : XHyp (RN P (bx Γ)) := fun h m =>
  match RN_inv P _ m with
  | ⟨a, ha, e⟩ => match bx_mem Γ ha with
    | ⟨_, c, ec⟩ => by subst ec; exact ⟨rn P c, e⟩

/-- the realization of cut-free derivations -/
theorem realize {Γ Δ : List MF} (d : G Γ Δ) : ∀ P : JT, Smd U P → ∃ Q, Smd U Q ∧ Rz (tsub Q P) Γ Δ := by
  induction d with
  | @ax Γ Δ n h1 h2 =>
    intro P _
    exact ⟨U, .self, .mp (.hyp (mem_japp_r _ (mem_NP _ h2))) (.hyp (mem_japp_l _ (mem_RN _ h1)))⟩
  | botL h =>
    intro P _
    exact ⟨U, .self, .hyp (mem_japp_l _ (mem_RN _ h))⟩
  | @impL Γ Δ a b h _ _ ih1 ih2 =>
    intro P hP
    match ih1 P hP with
    | ⟨Q1, hQ1, r1⟩ =>
      match ih2 (tsub Q1 P) (smd_trans hQ1 (smd_sub Q1 hP)) with
      | ⟨Q2, hQ2, r2⟩ =>
        refine ⟨tsub Q2 Q1, smd_trans hQ2 (smd_sub Q2 hQ1), ?_⟩
        rw [← tsub_tsub]
        have r1' := rz_sub Q2 r1
        -- H ⊢ rp a, from H, ¬ rp a ⊢ ⊥
        have da : Der (hl (tsub Q2 (tsub Q1 P)) Γ Δ) (rp (tsub Q2 (tsub Q1 P)) a) :=
          by_contra (der_weak r1' (fun x (m : x ∈ hl (tsub Q2 (tsub Q1 P)) Γ (a :: Δ)) => (mem_japp_inv _ m).elim
            (fun h => .tail _ (mem_japp_l _ h))
            (fun h => by
              cases h with
              | head => exact .head _
              | tail _ m' => exact .tail _ (mem_japp_r _ m'))))
        have db : Der (hl (tsub Q2 (tsub Q1 P)) Γ Δ) (.imp (rn (tsub Q2 (tsub Q1 P)) b) .bot) := deduction r2
        exact .mp db (.mp (.hyp (mem_japp_l _ (mem_RN _ h))) da)
  | @impR Γ Δ a b h _ ih =>
    intro P hP
    match ih P hP with
    | ⟨Q, hQ, r⟩ =>
      refine ⟨Q, hQ, ?_⟩
      have js : JSub (hl (tsub Q P) (a :: Γ) (b :: Δ))
          (jneg (rp (tsub Q P) b) :: rn (tsub Q P) a :: hl (tsub Q P) Γ Δ) := by
        intro x m
        cases m with
        | head => exact .tail _ (.head _)
        | tail _ m' =>
          cases mem_japp_inv _ m' with
          | inl h1 => exact .tail _ (.tail _ (mem_japp_l _ h1))
          | inr h2 =>
            cases h2 with
            | head => exact .head _
            | tail _ m'' => exact .tail _ (.tail _ (mem_japp_r _ m''))
      have d1 : Der (rn (tsub Q P) a :: hl (tsub Q P) Γ Δ) (rp (tsub Q P) b) := by_contra (der_weak r js)
      exact .mp (.hyp (mem_japp_r _ (mem_NP _ h))) (deduction d1)
  | @boxL Γ Δ a h _ ih =>
    intro P hP
    match ih P hP with
    | ⟨Q, hQ, r⟩ =>
      refine ⟨Q, hQ, ?_⟩
      have hb : JF.pf (.var 0) (rn (tsub Q P) a) ∈ hl (tsub Q P) Γ Δ := mem_japp_l _ (mem_RN _ h)
      exact .mp (deduction r) (.mp (.ax (.refl _ _)) (.hyp hb))
  | @boxR Γ Δ a h _ ih =>
    intro P hP
    match ih P hP with
    | ⟨Q', hQ', r⟩ =>
      -- RN (bx Γ) ⊢ rp a
      have d0 : Der (RN (tsub Q' P) (bx Γ)) (rp (tsub Q' P) a) :=
        by_contra (der_weak r (fun x (m : x ∈ hl (tsub Q' P) (bx Γ) [a]) => (mem_japp_inv _ m).elim
          (fun h => .tail _ h)
          (fun h => by
            cases h with
            | head => exact .head _
            | tail _ m' => exact nomatch m')))
      match lifting (xhyp_bx _ Γ) d0 with
      | ⟨t, ht, dt⟩ =>
        let s : JT := .sum t U
        have hPs : Smd t (tsub s (tsub Q' P)) :=
          smd_trans (.l U .self) (smd_sub s (smd_trans hQ' (smd_sub Q' hP)))
        refine ⟨tsub s Q', smd_trans (.r t .self) (smd_sub s hQ'), ?_⟩
        rw [← tsub_tsub]
        have dt' := der_sub s dt
        rw [mapF_RN] at dt'
        have e : fsub s (JF.pf t (rp (tsub Q' P) a)) = JF.pf t (rp (tsub s (tsub Q' P)) a) := by
          show JF.pf (tsub s t) (fsub s (rp (tsub Q' P) a)) = _
          rw [tsub_ufree s t ht, (sub_r s _ a).1]
        rw [e] at dt'
        have dP := Der.mp (smd_der hPs _ _) dt'
        exact .mp (.hyp (mem_japp_r _ (mem_NP _ h)))
          (der_weak dP (fun x m => match RN_inv _ _ m with
            | ⟨c, hc, ec⟩ => ec ▸ mem_japp_l _ (mem_RN _ (bx_sub Γ _ hc))))

/-! ## the realization theorem and the forgetful projection -/

/-- Artemov's realization theorem: every S4 theorem has a realization that is an LP theorem
  (negative boxes realized by the variable x, positive boxes by one polynomial) -/
theorem realization {A : MF} (h : HS4 A) : ∃ P, Der [] (rp P A) :=
  match realize (hs4_g h) U .self with
  | ⟨Q, _, r⟩ => ⟨tsub Q U, by_contra r⟩

def forget : JF → MF
  | .atom n => .atom n
  | .bot => .bot
  | .imp a b => .imp (forget a) (forget b)
  | .pf _ a => .box (forget a)

theorem forget_r (P : JT) : (A : MF) → forget (rp P A) = A ∧ forget (rn P A) = A
  | .atom _ => ⟨rfl, rfl⟩
  | .bot => ⟨rfl, rfl⟩
  | .imp a b => by
    refine ⟨?_, ?_⟩
    · show MF.imp (forget (rn P a)) (forget (rp P b)) = _
      rw [(forget_r P a).2, (forget_r P b).1]
    · show MF.imp (forget (rp P a)) (forget (rn P b)) = _
      rw [(forget_r P a).1, (forget_r P b).2]
  | .box a => by
    refine ⟨?_, ?_⟩
    · show MF.box (forget (rp P a)) = _
      rw [(forget_r P a).1]
    · show MF.box (forget (rn P a)) = _
      rw [(forget_r P a).2]

theorem hs4_id (a : MF) : HS4 (.imp a a) := .mp (.mp (.s a (.imp a a) a) (.k a (.imp a a))) (.k a a)

theorem lax_forget {φ : JF} (h : LAx φ) : HS4 (forget φ) := by
  cases h with
  | k => exact .k _ _
  | s => exact .s _ _ _
  | dne => exact .dne _
  | app => exact .kb _ _
  | sumL => exact hs4_id _
  | sumR => exact hs4_id _
  | refl => exact .t _
  | chk => exact .four _

/-- the forgetful projection: LP theorems forget to S4 theorems -/
theorem der_forget {φ : JF} (d : Der [] φ) : HS4 (forget φ) := by
  induction d with
  | hyp m => exact nomatch m
  | ax h => exact lax_forget h
  | cn _ h => exact .nec (lax_forget h)
  | mp _ _ ih1 ih2 => exact .mp ih1 ih2

/-- S4 is the forgetful projection of LP -/
theorem s4_iff_lp (A : MF) : HS4 A ↔ ∃ P, Der [] (rp P A) :=
  ⟨realization, fun ⟨P, d⟩ => (forget_r P A).1 ▸ der_forget d⟩

end RZ

end Found

#print axioms Found.RZ.sub_r
#print axioms Found.RZ.hl_sub
#print axioms Found.RZ.mapF_hl
#print axioms Found.RZ.rz_sub
#print axioms Found.RZ.realize
#print axioms Found.RZ.realization
#print axioms Found.RZ.forget_r
#print axioms Found.RZ.der_forget
#print axioms Found.RZ.s4_iff_lp

#print axioms: 9 theorems, no axioms.

85.143 Ackermann set theory is conservative over ZF

Inside any model of ZF: ordinals, transfinite recursion, the cumulative hierarchy and the reflection theorem; the classes over a reflecting level model the finitely many Ackermann instances used, so Ackermann’s A* proves no new set-theoretic sentences.

\[ \mathrm {A}^{*} \vdash \varphi ^{M} \Rightarrow \mathrm {ZF} \vdash \varphi \]

found/AckD.lean

/-
  T167, Ackermann set theory, part 3. found/AckD — the class structure over
  an arbitrary model D of ZF:
  * classes are the elements of D, membership is D's, sets are the members
    of a set Y of D (later a reflecting level V_α);
  * on L0 formulas it is D; relativised to the sets it is truth relativised
    to Y;
  * formulas of the class language translate into L0 formulas with Y as an
    extra variable; hence class comprehension (separation in D);
  * extensionality, heredity (Y a level), comprehension and class
    foundation hold.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.IZ10
import found.Ack2

namespace Found

namespace AKD

open FO FOCT NBGc RF IZ AK

variable (M : IZ.ZM)

/-- the class structure: 0 = membership, 1 = membership in Y -/
def RAD (Y : M.D) : Nat → List M.D → Prop
  | 0, [] => False
  | 0, [_] => False
  | 0, [a, b] => In M a b
  | 0, _ :: _ :: _ :: _ => False
  | 1, [] => False
  | 1, [a] => In M a Y
  | 1, _ :: _ :: _ => False
  | _ + 2, _ => False

variable (Y : M.D)

theorem satD_L0 : (φ : Fm) → L0 φ → ∀ v, (Sat (RAD M Y) φ v ↔ Sat M.R φ v)
  | .atom _ _, hl, v => match hl with
    | ⟨e0, a, b, e⟩ => by subst e0; subst e; exact Iff.rfl
  | .bot, _, _ => Iff.rfl
  | .conj a b, hl, v => ⟨fun s => ⟨(satD_L0 a hl.1 v).1 s.1, (satD_L0 b hl.2 v).1 s.2⟩,
      fun s => ⟨(satD_L0 a hl.1 v).2 s.1, (satD_L0 b hl.2 v).2 s.2⟩⟩
  | .disj a b, hl, v => ⟨fun s => s.elim (fun x => Or.inl ((satD_L0 a hl.1 v).1 x)) (fun y => Or.inr ((satD_L0 b hl.2 v).1 y)),
      fun s => s.elim (fun x => Or.inl ((satD_L0 a hl.1 v).2 x)) (fun y => Or.inr ((satD_L0 b hl.2 v).2 y))⟩
  | .imp a b, hl, v => ⟨fun s x => (satD_L0 b hl.2 v).1 (s ((satD_L0 a hl.1 v).2 x)),
      fun s x => (satD_L0 b hl.2 v).2 (s ((satD_L0 a hl.1 v).1 x))⟩
  | .all a, hl, v => ⟨fun s d => (satD_L0 a hl (ext v d)).1 (s d), fun s d => (satD_L0 a hl (ext v d)).2 (s d)⟩
  | .ex a, hl, v => ⟨fun ⟨d, s⟩ => ⟨d, (satD_L0 a hl (ext v d)).1 s⟩, fun ⟨d, s⟩ => ⟨d, (satD_L0 a hl (ext v d)).2 s⟩⟩

theorem satD_rel : (φ : Fm) → L0 φ → ∀ v, (Sat (RAD M Y) (relE φ) v ↔ SatG M.R (fun x => In M x Y) φ v)
  | .atom _ _, hl, v => match hl with
    | ⟨e0, a, b, e⟩ => by subst e0; subst e; exact Iff.rfl
  | .bot, _, _ => Iff.rfl
  | .conj a b, hl, v => ⟨fun s => ⟨(satD_rel a hl.1 v).1 s.1, (satD_rel b hl.2 v).1 s.2⟩,
      fun s => ⟨(satD_rel a hl.1 v).2 s.1, (satD_rel b hl.2 v).2 s.2⟩⟩
  | .disj a b, hl, v => ⟨fun s => s.elim (fun x => Or.inl ((satD_rel a hl.1 v).1 x)) (fun y => Or.inr ((satD_rel b hl.2 v).1 y)),
      fun s => s.elim (fun x => Or.inl ((satD_rel a hl.1 v).2 x)) (fun y => Or.inr ((satD_rel b hl.2 v).2 y))⟩
  | .imp a b, hl, v => ⟨fun s x => (satD_rel b hl.2 v).1 (s ((satD_rel a hl.1 v).2 x)),
      fun s x => (satD_rel b hl.2 v).2 (s ((satD_rel a hl.1 v).1 x))⟩
  | .all a, hl, v => ⟨fun s d hd => (satD_rel a hl (ext v d)).1 (s d hd), fun s d hd => (satD_rel a hl (ext v d)).2 (s d hd)⟩
  | .ex a, hl, v => ⟨fun ⟨d, hd, s⟩ => ⟨d, hd, (satD_rel a hl (ext v d)).1 s⟩,
      fun ⟨d, hd, s⟩ => ⟨d, hd, (satD_rel a hl (ext v d)).2 s⟩⟩

/-! ## translating the class language into L0 (Y as variable p) -/

def trA : Fm → Nat → Fm
  | .atom 0 [], _ => .bot
  | .atom 0 [_], _ => .bot
  | .atom 0 [a, b], _ => m a b
  | .atom 0 (_ :: _ :: _ :: _), _ => .bot
  | .atom 1 [], _ => .bot
  | .atom 1 [i], p => m i p
  | .atom 1 (_ :: _ :: _), _ => .bot
  | .atom (_ + 2) _, _ => .bot
  | .bot, _ => .bot
  | .conj a b, p => .conj (trA a p) (trA b p)
  | .disj a b, p => .disj (trA a p) (trA b p)
  | .imp a b, p => .imp (trA a p) (trA b p)
  | .all a, p => .all (trA a (p + 1))
  | .ex a, p => .ex (trA a (p + 1))

theorem l0_trA : (ψ : Fm) → (p : Nat) → L0 (trA ψ p)
  | .atom 0 [], _ => trivial
  | .atom 0 [_], _ => trivial
  | .atom 0 [a, b], _ => l0_m a b
  | .atom 0 (_ :: _ :: _ :: _), _ => trivial
  | .atom 1 [], _ => trivial
  | .atom 1 [i], p => l0_m i p
  | .atom 1 (_ :: _ :: _), _ => trivial
  | .atom (_ + 2) _, _ => trivial
  | .bot, _ => trivial
  | .conj a b, p => ⟨l0_trA a p, l0_trA b p⟩
  | .disj a b, p => ⟨l0_trA a p, l0_trA b p⟩
  | .imp a b, p => ⟨l0_trA a p, l0_trA b p⟩
  | .all a, p => l0_trA a (p + 1)
  | .ex a, p => l0_trA a (p + 1)

theorem sat_trA : (ψ : Fm) → (p : Nat) → ∀ v : Nat → M.D, v p = Y → (Sat (RAD M Y) ψ v ↔ Sat M.R (trA ψ p) v)
  | .atom 0 [], _, _, _ => Iff.rfl
  | .atom 0 [_], _, _, _ => Iff.rfl
  | .atom 0 [_, _], _, _, _ => Iff.rfl
  | .atom 0 (_ :: _ :: _ :: _), _, _, _ => Iff.rfl
  | .atom 1 [], _, _, _ => Iff.rfl
  | .atom 1 [i], p, v, hp => by
    show In M (v i) Y ↔ In M (v i) (v p)
    rw [hp]
  | .atom 1 (_ :: _ :: _), _, _, _ => Iff.rfl
  | .atom (_ + 2) _, _, _, _ => Iff.rfl
  | .bot, _, _, _ => Iff.rfl
  | .conj a b, p, v, hp => ⟨fun s => ⟨(sat_trA a p v hp).1 s.1, (sat_trA b p v hp).1 s.2⟩,
      fun s => ⟨(sat_trA a p v hp).2 s.1, (sat_trA b p v hp).2 s.2⟩⟩
  | .disj a b, p, v, hp => ⟨fun s => s.elim (fun x => Or.inl ((sat_trA a p v hp).1 x)) (fun y => Or.inr ((sat_trA b p v hp).1 y)),
      fun s => s.elim (fun x => Or.inl ((sat_trA a p v hp).2 x)) (fun y => Or.inr ((sat_trA b p v hp).2 y))⟩
  | .imp a b, p, v, hp => ⟨fun s x => (sat_trA b p v hp).1 (s ((sat_trA a p v hp).2 x)),
      fun s x => (sat_trA b p v hp).2 (s ((sat_trA a p v hp).1 x))⟩
  | .all a, p, v, hp => ⟨fun s d => (sat_trA a (p + 1) (ext v d) hp).1 (s d),
      fun s d => (sat_trA a (p + 1) (ext v d) hp).2 (s d)⟩
  | .ex a, p, v, hp => ⟨fun ⟨d, s⟩ => ⟨d, (sat_trA a (p + 1) (ext v d) hp).1 s⟩,
      fun ⟨d, s⟩ => ⟨d, (sat_trA a (p + 1) (ext v d) hp).2 s⟩⟩

/-! ## the axioms other than the schema -/

theorem ext_AD (v : Nat → M.D) : Sat (RAD M Y) extAx v := fun X Y' h Z hm =>
  IZ.extD M X Y' Z (fun u => ⟨(h u).1, (h u).2⟩) hm

theorem her1_AD (K : CP.Classical') {α : M.D} (hα : Ord M α) (hY : Vl M α Y) (v : Nat → M.D) :
    Sat (RAD M Y) her1 v := fun x y hy hxy => vl_trans M K hα hY y x hy hxy

theorem her2_AD (K : CP.Classical') {α : M.D} (hY : Vl M α Y) (v : Nat → M.D) : Sat (RAD M Y) her2 v :=
  fun _ _ hy hsub => vl_sub M K hY hy hsub

theorem comp_AD (ψ : Fm) (v : Nat → M.D) : Sat (RAD M Y) (compA ψ) v :=
  let p := bound ψ + 1
  let v' := upd M v (bound ψ) Y
  have hp : ∀ x, ext v' x p = Y := fun _ => upd_eq M v (bound ψ) Y
  have agree : ∀ x, Sat (RAD M Y) ψ (ext v x) ↔ Sat (RAD M Y) ψ (ext v' x) := fun x =>
    have h : ∀ n, n < bound ψ → ext v x n = ext v' x n := fun n hn => match n with
      | 0 => rfl
      | _ + 1 => (upd_ne M v Y (Nat.ne_of_lt (Nat.lt_of_succ_lt hn))).symm
    ⟨sat_agreeU _ ψ _ (fv_bound ψ) h, sat_agreeU _ ψ _ (fv_bound ψ) (fun n hn => (h n hn).symm)⟩
  match IZ.sep M (P := fun u => Sat M.R (trA ψ p) u) ⟨trA ψ p, l0_trA ψ p, fun _ => Iff.rfl⟩ v' Y with
  | ⟨Yc, hYc⟩ => ⟨Yc, fun x =>
    have e : Sat (RAD M Y) (ren σc ψ) (ext (ext v Yc) x) ↔ Sat (RAD M Y) ψ (ext v x) :=
      (sat_ren _ ψ σc _).trans (sat_ext _ ψ (fun n => match n with
        | 0 => rfl
        | _ + 1 => rfl))
    have e2 : Sat (RAD M Y) ψ (ext v x) ↔ Sat M.R (trA ψ p) (ext v' x) :=
      (agree x).trans (sat_trA M Y ψ p (ext v' x) (hp x))
    ⟨fun hm => match (hYc x).1 hm with
      | ⟨h1, h2⟩ => ⟨h1, e.2 (e2.2 h2)⟩,
     fun ⟨h1, h2⟩ => (hYc x).2 ⟨h1, e2.1 (e.1 h2)⟩⟩⟩

theorem found_AD (v : Nat → M.D) : Sat (RAD M Y) cfoundAx v := fun X ⟨x0, hx0, hm0⟩ =>
  let par : Nat → M.D := fun n => match n with
    | 0 => Y
    | _ + 1 => X
  match IZ.found M (P := fun u => In M (u 0) (u 1) ∧ In M (u 0) (u 2))
      (def_and M (def_mem M 0 1) (def_mem M 0 2)) par ⟨x0, hx0, hm0⟩ with
  | ⟨x, ⟨h1, h2⟩, hmin⟩ => ⟨x, h1, h2, fun y hy hyx hyX => hmin y hyx ⟨hy, hyX⟩⟩

/-! ## Ackermann's schema in a reflecting level -/

theorem ack_AD (hEY : ∃ e, In M e Y) (htr : ∀ x y, In M y Y → In M x y → In M x Y) {ψ : Fm} {k : Nat}
    (hl : L0 ψ) (hf : FV (k + 1) ψ)
    (r1 : ∀ v : Nat → M.D, (∀ n, In M (v n) Y) → (SatG M.R (fun x => In M x Y) (thetaA ψ) v ↔ Sat M.R (thetaA ψ) v))
    (r2 : ∀ v : Nat → M.D, (∀ n, In M (v n) Y) → (SatG M.R (fun x => In M x Y) (ren σc ψ) v ↔ Sat M.R (ren σc ψ) v))
    (v : Nat → M.D) : Sat (RAD M Y) (ackAx ψ k) v :=
  match hEY with
  | ⟨e0, he0⟩ => guard_intro (RAD M Y) k _ v (fun hg hall => by
    let v' : Nat → M.D := mixk M k v (fun _ => e0)
    have hv' : ∀ n, In M (v' n) Y := fun n => (Nat.lt_or_ge n k).elim
      (fun h => by show In M (mixk M k v (fun _ => e0) n) Y; rw [mixk_lt M k v _ h]; exact hg n h)
      (fun h => by show In M (mixk M k v (fun _ => e0) n) Y; rw [mixk_ge M k v _ h]; exact he0)
    have hag : ∀ n, n < k → v n = v' n := fun n hn => (mixk_lt M k v (fun _ => e0) hn).symm
    have psi_iff : ∀ x, Sat (RAD M Y) ψ (ext v x) ↔ Sat M.R ψ (ext v' x) := fun x =>
      (satD_L0 M Y ψ hl _).trans
        ⟨sat_agreeU M.R ψ (k + 1) hf (ext_agreeU hag x),
         sat_agreeU M.R ψ (k + 1) hf (ext_agreeU (fun n hn => (hag n hn).symm) x)⟩
    have ren_iff : ∀ {D : Type} (R : Nat → List D → Prop) (w : Nat → D) (y x : D),
        Sat R (ren σc ψ) (ext (ext w y) x) ↔ Sat R ψ (ext w x) := fun R w y x =>
      (sat_ren R ψ σc _).trans (sat_ext R ψ (fun n => match n with
        | 0 => rfl
        | _ + 1 => rfl))
    have inY : ∀ x, Sat M.R ψ (ext v' x) → In M x Y := fun x h => hall x ((psi_iff x).2 h)
    match IZ.sep M (P := fun u => Sat M.R ψ u) ⟨ψ, hl, fun _ => Iff.rfl⟩ v' Y with
    | ⟨y0, hy0⟩ =>
      have thV : Sat M.R (thetaA ψ) v' := ⟨y0, fun x =>
        ⟨fun hm => (ren_iff M.R v' _ x).2 ((hy0 x).1 hm).2,
         fun h => (hy0 x).2 ⟨inY x ((ren_iff M.R v' _ x).1 h), (ren_iff M.R v' _ x).1 h⟩⟩⟩
      match (r1 v' hv').2 thV with
      | ⟨y, hy, hyx⟩ =>
        have key : ∀ x, In M x Y → (In M x y ↔ Sat M.R ψ (ext v' x)) := fun x hx =>
          have rr : SatG M.R (fun x => In M x Y) (ren σc ψ) (ext (ext v' y) x) ↔ Sat M.R ψ (ext v' x) :=
            (r2 _ (CG_ext (fun x => In M x Y) (CG_ext (fun x => In M x Y) hv' hy) hx)).trans (ren_iff M.R v' y x)
          ⟨fun hm => rr.1 ((hyx x hx).1 hm), fun h => (hyx x hx).2 (rr.2 h)⟩
        exact ⟨y, hy, fun x =>
          ⟨fun hm => (ren_iff (RAD M Y) v y x).2 ((psi_iff x).2 ((key x (htr x y hy hm)).1 hm)),
           fun h =>
            have h' := (ren_iff (RAD M Y) v y x).1 h
            (key x (hall x h')).2 ((psi_iff x).1 h')⟩⟩)

/-- Ackermann's set theory A* is conservative over ZF -/
theorem ack_zf (K : CP.Classical') {φ : Fm} (hl : L0 φ) (hf : FV 0 φ) (h : PC Ack [] (relE φ)) :
    PC (ZF B0) [] φ :=
  completenessT (ZF B0) K (fun D R v hM _ =>
    let M : IZ.ZM := ⟨D, R, hM, v 0⟩
    match h with
    | ⟨Δ, cΔ, d⟩ => match AK.extract Δ cΔ with
      | ⟨L, hL, hΔ⟩ =>
        match reflection_D M K (φ :: rlist L) (fun ψ m => by
            cases m with
            | head => exact hl
            | tail _ m' => exact rlist_l0 L hL ψ m') with
        | ⟨α, Y, hαo, hY, hEY, hR⟩ =>
          have htr : ∀ x y, In M y Y → In M x y → In M x Y := fun x y hy hxy => vl_trans M K hαo hY y x hy hxy
          have hb : ∀ b, AckIn L b → ∀ w, Sat (RAD M Y) b w := fun b hb w => match hb with
            | .inl e => by rw [e]; exact ext_AD M Y w
            | .inr (.inl e) => by rw [e]; exact her1_AD M Y K hαo hY w
            | .inr (.inr (.inl e)) => by rw [e]; exact her2_AD M Y K hY w
            | .inr (.inr (.inr (.inl ⟨ψ, e⟩))) => by rw [e]; exact comp_AD M Y ψ w
            | .inr (.inr (.inr (.inr (.inl e)))) => by rw [e]; exact found_AD M Y w
            | .inr (.inr (.inr (.inr (.inr ⟨ψ, k, m, h1, h2, e⟩)))) => by
              rw [e]
              exact ack_AD M Y hEY htr h1 h2 (hR _ (.tail _ (rlist_mem m).1)) (hR _ (.tail _ (rlist_mem m).2)) w
          have hmod : ∀ δ, δ ∈ Δ → ∀ w, Sat (RAD M Y) δ w := fun δ m w => match hΔ δ m with
            | ⟨j, a, ha, e⟩ => by
              rw [e]
              exact clo_sat _ (fun w' => match ha with
                | .inl ⟨b, eb⟩ => by rw [eb]; exact K.lem (Sat (RAD M Y) b w')
                | .inr ⟨b, σ, hbb, eb⟩ => by rw [eb]; exact (sat_ren _ b σ w').2 (hb b hbb _)) j w
          match hEY with
          | ⟨e0, he0⟩ =>
            let w0 : Nat → D := fun _ => e0
            have s : Sat (RAD M Y) (relE φ) w0 := sound (RAD M Y) d w0 (fun γ m =>
              (mem_app_inv' Δ [] m).elim (fun mΔ => hmod γ mΔ w0) (fun m' => nomatch m'))
            have s2 : Sat R φ w0 := (hR φ (.head _) w0 (fun _ => he0)).1 ((satD_rel M Y φ hl w0).1 s)
            sat_agreeU R φ 0 hf (fun n hn => absurd hn (Nat.not_lt_zero n)) s2)

end AKD

end Found

#print axioms Found.AKD.satD_L0
#print axioms Found.AKD.satD_rel
#print axioms Found.AKD.sat_trA
#print axioms Found.AKD.ext_AD
#print axioms Found.AKD.her1_AD
#print axioms Found.AKD.her2_AD
#print axioms Found.AKD.comp_AD
#print axioms Found.AKD.found_AD
#print axioms Found.AKD.ack_AD
#print axioms Found.AKD.ack_zf

#print axioms: 10 theorems, no axioms.

85.144 IST is conservative over ZFC

Inside any model of ZFC: Zermelo’s theorem, the ultrafilter theorem, Kuratowski finiteness, the internal ultrapower of a reflecting level by a fine ultrafilter and Łoś’s theorem; it satisfies transfer, idealization and standardization, so Nelson’s IST proves no new internal sentences.

\[ \mathrm {IST} \vdash \varphi \Rightarrow \mathrm {ZFC} \vdash \varphi \]

found/IZ21.lean

/-
  T165 (general), part G7. found/IZ21 — Nelson's IST is conservative over
  ZFC: if IST proves an internal sentence φ, then ZFC proves φ.
  In any model of ZFC: reflect φ, FinF, the closure formula below and the
  finitely many internal axioms used to a level Y = V_α (found/IZ10);
  I = finite members of Y, an ultrafilter U ⊇ the fine base (found/IZ13,
  IZ14); the functions I → Y modulo U (found/IZ17–20) satisfy every IST
  axiom used, hence φ; by Łoś and reflection φ holds in the model;
  completeness (found/FOClassicalT) gives a ZFC proof.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.IZ20
import found.Ist5

namespace Found

namespace IZ

open FO FOCT NBGc RF AK

theorem zf01 {φ : Fm} (h : ZF B0 φ) : ZF B1 φ :=
  match h with
  | .inl e => .inl e
  | .inr (.inl hb) => .inr (.inl (.inl hb))
  | .inr (.inr r) => .inr (.inr r)

/-- ∀a ∀b ∃d (a ⊆ d ∧ b ∈ d) -/
def adjF : Fm := .all (.all (.ex (.conj (.all (.imp (m 0 3) (m 0 1))) (m 1 0))))

theorem l0_adjF : L0 adjF := ⟨fun_l0, l0_m 1 0⟩
where fun_l0 : L0 (.all (.imp (m 0 3) (m 0 1))) := ⟨l0_m 0 3, l0_m 0 1⟩

def ZMof {D : Type} (R : Nat → List D → Prop) (hM : ModT (ZF B1) R) (d : D) : ZM :=
  ⟨D, R, fun φ h => hM φ (zf01 h), d⟩

theorem ist_zfc (K : CP.Classical') {φ : Fm} (hl : L0 φ) (hf : FV 0 φ) (h : PC IST.Ist [] φ) :
    PC (ZF B1) [] φ :=
  completenessT (ZF B1) K (fun D R v hM _ => by
    let M : ZM := ZMof R hM (v 0)
    have hac : ACsem M := ac_sem M (hM acAx (.inr (.inl (.inr rfl))))
    match h with
    | ⟨Δ, cΔ, d⟩ =>
    match IST.extractI Δ cΔ with
    | ⟨L, hL, hΔ⟩ =>
    have hΦ : ∀ ψ, ψ ∈ φ :: IST.FinF :: adjF :: L → L0 ψ := fun ψ m => by
      cases m with
      | head => exact hl
      | tail _ m' =>
        cases m' with
        | head => exact IST.l0_FinF
        | tail _ m'' =>
          cases m'' with
          | head => exact l0_adjF
          | tail _ m3 => exact IST.zf_l0 (hL ψ m3)
    match reflection_D M K (φ :: IST.FinF :: adjF :: L) hΦ with
    | ⟨α, Y, hαo, hYv, hEY, hR⟩ =>
    have htr : ∀ x y, In M y Y → In M x y → In M x Y := fun x y hy hxy => vl_trans M K hαo hYv y x hy hxy
    have hsub : ∀ x z, In M z Y → SubS M x z → In M x Y := fun _ _ hz hs => vl_sub M K hYv hz hs
    match hEY with
    | ⟨e0, he0⟩ =>
    have hE : ∃ e, In M e Y ∧ ∀ s, ¬ In M s e := match sep M (def_false M) (fun _ => e0) e0 with
      | ⟨e, he⟩ => ⟨e, hsub e e0 he0 (fun s hs => ((he s).1 hs).1), fun s hs => ((he s).1 hs).2⟩
    have hadj : ∀ a b, In M a Y → In M b Y → ∃ d, In M d Y ∧ SubS M a d ∧ In M b d := fun a b ha hb =>
      have s1 : Sat M.R adjF (fun _ => e0) := fun a' b' => match adj_exists M a' b' with
        | ⟨c, hc⟩ => ⟨c, fun s hs => (hc s).2 (.inl hs), (hc b').2 (.inr (ceq_refl M.R b'))⟩
      have s2 := (hR adjF (.tail _ (.tail _ (.head _))) (fun _ => e0) (fun _ => he0)).2 s1
      match s2 a ha b hb with
      | ⟨d, hd, hsd, hbd⟩ => ⟨d, hd, fun s hs => hsd s (htr s a ha hs) hs, hbd⟩
    have hA : ∀ u t, In M u Y → In M t Y → ∃ c, In M c Y ∧ ∀ s, In M s c ↔ In M s u ∨ Ceq M.R s t :=
      fun u t hu ht => match hadj u t hu ht, adj_exists M u t with
        | ⟨d, hd, hud, htd⟩, ⟨c, hc⟩ => ⟨c, hsub c d hd (fun s hs => ((hc s).1 hs).elim (hud s)
            (fun e => mem_ceq_l M (ceq_symm M.R e) htd)), hc⟩
    match sep M (def_FinD M 0) (fun _ => e0) Y with
    | ⟨I, hI⟩ =>
    match power_ex M I with
    | ⟨PI, hPI⟩ =>
    match sep M (P := fun u => ∃ F, In M F (u 1) ∧ ∀ i, In M i (u 0) ↔ In M i (u 1) ∧ SubS M F i)
        (def_ex M (def_and M (def_mem M 0 2) (def_all M (def_iff M (def_mem M 0 2)
          (def_and M (def_mem M 0 3) (def_SubS M 1 0)))))) (fun _ => I) PI with
    | ⟨F0, hF0'⟩ =>
    have hF0 : ∀ A, In M A F0 ↔ SubS M A I ∧ ∃ F, In M F I ∧ ∀ i, In M i A ↔ In M i I ∧ SubS M F i := fun A =>
      (hF0' A).trans ⟨fun ⟨h1, h2⟩ => ⟨(hPI A).1 h1, h2⟩, fun ⟨h1, h2⟩ => ⟨(hPI A).2 h1, h2⟩⟩
    have hbase := fine_base M htr hE hA hI hF0
    match ultra_ext M K hac hbase with
    | ⟨U, hPF, hult⟩ =>
    have hIU : In M I U := match hbase.2.1 with
      | ⟨A0, hA0⟩ => hPF.2.2.2.1 A0 I (hPF.2.1 A0 hA0) (fun _ h => h) (hbase.1 A0 hA0)
    let P : UP M := ⟨I, Y, U, F0, hPF, hIU, hult, ⟨e0, he0⟩, hsub⟩
    have hfine : ∀ y, In M y Y → AEU M U (fun i => In M y i) := fun y hy =>
      match sep M (def_mem M 1 0) (fun _ => y) I with
      | ⟨A, hAs⟩ => ⟨A, fine_mem M hE hA hI hF0 hPF hy hAs, fun i hi => ((hAs i).1 hi).2⟩
    have hRF : ∀ w : Nat → M.D, (∀ n, In M (w n) Y) → (SatG M.R (YC M Y) IST.FinF w ↔ Sat M.R IST.FinF w) :=
      fun w hw => hR IST.FinF (.tail _ (.head _)) w hw
    have hI' : ∀ i, In M i I → In M i Y ∧ FinD M i := fun i hi => (hI i).1 hi
    -- the ultrapower structure
    let C : M.D → Prop := FnY M I Y
    let Rst := Rsub (RSt M U Y) C
    have vals : ∀ (fs : Nat → M.D), (∀ n, C (fs n)) → ∀ i, In M i I →
        ∃ vv : Nat → M.D, (∀ n, In M (vv n) Y) ∧ ∀ n, InG M (fs n) i (vv n) := fun fs hfs i hi =>
      ⟨fun n => K.ch (fun a => In M a Y ∧ InG M (fs n) i a) ((hfs n).1 i hi),
       fun n => (K.ch_spec (fun a => In M a Y ∧ InG M (fs n) i a) ((hfs n).1 i hi)).1,
       fun n => (K.ch_spec (fun a => In M a Y ∧ InG M (fs n) i a) ((hfs n).1 i hi)).2⟩
    have hb : ∀ b, IST.IstIn L b → ∀ w : Nat → {x // C x}, Sat Rst b w := fun b hb w =>
      have hfs : ∀ n, C ((fun n => (w n).1) n) := fun n => (w n).2
      (sat_sub _ C b w).2 (match hb with
        | .inl ⟨hz, m⟩ =>
          (los M K hac hPF hult ⟨e0, he0⟩ b (IST.zf_l0 hz) _ hfs).2 ⟨I, hIU, fun i hi =>
            match vals _ hfs i hi with
            | ⟨vv, hvY, hvv⟩ => (pt_val M (τ := vecI3 M i I Y) hi b (IST.zf_l0 hz) _ hfs vv hvv).2
                ((hR b (.tail _ (.tail _ (.tail _ m))) vv hvY).2 (hM b hz vv))⟩
        | .inr (.inl ⟨θ, k, h1, h2, e⟩) => by rw [e]; exact trans_S P K hac h1 h2 _ hfs
        | .inr (.inr (.inl ⟨B, k, h1, h2, e⟩)) => by rw [e]; exact ideal_S P K hac hRF hfine htr hI' h1 h2 _ hfs
        | .inr (.inr (.inr ⟨Φ', k, _, e⟩)) => by rw [e]; exact std_S P Φ' k _ hfs)
    have hmod : ∀ δ, δ ∈ Δ → ∀ w, Sat Rst δ w := fun δ m w => match hΔ δ m with
      | ⟨j, a, ha, e⟩ => by
        rw [e]
        exact clo_sat _ (fun w' => match ha with
          | .inl ⟨b, eb⟩ => by rw [eb]; exact K.lem (Sat Rst b w')
          | .inr ⟨b, σ, hbb, eb⟩ => by rw [eb]; exact (sat_ren _ b σ w').2 (hb b hbb _)) j w
    match isC_ex P he0 with
    | ⟨c0, hc0⟩ =>
    let w0 : Nat → {x // C x} := fun _ => ⟨c0, hc0.1⟩
    have s : Sat Rst φ w0 := sound Rst d w0 (fun γ m =>
      (mem_app_inv' Δ [] m).elim (fun mΔ => hmod γ mΔ w0) (fun m' => nomatch m'))
    have s1 : SatG M.R (YC M Y) φ (fun _ => e0) :=
      (losC M hPF hIU K hac hult ⟨e0, he0⟩ φ hl (fun _ => c0) (fun _ => e0) (fun _ => hc0.1)
        (fun _ i hi => hc0.2 i hi)).1 ((sat_sub _ C φ w0).1 s)
    have s2 : Sat M.R φ (fun _ => e0) := (hR φ (.head _) (fun _ => e0) (fun _ => he0)).1 s1
    exact sat_agreeU R φ 0 hf (fun n hn => absurd hn (Nat.not_lt_zero n)) s2)

end IZ

end Found

#print axioms Found.IZ.zf01
#print axioms Found.IZ.ist_zfc

#print axioms: 2 theorems, no axioms.

85.145 Danos–Regnier sequentialization

Every correct MLL proof structure (all switching graphs connected with one edge fewer than vertices) is realized by a derivation built from exactly its links: blocks are merged greedily, and progress follows from counting tensors against blocks.

\[ \forall s.\ G_s \text { is a tree} \Rightarrow \exists \, \pi \vdash \Gamma ,\ \mathrm {net}(\pi ) = N \]

found/Seq6.lean

/-
  T179, sequentialization, part 6. found/Seq6 — the parsing steps and
  Danos–Regnier sequentialization: every correct MLL proof structure is the
  proof net of a derivation. A ready ⅋ joins its block; a ready ⊗ merges
  the two blocks of its premises; by the progress lemma (found/Seq4) the
  parse goes on until one block holds every vertex; its realization is a
  derivation built from exactly the links of the net, whose conclusions
  are the vertices with no link below.

  Lean 4 core only, hand-written proofs, no axioms.
  Classical point: K (case distinctions of the progress lemma), as a parameter.
-/
import found.Seq5

namespace Found

namespace SQ

open PN

variable (N : Net)

/-! ## list tools -/

theorem sumL_app (f : Nat → Nat) : (a b : List Nat) → sumL f (a ++ b) = sumL f a + sumL f b
  | [], b => (Nat.zero_add _).symm
  | x :: a, b => by
    show f x + sumL f (a ++ b) = f x + sumL f a + sumL f b
    rw [sumL_app f a b, Nat.add_assoc]

theorem mem_swap_end (a b : List Nat) (x z : Nat) : z ∈ a ++ b ++ [x] ↔ z ∈ a ++ [x] ++ b :=
  ⟨fun h => ((mem_app_iff _ _).1 h).elim
      (fun h' => ((mem_app_iff a b).1 h').elim (fun m => (mem_app_iff _ _).2 (.inl ((mem_app_iff _ _).2 (.inl m))))
        (fun m => (mem_app_iff _ _).2 (.inr m)))
      (fun m => (mem_app_iff _ _).2 (.inl ((mem_app_iff _ _).2 (.inr m)))),
   fun h => ((mem_app_iff _ _).1 h).elim
      (fun h' => ((mem_app_iff a [x]).1 h').elim (fun m => (mem_app_iff _ _).2 (.inl ((mem_app_iff _ _).2 (.inl m))))
        (fun m => (mem_app_iff _ _).2 (.inr m)))
      (fun m => (mem_app_iff _ _).2 (.inl ((mem_app_iff _ _).2 (.inr m))))⟩

theorem nd_toEnd (x : Nat) : (a b : List Nat) → Nd (a ++ [x] ++ b) → Nd (a ++ b ++ [x])
  | [], b, h => nd_app b [x] h.2 (nd_single x) (fun _ hy hyx => h.1 ((mem_one hyx) ▸ hy))
  | y :: a, b, h => ⟨fun m => h.1 ((mem_swap_end a b x y).1 m), nd_toEnd x a b h.2⟩

/-- move one conclusion to the end, keeping track of membership and repetition -/
theorem mv {B ds : List Nat} (r : Nonempty (Rz N B ds)) {x : Nat} (hx : x ∈ ds) (hnd : Nd ds) :
    ∃ Γ, (∀ y, y ∈ Γ ++ [x] ↔ y ∈ ds) ∧ Nd (Γ ++ [x]) ∧ Nonempty (Rz N B (Γ ++ [x])) :=
  match split_mem hx, r with
  | ⟨a, b, e⟩, ⟨r'⟩ => ⟨a ++ b, fun y => (mem_swap_end a b x y).trans (by rw [e]),
      nd_toEnd x a b (e ▸ hnd), ⟨toEnd N a x b (castR N e r')⟩⟩

/-- move two conclusions to the end, in this order -/
theorem mv2 {B ds : List Nat} (r : Nonempty (Rz N B ds)) {x y : Nat} (hx : x ∈ ds) (hy : y ∈ ds) (hxy : x ≠ y)
    (hnd : Nd ds) : ∃ Γ, (∀ z, z ∈ Γ ++ [x, y] ↔ z ∈ ds) ∧ Nd (Γ ++ [x, y]) ∧ Nonempty (Rz N B (Γ ++ [x, y])) :=
  match mv N r hx hnd with
  | ⟨Γ1, hm1, hn1, ⟨r1⟩⟩ =>
    have hy1 : y ∈ Γ1 := ((mem_app_iff Γ1 [x]).1 ((hm1 y).2 hy)).elim id (fun m => absurd (mem_one m).symm hxy)
    match split_mem hy1 with
    | ⟨a, b, e⟩ =>
      have e2 : Γ1 ++ [x] = a ++ [y] ++ (b ++ [x]) := by rw [e, app_assocN (a ++ [y]) b [x]]
      have e3 : a ++ (b ++ [x]) ++ [y] = (a ++ b) ++ [x, y] := by
        rw [app_assocN a (b ++ [x]) [y], app_assocN a b [x, y], app_assocN b [x] [y]]; rfl
      ⟨a ++ b, fun z => by
          rw [← e3]
          exact (mem_swap_end a (b ++ [x]) y z).trans (by rw [← e2]; exact hm1 z),
        by rw [← e3]; exact nd_toEnd y a (b ++ [x]) (e2 ▸ hn1),
        ⟨castR N e3 (toEnd N a y (b ++ [x]) (castR N e2 r1))⟩⟩

/-! ## the count of unprocessed vertices -/

def UC (Bs : List (Blk N)) : Nat := sumR (fun v => cond (!inAny N v Bs) 1 0) N.n

theorem uc_step {Bs Bs' : List (Blk N)} {P : Nat} (hP : P < N.n) (hu : inAny N P Bs = false)
    (h : ∀ v, inAny N v Bs' = (inAny N v Bs || eqB v P)) : UC N Bs = UC N Bs' + 1 := by
  have e : sumR (fun v => cond (!inAny N v Bs) 1 0) N.n =
      sumR (fun v => cond (!inAny N v Bs') 1 0 + cond (eqB v P) 1 0) N.n :=
    sumR_congr N.n (fun v _ => by
      rw [h v]
      match he : eqB v P with
      | true => rw [eqB_eq he, hu]; rfl
      | false => cases inAny N v Bs <;> rfl)
  unfold UC
  rw [e, sumR_add, sumR_single (fun _ => 1) P N.n hP]

theorem mem_cons' {x a : Nat} {l : List Nat} (h : x ∈ a :: l) : x = a ∨ x ∈ l :=
  match h with
  | .head _ => .inl rfl
  | .tail _ m => .inr m

theorem memB {D E : Blk N} {l : List (Blk N)} (h : D ∈ E :: l) : D = E ∨ D ∈ l :=
  match h with
  | .head _ => .inl rfl
  | .tail _ m => .inr m

theorem cond_tt (b c : Bool) : cond b true c = (b || c) := by cases b <;> rfl

/-! ## a ready ⅋ joins its block -/

theorem step_par (hw : WF N) {Bs : List (Blk N)} (hi : Inv N Bs) {P : Nat} (hr : ReadyP N Bs P) :
    ∃ Bs', Inv N Bs' ∧ UC N Bs = UC N Bs' + 1 := by
  match hr with
  | ⟨hPn, hPu, hPk, B, hB, hlB, hrB⟩ =>
  match split_blk N hB with
  | ⟨A, C, eBs⟩ =>
  have bi := hi.blk B hB
  have hPB : ¬ P ∈ B.vs := fun m => absurd (mem_inAny N hB m) (by rw [hPu]; exact fun e => Bool.noConfusion e)
  have chP : ∀ c, (c = N.lc P ∨ c = N.rc P) → Child N c P := fun c hc => ⟨hPn, .inr hPk, hc⟩
  have pdoor : ∀ c, (c = N.lc P ∨ c = N.rc P) → c ∈ B.vs → c ∈ B.ds := fun c hc hcB =>
    (bi.door c).2 ⟨hcB, fun u hu huB => hPB ((hw.par1 c u P hu (chP c hc)) ▸ huB)⟩
  have hne : N.lc P ≠ N.rc P := (hw.ch P hPn (.inr hPk)).2.2
  match mv2 N bi.rz (pdoor _ (.inl rfl) hlB) (pdoor _ (.inr rfl) hrB) hne bi.dnd with
  | ⟨Γ, hmΓ, hnΓ, ⟨r⟩⟩ =>
  have inΓ : ∀ x, x ∈ Γ → x ∈ B.ds ∧ x ≠ N.lc P ∧ x ≠ N.rc P := fun x hx =>
    ⟨(hmΓ x).1 ((mem_app_iff _ _).2 (.inl hx)),
     fun e => nd_app_disj Γ [N.lc P, N.rc P] hnΓ x hx (e ▸ .head _),
     fun e => nd_app_disj Γ [N.lc P, N.rc P] hnΓ x hx (e ▸ .tail _ (.head _))⟩
  have parentP : ∀ u, Child N P u → ¬ u ∈ P :: B.vs := fun u hu hm => match hm with
    | .head _ => hPB (hu.2.2.elim (fun e => by rw [e]; exact hlB) (fun e => by rw [e]; exact hrB))
    | .tail _ m => hPB (hu.2.2.elim (fun e => by rw [e]; exact (bi.clc u m hu.2.1).1)
        (fun e => by rw [e]; exact (bi.clc u m hu.2.1).2))
  have bi' : BInv N ⟨P :: B.vs, Γ ++ [P]⟩ :=
    { rz := ⟨Rz.par P hPk (hw.labP P hPn hPk) r⟩
      nd := ⟨hPB, bi.nd⟩
      dnd := nd_app Γ [P] (nd_app_l Γ _ hnΓ) (nd_single P) (fun x hx hxP => hPB ((mem_one hxP) ▸ (bi.door x).1 (inΓ x hx).1 |>.1))
      lt := fun x (hx : x ∈ P :: B.vs) => match hx with
        | .head _ => hPn
        | .tail _ m => bi.lt x m
      clc := fun v (hv : v ∈ P :: B.vs) hc => match hv with
        | .head _ => ⟨.tail _ hlB, .tail _ hrB⟩
        | .tail _ m => ⟨.tail _ (bi.clc v m hc).1, .tail _ (bi.clc v m hc).2⟩
      cax := fun v (hv : v ∈ P :: B.vs) hk => match hv with
        | .head _ => absurd (hPk.symm.trans hk) (fun e => Kd.noConfusion e)
        | .tail _ m => .tail _ (bi.cax v m hk)
      door := fun x => ⟨fun (hx : x ∈ Γ ++ [P]) => ((mem_app_iff Γ [P]).1 hx).elim
          (fun hxΓ =>
            have hd := (bi.door x).1 (inΓ x hxΓ).1
            ⟨.tail _ hd.1, fun u hu (hm : u ∈ P :: B.vs) => match hm with
              | .head _ => hu.2.2.elim (inΓ x hxΓ).2.1 (inΓ x hxΓ).2.2
              | .tail _ m => hd.2 u hu m⟩)
          (fun hxP => by rw [mem_one hxP]; exact ⟨.head _, parentP⟩),
        fun ⟨(hm : x ∈ P :: B.vs), hpar⟩ => (mem_cons' hm).elim
          (fun e => by rw [e]; exact (mem_app_iff Γ [P]).2 (.inr (.head _)))
          (fun m =>
            have hd : x ∈ B.ds := (bi.door x).2 ⟨m, fun u hu huB => hpar u hu (.tail _ huB)⟩
            ((mem_app_iff Γ [N.lc P, N.rc P]).1 ((hmΓ x).2 hd)).elim (fun h => (mem_app_iff Γ [P]).2 (.inl h))
              (fun h => absurd (.head _) (hpar P (chP x ((mem2 h).elim .inl .inr)))))⟩
      cnt := by
        show w N P + sumL (w N) B.vs + 1 = 1 + sumL (fun _ => 1) B.vs
        have hwP : w N P = 1 := by unfold w; rw [hPk]
        rw [hwP, ← bi.cnt, Nat.add_assoc] }
  have dp := disj_pick N B A C (eBs ▸ hi.disj)
  have hPAC : inAny N P (A ++ C) = false := by
    have := hPu; rw [eBs, inAny_pick] at this; exact or_false_r this
  refine ⟨⟨P :: B.vs, Γ ++ [P]⟩ :: (A ++ C), ⟨fun D hD => (memB N hD).elim (fun e => by rw [e]; exact bi')
      (fun m => hi.blk D (eBs ▸ mem_of_pick N A C m)),
    ⟨fun x (hx : x ∈ P :: B.vs) => match hx with
      | .head _ => hPAC
      | .tail _ m => dp.1 x m, dp.2⟩,
    fun v hv hk => by
      have h0 := hi.atoms v hv hk
      rw [eBs, inAny_pick] at h0
      show (cond (eqB v P) true (inl v B.vs) || inAny N v (A ++ C)) = true
      rw [cond_tt]
      cases hb : inl v B.vs with
      | true => cases eqB v P <;> rfl
      | false =>
        rw [hb] at h0
        have h0' : inAny N v (A ++ C) = true := h0
        rw [h0']; cases eqB v P <;> rfl⟩, ?_⟩
  exact uc_step N hPn hPu (fun v => by
    show (cond (eqB v P) true (inl v B.vs) || inAny N v (A ++ C)) = (inAny N v Bs || eqB v P)
    rw [eBs, inAny_pick, cond_tt]
    cases eqB v P <;> cases inl v B.vs <;> cases inAny N v (A ++ C) <;> rfl)

/-! ## a ready ⊗ merges two blocks -/

theorem inl_app (v : Nat) : (a b : List Nat) → inl v (a ++ b) = (inl v a || inl v b)
  | [], _ => rfl
  | x :: a, b => by
    show cond (eqB v x) true (inl v (a ++ b)) = (cond (eqB v x) true (inl v a) || inl v b)
    rw [inl_app v a b]
    cases eqB v x <;> rfl

theorem ar3 (s1 s2 l1 l2 : Nat) (h1 : s1 + 1 = l1) (h2 : s2 + 1 = l2) : 2 + (s1 + s2) + 1 = 1 + (l1 + l2) := by
  rw [← h1, ← h2, Nat.add_comm 2, Nat.add_assoc, Nat.add_comm 1 (s1 + 1 + (s2 + 1)), Nat.add_assoc (s1 + 1),
    Nat.add_assoc s1 1, Nat.add_comm 1 (s2 + 1 + 1), Nat.add_assoc s2 1 1, Nat.add_assoc s1 s2]

theorem step_ten (hw : WF N) {Bs : List (Blk N)} (hi : Inv N Bs) {T : Nat} (hr : ReadyT N Bs T) :
    ∃ Bs', Inv N Bs' ∧ UC N Bs = UC N Bs' + 1 := by
  match hr with
  | ⟨hTn, hTu, hTk, hl, hr', hno⟩ =>
  match inAny_mem N hl, inAny_mem N hr' with
  | ⟨B1, hB1, hlB1⟩, ⟨B2, hB2, hrB2⟩ =>
  match split_blk N hB1 with
  | ⟨A, C, eBs⟩ =>
  have hB2AC : B2 ∈ A ++ C := (mem_pick N A C (eBs ▸ hB2)).elim
    (fun e => absurd ⟨B1, hB1, hlB1, by rw [← e]; exact hrB2⟩ hno) id
  match split_blk N hB2AC with
  | ⟨A', C', e2⟩ =>
  have bi1 := hi.blk B1 hB1
  have bi2 := hi.blk B2 hB2
  have dp1 := disj_pick N B1 A C (eBs ▸ hi.disj)
  have dp2 := disj_pick N B2 A' C' (e2 ▸ dp1.2)
  have d12 : ∀ x, x ∈ B1.vs → ¬ x ∈ B2.vs := fun x h1 h2 =>
    absurd (mem_inAny N hB2AC h2) (by rw [dp1.1 x h1]; exact fun e => Bool.noConfusion e)
  have sub' : ∀ x, inAny N x (A' ++ C') = true → inAny N x (A ++ C) = true := fun x h => by
    rw [e2, inAny_pick, h]; cases inl x B2.vs <;> rfl
  have hTB1 : ¬ T ∈ B1.vs := fun m => absurd (mem_inAny N hB1 m) (by rw [hTu]; exact fun e => Bool.noConfusion e)
  have hTB2 : ¬ T ∈ B2.vs := fun m => absurd (mem_inAny N hB2 m) (by rw [hTu]; exact fun e => Bool.noConfusion e)
  have chT : ∀ c, (c = N.lc T ∨ c = N.rc T) → Child N c T := fun c hc => ⟨hTn, .inl hTk, hc⟩
  have ld : N.lc T ∈ B1.ds := (bi1.door _).2 ⟨hlB1, fun u hu huB => hTB1 ((hw.par1 _ u T hu (chT _ (.inl rfl))) ▸ huB)⟩
  have rd : N.rc T ∈ B2.ds := (bi2.door _).2 ⟨hrB2, fun u hu huB => hTB2 ((hw.par1 _ u T hu (chT _ (.inr rfl))) ▸ huB)⟩
  match mv N bi1.rz ld bi1.dnd, mv N bi2.rz rd bi2.dnd with
  | ⟨Γ, hm1, hn1, ⟨r1⟩⟩, ⟨Δ, hm2, hn2, ⟨r2⟩⟩ =>
  have inΓ : ∀ x, x ∈ Γ → x ∈ B1.ds ∧ x ≠ N.lc T := fun x hx =>
    ⟨(hm1 x).1 ((mem_app_iff _ _).2 (.inl hx)), fun e => nd_app_disj Γ [N.lc T] hn1 x hx (e ▸ .head _)⟩
  have inΔ : ∀ x, x ∈ Δ → x ∈ B2.ds ∧ x ≠ N.rc T := fun x hx =>
    ⟨(hm2 x).1 ((mem_app_iff _ _).2 (.inl hx)), fun e => nd_app_disj Δ [N.rc T] hn2 x hx (e ▸ .head _)⟩
  have inV : ∀ x, x ∈ T :: (B1.vs ++ B2.vs) → x = T ∨ x ∈ B1.vs ∨ x ∈ B2.vs := fun x hx =>
    (mem_cons' hx).elim .inl (fun m => .inr ((mem_app_iff _ _).1 m))
  have parentT : ∀ u, Child N T u → ¬ u ∈ T :: (B1.vs ++ B2.vs) := fun u hu hm =>
    (inV u hm).elim
      (fun e => by
        rw [e] at hu
        exact hu.2.2.elim (fun e' => hTB1 (by rw [e']; exact hlB1)) (fun e' => hTB2 (by rw [e']; exact hrB2)))
      (fun h => h.elim
        (fun m => hTB1 (hu.2.2.elim (fun e => by rw [e]; exact (bi1.clc u m hu.2.1).1)
          (fun e => by rw [e]; exact (bi1.clc u m hu.2.1).2)))
        (fun m => hTB2 (hu.2.2.elim (fun e => by rw [e]; exact (bi2.clc u m hu.2.1).1)
          (fun e => by rw [e]; exact (bi2.clc u m hu.2.1).2))))
  have bi' : BInv N ⟨T :: (B1.vs ++ B2.vs), Γ ++ Δ ++ [T]⟩ :=
    { rz := ⟨Rz.ten T hTk (hw.labT T hTn hTk) r1 r2⟩
      nd := ⟨fun m => ((mem_app_iff _ _).1 m).elim hTB1 hTB2, nd_app _ _ bi1.nd bi2.nd d12⟩
      dnd := nd_app (Γ ++ Δ) [T]
        (nd_app Γ Δ (nd_app_l Γ _ hn1) (nd_app_l Δ _ hn2)
          (fun x hx hxD => d12 x ((bi1.door x).1 (inΓ x hx).1).1 ((bi2.door x).1 (inΔ x hxD).1).1))
        (nd_single T)
        (fun x hx hxT => ((mem_app_iff Γ Δ).1 hx).elim
          (fun h => hTB1 ((mem_one hxT) ▸ ((bi1.door x).1 (inΓ x h).1).1))
          (fun h => hTB2 ((mem_one hxT) ▸ ((bi2.door x).1 (inΔ x h).1).1)))
      lt := fun x (hx : x ∈ T :: (B1.vs ++ B2.vs)) => (inV x hx).elim (fun e => e ▸ hTn)
        (fun h => h.elim (bi1.lt x) (bi2.lt x))
      clc := fun v (hv : v ∈ T :: (B1.vs ++ B2.vs)) hc => (inV v hv).elim
        (fun e => by
          rw [e]
          exact ⟨.tail _ ((mem_app_iff _ _).2 (.inl hlB1)), .tail _ ((mem_app_iff _ _).2 (.inr hrB2))⟩)
        (fun h => h.elim
          (fun m => ⟨.tail _ ((mem_app_iff _ _).2 (.inl (bi1.clc v m hc).1)),
            .tail _ ((mem_app_iff _ _).2 (.inl (bi1.clc v m hc).2))⟩)
          (fun m => ⟨.tail _ ((mem_app_iff _ _).2 (.inr (bi2.clc v m hc).1)),
            .tail _ ((mem_app_iff _ _).2 (.inr (bi2.clc v m hc).2))⟩))
      cax := fun v (hv : v ∈ T :: (B1.vs ++ B2.vs)) hk => (inV v hv).elim
        (fun e => absurd (hTk.symm.trans (e ▸ hk)) (fun e' => Kd.noConfusion e'))
        (fun h => h.elim (fun m => .tail _ ((mem_app_iff _ _).2 (.inl (bi1.cax v m hk))))
          (fun m => .tail _ ((mem_app_iff _ _).2 (.inr (bi2.cax v m hk)))))
      door := fun x => ⟨fun (hx : x ∈ Γ ++ Δ ++ [T]) => ((mem_app_iff (Γ ++ Δ) [T]).1 hx).elim
          (fun h => ((mem_app_iff Γ Δ).1 h).elim
            (fun hxΓ =>
              have hd := (bi1.door x).1 (inΓ x hxΓ).1
              ⟨.tail _ ((mem_app_iff _ _).2 (.inl hd.1)), fun u hu (hm : u ∈ T :: (B1.vs ++ B2.vs)) =>
                (inV u hm).elim
                  (fun e => (e ▸ hu).2.2.elim (inΓ x hxΓ).2 (fun e' => d12 x hd.1 (by rw [e']; exact hrB2)))
                  (fun h' => h'.elim (hd.2 u hu)
                    (fun m => d12 x hd.1 (hu.2.2.elim (fun e => by rw [e]; exact (bi2.clc u m hu.2.1).1)
                      (fun e => by rw [e]; exact (bi2.clc u m hu.2.1).2))))⟩)
            (fun hxΔ =>
              have hd := (bi2.door x).1 (inΔ x hxΔ).1
              ⟨.tail _ ((mem_app_iff _ _).2 (.inr hd.1)), fun u hu (hm : u ∈ T :: (B1.vs ++ B2.vs)) =>
                (inV u hm).elim
                  (fun e => (e ▸ hu).2.2.elim (fun e' => d12 x (by rw [e']; exact hlB1) hd.1) (inΔ x hxΔ).2)
                  (fun h' => h'.elim
                    (fun m => d12 x (hu.2.2.elim (fun e => by rw [e]; exact (bi1.clc u m hu.2.1).1)
                      (fun e => by rw [e]; exact (bi1.clc u m hu.2.1).2)) hd.1)
                    (hd.2 u hu))⟩))
          (fun hxT => by rw [mem_one hxT]; exact ⟨.head _, parentT⟩),
        fun ⟨(hm : x ∈ T :: (B1.vs ++ B2.vs)), hpar⟩ => (inV x hm).elim
          (fun e => by rw [e]; exact (mem_app_iff _ _).2 (.inr (.head _)))
          (fun h => h.elim
            (fun m =>
              have hd : x ∈ B1.ds := (bi1.door x).2 ⟨m, fun u hu huB => hpar u hu (.tail _ ((mem_app_iff _ _).2 (.inl huB)))⟩
              ((mem_app_iff Γ [N.lc T]).1 ((hm1 x).2 hd)).elim
                (fun h' => (mem_app_iff _ _).2 (.inl ((mem_app_iff _ _).2 (.inl h'))))
                (fun h' => absurd (.head _) (hpar T (chT x (.inl (mem_one h'))))))
            (fun m =>
              have hd : x ∈ B2.ds := (bi2.door x).2 ⟨m, fun u hu huB => hpar u hu (.tail _ ((mem_app_iff _ _).2 (.inr huB)))⟩
              ((mem_app_iff Δ [N.rc T]).1 ((hm2 x).2 hd)).elim
                (fun h' => (mem_app_iff _ _).2 (.inl ((mem_app_iff _ _).2 (.inr h'))))
                (fun h' => absurd (.head _) (hpar T (chT x (.inr (mem_one h')))))))⟩
      cnt := by
        show w N T + sumL (w N) (B1.vs ++ B2.vs) + 1 = 1 + sumL (fun _ => 1) (B1.vs ++ B2.vs)
        have hwT : w N T = 2 := by unfold w; rw [hTk]
        rw [hwT, sumL_app, sumL_app]
        exact ar3 _ _ _ _ bi1.cnt bi2.cnt }
  have hTAC : inAny N T (A' ++ C') = false := by
    match h : inAny N T (A' ++ C') with
    | false => rfl
    | true =>
      have h1 := sub' T h
      have h2 := hTu
      rw [eBs, inAny_pick, h1] at h2
      revert h2
      cases inl T B1.vs <;> exact fun e => Bool.noConfusion e
  have nB1 : ∀ x, x ∈ B1.vs → inAny N x (A' ++ C') = false := fun x hx => by
    match h : inAny N x (A' ++ C') with
    | false => rfl
    | true => exact absurd (sub' x h) (by rw [dp1.1 x hx]; exact fun e => Bool.noConfusion e)
  refine ⟨⟨T :: (B1.vs ++ B2.vs), Γ ++ Δ ++ [T]⟩ :: (A' ++ C'), ⟨fun D hD => (memB N hD).elim
      (fun e => by rw [e]; exact bi')
      (fun m => hi.blk D (eBs ▸ mem_of_pick N A C (e2 ▸ mem_of_pick N A' C' m))),
    ⟨fun x (hx : x ∈ T :: (B1.vs ++ B2.vs)) => (inV x hx).elim (fun e => e ▸ hTAC)
      (fun h => h.elim (nB1 x) (dp2.1 x)), dp2.2⟩,
    fun v hv hk => by
      have h0 := hi.atoms v hv hk
      rw [eBs, inAny_pick, e2, inAny_pick] at h0
      show (cond (eqB v T) true (inl v (B1.vs ++ B2.vs)) || inAny N v (A' ++ C')) = true
      rw [cond_tt, inl_app]
      revert h0
      cases eqB v T <;> cases inl v B1.vs <;> cases inl v B2.vs <;> cases inAny N v (A' ++ C') <;>
        (intro h; first | rfl | exact h)⟩, ?_⟩
  exact uc_step N hTn hTu (fun v => by
    show (cond (eqB v T) true (inl v (B1.vs ++ B2.vs)) || inAny N v (A' ++ C')) = (inAny N v Bs || eqB v T)
    rw [eBs, inAny_pick, e2, inAny_pick, cond_tt, inl_app]
    cases eqB v T <;> cases inl v B1.vs <;> cases inl v B2.vs <;> cases inAny N v (A' ++ C') <;> rfl)

/-! ## the parse and sequentialization -/

theorem fin_state (hc : Correct N) {Bs : List (Blk N)} (hi : Inv N Bs)
    (hno : ¬ (2 ≤ Bs.length ∨ ∃ v, v < N.n ∧ inAny N v Bs = false)) :
    ∃ B, BInv N B ∧ ∀ v, v < N.n → v ∈ B.vs := by
  have hall : ∀ v, v < N.n → inAny N v Bs = true := fun v hv => by
    match h : inAny N v Bs with
    | true => rfl
    | false => exact absurd (.inr ⟨v, hv, h⟩) hno
  have hn : 0 < N.n := by
    have hcnt := hc.count
    match hN : N.n with
    | 0 => rw [hN] at hcnt; exact absurd hcnt (fun e => Nat.noConfusion e)
    | k + 1 => exact Nat.zero_lt_succ k
  have hlen : Bs.length < 2 := Nat.lt_of_not_le (fun h => hno (.inl h))
  match inAny_mem N (hall 0 hn) with
  | ⟨B, hB, _⟩ => exact ⟨B, hi.blk B hB, fun v hv => match inAny_mem N (hall v hv) with
    | ⟨D, hD, hvD⟩ => (one_block hlen hD hB) ▸ hvD⟩

theorem run (K : CP.Classical') (hw : WF N) (hc : Correct N) : (m : Nat) → ∀ Bs : List (Blk N), Inv N Bs →
    UC N Bs ≤ m → ∃ B, BInv N B ∧ ∀ v, v < N.n → v ∈ B.vs
  | m, Bs, hi, hm => (K.lem (2 ≤ Bs.length ∨ ∃ v, v < N.n ∧ inAny N v Bs = false)).elim
    (fun hne =>
      have next : ∀ Bs', Inv N Bs' → UC N Bs = UC N Bs' + 1 → ∃ B, BInv N B ∧ ∀ v, v < N.n → v ∈ B.vs :=
        fun Bs' hi' he => match m, hm with
          | 0, hm => absurd (by rw [he] at hm; exact hm) (Nat.not_succ_le_zero _)
          | m' + 1, hm => run K hw hc m' Bs' hi' (Nat.le_of_succ_le_succ (by rw [he] at hm; exact hm))
      match progress N K hw hc hi hne with
      | .inl ⟨_, hT⟩ => match step_ten N hw hi hT with
        | ⟨Bs', hi', he⟩ => next Bs' hi' he
      | .inr ⟨_, hP⟩ => match step_par N hw hi hP with
        | ⟨Bs', hi', he⟩ => next Bs' hi' he)
    (fun hno => fin_state N hc hi hno)

theorem uc_le (Bs : List (Blk N)) : UC N Bs ≤ N.n := by
  have h : sumR (fun _ => 1) N.n = N.n := by
    have : ∀ k, sumR (fun _ => 1) k = k := fun k => by
      induction k with
      | zero => rfl
      | succ k ih => show sumR (fun _ => 1) k + 1 = k + 1; rw [ih]
    exact this N.n
  have e := sumR_mono (f := fun v => cond (!inAny N v Bs) 1 0) (g := fun _ => 1) N.n (fun v _ => by
    cases inAny N v Bs with
    | true => exact Nat.zero_le _
    | false => exact Nat.le_refl _)
  rw [h] at e
  exact e

/-- Danos–Regnier sequentialization: a correct proof structure is realized by a derivation built from
    exactly its links, with the vertices without a link below as conclusions -/
theorem sequentialization (K : CP.Classical') (hw : WF N) (hc : Correct N) :
    ∃ vs ds : List Nat, (∀ v, v ∈ vs ↔ v < N.n) ∧ (∀ x, x ∈ ds ↔ x < N.n ∧ ∀ u, ¬ Child N x u) ∧
      Nonempty (Rz N vs ds) :=
  match run N K hw hc N.n (initB N N.n) (init_inv N hw) (uc_le N _) with
  | ⟨B, bi, hall⟩ => ⟨B.vs, B.ds, fun v => ⟨bi.lt v, hall v⟩,
    fun x => (bi.door x).trans ⟨fun ⟨hx, hp⟩ => ⟨bi.lt x hx, fun u hu => hp u hu (hall u hu.1)⟩,
      fun ⟨hx, hp⟩ => ⟨hall x hx, fun u hu _ => hp u hu⟩⟩, bi.rz⟩

/-- in particular the conclusions are derivable in MLL -/
theorem derivable (K : CP.Classical') (hw : WF N) (hc : Correct N) :
    ∃ ds : List Nat, (∀ x, x ∈ ds ↔ x < N.n ∧ ∀ u, ¬ Child N x u) ∧ Nonempty (D (mapF N.lab ds)) :=
  match sequentialization N K hw hc with
  | ⟨_, ds, _, hd, ⟨r⟩⟩ => ⟨ds, hd, ⟨toD N r⟩⟩

end SQ

end Found

#print axioms Found.SQ.mv2
#print axioms Found.SQ.uc_step
#print axioms Found.SQ.step_par
#print axioms Found.SQ.step_ten
#print axioms Found.SQ.run
#print axioms Found.SQ.sequentialization
#print axioms Found.SQ.derivable

#print axioms: 7 theorems, no axioms.

85.146 String diagrams: the topological Joyal–Street theorem

Piecewise-linear plane drawings over any ordered field (boxes as horizontal bars, wires as straight segments) up to planar isotopy, generated by horizontal motions, vertical families meeting no other node, two boxes passing each other’s height, and renumbering: two terms of the same type are equal iff their standard drawings are isotopic.

\[ t \approx u \iff \mathrm {real}(\mathrm {diag}\,t) \simeq \mathrm {real}(\mathrm {diag}\,u) \]

found/Top37.lean

/-
  T193 (topological), part 37. found/Top37 — the topological Joyal–Street
  theorem (piecewise-linear, over any ordered field F): two terms of the
  same type are equal in the free strict monoidal category iff the standard
  plane drawings of their string diagrams are planar isotopic (generated by
  horizontal motions, vertical linear families meeting nothing, two boxes
  passing each other's height, and renumbering, through valid generic
  drawings). With found/StrDiag2 (combinatorial version): planar isotopy of
  drawings = interchange moves of diagrams = equality of terms.

  Lean 4 core only, hand-written proofs, no axioms (classical logic only as
  the parameter K, used for "isotopic ⇒ equal").
-/
import found.Top36

namespace Found

namespace TP

open DetChain LibRing SD

variable {F : OF} {S : Sig}

/-- every interchange step of a typed diagram is realized by an isotopy -/
theorem iso_istep {D D' : List (Ly S)} (h : IStep D D') {A B : Ob} (hD : DTy D A B) : Iso (real F A D) (real F A D') :=
  match istep_form h with
  | ⟨P, X, M, Y, g1, g2, T, e1, e2⟩ => by subst e1; subst e2; exact iso_form P X M Y g1 g2 T hD

/-- diagrams related by interchange moves have isotopic standard drawings -/
theorem iso_deq {D D' : List (Ly S)} (h : DEq D D') : ∀ {A B : Ob}, DTy D A B → Iso (real F A D) (real F A D') := by
  induction h with
  | refl D => exact fun hD => iso_refl ⟨(real_ok hD).1, (real_ok hD).2.1⟩
  | step s => exact fun hD => iso_istep s hD
  | symm h ih => exact fun hD => Iso.symm (ih ((deq_read h).1.2 hD))
  | trans h1 _ ih1 ih2 => exact fun hD => Iso.trans (ih1 hD) (ih2 ((deq_read h1).1.1 hD))

/-- the topological Joyal–Street theorem -/
theorem topo_joyal_street (K : CP.Classical') {t u : Tm S} {A B : Ob} (ht : Ty t A B) (hu : Ty u A B) :
    Eqv t u ↔ Iso (real F A (diag t)) (real F A (diag u)) :=
  ⟨fun h => iso_deq ((joyal_street ht hu).1 h) (diag_ty ht),
   fun h => (joyal_street ht hu).2 (match iso_reads K h (diag t) (real_ok (diag_ty ht)).2.2 with
     | ⟨D', hr, e⟩ => by rw [reads_uniq _ hr (real_ok (diag_ty hu)).2.2] at e; exact e)⟩

end TP

end Found

#print axioms Found.TP.iso_istep
#print axioms Found.TP.iso_deq
#print axioms Found.TP.topo_joyal_street

#print axioms: 3 theorems, no axioms.

85.147 The effective topos

The tripos-to-topos construction over any partial combinatory algebra gives a category with finite limits and power objects (arrows are functional relations up to equivalence); Kleene’s first algebra, in the numbering by codes of closed lambda-terms, is a partial combinatory algebra, so the effective topos RT(K1) is a topos. \(\mathrm {RT}(K_1)\) has \(1\), \(\times \), equalizers and power objects \(PA\) classifying relations

found/K1d.lean

/-
  T96b, K1 part d. found/K1d — the effective topos: the realizability
  topos over Kleene's first algebra K1 (found/K1c), with the topos structure
  of found/Eff1–Eff11 specialised: a terminal object, binary products and
  equalizers (finite limits), and power objects classifying relations.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.K1c

namespace Found

namespace Eff

open K1C

/-- the effective topos: objects and arrows over K1 -/
abbrev EffObj := Obj K1
abbrev EffFn (A B : EffObj) := Fn A B

/-- the effective topos has finite limits and power objects -/
theorem effective_topos :
    (∀ (A : EffObj) (G : EffFn A (one K1)), FEq G (bang A)) ∧
    (∀ (A B C : EffObj) (F : EffFn C A) (G : EffFn C B),
      FEq (compF (pairF F G) (pi1 A B)) F ∧ FEq (compF (pairF F G) (pi2 A B)) G ∧
      ∀ K : EffFn C (prodO A B), FEq (compF K (pi1 A B)) F → FEq (compF K (pi2 A B)) G → FEq K (pairF F G)) ∧
    (∀ (A B C : EffObj) (F G : EffFn A B) (H : EffFn C A) (heq : FEq (compF H F) (compF H G)),
      FEq (compF (incl F G) F) (compF (incl F G) G) ∧ FEq (compF (liftK F G H heq) (incl F G)) H ∧
      ∀ K : EffFn C (eqO F G), FEq (compF K (incl F G)) H → FEq K (liftK F G H heq)) ∧
    (∀ (B A : EffObj) (R : Rel B A),
      (Ent (fun p : B.X × A.X => R.R p.1 p.2) (pbR (chiF R)) ∧ Ent (pbR (chiF R)) (fun p : B.X × A.X => R.R p.1 p.2)) ∧
      ∀ χ : EffFn B (powO A), Ent (fun p : B.X × A.X => R.R p.1 p.2) (pbR χ) → Ent (pbR χ) (fun p : B.X × A.X => R.R p.1 p.2) →
        FEq χ (chiF R)) :=
  ⟨fun _ G => bang_uniq G,
   fun _ _ _ F G => ⟨beta1 F G, beta2 F G, fun K h1 h2 => prod_uniq F G K h1 h2⟩,
   fun _ _ _ F G H heq => ⟨incl_eq F G, lift_comm F G H heq, fun K hK => lift_uniq F G H heq K hK⟩,
   fun _ _ R => ⟨chi_pb R, fun χ h1 h2 => chi_uniq R χ h1 h2⟩⟩

end Eff

end Found

#print axioms Found.Eff.effective_topos

#print axioms: 1 theorem, no axioms.

85.148 Lawvere–Mitchell: ETCS and bounded Zermelo set theory

In any model of ZF(C) the sets and functions satisfy the ETCS axioms (found/EtZ1–EtZ7); conversely, in any model of ETCS (with a classical point) the nodes of well-founded internal graphs, with bisimilarity as equality, form a model of BZC: extensionality, empty set, pairing, union, power set, infinity, \(\Delta _0\)-separation, foundation and choice.

\[ \mathcal {E} \models \mathrm {ETCS} \implies \{(G,x) : G \text { well-founded}\}/\!\simeq \ \models \mathrm {BZC} \]

found/EtB13.lean

/-
  T209 (Lawvere–Mitchell), direction B, part 13. found/EtB13 — every model
  of ETCS gives a model of bounded Zermelo set theory with choice (BZC,
  Mac Lane set theory): the candidate sets are the nodes of well-founded
  internal graphs, equality is bisimilarity and membership is "equivalent
  to a node below". Members of such nodes are again such nodes; all the
  constructions (empty set, pairing, union, power set, ω, Δ₀-separation,
  choice sets) stay among them, and foundation holds (a minimal node of the
  internal set of nodes equivalent to members).

  Lean 4 core only, hand-written proofs, no axioms (classical logic only as
  the parameter K).
-/
import found.EtB12

namespace Found

namespace ETB

namespace ETCS

variable (E : ETCS)

/-- foundation: a nonempty well-founded node has a member disjoint from it -/
theorem foundation (K : CP.Classical') (a : Nd E) (wa : WFG E a.G) (hne : ∃ u, MemN E u a) :
    ∃ m, MemN E m a ∧ ∀ d, MemN E d m → MemN E d a → False := by
  let G := a.G
  let L := Lc E K G G
  match comprE E K (Γ := []) (A := G.X) (.ex G.X (.and (edgeT E G (.var .z) (.cst a.x))
      (memT E (.pr (.var (.s .z)) (.var .z)) (.cst L)))) () with
  | ⟨S, hS⟩ =>
  have sm : ∀ y, Mem E y S ↔ ∃ y', Edge E G y' a.x ∧ EqvR G G y y' := fun y =>
    (hS y).trans ⟨fun ⟨y', h1, h2⟩ => ⟨y', h1, (Lc_spec E K G G y y').1 h2⟩,
      fun ⟨y', h1, h2⟩ => ⟨y', h1, (Lc_spec E K G G y y').2 h2⟩⟩
  match hne with
  | ⟨_, y0, hy0, _⟩ =>
  match wa S ⟨y0, (sm y0).2 ⟨y0, hy0, eqv_refl E K G y0⟩⟩ with
  | ⟨y, hy, hmin⟩ =>
  match (sm y).1 hy with
  | ⟨y', hy', eyy⟩ =>
  exact ⟨⟨G, y⟩, ⟨y', hy', eyy⟩, fun d ⟨z, hz, ed⟩ ⟨z', hz', ed'⟩ =>
    hmin z hz ((sm z).2 ⟨z', hz', eqv_trans E K (eqv_symm E K ed) ed'⟩)⟩

/-- the BZC (Mac Lane) model of an ETCS model, on well-founded nodes -/
theorem bzc_of_etcs (K : CP.Classical') :
    -- members of well-founded nodes are well-founded nodes
    (∀ a, WFG E a.G → ∀ d, MemN E d a → ∃ d', WFG E d'.G ∧ Eqv E d d') ∧
    -- equality is an equivalence respected by membership; extensionality
    (∀ a, Eqv E a a) ∧ (∀ a b, Eqv E a b → Eqv E b a) ∧ (∀ a b c, Eqv E a b → Eqv E b c → Eqv E a c) ∧
    (∀ a a' b b', Eqv E a a' → Eqv E b b' → MemN E a b → MemN E a' b') ∧
    (∀ a b, (∀ c, MemN E c a ↔ MemN E c b) → Eqv E a b) ∧
    -- empty set, pairing, union, power set
    (∃ c, WFG E c.G ∧ ∀ d, MemN E d c → False) ∧
    (∀ a b, WFG E a.G → WFG E b.G → ∃ c, WFG E c.G ∧ ∀ d, MemN E d c ↔ Eqv E d a ∨ Eqv E d b) ∧
    (∀ a, WFG E a.G → ∃ c, WFG E c.G ∧ ∀ d, MemN E d c ↔ ∃ y, MemN E y a ∧ MemN E d y) ∧
    (∀ a, WFG E a.G → ∃ c, WFG E c.G ∧ ∀ d, MemN E d c ↔ ∀ e, MemN E e d → MemN E e a) ∧
    -- infinity
    (∃ w, WFG E w.G ∧ (∃ e, MemN E e w ∧ ∀ d, MemN E d e → False) ∧
      ∀ y, MemN E y w → ∃ z, MemN E z w ∧ ∀ d, MemN E d z ↔ MemN E d y ∨ Eqv E d y) ∧
    -- Δ₀-separation
    (∀ (φ : KP.D0) (ρ : Nat → Nd E) a, WFG E a.G →
      ∃ c, WFG E c.G ∧ ∀ d, MemN E d c ↔ MemN E d a ∧ satN E φ (consN E d ρ)) ∧
    -- foundation
    (∀ a, WFG E a.G → (∃ u, MemN E u a) → ∃ m, MemN E m a ∧ ∀ d, MemN E d m → MemN E d a → False) ∧
    -- choice
    (∀ a, WFG E a.G → (∀ u, MemN E u a → ∃ z, MemN E z u) →
      (∀ u v, MemN E u a → MemN E v a → (∃ z, MemN E z u ∧ MemN E z v) → Eqv E u v) →
      ∃ c, WFG E c.G ∧ ∀ u, MemN E u a → ∃ z, MemN E z u ∧ MemN E z c ∧ ∀ z', MemN E z' u → MemN E z' c → Eqv E z' z) :=
  ⟨fun a wa _ ⟨y, _, ed⟩ => ⟨⟨a.G, y⟩, wa, ed⟩,
   fun a => eqv_refl E K a.G a.x, fun _ _ h => eqv_symm E K h, fun _ _ _ h1 h2 => eqv_trans E K h1 h2,
   fun _ _ _ _ ea eb m => memN_r E K eb (memN_l E K ea m),
   fun _ _ h => ext E K h,
   match empty E K with | ⟨c, h, w⟩ => ⟨c, w, h⟩,
   fun a b wa wb => match pairing E K a b with | ⟨c, h, w⟩ => ⟨c, w wa wb, h⟩,
   fun a wa => match union E K a with | ⟨c, h, w⟩ => ⟨c, w wa, h⟩,
   fun a wa => match power E K a with | ⟨c, h, w⟩ => ⟨c, w wa, h⟩,
   match infinity E K with | ⟨w, h, ww⟩ => ⟨w, ww, h⟩,
   fun φ ρ a wa => match separation E K φ ρ a with | ⟨c, h, w⟩ => ⟨c, w wa, h⟩,
   fun a wa hne => foundation E K a wa hne,
   fun a wa hne hdis => match choice_model E K a hne hdis with | ⟨c, h, w⟩ => ⟨c, w wa, h⟩⟩

end ETCS

end ETB

end Found

#print axioms Found.ETB.ETCS.foundation
#print axioms Found.ETB.ETCS.bzc_of_etcs

#print axioms: 2 theorems, no axioms.

85.149 Friedman: ZF interpreted in intuitionistic set theory

Every model of ZF without extensionality carries the model \((D,\in ^\star )\) of ZF, where \(\sim \) is bisimilarity coded by sets of pair codes and \(x\in ^\star y\) means \(x\sim \) some member of \(y\); with the Gödel–Gentzen translation, whose instances for the axioms are derivable intuitionistically, every theorem of ZF is interpreted in IZF without extensionality.

\[ \mathrm {ZF}\vdash \varphi \implies \mathrm {IZF}\setminus \mathrm {Ext}\vdash _{\mathrm {int}} (\varphi ^\star )^{N} \]

found/Fz6.lean

/-
  T89 (Friedman), part 11. found/Fz6 — Friedman's theorem (1973):
  * every model of ZF∖Ext gives the model (D, ∈⋆) of ZF(B0);
  * hence (soundness and completeness) ZF ⊢ φ implies ZF∖Ext ⊢ φ⋆;
  * with the double-negation interpretation (found/DNeg5): ZF ⊢ φ implies
    IZF∖Ext ⊢ (φ⋆)* intuitionistically — ZF is interpreted in the
    intuitionistic set theory IZF∖Ext.

  Lean 4 core only, hand-written proofs, no axioms (classical logic only as
  the parameter K, for the classical side).
-/
import found.Fz5
import found.NbgZ5

namespace Found

namespace FZ

open FO FOCT NBGc DN

theorem model_s (M : EM) (K : CP.Classical') : ∀ φ, ZF B0 φ → ∀ v : Nat → M.D, Sat (Rs M) φ v := by
  intro φ hφ v
  match hφ with
  | .inl e =>
    rw [e]
    exact fun _ _ hco _ hxw => memS_l M (memS_ext M (fun z => ⟨(hco z).1, (hco z).2⟩)) hxw
  | .inr (.inl hb) =>
    match hb with
    | .inl e =>
      rw [e]
      exact fun a b => match pair_s M a b with
        | ⟨c, hc⟩ => ⟨c, fun u => ⟨fun h => ((hc u).1 h).elim (fun x => .inl ((eqF_sim M).2 x)) (fun x => .inr ((eqF_sim M).2 x)),
            fun h => (hc u).2 (h.elim (fun x => .inl ((eqF_sim M).1 x)) (fun x => .inr ((eqF_sim M).1 x)))⟩⟩
    | .inr (.inl e) =>
      rw [e]
      exact fun a => match union_s M a with
        | ⟨c, hc⟩ => ⟨c, fun u => ⟨fun h => (hc u).1 h, fun h => (hc u).2 h⟩⟩
    | .inr (.inr (.inl e)) =>
      rw [e]
      exact fun a => match power_s M a with
        | ⟨c, hc⟩ => ⟨c, fun u => ⟨fun h => (hc u).1 h, fun h => (hc u).2 h⟩⟩
    | .inr (.inr (.inr e)) =>
      rw [e]
      exact match inf_s M with
        | ⟨w, he, hs⟩ => ⟨w, he, fun x hx => match hs x hx with
          | ⟨y, hy, hy'⟩ => ⟨y, hy, fun s => ⟨fun h => ((hy' s).1 h).elim .inl (fun e' => .inr ((eqF_sim M).2 e')),
              fun h => (hy' s).2 (h.elim .inl (fun e' => .inr ((eqF_sim M).1 e')))⟩⟩⟩
  | .inr (.inr (.inl ⟨θ, hl, e⟩)) =>
    rw [e]
    intro x hpre
    have eA : ∀ w z z', Sat (Rs M) (ren (r3 2 1) θ) (ext (ext (ext (ext v x) w) z) z') ↔ Sat (Rs M) θ (ext (ext v z) w) :=
      fun _ _ _ => (sat_ren (Rs M) θ _ _).trans (sat_ext (Rs M) θ (fun n => match n with
        | 0 => rfl
        | 1 => rfl
        | _ + 2 => rfl))
    have eB : ∀ w z z', Sat (Rs M) (ren (r3 2 0) θ) (ext (ext (ext (ext v x) w) z) z') ↔ Sat (Rs M) θ (ext (ext v z') w) :=
      fun _ _ _ => (sat_ren (Rs M) θ _ _).trans (sat_ext (Rs M) θ (fun n => match n with
        | 0 => rfl
        | 1 => rfl
        | _ + 2 => rfl))
    have eC : ∀ y z w, Sat (Rs M) (ren (r3 0 1) θ) (ext (ext (ext (ext v x) y) z) w) ↔ Sat (Rs M) θ (ext (ext v z) w) :=
      fun _ _ _ => (sat_ren (Rs M) θ _ _).trans (sat_ext (Rs M) θ (fun n => match n with
        | 0 => rfl
        | 1 => rfl
        | _ + 2 => rfl))
    match repl_s M K hl v x (fun w hw z z' h1 h2 =>
        (eqF_sim M (v := ext (ext (ext (ext v x) w) z) z') (i := 1) (j := 0)).1
          (hpre w hw z z' ⟨(eA w z z').2 h1, (eB w z z').2 h2⟩)) with
    | ⟨y, hy⟩ => exact ⟨y, fun z => ⟨fun hz => match (hy z).1 hz with
        | ⟨w, h1, h2⟩ => ⟨w, h1, (eC y z w).2 h2⟩,
      fun ⟨w, h1, h2⟩ => (hy z).2 ⟨w, h1, (eC y z w).1 h2⟩⟩⟩
  | .inr (.inr (.inr ⟨θ, hl, e⟩)) =>
    rw [e]
    intro hx
    have e1 : ∀ x y, Sat (Rs M) (ren (up Nat.succ) θ) (ext (ext v x) y) ↔ Sat (Rs M) θ (ext v y) := fun _ _ =>
      (sat_ren (Rs M) θ _ _).trans (sat_ext (Rs M) θ (fun n => match n with
        | 0 => rfl
        | _ + 1 => rfl))
    match found_s M K hl v hx with
    | ⟨x, h1, h2⟩ => exact ⟨x, h1, fun y hy ht => h2 y hy ((e1 x y).1 ht)⟩

/-- ZF ⊢ φ ⇒ ZF∖Ext ⊢ φ⋆ -/
theorem zf_zfe (K : CP.Classical') {φ : Fm} (hl : L0 φ) (h : PC (ZF B0) [] φ) : PC ZFE [] (star K φ) :=
  completenessT ZFE K (fun D R v hM _ =>
    let M : EM := ⟨D, R, hM, v 0⟩
    (star_sat M K φ hl v).2 (soundnessT (ZF B0) K h D (Rs M) v (model_s M K) (fun _ m => nomatch m)))

/-- Friedman: ZF ⊢ φ ⇒ IZF∖Ext ⊢ (φ⋆)* (intuitionistically) -/
theorem friedman (K : CP.Classical') {φ : Fm} (hl : L0 φ) (h : PC (ZF B0) [] φ) : IPC ZFE [] (gg (star K φ)) :=
  zfe_izfe (zf_zfe K hl h)

end FZ

end Found

#print axioms Found.FZ.model_s
#print axioms Found.FZ.zf_zfe
#print axioms Found.FZ.friedman

#print axioms: 3 theorems, no axioms.

85.150 The classifying topos of a geometric theory

For a geometric theory \(T\) (sequents in finite contexts, inhabited models), the countable syntactic site \((\mathcal {C}_T, J_T)\) is subcanonical with a generic universal model \(U\); for every site \((D,K)\), left exact geometric morphisms \(\mathrm {Sh}(D,K)\to \mathrm {Sh}(\mathcal {C}_T,J_T)\) correspond to inhabited \(T\)-models in \(\mathrm {Sh}(D,K)\) (via flat continuous functors and Diaconescu’s theorem), with \(N_{f_N}\cong N\) and \((f_{N_f})_*\cong f_*\).

\[ \mathbf {Geom}_{\mathrm {lex}}(\mathrm {Sh}(D,K), \mathrm {Sh}(\mathcal {C}_T,J_T)) \simeq T\text {-}\mathbf {Mod}_{\mathrm {inh}}(\mathrm {Sh}(D,K)),\quad f \mapsto f^*(U) \]

found/Gt88.lean

/-
  T194 (classifying topos), part 88. found/Gt88 — the classifying topos of
  a geometric theory T (sequents in finite contexts; models inhabited):
  B[T] = Sh(C_T, J_T). For every site (D, K):
  * a left exact geometric morphism f : Sh(D, K) → B[T] gives an
    inhabited T-model N_f, whose carrier is f*(U), the inverse image of
    the carrier of the universal model;
  * an inhabited T-model N gives a left exact geometric morphism f_N;
  * N_{f_N} ≅ N, and f_{N_f} has the same direct image as f (up to
    natural isomorphism).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Gt87

namespace Found

namespace Gt

open Sh

variable (T : Seq → Prop) (hT : ∀ σ, T σ → ∃ k, FVg k σ.lhs ∧ FVg k σ.rhs) (Kc : CP.Classical')

/-- the model of a left exact geometric morphism into B[T] -/
def modelOfGeom {D : ECat.{0, 0}} {K : GTop D} (f : Geom (JTc T Kc) K) (hE : EqPres (JTc T Kc) K f) : SModel T :=
  NFModel T K (Ff (JTc T Kc) (yo_sheaf T Kc) K f) Kc (ff_flat (JTc T Kc) (yo_sheaf T Kc) K f hE)
    (ff_cont (JTc T Kc) (yo_sheaf T Kc) K f) hT

/-- the geometric morphism of an inhabited model -/
def geomOfModel (N : SModel T) (hI : Inh N) : Geom (JTc T Kc) N.K :=
  geomD (JTc T Kc) N.K (FN N Kc hI) (fn_flat N Kc hI) Kc (fn_cont N Kc hI)

theorem geomOfModel_lex (N : SModel T) (hI : Inh N) : EqPres (JTc T Kc) N.K (geomOfModel T Kc N hI) :=
  geomD_eq (JTc T Kc) N.K (FN N Kc hI) (fn_flat N Kc hI) Kc (fn_cont N Kc hI)

/-- the carrier of N_f is f*(U) -/
theorem modelOfGeom_carrier {D : ECat.{0, 0}} {K : GTop D} (f : Geom (JTc T Kc) K) (hE : EqPres (JTc T Kc) K f) :
    (modelOfGeom T hT Kc f hE).M.P = (f.inv.obj ⟨(UStr T).P, yo_sheaf T Kc U1⟩).1 := rfl

/-- N_{f_N} ≅ N -/
def model_roundtrip (N : SModel T) (hI : Inh N) :
    SIso (modelOfGeom T hT Kc (geomOfModel T Kc N hI) (geomOfModel_lex T Kc N hI)).M N.M :=
  SIso.trans (nf_fiso T N.K (fiso_geomD (JTc T Kc) (yo_sheaf T Kc) N.K (FN N Kc hI) (fn_flat N Kc hI) Kc
    (fn_cont N Kc hI))) (nfn_iso N Kc hI)

section G

variable {D : ECat.{0, 0}} {K : GTop D} (f : Geom (JTc T Kc) K) (hE : EqPres (JTc T Kc) K f) (Q : (ShCat K).Ob)

/-- f_* Q → (f_{N_f})_* Q -/
def dirForth : PNat (f.dir.obj Q).1
    ((geomOfModel T Kc (modelOfGeom T hT Kc f hE) (nf_inh T K _ Kc _ _ hT)).dir.obj Q).1 :=
  compN (dirTo (JTc T Kc) (yo_sheaf T Kc) K f Q)
    (dirP_fiso K (fiso_fnf T K (Ff (JTc T Kc) (yo_sheaf T Kc) K f) Kc (ff_flat (JTc T Kc) (yo_sheaf T Kc) K f hE)
      (ff_cont (JTc T Kc) (yo_sheaf T Kc) K f) hT).symm Q)

/-- (f_{N_f})_* Q → f_* Q -/
def dirBack : PNat ((geomOfModel T Kc (modelOfGeom T hT Kc f hE) (nf_inh T K _ Kc _ _ hT)).dir.obj Q).1
    (f.dir.obj Q).1 :=
  compN (dirP_fiso K (fiso_fnf T K (Ff (JTc T Kc) (yo_sheaf T Kc) K f) Kc (ff_flat (JTc T Kc) (yo_sheaf T Kc) K f hE)
      (ff_cont (JTc T Kc) (yo_sheaf T Kc) K f) hT) Q)
    (dirFrom (JTc T Kc) (yo_sheaf T Kc) K f Q)

theorem dir_back_forth {A : SObj} (q : ((f.dir.obj Q).1.obj A).car) :
    ((f.dir.obj Q).1.obj A).eqv ((dirBack T hT Kc f hE Q).app A ((dirForth T hT Kc f hE Q).app A q)) q :=
  ((f.dir.obj Q).1.obj A).trans ((dirFrom (JTc T Kc) (yo_sheaf T Kc) K f Q).app_eqv A
    (dirP_fiso_inv K (fiso_fnf T K _ Kc (ff_flat (JTc T Kc) (yo_sheaf T Kc) K f hE)
      (ff_cont (JTc T Kc) (yo_sheaf T Kc) K f) hT).symm Q _))
    (dir_from_to (JTc T Kc) (yo_sheaf T Kc) K f Q q)

theorem dir_forth_back {A : SObj}
    (β : (((geomOfModel T Kc (modelOfGeom T hT Kc f hE) (nf_inh T K _ Kc _ _ hT)).dir.obj Q).1.obj A).car) :
    (((geomOfModel T Kc (modelOfGeom T hT Kc f hE) (nf_inh T K _ Kc _ _ hT)).dir.obj Q).1.obj A).eqv
      ((dirForth T hT Kc f hE Q).app A ((dirBack T hT Kc f hE Q).app A β)) β := fun c x =>
  (Q.1.obj c).trans (dir_to_from (JTc T Kc) (yo_sheaf T Kc) K f Q _ c _)
    (dirP_fiso_inv K (fiso_fnf T K _ Kc (ff_flat (JTc T Kc) (yo_sheaf T Kc) K f hE)
      (ff_cont (JTc T Kc) (yo_sheaf T Kc) K f) hT) Q β c x)

end G

/-- the classifying topos of T -/
theorem classifying_topos :
    (∀ {D : ECat.{0, 0}} {K : GTop D} (f : Geom (JTc T Kc) K) (hE : EqPres (JTc T Kc) K f),
      Inh (modelOfGeom T hT Kc f hE)) ∧
    (∀ (N : SModel T) (hI : Inh N), EqPres (JTc T Kc) N.K (geomOfModel T Kc N hI) ∧
      Nonempty (SIso (modelOfGeom T hT Kc (geomOfModel T Kc N hI) (geomOfModel_lex T Kc N hI)).M N.M)) ∧
    (∀ {D : ECat.{0, 0}} {K : GTop D} (f : Geom (JTc T Kc) K) (hE : EqPres (JTc T Kc) K f) (Q : (ShCat K).Ob)
      (A : SObj), (∀ q, ((f.dir.obj Q).1.obj A).eqv ((dirBack T hT Kc f hE Q).app A ((dirForth T hT Kc f hE Q).app A q)) q) ∧
      ∀ β, (((geomOfModel T Kc (modelOfGeom T hT Kc f hE) (nf_inh T K _ Kc _ _ hT)).dir.obj Q).1.obj A).eqv
        ((dirForth T hT Kc f hE Q).app A ((dirBack T hT Kc f hE Q).app A β)) β) :=
  ⟨fun _ _ => nf_inh T _ _ Kc _ _ hT,
   fun N hI => ⟨geomOfModel_lex T Kc N hI, ⟨model_roundtrip T hT Kc N hI⟩⟩,
   fun f hE Q _ => ⟨fun q => dir_back_forth T hT Kc f hE Q q, fun β => dir_forth_back T hT Kc f hE Q β⟩⟩

end Gt

end Found

#print axioms Found.Gt.model_roundtrip
#print axioms Found.Gt.dir_back_forth
#print axioms Found.Gt.dir_forth_back
#print axioms Found.Gt.classifying_topos

#print axioms: 4 theorems, no axioms.

85.151 Spaces and Grothendieck infinity-topoi

From the simplicial sets of the chart (functions, full subobjects, a universe of Kan complexes): \(\mathrm {Fun}(K,X)\) is a quasi-category (a Kan complex) when \(X\) is; the homotopy coherent nerve \(\mathcal {S}\) of Kan complexes is a quasi-category; presheaves \(\mathcal {P}(C)=\mathrm {Fun}(C^{\mathrm {op}},\mathcal {S})\) form a Grothendieck \(\infty \)-topos, as do accessible left exact localizations of \(\mathcal {P}(C)\); and full subcategories reflect limits.

\[ \mathcal {S}=N^{hc}(\mathrm {Kan})\ \text {a quasi-category},\qquad \mathcal {P}(C)=\mathrm {Fun}(C^{\mathrm {op}},\mathcal {S})\ \text {a Grothendieck }\infty \text {-topos}. \]

found/IC50.lean

/-
  T153 ((infinity,1)-categories), part 50. found/IC50 — localizations,
  presentable infinity-categories and Grothendieck infinity-topoi.
  * equivalences (edges with a two-sided inverse up to 2-simplices),
    natural transformations as maps Delta^1 x X -> Y, natural equivalences,
    categorical equivalences of simplicial sets;
  * localization functors (L, alpha : id -> L with L(alpha_x) and
    alpha_(Lx) equivalences), local objects, the full subcategory of local
    objects (a quasi-category when X is);
  * presentable (kappa): equivalent to the local objects of an accessible
    localization of P(C), C kappa-small; Grothendieck infinity-topos: the
    same with a left exact localization (kappa and smallness are free
    parameters);
  * P(C) itself is a Grothendieck infinity-topos (the identity
    localization), hence presentable; every topos is presentable.

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.IC49

namespace Found

namespace IC

open Simp

universe w

/-! ## equivalences and natural transformations -/

/-- an equivalence: an edge with a two-sided inverse up to 2-simplices -/
def EquivE {X : SSet.{w}} {x y : (V X).car} (f : Mor (X := X) x y) : Prop :=
  ∃ g : Mor (X := X) y x, Tri X f.1 g.1 (idv X x) ∧ Tri X g.1 f.1 (idv X y)

/-- the component of a transformation H : Delta^1 x X -> Y at a vertex -/
def cmpE {X Y : SSet.{w}} (H : PNat (SProd (Simp.{w} 1) X) Y) (x : (V X).car) : (E Y).car :=
  H.app (1 : Nat) (⟨dId 1⟩, idv X x)

/-- H : F => G is a natural equivalence -/
def NatEquiv {X Y : SSet.{w}} (F G : PNat X Y) (H : PNat (SProd (Simp.{w} 1) X) Y) : Prop :=
  (∀ (n : Nat) x, (Y.obj (n : Nat)).eqv (H.app n (⟨c0D n⟩, x)) (F.app n x)) ∧
  (∀ (n : Nat) x, (Y.obj (n : Nat)).eqv (H.app n (⟨c1D n⟩, x)) (G.app n x)) ∧
  ∀ x : (V X).car, ∃ f : Mor (X := Y) (F.app (0 : Nat) x) (G.app (0 : Nat) x), (E Y).eqv f.1 (cmpE H x) ∧ EquivE f

/-- categorical equivalence -/
def CatEquiv (X Y : SSet.{w}) : Prop :=
  ∃ (F : PNat X Y) (G : PNat Y X) (H1 : PNat (SProd (Simp.{w} 1) X) X) (H2 : PNat (SProd (Simp.{w} 1) Y) Y),
    NatEquiv (idN X) (pcomp F G) H1 ∧ NatEquiv (idN Y) (pcomp G F) H2

/-- identities are equivalences -/
theorem idv_equiv {X : SSet.{w}} {x y : (V X).car} (h : (V X).eqv x y) :
    ∃ f : Mor (X := X) x y, (E X).eqv f.1 (idv X x) ∧ EquivE f :=
  ⟨⟨idv X x, d1_idv X x, (V X).trans (d0_idv X x) h⟩, (E X).refl _,
    ⟨⟨idv X x, (V X).trans (d1_idv X x) h, d0_idv X x⟩, tri_ids x,
      tri_resp (tri_ids x) ((E X).refl _) ((E X).refl _) (idv_eqv h)⟩⟩

/-- the projection Delta^1 x X -> X -/
def prS (X : SSet.{w}) : PNat (SProd (Simp.{w} 1) X) X where
  app _ z := z.2
  app_eqv _ {_ _} h := h.2
  nat _ _ := (X.obj _).refl _

/-! ## localizations -/

/-- a localization functor: alpha : id => L with L(alpha_x) and alpha_(Lx) equivalences -/
structure Loc (X : SSet.{w}) where
  L : PNat X X
  H : PNat (SProd (Simp.{w} 1) X) X
  h0 : ∀ (n : Nat) x, (X.obj (n : Nat)).eqv (H.app n (⟨c0D n⟩, x)) x
  h1 : ∀ (n : Nat) x, (X.obj (n : Nat)).eqv (H.app n (⟨c1D n⟩, x)) (L.app n x)
  idem1 : ∀ x : (V X).car, ∃ f : Mor (X := X) (L.app (0 : Nat) x) (L.app (0 : Nat) (L.app (0 : Nat) x)),
    (E X).eqv f.1 (cmpE H (L.app (0 : Nat) x)) ∧ EquivE f
  idem2 : ∀ x : (V X).car, ∃ f : Mor (X := X) (L.app (0 : Nat) x) (L.app (0 : Nat) (L.app (0 : Nat) x)),
    (E X).eqv f.1 (L.app (1 : Nat) (cmpE H x)) ∧ EquivE f

variable {X : SSet.{w}}

/-- local objects: alpha_x is an equivalence -/
def Local (Lc : Loc X) (x : (V X).car) : Prop :=
  ∃ f : Mor (X := X) x (Lc.L.app (0 : Nat) x), (E X).eqv f.1 (cmpE Lc.H x) ∧ EquivE f

theorem local_eqv (Lc : Loc X) {x x' : (V X).car} (h : (V X).eqv x x') (hl : Local Lc x) : Local Lc x' :=
  match hl with
  | ⟨f, hf, ⟨g, t1, t2⟩⟩ =>
    have hL : (V X).eqv (Lc.L.app (0 : Nat) x) (Lc.L.app (0 : Nat) x') := Lc.L.app_eqv _ h
    ⟨⟨f.1, (V X).trans f.2.1 h, (V X).trans f.2.2 hL⟩,
      (E X).trans hf (Lc.H.app_eqv _ ⟨fun _ _ => rfl, idv_eqv h⟩),
      ⟨⟨g.1, (V X).trans g.2.1 hL, (V X).trans g.2.2 h⟩,
        tri_resp t1 ((E X).refl _) ((E X).refl _) (idv_eqv h),
        tri_resp t2 ((E X).refl _) ((E X).refl _) (idv_eqv hL)⟩⟩

/-- the full subcategory of local objects -/
def LocSub (Lc : Loc X) : SSet.{w} := FullSub X (Local Lc) (local_eqv Lc)

theorem locSub_quasi (Lc : Loc X) (hQ : Quasi X) : Quasi (LocSub Lc) := quasi_full X _ _ hQ

variable (X)

/-- the identity localization -/
def idLoc : Loc X where
  L := idN X
  H := prS X
  h0 _ _ := (X.obj _).refl _
  h1 _ _ := (X.obj _).refl _
  idem1 x := idv_equiv ((V X).refl x)
  idem2 x := idv_equiv ((V X).refl x)

theorem local_id (x : (V X).car) : Local (idLoc X) x := idv_equiv ((V X).refl x)

/-- a full subcategory containing every vertex is equivalent to X -/
theorem catEquiv_full_all (P : (V X).car → Prop) (hP : ∀ {x x' : (V X).car}, (V X).eqv x x' → P x → P x')
    (hall : ∀ x, P x) : CatEquiv X (FullSub X P hP) :=
  ⟨{ app := fun _ σ => ⟨σ, fun _ _ => hall _⟩, app_eqv := fun _ {_ _} h => h, nat := fun _ _ => (X.obj _).refl _ },
    fullIncl X P hP, prS X, prS (FullSub X P hP),
    ⟨fun _ _ => (X.obj _).refl _, fun _ _ => (X.obj _).refl _, fun x => idv_equiv ((V X).refl x)⟩,
    ⟨fun _ _ => (X.obj _).refl _, fun _ _ => (X.obj _).refl _,
      fun x => idv_equiv (X := FullSub X P hP) ((V X).refl x.1)⟩⟩

variable {X}

/-! ## presentable infinity-categories and Grothendieck infinity-topoi -/

/-- presentable: the local objects of an accessible localization of P(C), C kappa-small -/
def Presentable (κ : SSet.{w + 1} → Prop) (Y : SSet.{w + 1}) : Prop :=
  ∃ C : SSet.{w + 1}, κ C ∧ ∃ Lc : Loc (PshS.{w} C), Accessible κ Lc.L ∧ CatEquiv Y (LocSub Lc)

/-- Grothendieck infinity-topos: the local objects of an accessible left exact localization of P(C) -/
def GrothTopos (κ : SSet.{w + 1} → Prop) (Y : SSet.{w + 1}) : Prop :=
  ∃ C : SSet.{w + 1}, κ C ∧ ∃ Lc : Loc (PshS.{w} C), Accessible κ Lc.L ∧ LeftExact Lc.L ∧ CatEquiv Y (LocSub Lc)

/-- every Grothendieck infinity-topos is presentable -/
theorem topos_presentable {κ : SSet.{w + 1} → Prop} {Y : SSet.{w + 1}} (h : GrothTopos κ Y) : Presentable κ Y :=
  match h with
  | ⟨C, hC, Lc, ha, _, he⟩ => ⟨C, hC, Lc, ha, he⟩

/-- presheaves of spaces on a kappa-small simplicial set form a Grothendieck infinity-topos -/
theorem psh_topos (κ : SSet.{w + 1} → Prop) (C : SSet.{w + 1}) (hC : κ C) : GrothTopos κ (PshS.{w} C) :=
  ⟨C, hC, idLoc _, id_accessible κ _, id_leftExact _,
    catEquiv_full_all _ (Local (idLoc _)) (local_eqv (idLoc _)) (local_id _)⟩

/-- the local objects of a localization of P(C) form a quasi-category -/
theorem locSub_psh_quasi (Kw : ClW.{w}) (Kw' : ClW.{w + 1}) (Kc : CP.Classical') {C : SSet.{w + 1}}
    (Lc : Loc (PshS.{w} C)) : Quasi (LocSub Lc) :=
  locSub_quasi Lc (psh_quasi Kw Kw' Kc C)

end IC

end Found

#print axioms Found.IC.idv_equiv
#print axioms Found.IC.local_eqv
#print axioms Found.IC.locSub_quasi
#print axioms Found.IC.idLoc
#print axioms Found.IC.local_id
#print axioms Found.IC.catEquiv_full_all
#print axioms Found.IC.topos_presentable
#print axioms Found.IC.psh_topos
#print axioms Found.IC.locSub_psh_quasi

#print axioms: 9 theorems, no axioms.

85.152 Frege and Hume’s principle

Basic Law V refutes itself by Russell’s paradox, which is Cantor’s diagonal for the map \(D \to \Omega ^D\); Hume’s principle gives zero, Frege’s predecessor and induction over the ancestral.

\[ \mathrm {ext}\,F = \mathrm {ext}\,G \leftrightarrow \forall x\,(Fx \leftrightarrow Gx) \vdash \bot ,\qquad \#F = \#G \leftrightarrow F \approx G \]

found/Frege.lean

/-
  T211. found/Frege — Frege and neo-logicism as a point of the chart: a
  domain D (a type), concepts D → Prop (the power/Ω operation), and an
  abstraction operator (concepts → objects) constrained by
  * Basic Law V: ext F = ext G ↔ ∀ x, F x ↔ G x — inconsistent (Russell's
    paradox), equivalently: ext would invert the map D → Ω^D, against
    Cantor's diagonal (the line to Lawvere's fixed-point theorem);
  * Hume's principle: # F = # G ↔ F and G are equinumerous (a bijective
    relation between them) — the neo-logicist base.  From HP: 0 := #(empty)
    is not a successor, numbers of equinumerous concepts agree, and the
    predecessor relation of Frege's definition is stated.  Frege's theorem
    (all Peano axioms from HP in second-order logic) is a theorem inside this
    point (out of scope).

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Frege

/-! ## Basic Law V -/

/-- an extension operator satisfying Basic Law V -/
structure BLV (D : Type) where
  ext : (D → Prop) → D
  law : ∀ F G : D → Prop, ext F = ext G ↔ ∀ x, (F x ↔ G x)

/-- Russell's paradox: Basic Law V is inconsistent -/
theorem russell {D : Type} (B : BLV D) : False :=
  let R : D → Prop := fun x => ∃ F : D → Prop, x = B.ext F ∧ ¬ F x
  have nR : ¬ R (B.ext R) := fun ⟨F, e, nF⟩ => nF (((B.law R F).1 e (B.ext R)).1 ⟨F, e, nF⟩)
  nR ⟨R, rfl, nR⟩

/-- Cantor's diagonal: no map D → (D → Prop) is onto up to ↔ -/
theorem cantor {D : Type} (r : D → D → Prop) : ¬ ∀ F : D → Prop, ∃ d, ∀ x, (r d x ↔ F x) :=
  fun h => match h (fun x => ¬ r x x) with
  | ⟨d, hd⟩ =>
    have n : ¬ r d d := fun hr => (hd d).1 hr hr
    n ((hd d).2 n)

/-- the line to Cantor (and Lawvere's fixed-point theorem): Basic Law V makes
  membership in extensions onto -/
theorem blv_onto {D : Type} (B : BLV D) : ∀ F : D → Prop, ∃ d, ∀ x,
    ((∃ G : D → Prop, d = B.ext G ∧ G x) ↔ F x) :=
  fun F => ⟨B.ext F, fun x =>
    ⟨fun ⟨G, e, hG⟩ => ((B.law F G).1 e x).2 hG, fun hF => ⟨F, rfl, hF⟩⟩⟩

theorem russell' {D : Type} (B : BLV D) : False :=
  cantor (fun d x => ∃ G : D → Prop, d = B.ext G ∧ G x) (blv_onto B)

/-! ## Hume's principle -/

/-- equinumerosity: a relation that is a bijection between F and G -/
def Eqn {D : Type} (F G : D → Prop) : Prop :=
  ∃ R : D → D → Prop,
    (∀ x, F x → ∃ y, G y ∧ R x y) ∧ (∀ y, G y → ∃ x, F x ∧ R x y) ∧
    (∀ x y y', F x → R x y → R x y' → y = y') ∧ (∀ x x' y, G y → R x y → R x' y → x = x') ∧
    (∀ x y, R x y → F x ∧ G y)

theorem eqn_refl {D : Type} (F : D → Prop) : Eqn F F :=
  ⟨fun x y => F x ∧ x = y, fun x hx => ⟨x, hx, hx, rfl⟩, fun y hy => ⟨y, hy, hy, rfl⟩,
    fun _ _ _ _ h h' => h.2.symm.trans h'.2, fun _ _ _ _ h h' => h.2.trans h'.2.symm,
    fun _ _ h => ⟨h.1, h.2 ▸ h.1⟩⟩

theorem eqn_symm {D : Type} {F G : D → Prop} (h : Eqn F G) : Eqn G F :=
  match h with
  | ⟨R, t, s, f, i, d⟩ => ⟨fun y x => R x y, s, t, fun y x x' hy h1 h2 => i x x' y hy h1 h2,
      fun y y' x hx h1 h2 => f x y y' hx h1 h2, fun y x h => ⟨(d x y h).2, (d x y h).1⟩⟩

/-- a number operator satisfying Hume's principle -/
structure HP (D : Type) where
  num : (D → Prop) → D
  law : ∀ F G : D → Prop, num F = num G ↔ Eqn F G

variable {D : Type} (H : HP D)

/-- zero: the number of the empty concept -/
def zero : D := H.num (fun _ => False)

/-- Frege's predecessor: m immediately precedes n -/
def Pred (m n : D) : Prop :=
  ∃ (F : D → Prop) (y : D), F y ∧ n = H.num F ∧ m = H.num (fun x => F x ∧ x ≠ y)

/-- natural numbers: zero and its successors under the ancestral -/
def IsNat (n : D) : Prop :=
  ∀ P : D → Prop, P (zero H) → (∀ a b, P a → Pred H a b → P b) → P n

/-- zero is not a successor -/
theorem zero_not_succ (m : D) : ¬ Pred H m (zero H) :=
  fun ⟨F, y, hy, e, _⟩ => match (H.law F (fun _ => False)).1 e.symm with
    | ⟨_, t, _, _, _, _⟩ => match t y hy with
      | ⟨_, f, _⟩ => f

theorem zero_nat : IsNat H (zero H) := fun _ h0 _ => h0

/-- the successor of a natural number is natural -/
theorem nat_succ {m n : D} (hm : IsNat H m) (hp : Pred H m n) : IsNat H n :=
  fun P h0 hs => hs m n (hm P h0 hs) hp

/-- induction over the natural numbers -/
theorem nat_ind (P : D → Prop) (h0 : P (zero H)) (hs : ∀ a b, IsNat H a → P a → Pred H a b → P b) :
    ∀ n, IsNat H n → P n :=
  fun _ hn => (hn (fun x => IsNat H x ∧ P x) ⟨zero_nat H, h0⟩
    (fun a b ⟨na, pa⟩ hp => ⟨nat_succ H na hp, hs a b na pa hp⟩)).2

/-- equinumerous concepts have the same number -/
theorem num_eq {F G : D → Prop} (h : Eqn F G) : H.num F = H.num G := (H.law F G).2 h

/-- the number of a concept that holds of something is not zero -/
theorem num_ne_zero {F : D → Prop} {y : D} (hy : F y) : H.num F ≠ zero H :=
  fun e => match (H.law F (fun _ => False)).1 e with
    | ⟨_, t, _, _, _, _⟩ => match t y hy with
      | ⟨_, f, _⟩ => f

end Frege

end Found

#print axioms Found.Frege.russell
#print axioms Found.Frege.cantor
#print axioms Found.Frege.blv_onto
#print axioms Found.Frege.russell'
#print axioms Found.Frege.eqn_refl
#print axioms Found.Frege.eqn_symm
#print axioms Found.Frege.zero_not_succ
#print axioms Found.Frege.nat_succ
#print axioms Found.Frege.nat_ind
#print axioms Found.Frege.num_eq
#print axioms Found.Frege.num_ne_zero

#print axioms: 11 theorems, no axioms.

85.153 Russell: ramified type theory

Orders on top of the simple types of the power operation; a cumulative hierarchy of predicate levels with predicative comprehension; under the Axiom of Reducibility quantification over any order equals quantification over order 0, and without it the hierarchy can be strict.

\[ \mathrm {Red} \implies (\forall F^{(n)}\, P F \leftrightarrow \forall G^{(0)}\, P G) \]

found/Ramified.lean

/-
  T212. found/Ramified — Russell's ramified type theory (Principia) as a
  point of the chart: simple types built by the power operation (Ω^(-)),
  and orders on top of them.
  * Syntax: ramified types (individuals; predicates of a given order over a
    list of argument types, the order exceeding the orders of the
    arguments); erasure of orders gives simple types (the HOL point, T205).
  * Semantics over a domain D: a cumulative hierarchy of predicate levels
    Pr n ⊆ (D → Prop), each level closed under the predicative comprehension
    of the next (formulas quantifying only over lower levels).
  * Axiom of Reducibility: every predicate of any order is coextensive with
    one of order 0.  Under it, quantifying over any order is the same as
    quantifying over order 0: the hierarchy collapses to the simple theory.
  * Without it the hierarchy can be strict: over Bool, with order 0 the
    constant predicates and order 1 all predicates, reducibility fails.

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Ramified

/-! ## syntax -/

/-- simple types: individuals and predicates over lists of types -/
inductive STy where
  | ind : STy
  | pred : List STy → STy

/-- ramified types: predicates carry an order -/
inductive RTy where
  | ind : RTy
  | pred : Nat → List RTy → RTy

/-- order of a ramified type -/
def ord : RTy → Nat
  | .ind => 0
  | .pred n _ => n

-- well-formed: each predicate's order exceeds the orders of its arguments
mutual
def WF : RTy → Prop
  | .ind => True
  | .pred n ts => WFL n ts

def WFL (n : Nat) : List RTy → Prop
  | [] => True
  | t :: ts => WF t ∧ ord t < n ∧ WFL n ts
end

/-- a well-formed predicate of order 1 over individuals -/
theorem wf_example : WF (.pred 1 [.ind, .ind]) := ⟨trivial, Nat.zero_lt_one, trivial, Nat.zero_lt_one, trivial⟩

mutual
/-- erasing orders: the simple type underneath -/
def erase : RTy → STy
  | .ind => .ind
  | .pred _ ts => .pred (eraseL ts)

def eraseL : List RTy → List STy
  | [] => []
  | t :: ts => erase t :: eraseL ts
end

/-- erasure forgets the order: predicates of different orders over the same arguments
  have the same simple type -/
theorem erase_order (n m : Nat) (ts : List RTy) : erase (.pred n ts) = erase (.pred m ts) := rfl

/-! ## semantics: a hierarchy of predicate levels -/

/-- a ramified hierarchy of unary predicates on D -/
structure Hier (D : Type) where
  Pr : Nat → (D → Prop) → Prop
  cum : ∀ n F, Pr n F → Pr (n + 1) F
  /-- predicative comprehension: quantifying over level n gives a predicate of level n + 1 -/
  compAll : ∀ n (R : (D → Prop) → D → Prop), Pr (n + 1) (fun x => ∀ F, Pr n F → R F x)
  compEx : ∀ n (R : (D → Prop) → D → Prop), Pr (n + 1) (fun x => ∃ F, Pr n F ∧ R F x)

/-- coextensive predicates -/
def Coext {D : Type} (F G : D → Prop) : Prop := ∀ x, F x ↔ G x

/-- the Axiom of Reducibility -/
def Reducibility {D : Type} (H : Hier D) : Prop := ∀ n F, H.Pr n F → ∃ G, H.Pr 0 G ∧ Coext F G

/-- predicates respecting coextension (extensional properties of predicates) -/
def Ext {D : Type} (P : (D → Prop) → Prop) : Prop := ∀ F G, Coext F G → P F → P G

/-- under reducibility, quantifying over any order is quantifying over order 0 -/
theorem collapse_all {D : Type} (H : Hier D) (hR : Reducibility H) (P : (D → Prop) → Prop) (hP : Ext P) (n : Nat) :
    (∀ F, H.Pr n F → P F) ↔ (∀ G, H.Pr 0 G → P G) :=
  ⟨fun h G hG => h G (lift0 n G hG),
   fun h F hF => match hR n F hF with
    | ⟨G, hG, hc⟩ => hP G F (fun x => (hc x).symm) (h G hG)⟩
where
  lift0 : ∀ n (G : D → Prop), H.Pr 0 G → H.Pr n G
    | 0, _, hG => hG
    | n + 1, G, hG => H.cum n G (lift0 n G hG)

theorem collapse_ex {D : Type} (H : Hier D) (hR : Reducibility H) (P : (D → Prop) → Prop) (hP : Ext P) (n : Nat) :
    (∃ F, H.Pr n F ∧ P F) ↔ (∃ G, H.Pr 0 G ∧ P G) :=
  ⟨fun ⟨F, hF, p⟩ => match hR n F hF with
    | ⟨G, hG, hc⟩ => ⟨G, hG, hP F G hc p⟩,
   fun ⟨G, hG, p⟩ => ⟨G, collapse_all.lift0 H n G hG, p⟩⟩

/-! ## a strict hierarchy: reducibility can fail -/

/-- order 0: the constant predicates on Bool; higher orders: all predicates -/
def boolHier : Hier Bool where
  Pr n F := match n with
    | 0 => Coext F (fun _ => True) ∨ Coext F (fun _ => False)
    | _ + 1 => True
  cum n _ _ := match n with
    | 0 => trivial
    | _ + 1 => trivial
  compAll _ _ := trivial
  compEx _ _ := trivial

theorem bool_not_reducible : ¬ Reducibility boolHier :=
  fun h => match h 1 (fun b => b = true) trivial with
  | ⟨_, .inl hT, hc⟩ => Bool.noConfusion ((hc false).2 ((hT false).2 trivial))
  | ⟨_, .inr hF, hc⟩ => (hF true).1 ((hc true).1 rfl)

end Ramified

end Found

#print axioms Found.Ramified.erase_order
#print axioms Found.Ramified.wf_example
#print axioms Found.Ramified.collapse_all
#print axioms Found.Ramified.collapse_ex
#print axioms Found.Ramified.boolHier
#print axioms Found.Ramified.bool_not_reducible

#print axioms: 6 theorems, no axioms.

85.154 Lawvere: the category of categories

The arrows of ETCC are functors; objects and arrows of a category are the functors from the test categories 1 and 2, composable pairs come from 3, categories have products, and discrete categories carry ETCS.

\[ \mathrm {Ob}\,C \cong \mathrm {Fun}(1,C),\quad \mathrm {Arr}\,C \cong \mathrm {Fun}(2,C) \]

found/ETCC.lean

/-
  T213. found/ETCC — Lawvere's elementary theory of the category of
  categories as a point of the chart: the arrows of the theory are functors
  between (small) categories, and the primitive notions of a category are
  read off from three test objects:
  * 1 (terminal): objects of C = functors 1 → C;
  * 2 (one arrow 0 → 1): arrows of C = functors 2 → C, with domain and
    codomain the restrictions to the two objects;
  * 3 (0 → 1 → 2): composable pairs = functors 3 → C, and composition is the
    image of the long arrow 0 → 2 (3 is the pushout 2 ⊔_1 2);
  * products of categories with pairing (finite limits), and discrete
    categories: functors between discrete categories are functions (ETCS,
    T107, inside ETCC as the discrete objects).

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace ETCC

universe u v

/-- small categories -/
structure Cat where
  Ob : Type u
  Hom : Ob → Ob → Type v
  id : (a : Ob) → Hom a a
  comp : {a b c : Ob} → Hom a b → Hom b c → Hom a c
  id_comp : ∀ {a b} (f : Hom a b), comp (id a) f = f
  comp_id : ∀ {a b} (f : Hom a b), comp f (id b) = f
  assoc : ∀ {a b c d} (f : Hom a b) (g : Hom b c) (h : Hom c d), comp (comp f g) h = comp f (comp g h)

/-- functors: the arrows of ETCC -/
structure Fun (C D : Cat.{u, v}) where
  obj : C.Ob → D.Ob
  map : {a b : C.Ob} → C.Hom a b → D.Hom (obj a) (obj b)
  map_id : ∀ a, map (C.id a) = D.id (obj a)
  map_comp : ∀ {a b c} (f : C.Hom a b) (g : C.Hom b c), map (C.comp f g) = D.comp (map f) (map g)

/-! ## the terminal category 1 -/

def one : Cat.{u, v} where
  Ob := PUnit
  Hom _ _ := PUnit
  id _ := PUnit.unit
  comp _ _ := PUnit.unit
  id_comp _ := rfl
  comp_id _ := rfl
  assoc _ _ _ := rfl

variable {C : Cat.{u, v}}

/-- objects of C are functors 1 → C -/
def ofObj (a : C.Ob) : Fun one.{u, v} C where
  obj _ := a
  map _ := C.id a
  map_id _ := rfl
  map_comp _ _ := (C.id_comp (C.id a)).symm

def toObj (F : Fun one.{u, v} C) : C.Ob := F.obj PUnit.unit

theorem toObj_ofObj (a : C.Ob) : toObj (ofObj a) = a := rfl

theorem ofObj_toObj (F : Fun one.{u, v} C) : ∀ x, (ofObj (toObj F)).obj x = F.obj x := fun _ => rfl

/-- a functor out of 1 sends its arrow to an identity -/
theorem one_map (F : Fun one.{u, v} C) (f : one.{u, v}.Hom PUnit.unit PUnit.unit) :
    F.map f = C.id (F.obj PUnit.unit) := F.map_id PUnit.unit

/-! ## the arrow category 2 -/

inductive Two where
  | z : Two
  | o : Two

def Hom2 : Two → Two → Type v
  | .z, .z => PUnit
  | .z, .o => PUnit
  | .o, .z => PEmpty
  | .o, .o => PUnit

def comp2 : {a b c : Two} → Hom2.{v} a b → Hom2.{v} b c → Hom2.{v} a c
  | .z, .z, .z, _, _ => PUnit.unit
  | .z, .z, .o, _, _ => PUnit.unit
  | .z, .o, .z, _, g => PEmpty.elim g
  | .z, .o, .o, _, _ => PUnit.unit
  | .o, .z, _, f, _ => PEmpty.elim f
  | .o, .o, .z, _, g => g
  | .o, .o, .o, _, _ => PUnit.unit

def id2 : (a : Two) → Hom2.{v} a a
  | .z => PUnit.unit
  | .o => PUnit.unit

def two : Cat.{0, v} where
  Ob := Two
  Hom := Hom2
  id := id2
  comp := comp2
  id_comp {a b} f := match a, b, f with
    | .z, .z, _ => rfl
    | .z, .o, _ => rfl
    | .o, .z, f => PEmpty.elim f
    | .o, .o, _ => rfl
  comp_id {a b} f := match a, b, f with
    | .z, .z, _ => rfl
    | .z, .o, _ => rfl
    | .o, .z, f => PEmpty.elim f
    | .o, .o, _ => rfl
  assoc {a b c d} f g h := match a, b, c, d, f, g, h with
    | .z, .z, .z, .z, _, _, _ => rfl
    | .z, .z, .z, .o, _, _, _ => rfl
    | .z, .z, .o, .z, _, _, h => PEmpty.elim h
    | .z, .z, .o, .o, _, _, _ => rfl
    | .z, .o, .z, _, _, g, _ => PEmpty.elim g
    | .z, .o, .o, .z, _, _, h => PEmpty.elim h
    | .z, .o, .o, .o, _, _, _ => rfl
    | .o, .z, _, _, f, _, _ => PEmpty.elim f
    | .o, .o, .z, _, _, g, _ => PEmpty.elim g
    | .o, .o, .o, .z, _, _, h => PEmpty.elim h
    | .o, .o, .o, .o, _, _, _ => rfl

/-- the generic arrow 0 → 1 of 2 -/
def arr : Hom2.{v} .z .o := PUnit.unit

variable {C : Cat.{0, v}}

/-- arrows of C are functors 2 → C -/
def ofArr {a b : C.Ob} (f : C.Hom a b) : Fun two.{v} C where
  obj x := match x with
    | .z => a
    | .o => b
  map {x y} g := match x, y, g with
    | .z, .z, _ => C.id a
    | .z, .o, _ => f
    | .o, .z, g => PEmpty.elim g
    | .o, .o, _ => C.id b
  map_id x := match x with
    | .z => rfl
    | .o => rfl
  map_comp {x y w} g h := match x, y, w, g, h with
    | .z, .z, .z, _, _ => (C.id_comp _).symm
    | .z, .z, .o, _, _ => (C.id_comp f).symm
    | .z, .o, .z, _, h => PEmpty.elim h
    | .z, .o, .o, _, _ => (C.comp_id f).symm
    | .o, .z, _, g, _ => PEmpty.elim g
    | .o, .o, .z, _, h => PEmpty.elim h
    | .o, .o, .o, _, _ => (C.id_comp _).symm

/-- the arrow named by a functor 2 → C -/
def toArr (F : Fun two.{v} C) : C.Hom (F.obj .z) (F.obj .o) := F.map arr

theorem toArr_ofArr {a b : C.Ob} (f : C.Hom a b) : toArr (ofArr f) = f := rfl

theorem ofArr_obj (F : Fun two.{v} C) : ∀ x, (ofArr (toArr F)).obj x = F.obj x
  | .z => rfl
  | .o => rfl

/-! ## composition from 3 -/

inductive Three where
  | a0 : Three
  | a1 : Three
  | a2 : Three

/-- the composable pair named by a functor out of 3: its long arrow is the composite -/
structure Pair3 (C : Cat.{0, v}) where
  x0 : C.Ob
  x1 : C.Ob
  x2 : C.Ob
  f : C.Hom x0 x1
  g : C.Hom x1 x2

def long (P : Pair3 C) : C.Hom P.x0 P.x2 := C.comp P.f P.g

/-- composition is functorial along the two arrows of 3: restricting to 0 → 1 and 1 → 2 gives f and g,
  and the long arrow is their composite (3 = 2 ⊔_1 2) -/
theorem long_comp (P : Pair3 C) (F : Fun C C) : F.map (long P) = C.comp (F.map P.f) (F.map P.g) := F.map_comp _ _

/-! ## products of categories -/

def prod (C D : Cat.{u, v}) : Cat.{u, v} where
  Ob := C.Ob × D.Ob
  Hom x y := C.Hom x.1 y.1 × D.Hom x.2 y.2
  id x := (C.id x.1, D.id x.2)
  comp f g := (C.comp f.1 g.1, D.comp f.2 g.2)
  id_comp f := by
    show (C.comp (C.id _) f.1, D.comp (D.id _) f.2) = f
    rw [C.id_comp, D.id_comp]
  comp_id f := by
    show (C.comp f.1 (C.id _), D.comp f.2 (D.id _)) = f
    rw [C.comp_id, D.comp_id]
  assoc f g h := by
    show (C.comp (C.comp f.1 g.1) h.1, D.comp (D.comp f.2 g.2) h.2) = (C.comp f.1 (C.comp g.1 h.1), D.comp f.2 (D.comp g.2 h.2))
    rw [C.assoc, D.assoc]

def pairF {B C D : Cat.{u, v}} (F : Fun B C) (G : Fun B D) : Fun B (prod C D) where
  obj b := (F.obj b, G.obj b)
  map f := (F.map f, G.map f)
  map_id b := by
    show (F.map (B.id b), G.map (B.id b)) = (C.id (F.obj b), D.id (G.obj b))
    rw [F.map_id, G.map_id]
  map_comp f g := by
    show (F.map (B.comp f g), G.map (B.comp f g)) = (C.comp (F.map f) (F.map g), D.comp (G.map f) (G.map g))
    rw [F.map_comp, G.map_comp]

def fstF {C D : Cat.{u, v}} : Fun (prod C D) C := ⟨fun x => x.1, fun f => f.1, fun _ => rfl, fun _ _ => rfl⟩
def sndF {C D : Cat.{u, v}} : Fun (prod C D) D := ⟨fun x => x.2, fun f => f.2, fun _ => rfl, fun _ _ => rfl⟩

theorem pair_fst {B C D : Cat.{u, v}} (F : Fun B C) (G : Fun B D) (b : B.Ob) : fstF.obj ((pairF F G).obj b) = F.obj b := rfl
theorem pair_snd {B C D : Cat.{u, v}} (F : Fun B C) (G : Fun B D) (b : B.Ob) : sndF.obj ((pairF F G).obj b) = G.obj b := rfl

/-! ## discrete categories: sets inside ETCC -/

def disc (X : Type u) : Cat.{u, u} where
  Ob := X
  Hom a b := ULift.{u} (PLift (a = b))
  id _ := ⟨⟨rfl⟩⟩
  comp f g := ⟨⟨f.down.down.trans g.down.down⟩⟩
  id_comp _ := rfl
  comp_id _ := rfl
  assoc _ _ _ := rfl

/-- every function is a functor between discrete categories -/
def discF {X Y : Type u} (f : X → Y) : Fun (disc X) (disc Y) where
  obj := f
  map e := ⟨⟨congrArg f e.down.down⟩⟩
  map_id _ := rfl
  map_comp _ _ := rfl

/-- and every functor between discrete categories is a function on objects -/
theorem discF_obj {X Y : Type u} (F : Fun (disc X) (disc Y)) (x : X) :
    (discF (X := X) (Y := Y) F.obj).obj x = F.obj x := rfl

theorem disc_round {X Y : Type u} (f : X → Y) : (discF f).obj = f := rfl

end ETCC

end Found

#print axioms Found.ETCC.toObj_ofObj
#print axioms Found.ETCC.one_map
#print axioms Found.ETCC.two
#print axioms Found.ETCC.ofArr
#print axioms Found.ETCC.toArr_ofArr
#print axioms Found.ETCC.ofArr_obj
#print axioms Found.ETCC.long_comp
#print axioms Found.ETCC.prod
#print axioms Found.ETCC.pairF
#print axioms Found.ETCC.pair_fst
#print axioms Found.ETCC.disc
#print axioms Found.ETCC.discF_obj
#print axioms Found.ETCC.disc_round

#print axioms: 13 theorems, no axioms.

85.155 Hilbert’s epsilon-calculus

An epsilon-operator with the critical axiom defines the quantifiers, gives choice functions and, when extensional on Bool, excluded middle.

\[ A(t)\to A(\varepsilon A),\qquad (\exists x\,A x)\leftrightarrow A(\varepsilon A) \]

found/Epsilon.lean

/-
  T214. found/Epsilon — Hilbert's ε-calculus as a point of the chart: an
  ε-operator on a domain D (a value of the choice parameter, T89) with the
  critical axiom A(t) → A(εx.A(x)).
  * ∃ is definable: (∃ x, A x) ↔ A(εA);
  * ∀ is definable at the classical point: (∀ x, A x) ↔ A(ε¬A) (with
    excluded middle as a hypothesis variable);
  * ε gives the axiom of choice: ∀ a ∃ b R a b ⇒ a choice function a ↦ ε(R a);
  * extensional ε (coextensive predicates get the same witness) on Bool
    gives excluded middle (Diaconescu's argument, no propext): the line from
    the ε-point to the classical point (T66).

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Epsilon

/-- an ε-operator with the critical axiom -/
structure Eps (D : Type) where
  eps : (D → Prop) → D
  crit : ∀ (A : D → Prop) (t : D), A t → A (eps A)

variable {D : Type} (E : Eps D)

/-- ∃ from ε -/
theorem ex_iff (A : D → Prop) : (∃ x, A x) ↔ A (E.eps A) :=
  ⟨fun ⟨t, h⟩ => E.crit A t h, fun h => ⟨_, h⟩⟩

/-- ∀ from ε, at the classical point -/
theorem all_iff (lem : ∀ p : Prop, p ∨ ¬ p) (A : D → Prop) : (∀ x, A x) ↔ A (E.eps (fun x => ¬ A x)) :=
  ⟨fun h => h _, fun h x => (lem (A x)).elim id
    (fun hn => absurd h (E.crit (fun x => ¬ A x) x hn))⟩

/-- ε gives choice functions -/
theorem choice (E : Eps D) {A : Type} (R : A → D → Prop) (h : ∀ a, ∃ b, R a b) : ∃ f : A → D, ∀ a, R a (f a) :=
  ⟨fun a => E.eps (R a), fun a => (h a).elim (fun b hb => E.crit (R a) b hb)⟩

/-- extensional ε -/
def Extensional : Prop := ∀ A B : D → Prop, (∀ x, A x ↔ B x) → E.eps A = E.eps B

/-- Diaconescu: an extensional ε on Bool decides every proposition -/
theorem diaconescu (E : Eps Bool) (hE : Extensional E) (p : Prop) : p ∨ ¬ p :=
  let U : Bool → Prop := fun b => b = true ∨ p
  let V : Bool → Prop := fun b => b = false ∨ p
  have hu : U (E.eps U) := E.crit U true (.inl rfl)
  have hv : V (E.eps V) := E.crit V false (.inl rfl)
  hu.elim
    (fun eu => hv.elim
      (fun ev => .inr (fun hp =>
        have e : E.eps U = E.eps V := hE U V (fun _ => ⟨fun _ => .inr hp, fun _ => .inr hp⟩)
        Bool.noConfusion (eu.symm.trans (e.trans ev))))
      (fun h => .inl h))
    (fun h => .inl h)

end Epsilon

end Found

#print axioms Found.Epsilon.ex_iff
#print axioms Found.Epsilon.all_iff
#print axioms Found.Epsilon.choice
#print axioms Found.Epsilon.diaconescu

#print axioms: 4 theorems, no axioms.

85.156 Plural logic

Pluralities are inhabited predicates; monadic second-order quantification reduces to plural quantification, and pluralities are the parts of a mereology.

\[ (\exists X\,\Phi X)\leftrightarrow \Phi (\emptyset )\lor \exists xx\,\Phi (xx) \]

found/Plural.lean

/-
  T215. found/Plural — plural logic (Boolos) as a point of the chart: plural
  variables range over inhabited sub-predicates of the domain (the power
  operation Ω^D restricted to inhabited values), with "a is one of xx".
  * plural comprehension: if something is φ, there are some things that are
    exactly the φs;
  * Boolos' translation: monadic second-order quantification over an
    extensional condition reduces to the empty case or a plural quantifier
    (at the classical point, excluded middle as a hypothesis variable) —
    the line to second-order logic (T142);
  * pluralities are exactly the parts of the mereology of inhabited
    predicates, and "one of" is parthood of the singleton — the line to
    mereology (T201).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.Mereology

namespace Found

namespace Plural

universe u

variable {D : Type u}

/-- some things: an inhabited predicate -/
structure Pl (D : Type u) where
  among : D → Prop
  ne : ∃ a, among a

/-- a is one of xx -/
def OneOf (a : D) (xx : Pl D) : Prop := xx.among a

/-- plural comprehension -/
theorem compr (φ : D → Prop) (h : ∃ a, φ a) : ∃ xx : Pl D, ∀ a, OneOf a xx ↔ φ a :=
  ⟨⟨φ, h⟩, fun _ => ⟨id, id⟩⟩

/-- an extensional condition on monadic second-order values -/
def Ext (Φ : (D → Prop) → Prop) : Prop :=
  ∀ X Y : D → Prop, (∀ a, X a ↔ Y a) → Φ X → Φ Y

/-- Boolos: monadic second-order ∃ = empty case ∨ plural ∃ -/
theorem boolos_ex (lem : ∀ p : Prop, p ∨ ¬ p) (Φ : (D → Prop) → Prop) (hΦ : Ext Φ) :
    (∃ X, Φ X) ↔ (Φ (fun _ => False) ∨ ∃ xx : Pl D, Φ xx.among) :=
  ⟨fun ⟨X, hX⟩ => (lem (∃ a, X a)).elim
      (fun hi => .inr ⟨⟨X, hi⟩, hX⟩)
      (fun hn => .inl (hΦ X _ (fun a => ⟨fun x => hn ⟨a, x⟩, False.elim⟩) hX)),
   fun h => h.elim (fun e => ⟨_, e⟩) (fun ⟨_, e⟩ => ⟨_, e⟩)⟩

/-- Boolos: monadic second-order ∀ = empty case ∧ plural ∀ -/
theorem boolos_all (lem : ∀ p : Prop, p ∨ ¬ p) (Φ : (D → Prop) → Prop) (hΦ : Ext Φ) :
    (∀ X, Φ X) ↔ (Φ (fun _ => False) ∧ ∀ xx : Pl D, Φ xx.among) :=
  ⟨fun h => ⟨h _, fun xx => h xx.among⟩,
   fun ⟨e, p⟩ X => (lem (∃ a, X a)).elim
      (fun hi => p ⟨X, hi⟩)
      (fun hn => hΦ _ X (fun a => ⟨False.elim, fun x => hn ⟨a, x⟩⟩) e)⟩

/-! ## the line to mereology (T201) -/

/-- a plurality is a part of the mereology of inhabited predicates -/
def toPart (xx : Pl D) : (Mereo.setsM D).E := ⟨xx.among, xx.ne⟩

def ofPart (x : (Mereo.setsM D).E) : Pl D := ⟨x.val, x.property⟩

theorem of_to (xx : Pl D) : ofPart (toPart xx) = xx := rfl

theorem to_of (x : (Mereo.setsM D).E) : toPart (ofPart x) = x := rfl

/-- the single thing a -/
def single (a : D) : Pl D := ⟨fun b => a = b, ⟨a, rfl⟩⟩

/-- "a is one of xx" is parthood of the singleton -/
theorem oneOf_iff_part (a : D) (xx : Pl D) :
    OneOf a xx ↔ (Mereo.setsM D).P (toPart (single a)) (toPart xx) :=
  ⟨fun h _ e => e ▸ h, fun h => h a rfl⟩

/-- inclusion of pluralities is parthood -/
theorem sub_iff_part (xx yy : Pl D) :
    (∀ a, OneOf a xx → OneOf a yy) ↔ (Mereo.setsM D).P (toPart xx) (toPart yy) :=
  ⟨id, id⟩

end Plural

end Found

#print axioms Found.Plural.compr
#print axioms Found.Plural.boolos_ex
#print axioms Found.Plural.boolos_all
#print axioms Found.Plural.of_to
#print axioms Found.Plural.to_of
#print axioms Found.Plural.oneOf_iff_part
#print axioms Found.Plural.sub_iff_part

#print axioms: 7 theorems, no axioms.

85.157 Krivine classical realizability

Over a pole, cc realizes Peirce’s law and realizability is sound for modus ponens; the empty pole gives two-valued truth.

\[ \mathsf {cc}\Vdash ((A\to B)\to A)\to A \]

found/Krivine.lean

/-
  T216. found/Krivine — Krivine's classical realizability as a point of the
  chart: a realizability structure (terms, stacks, push, application, the
  control operator cc, continuations k_π) with a pole (a free parameter: a
  set of processes closed under anti-evaluation). Formulas are falsity
  values (predicates on stacks, i.e. values of the power operation Ω^Π);
  a term realizes a formula when it is orthogonal to every stack of it.
  * modus ponens is sound: realizers of A → B and A give one of B;
  * cc realizes Peirce's law ((A → B) → A) → A for every A, B — the line to
    the classical point (T66); without cc this is the intuitionistic
    realizability point (T96);
  * with the empty pole, realizability collapses to two-valued truth
    (a formula is true iff its falsity value is empty, and → is the Boolean
    implication).
  Krivine's realizability models of ZF with dependent choice (T89) are
  internal theorems of the point (out of scope).

  Lean 4 core only, hand-written proofs, no axioms.
-/

namespace Found

namespace Krivine

/-- a realizability structure with a pole -/
structure KS where
  Tm : Type
  Stk : Type
  push : Tm → Stk → Stk
  app : Tm → Tm → Tm
  cc : Tm
  k : Stk → Tm
  pole : Tm → Stk → Prop
  sat_app : ∀ t u π, pole t (push u π) → pole (app t u) π
  sat_cc : ∀ t π, pole t (push (k π) π) → pole cc (push t π)
  sat_k : ∀ t π ρ, pole t π → pole (k π) (push t ρ)

variable (K : KS)

/-- formulas as falsity values -/
abbrev Fal := K.Stk → Prop

/-- t realizes A -/
def Real (A : Fal K) (t : K.Tm) : Prop := ∀ π, A π → K.pole t π

/-- falsity value of an implication -/
def Arr (A B : Fal K) : Fal K := fun π => ∃ t ρ, Real K A t ∧ B ρ ∧ π = K.push t ρ

/-- modus ponens -/
theorem mp (A B : Fal K) (t u : K.Tm) (ht : Real K (Arr K A B) t) (hu : Real K A u) :
    Real K B (K.app t u) :=
  fun π hπ => K.sat_app t u π (ht _ ⟨u, π, hu, hπ, rfl⟩)

/-- the continuation k_ρ realizes A → B whenever ρ is a stack of A -/
theorem k_real (A B : Fal K) (ρ : K.Stk) (hρ : A ρ) : Real K (Arr K A B) (K.k ρ) :=
  fun _ ⟨u, σ, hu, _, e⟩ => e ▸ K.sat_k u ρ σ (hu ρ hρ)

/-- cc realizes Peirce's law -/
theorem peirce (A B : Fal K) : Real K (Arr K (Arr K (Arr K A B) A) A) K.cc :=
  fun _ ⟨t, ρ, ht, hρ, e⟩ => e ▸ K.sat_cc t ρ (ht _ ⟨K.k ρ, ρ, k_real K A B ρ hρ, hρ, rfl⟩)

/-! ## the empty pole: two-valued truth -/

/-- a formula is true when its falsity value is empty -/
def True' (A : Fal K) : Prop := ∀ π, ¬ A π

theorem empty_real (h0 : ∀ t π, ¬ K.pole t π) (A : Fal K) (t : K.Tm) : Real K A t ↔ True' K A :=
  ⟨fun h π a => h0 t π (h π a), fun h π a => False.elim (h π a)⟩

theorem empty_arr (h0 : ∀ t π, ¬ K.pole t π) (A B : Fal K) :
    True' K (Arr K A B) ↔ (True' K A → True' K B) :=
  ⟨fun h ha ρ hb => h _ ⟨K.cc, ρ, (empty_real K h0 A K.cc).2 ha, hb, rfl⟩,
   fun h _ ⟨t, ρ, ht, hb, _⟩ => h ((empty_real K h0 A t).1 ht) ρ hb⟩

end Krivine

end Found

#print axioms Found.Krivine.mp
#print axioms Found.Krivine.k_real
#print axioms Found.Krivine.peirce
#print axioms Found.Krivine.empty_real
#print axioms Found.Krivine.empty_arr

#print axioms: 5 theorems, no axioms.

85.158 Orton–Pitts core: a univalent universe

From an interval with cofibrations: composition and fibrations, closure under \(\Sigma \) and path types, Glue types, and a universe closed under Glue codes in which every isomorphism gives a path with \(\mathsf {ua}\beta \).

\[ e : \mathrm {El}\,a\cong \mathrm {El}\,b \;\Rightarrow \; \mathsf {ua}\,e : a \leadsto b,\quad \mathsf {transp}^{\mathrm {El}\circ \mathsf {ua}\,e} = e \]

found/OP7.lean

/-
  T127 (core, slice OP7). found/OP7 — a univalent universe (Orton–Pitts).
  A universe is a type of codes U with decoding El, closed under Glue codes
  (the code of a Glue type decodes to the strictified type of OP5 and agrees
  on its face with the partial code).  The universe itself is data (a
  hypothesis structure, as in Licata–Orton–Pitts–Spitters where its
  construction needs a tiny interval), never a Lean axiom.  Then:
  * every isomorphism e : El a ≅ El b gives a path a ~> b in U (uaPath),
  * the decoded line along it is a fibration whenever El b is (fibUaU),
  * uaβ: transport along the decoded line, read at the start in El a and at
    the end in El b, is e (given regular composition on the empty face).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.OP6

namespace Found

namespace OP

/-- composition of isomorphisms -/
def TIso.comp {X Y Z : Type} (e1 : TIso X Y) (e2 : TIso Y Z) : TIso X Z :=
  ⟨fun x => e2.to (e1.to x), fun z => e1.inv (e2.inv z),
   fun x => (congrArg e1.inv (e2.li (e1.to x))).trans (e1.li x),
   fun z => (congrArg e2.to (e1.ri (e2.inv z))).trans (e2.ri z)⟩

/-- the isomorphism given by an equality of types -/
def castIso {X Y : Type} (h : X = Y) : TIso X Y :=
  ⟨castT h, castT h.symm, castT_back h, castT_back h.symm⟩

/-- a universe closed under Glue codes -/
structure Univ (J : Interval) (C : Cof J) (S : Strict J C) where
  U : Type
  El : U → Type
  code : (φ : Prop) → C.isCof φ → (T : φ → U) → (b : U) → ((h : φ) → TIso (El (T h)) (El b)) → U
  el_code : ∀ φ hφ T b f, El (code φ hφ T b f) = S.G φ hφ (fun h => El (T h)) (El b) f
  code_on : ∀ φ hφ T b f (h : φ), code φ hφ T b f = T h

section univ

variable {J : Interval} {C : Cof J} {S : Strict J C} (O : OrRec) (V : Univ J C S)
  {a b : V.U} (e : TIso (V.El a) (V.El b))

theorem sigU_to {b : V.U} {x : V.U} {e : TIso (V.El x) (V.El b)} (p : (X : V.U) × TIso (V.El X) (V.El b))
    (hp : p = ⟨x, e⟩) (y : V.El x) :
    p.2.to (castT (congrArg (fun q : (X : V.U) × TIso (V.El X) (V.El b) => V.El q.1) hp).symm y) = e.to y := by
  cases hp; rfl

/-- the partial code on the boundary: (a, e) at 0, (b, id) at 1 -/
def bdU (i : J.I) : bd J i → (X : V.U) × TIso (V.El X) (V.El b) :=
  O.glue (fun _ => ⟨a, e⟩) (fun _ => ⟨b, TIso.refl _⟩) (fun e0 e1 => absurd (e0.symm.trans e1) J.ne)

theorem bdU_0 : bdU O V e J.i0 (Or.inl rfl) = ⟨a, e⟩ := O.glue_l _ _ _ rfl

theorem bdU_1 : bdU O V e J.i1 (Or.inr rfl) = ⟨b, TIso.refl _⟩ := O.glue_r _ _ _ rfl

/-- the Glue code line -/
def uaU (i : J.I) : V.U :=
  V.code (bd J i) (cof_bd i) (fun h => (bdU O V e i h).1) b (fun h => (bdU O V e i h).2)

theorem uaU_0 : uaU O V e J.i0 = a :=
  (V.code_on _ _ _ _ _ (Or.inl rfl)).trans (congrArg Sigma.fst (bdU_0 O V e))

theorem uaU_1 : uaU O V e J.i1 = b :=
  (V.code_on _ _ _ _ _ (Or.inr rfl)).trans (congrArg Sigma.fst (bdU_1 O V e))

/-- univalence: a path in the universe from an isomorphism -/
def uaPath : Path J V.U a b := ⟨uaU O V e, uaU_0 O V e, uaU_1 O V e⟩

/-- the decoded line is pointwise isomorphic to El b -/
def elIso (i : J.I) : TIso (V.El (uaU O V e i)) (V.El b) :=
  TIso.comp (castIso (V.el_code _ (cof_bd i) _ b _))
    (S.iso _ (cof_bd i) (fun h => V.El (bdU O V e i h).1) (V.El b) (fun h => (bdU O V e i h).2))

/-- the decoded line is a fibration whenever El b is -/
def fibUaU (F : Fib J C (fun _ : J.I => V.El b)) : Fib J C (fun i => V.El (uaU O V e i)) :=
  fibIso (elIso O V e) F

/-- composition on the decoded line -/
def compUaU (F : Comp J C (fun _ => V.El b)) : Comp J C (fun i => V.El (uaU O V e i)) :=
  compIso (elIso O V e) F

/-- at the start the glued isomorphism is e -/
theorem elIso_start (x : V.El a) :
    (elIso O V e J.i0).to (castT (congrArg V.El (uaU_0 O V e)).symm x) = e.to x :=
  let q := congrArg (fun p : (X : V.U) × TIso (V.El X) (V.El b) => V.El p.1) (bdU_0 O V e)
  have A := (castT_trans (congrArg V.El (uaU_0 O V e)).symm
    (V.el_code _ (cof_bd J.i0) (fun h => (bdU O V e J.i0 h).1) b (fun h => (bdU O V e J.i0 h).2)) x).trans
    (castT_trans q.symm (S.eqT _ (cof_bd J.i0) (fun h => V.El (bdU O V e J.i0 h).1) (V.El b)
      (fun h => (bdU O V e J.i0 h).2) (Or.inl rfl)) x).symm
  (congrArg (S.iso _ (cof_bd J.i0) (fun h => V.El (bdU O V e J.i0 h).1) (V.El b)
      (fun h => (bdU O V e J.i0 h).2)).to A).trans
    ((S.iso_ext _ (cof_bd J.i0) (fun h => V.El (bdU O V e J.i0 h).1) (V.El b)
      (fun h => (bdU O V e J.i0 h).2) (Or.inl rfl) _).trans (sigU_to V _ (bdU_0 O V e) x))

/-- at the end the glued isomorphism is the identity -/
theorem elIso_end (y : V.El b) :
    castT (congrArg V.El (uaU_1 O V e)) ((elIso O V e J.i1).inv y) = y :=
  let q := congrArg (fun p : (X : V.U) × TIso (V.El X) (V.El b) => V.El p.1) (bdU_1 O V e)
  let E := S.eqT _ (cof_bd J.i1) (fun h => V.El (bdU O V e J.i1 h).1) (V.El b)
      (fun h => (bdU O V e J.i1 h).2) (Or.inr rfl)
  let I := S.iso _ (cof_bd J.i1) (fun h => V.El (bdU O V e J.i1 h).1) (V.El b) (fun h => (bdU O V e J.i1 h).2)
  have h1 : I.to (castT E (castT q.symm y)) = y :=
    (S.iso_ext _ (cof_bd J.i1) (fun h => V.El (bdU O V e J.i1 h).1) (V.El b)
      (fun h => (bdU O V e J.i1 h).2) (Or.inr rfl) _).trans (sigU_to V _ (bdU_1 O V e) y)
  have h2 : I.inv y = castT E (castT q.symm y) := (congrArg I.inv h1).symm.trans (I.li _)
  (congrArg (fun z => castT (congrArg V.El (uaU_1 O V e))
      (castT (V.el_code _ (cof_bd J.i1) (fun h => (bdU O V e J.i1 h).1) b (fun h => (bdU O V e J.i1 h).2)).symm z)) h2).trans
    ((congrArg (castT (congrArg V.El (uaU_1 O V e))) ((castT_trans _ _ _).trans (castT_trans _ _ _))).trans
      ((castT_trans _ _ _).trans (castT_self _ y)))

/-- uaβ in the universe: transport along the decoded line of ua e is e -/
theorem uaU_beta (F : Comp J C (fun _ => V.El b)) (hF : Reg F)
    (u : (i : J.I) → (J.i0 = J.i1) → V.El (uaU O V e i)) (x : V.El a)
    (hu : ∀ h, u J.i0 h = castT (congrArg V.El (uaU_0 O V e)).symm x) :
    castT (congrArg V.El (uaU_1 O V e))
      ((compUaU O V e F).c _ (cof_empty J C) u (castT (congrArg V.El (uaU_0 O V e)).symm x) hu) = e.to x :=
  (congrArg (fun y => castT (congrArg V.El (uaU_1 O V e)) ((elIso O V e J.i1).inv y)) (hF _ _ _)).trans
    ((elIso_end O V e _).trans (elIso_start O V e x))

end univ

end OP

end Found

#print axioms Found.OP.TIso.comp
#print axioms Found.OP.castIso
#print axioms Found.OP.sigU_to
#print axioms Found.OP.uaU_0
#print axioms Found.OP.uaU_1
#print axioms Found.OP.uaPath
#print axioms Found.OP.fibUaU
#print axioms Found.OP.elIso_start
#print axioms Found.OP.elIso_end
#print axioms Found.OP.uaU_beta

#print axioms: 10 theorems, no axioms.

85.159 Shulman’s theorem as a corollary

Inserting a Grothendieck \(\infty \)-topos over the classical point into the Orton–Pitts core: the topos is presentable, its objects are the types of a univalent universe up to equivalence, and isomorphisms give paths along which transport is the isomorphism.

\[ \mathrm {GrothTopos}(Y)\ \wedge \ \mathrm {Presents}(Y,M) \;\Rightarrow \; \forall e : \mathrm {El}\,a\cong \mathrm {El}\,b,\ \exists p : a \leadsto b,\ \mathsf {transp}^{p} = e \]

found/ShulmanCor.lean

/-
  T136. found/ShulmanCor — Shulman (2019) as a corollary of the Orton–Pitts
  core (T127, OP1–OP7) at the value E = a Grothendieck infinity-topos (T153)
  over the classical point (excluded middle and choice as hypothesis
  variables, CP.Classical').
  A cubical type-theoretic model is the data the Orton–Pitts core takes (an
  interval with cofibrations, gluing on disjunctions, strictification, a
  universe closed under Glue codes, composition in every decoded type,
  regular on the empty face).  A presentation of an infinity-category Y by
  such a model sends codes to objects of Y, every object being equivalent
  to one in the image.  The existence of a presentation for every
  Grothendieck infinity-topos (Shulman's model-categorical theorem: type-
  theoretic model topoi) is an internal theorem of the point (out of scope).
  Inserting the value gives Shulman's conclusion:
  * Y is presentable and its defining localization is a quasi-category
    (at the classical point, T153);
  * every object of Y is, up to equivalence, a type El a of the universe;
  * the universe is univalent: every isomorphism e : El a ≅ El b gives a
    path a ~> b in U along which transport is e (OP7).

  Lean 4 core only, hand-written proofs, no axioms.
-/
import found.OP7
import found.IC51

namespace Found

namespace ShulmanCor

open OP IC

/-- a cubical type-theoretic model: the data of the Orton–Pitts core -/
structure TTModel (J : Interval) (C : Cof J) where
  O : OrRec
  O1 : OrRec1
  S : Strict J C
  V : Univ J C S
  compEl : ∀ b : V.U, Comp J C (fun _ => V.El b)
  regEl : ∀ b : V.U, Reg (compEl b)

universe w

/-- a presentation of an infinity-category Y by a model -/
structure Presents {J : Interval} {C : Cof J} (Y : SSet.{w}) (M : TTModel J C) where
  ob : M.V.U → (V Y).car
  ess : ∀ y : (V Y).car, ∃ a : M.V.U, ∃ f : Mor (X := Y) (ob a) y, EquivE f

variable {J : Interval} {C : Cof J}

/-- univalence of the universe of a model, with transport -/
theorem univalent (M : TTModel J C) {a b : M.V.U} (e : TIso (M.V.El a) (M.V.El b)) :
    ∃ p : Path J M.V.U a b, ∃ Fp : Comp J C (fun i => M.V.El (p.p i)),
      ∀ x, OP.castT (congrArg M.V.El p.tgt) (transp J C Fp (OP.castT (congrArg M.V.El p.src).symm x)) = e.to x :=
  ⟨uaPath M.O M.V e, compUaU M.O M.V e (M.compEl b),
    fun x => uaU_beta M.O M.V e (M.compEl b) (M.regEl b) _ x _⟩

/-- Shulman's conclusion, from the Orton–Pitts core at a Grothendieck infinity-topos over the classical point -/
theorem shulman (Kw : ClW.{w}) (Kw' : ClW.{w + 1}) (Kc : CP.Classical')
    {κ : SSet.{w + 1} → Prop} {Y : SSet.{w + 1}} (hY : GrothTopos.{w} κ Y)
    (M : TTModel J C) (P : Presents Y M) :
    Presentable.{w} κ Y ∧
    (∃ (C' : SSet.{w + 1}) (Lc : Loc (PshS.{w} C')), κ C' ∧ LeftExact Lc.L ∧ CatEquiv Y (LocSub Lc) ∧
      Quasi (LocSub Lc)) ∧
    (∀ y : (V Y).car, ∃ a : M.V.U, ∃ f : Mor (X := Y) (P.ob a) y, EquivE f) ∧
    (∀ (a b : M.V.U) (e : TIso (M.V.El a) (M.V.El b)),
      ∃ p : Path J M.V.U a b, ∃ Fp : Comp J C (fun i => M.V.El (p.p i)),
        ∀ x, OP.castT (congrArg M.V.El p.tgt) (transp J C Fp (OP.castT (congrArg M.V.El p.src).symm x)) = e.to x) :=
  ⟨topos_presentable hY,
   match hY with
   | ⟨C', hC, Lc, _, hl, he⟩ => ⟨C', Lc, hC, hl, he, locSub_psh_quasi Kw Kw' Kc Lc⟩,
   P.ess,
   fun _ _ e => univalent M e⟩

end ShulmanCor

end Found

#print axioms Found.ShulmanCor.univalent
#print axioms Found.ShulmanCor.shulman

#print axioms: 2 theorems, no axioms.